blob: c395e20df3c680ac5d4346dc90d5ed09abcd3624 [file] [log] [blame]
Fyodor Kyslovdd7d5992024-11-05 21:40:16 +00001/*
2 * Copyright (C) 2024 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 "C2SoftApvEnc"
19#include <log/log.h>
20
21#include <media/hardware/VideoAPI.h>
22#include <media/stagefright/MediaDefs.h>
23#include <media/stagefright/MediaErrors.h>
24#include <media/stagefright/MetaData.h>
25#include <media/stagefright/foundation/AUtils.h>
26
27#include <C2Debug.h>
28#include <C2PlatformSupport.h>
29#include <Codec2BufferUtils.h>
30#include <Codec2CommonUtils.h>
31#include <Codec2Mapper.h>
32#include <SimpleC2Interface.h>
33#include <media/stagefright/foundation/ABitReader.h>
34#include <util/C2InterfaceHelper.h>
35#include <cmath>
36#include "C2SoftApvEnc.h"
37
38namespace android {
39
40namespace {
41
42constexpr char COMPONENT_NAME[] = "c2.android.apv.encoder";
43constexpr uint32_t kMinOutBufferSize = 524288;
44constexpr uint32_t kMaxBitstreamBufSize = 16 * 1024 * 1024;
45constexpr int32_t kApvQpMin = 0;
46constexpr int32_t kApvQpMax = 51;
47constexpr int32_t kApvDefaultQP = 32;
48
49#define PROFILE_APV_DEFAULT 0
50#define LEVEL_APV_DEFAULT 0
51#define MAX_NUM_FRMS (1) // supports only 1-frame input
52
53} // namespace
54
55class C2SoftApvEnc::IntfImpl : public SimpleInterface<void>::BaseParams {
56 public:
57 explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper>& helper)
58 : SimpleInterface<void>::BaseParams(helper, COMPONENT_NAME, C2Component::KIND_ENCODER,
59 C2Component::DOMAIN_VIDEO, MEDIA_MIMETYPE_VIDEO_APV) {
60 noPrivateBuffers();
61 noInputReferences();
62 noOutputReferences();
63 noTimeStretch();
64 setDerivedInstance(this);
65
66 addParameter(DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
67 .withConstValue(new C2ComponentAttributesSetting(
68 C2Component::ATTRIB_IS_TEMPORAL))
69 .build());
70
71 addParameter(DefineParam(mUsage, C2_PARAMKEY_INPUT_STREAM_USAGE)
72 .withConstValue(new C2StreamUsageTuning::input(
73 0u, (uint64_t)C2MemoryUsage::CPU_READ))
74 .build());
75
76 // matches size limits in codec library
77 addParameter(DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
78 .withDefault(new C2StreamPictureSizeInfo::input(0u, 320, 240))
79 .withFields({
80 C2F(mSize, width).inRange(2, 4096, 2),
81 C2F(mSize, height).inRange(2, 4096, 2),
82 })
83 .withSetter(SizeSetter)
84 .build());
85
86 // matches limits in codec library
87 addParameter(DefineParam(mBitrateMode, C2_PARAMKEY_BITRATE_MODE)
88 .withDefault(new C2StreamBitrateModeTuning::output(
89 0u, C2Config::BITRATE_VARIABLE))
90 .withFields({C2F(mBitrateMode, value)
91 .oneOf({C2Config::BITRATE_CONST,
92 C2Config::BITRATE_VARIABLE,
93 C2Config::BITRATE_IGNORE})})
94 .withSetter(Setter<decltype(*mBitrateMode)>::StrictValueWithNoDeps)
95 .build());
96
97 addParameter(DefineParam(mBitrate, C2_PARAMKEY_BITRATE)
98 .withDefault(new C2StreamBitrateInfo::output(0u, 512000))
99 .withFields({C2F(mBitrate, value).inRange(512000, 240000000)})
100 .withSetter(BitrateSetter)
101 .build());
102
103 addParameter(DefineParam(mFrameRate, C2_PARAMKEY_FRAME_RATE)
104 .withDefault(new C2StreamFrameRateInfo::output(0u, 15.))
105 .withFields({C2F(mFrameRate, value).greaterThan(0.)})
106 .withSetter(Setter<decltype(*mFrameRate)>::StrictValueWithNoDeps)
107 .build());
108
109 addParameter(DefineParam(mQuality, C2_PARAMKEY_QUALITY)
110 .withDefault(new C2StreamQualityTuning::output(0u, 40))
111 .withFields({C2F(mQuality, value).inRange(0, 100)})
112 .withSetter(Setter<decltype(*mQuality)>::NonStrictValueWithNoDeps)
113 .build());
114
115 addParameter(
116 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
117 .withDefault(new C2StreamProfileLevelInfo::output(
118 0u, C2Config::PROFILE_APV_422_10, LEVEL_APV_1_BAND_0))
119 .withFields({
120 C2F(mProfileLevel, profile).oneOf({C2Config::PROFILE_APV_422_10}),
121 C2F(mProfileLevel, level)
122 .oneOf({
123 C2Config::LEVEL_APV_1_BAND_0,
124 C2Config::LEVEL_APV_1_1_BAND_0,
125 C2Config::LEVEL_APV_2_BAND_0,
126 C2Config::LEVEL_APV_2_1_BAND_0,
127 C2Config::LEVEL_APV_3_BAND_0,
128 C2Config::LEVEL_APV_3_1_BAND_0,
129 C2Config::LEVEL_APV_4_BAND_0,
130 C2Config::LEVEL_APV_4_1_BAND_0,
131 C2Config::LEVEL_APV_5_BAND_0,
132 C2Config::LEVEL_APV_5_1_BAND_0,
133 C2Config::LEVEL_APV_6_BAND_0,
134 C2Config::LEVEL_APV_6_1_BAND_0,
135 C2Config::LEVEL_APV_7_BAND_0,
136 C2Config::LEVEL_APV_7_1_BAND_0,
137 C2Config::LEVEL_APV_1_BAND_1,
138 C2Config::LEVEL_APV_1_1_BAND_1,
139 C2Config::LEVEL_APV_2_BAND_1,
140 C2Config::LEVEL_APV_2_1_BAND_1,
141 C2Config::LEVEL_APV_3_BAND_1,
142 C2Config::LEVEL_APV_3_1_BAND_1,
143 C2Config::LEVEL_APV_4_BAND_1,
144 C2Config::LEVEL_APV_4_1_BAND_1,
145 C2Config::LEVEL_APV_5_BAND_1,
146 C2Config::LEVEL_APV_5_1_BAND_1,
147 C2Config::LEVEL_APV_6_BAND_1,
148 C2Config::LEVEL_APV_6_1_BAND_1,
149 C2Config::LEVEL_APV_7_BAND_1,
150 C2Config::LEVEL_APV_7_1_BAND_1,
151 C2Config::LEVEL_APV_1_BAND_2,
152 C2Config::LEVEL_APV_1_1_BAND_2,
153 C2Config::LEVEL_APV_2_BAND_2,
154 C2Config::LEVEL_APV_2_1_BAND_2,
155 C2Config::LEVEL_APV_3_BAND_2,
156 C2Config::LEVEL_APV_3_1_BAND_2,
157 C2Config::LEVEL_APV_4_BAND_2,
158 C2Config::LEVEL_APV_4_1_BAND_2,
159 C2Config::LEVEL_APV_5_BAND_2,
160 C2Config::LEVEL_APV_5_1_BAND_2,
161 C2Config::LEVEL_APV_6_BAND_2,
162 C2Config::LEVEL_APV_6_1_BAND_2,
163 C2Config::LEVEL_APV_7_BAND_2,
164 C2Config::LEVEL_APV_7_1_BAND_2,
165 C2Config::LEVEL_APV_1_BAND_3,
166 C2Config::LEVEL_APV_1_1_BAND_3,
167 C2Config::LEVEL_APV_2_BAND_3,
168 C2Config::LEVEL_APV_2_1_BAND_3,
169 C2Config::LEVEL_APV_3_BAND_3,
170 C2Config::LEVEL_APV_3_1_BAND_3,
171 C2Config::LEVEL_APV_4_BAND_3,
172 C2Config::LEVEL_APV_4_1_BAND_3,
173 C2Config::LEVEL_APV_5_BAND_3,
174 C2Config::LEVEL_APV_5_1_BAND_3,
175 C2Config::LEVEL_APV_6_BAND_3,
176 C2Config::LEVEL_APV_6_1_BAND_3,
177 C2Config::LEVEL_APV_7_BAND_3,
178 C2Config::LEVEL_APV_7_1_BAND_3,
179 }),
180 })
181 .withSetter(ProfileLevelSetter, mSize, mFrameRate, mBitrate)
182 .build());
183
184 addParameter(DefineParam(mColorAspects, C2_PARAMKEY_COLOR_ASPECTS)
185 .withDefault(new C2StreamColorAspectsInfo::input(
186 0u, C2Color::RANGE_UNSPECIFIED, C2Color::PRIMARIES_UNSPECIFIED,
187 C2Color::TRANSFER_UNSPECIFIED, C2Color::MATRIX_UNSPECIFIED))
188 .withFields({C2F(mColorAspects, range)
189 .inRange(C2Color::RANGE_UNSPECIFIED,
190 C2Color::RANGE_OTHER),
191 C2F(mColorAspects, primaries)
192 .inRange(C2Color::PRIMARIES_UNSPECIFIED,
193 C2Color::PRIMARIES_OTHER),
194 C2F(mColorAspects, transfer)
195 .inRange(C2Color::TRANSFER_UNSPECIFIED,
196 C2Color::TRANSFER_OTHER),
197 C2F(mColorAspects, matrix)
198 .inRange(C2Color::MATRIX_UNSPECIFIED,
199 C2Color::MATRIX_OTHER)})
200 .withSetter(ColorAspectsSetter)
201 .build());
202
203 addParameter(DefineParam(mCodedColorAspects, C2_PARAMKEY_VUI_COLOR_ASPECTS)
204 .withDefault(new C2StreamColorAspectsInfo::output(
205 0u, C2Color::RANGE_LIMITED, C2Color::PRIMARIES_UNSPECIFIED,
206 C2Color::TRANSFER_UNSPECIFIED, C2Color::MATRIX_UNSPECIFIED))
207 .withFields({C2F(mCodedColorAspects, range)
208 .inRange(C2Color::RANGE_UNSPECIFIED,
209 C2Color::RANGE_OTHER),
210 C2F(mCodedColorAspects, primaries)
211 .inRange(C2Color::PRIMARIES_UNSPECIFIED,
212 C2Color::PRIMARIES_OTHER),
213 C2F(mCodedColorAspects, transfer)
214 .inRange(C2Color::TRANSFER_UNSPECIFIED,
215 C2Color::TRANSFER_OTHER),
216 C2F(mCodedColorAspects, matrix)
217 .inRange(C2Color::MATRIX_UNSPECIFIED,
218 C2Color::MATRIX_OTHER)})
219 .withSetter(CodedColorAspectsSetter, mColorAspects)
220 .build());
221 std::vector<uint32_t> pixelFormats = {
222 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,
223 };
224 if (isHalPixelFormatSupported((AHardwareBuffer_Format)HAL_PIXEL_FORMAT_YCBCR_P010)) {
225 pixelFormats.push_back(HAL_PIXEL_FORMAT_YCBCR_P010);
226 }
227 addParameter(DefineParam(mPixelFormat, C2_PARAMKEY_PIXEL_FORMAT)
228 .withDefault(new C2StreamPixelFormatInfo::input(
229 0u, HAL_PIXEL_FORMAT_YCBCR_P010))
230 .withFields({C2F(mPixelFormat, value).oneOf({pixelFormats})})
231 .withSetter((Setter<decltype(*mPixelFormat)>::StrictValueWithNoDeps))
232 .build());
233 }
234
235 static C2R BitrateSetter(bool mayBlock, C2P<C2StreamBitrateInfo::output>& me) {
236 (void)mayBlock;
237 C2R res = C2R::Ok();
238 if (me.v.value < 1000000) {
239 me.set().value = 1000000;
240 }
241 return res;
242 }
243
244 static C2R SizeSetter(bool mayBlock, const C2P<C2StreamPictureSizeInfo::input>& oldMe,
245 C2P<C2StreamPictureSizeInfo::input>& me) {
246 (void)mayBlock;
247 C2R res = C2R::Ok();
248 if (!me.F(me.v.width).supportsAtAll(me.v.width)) {
249 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.width)));
250 me.set().width = oldMe.v.width;
251 }
252 if (!me.F(me.v.height).supportsAtAll(me.v.height)) {
253 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.height)));
254 me.set().height = oldMe.v.height;
255 }
256 return res;
257 }
258
259 static C2R ProfileLevelSetter(bool mayBlock, C2P<C2StreamProfileLevelInfo::output>& me,
260 const C2P<C2StreamPictureSizeInfo::input>& size,
261 const C2P<C2StreamFrameRateInfo::output>& frameRate,
262 const C2P<C2StreamBitrateInfo::output>& bitrate) {
263 (void)mayBlock;
264 if (!me.F(me.v.profile).supportsAtAll(me.v.profile)) {
265 me.set().profile = C2Config::PROFILE_APV_422_10;
266 }
267 if (!me.F(me.v.level).supportsAtAll(me.v.level)) {
268 me.set().level = LEVEL_APV_1_BAND_0;
269 }
270 return C2R::Ok();
271 }
272
273 static C2R ColorAspectsSetter(bool mayBlock, C2P<C2StreamColorAspectsInfo::input>& me) {
274 (void)mayBlock;
275 if (me.v.range > C2Color::RANGE_OTHER) {
276 me.set().range = C2Color::RANGE_OTHER;
277 }
278 if (me.v.primaries > C2Color::PRIMARIES_OTHER) {
279 me.set().primaries = C2Color::PRIMARIES_OTHER;
280 }
281 if (me.v.transfer > C2Color::TRANSFER_OTHER) {
282 me.set().transfer = C2Color::TRANSFER_OTHER;
283 }
284 if (me.v.matrix > C2Color::MATRIX_OTHER) {
285 me.set().matrix = C2Color::MATRIX_OTHER;
286 }
287 return C2R::Ok();
288 }
289
290 static C2R CodedColorAspectsSetter(bool mayBlock, C2P<C2StreamColorAspectsInfo::output>& me,
291 const C2P<C2StreamColorAspectsInfo::input>& coded) {
292 (void)mayBlock;
293 me.set().range = coded.v.range;
294 me.set().primaries = coded.v.primaries;
295 me.set().transfer = coded.v.transfer;
296 me.set().matrix = coded.v.matrix;
297 return C2R::Ok();
298 }
299
300 uint32_t getProfile_l() const {
301 int32_t profile = PROFILE_UNUSED;
302
303 switch (mProfileLevel->profile) {
304 case C2Config::PROFILE_APV_422_10:
305 profile = 33;
306 break;
307 case C2Config::PROFILE_APV_422_12:
308 profile = 44;
309 break;
310 case C2Config::PROFILE_APV_444_10:
311 profile = 55;
312 break;
313 case C2Config::PROFILE_APV_444_12:
314 profile = 66;
315 break;
316 case C2Config::PROFILE_APV_4444_10:
317 profile = 77;
318 break;
319 case C2Config::PROFILE_APV_4444_12:
320 profile = 88;
321 break;
322 case C2Config::PROFILE_APV_400_10:
323 profile = 99;
324 break;
325 default:
326 ALOGD("Unrecognized profile: %x", mProfileLevel->profile);
327 }
328 return profile;
329 }
330
331 uint32_t getLevel_l() const {
332 int32_t level = LEVEL_UNUSED;
333
334 // TODO: Add Band settings
335 switch (mProfileLevel->level) {
336 case C2Config::LEVEL_APV_1_BAND_0:
337 level = 10;
338 break;
339 case C2Config::LEVEL_APV_1_1_BAND_0:
340 level = 11;
341 break;
342 case C2Config::LEVEL_APV_2_BAND_0:
343 level = 20;
344 break;
345 case C2Config::LEVEL_APV_2_1_BAND_0:
346 level = 21;
347 break;
348 case C2Config::LEVEL_APV_3_BAND_0:
349 level = 30;
350 break;
351 case C2Config::LEVEL_APV_3_1_BAND_0:
352 level = 31;
353 break;
354 case C2Config::LEVEL_APV_4_BAND_0:
355 level = 40;
356 break;
357 case C2Config::LEVEL_APV_4_1_BAND_0:
358 level = 41;
359 break;
360 case C2Config::LEVEL_APV_5_BAND_0:
361 level = 50;
362 break;
363 case C2Config::LEVEL_APV_5_1_BAND_0:
364 level = 51;
365 break;
366 case C2Config::LEVEL_APV_6_BAND_0:
367 level = 60;
368 break;
369 case C2Config::LEVEL_APV_6_1_BAND_0:
370 level = 61;
371 break;
372 case C2Config::LEVEL_APV_7_BAND_0:
373 level = 70;
374 break;
375 case C2Config::LEVEL_APV_7_1_BAND_0:
376 level = 71;
377 break;
378 default:
379 ALOGD("Unrecognized level: %x", mProfileLevel->level);
380 }
381 // Convert to APV level_idc according to APV spec
382 return level * 3;
383 }
384
385 int32_t getBitrateMode_l() const {
386 int32_t bitrateMode = C2Config::BITRATE_CONST;
387
388 switch (mBitrateMode->value) {
389 case C2Config::BITRATE_CONST:
390 bitrateMode = OAPV_RC_CQP;
391 break;
392 case C2Config::BITRATE_VARIABLE:
393 bitrateMode = OAPV_RC_ABR;
394 break;
395 case C2Config::BITRATE_IGNORE:
396 bitrateMode = 0;
397 break;
398 default:
399 ALOGE("Unrecognized bitrate mode: %x", mBitrateMode->value);
400 }
401 return bitrateMode;
402 }
403
404 std::shared_ptr<C2StreamPictureSizeInfo::input> getSize_l() const { return mSize; }
405 std::shared_ptr<C2StreamFrameRateInfo::output> getFrameRate_l() const { return mFrameRate; }
406 std::shared_ptr<C2StreamBitrateInfo::output> getBitrate_l() const { return mBitrate; }
407 std::shared_ptr<C2StreamQualityTuning::output> getQuality_l() const { return mQuality; }
408 std::shared_ptr<C2StreamColorAspectsInfo::input> getColorAspects_l() const {
409 return mColorAspects;
410 }
411 std::shared_ptr<C2StreamColorAspectsInfo::output> getCodedColorAspects_l() const {
412 return mCodedColorAspects;
413 }
414 std::shared_ptr<C2StreamPictureQuantizationTuning::output> getPictureQuantization_l() const {
415 return mPictureQuantization;
416 }
417 std::shared_ptr<C2StreamProfileLevelInfo::output> getProfileLevel_l() const {
418 return mProfileLevel;
419 }
420 std::shared_ptr<C2StreamPixelFormatInfo::input> getPixelFormat_l() const {
421 return mPixelFormat;
422 }
423
424 private:
425 std::shared_ptr<C2StreamProfileLevelInfo::output> mProfileLevel;
426 std::shared_ptr<C2StreamUsageTuning::input> mUsage;
427 std::shared_ptr<C2StreamPictureSizeInfo::input> mSize;
428 std::shared_ptr<C2StreamFrameRateInfo::output> mFrameRate;
429 std::shared_ptr<C2StreamBitrateInfo::output> mBitrate;
430 std::shared_ptr<C2StreamBitrateModeTuning::output> mBitrateMode;
431 std::shared_ptr<C2StreamQualityTuning::output> mQuality;
432 std::shared_ptr<C2StreamColorAspectsInfo::input> mColorAspects;
433 std::shared_ptr<C2StreamColorAspectsInfo::output> mCodedColorAspects;
434 std::shared_ptr<C2StreamPictureQuantizationTuning::output> mPictureQuantization;
435 std::shared_ptr<C2StreamColorInfo::input> mColorFormat;
436 std::shared_ptr<C2StreamPixelFormatInfo::input> mPixelFormat;
437};
438
439C2SoftApvEnc::C2SoftApvEnc(const char* name, c2_node_id_t id,
440 const std::shared_ptr<IntfImpl>& intfImpl)
441 : SimpleC2Component(std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
442 mIntf(intfImpl),
443 mColorFormat(OAPV_CF_PLANAR2),
444 mStarted(false),
445 mSignalledEos(false),
446 mSignalledError(false),
447 mOutBlock(nullptr) {
448 reset();
449}
450
451C2SoftApvEnc::~C2SoftApvEnc() {
452 onRelease();
453}
454
455c2_status_t C2SoftApvEnc::onInit() {
456 return C2_OK;
457}
458
459c2_status_t C2SoftApvEnc::onStop() {
460 return C2_OK;
461}
462
463void C2SoftApvEnc::onReset() {
464 releaseEncoder();
465 reset();
466}
467
468void C2SoftApvEnc::onRelease() {
469 releaseEncoder();
470}
471
472c2_status_t C2SoftApvEnc::onFlush_sm() {
473 return C2_OK;
474}
475
476static void fillEmptyWork(const std::unique_ptr<C2Work>& work) {
477 uint32_t flags = 0;
478 if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
479 flags |= C2FrameData::FLAG_END_OF_STREAM;
480 ALOGV("Signalling EOS");
481 }
482 work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
483 work->worklets.front()->output.buffers.clear();
484 work->worklets.front()->output.ordinal = work->input.ordinal;
485 work->workletsProcessed = 1u;
486}
487
488int32_t C2SoftApvEnc::getQpFromQuality(int32_t quality) {
489 int32_t qp = ((kApvQpMin - kApvQpMax) * quality / 100) + kApvQpMax;
490 qp = std::min(qp, (int)kApvQpMax);
491 qp = std::max(qp, (int)kApvQpMin);
492 return qp;
493}
494
495c2_status_t C2SoftApvEnc::reset() {
496 ALOGV("reset");
497 mInitEncoder = false;
498 mStarted = false;
499 mSignalledEos = false;
500 mSignalledError = false;
501 mBitDepth = 10;
502 mMaxFrames = MAX_NUM_FRMS;
503 mReceivedFrames = 0;
504 mReceivedFirstFrame = false;
505 mColorFormat = OAPV_CF_PLANAR2;
506 return C2_OK;
507}
508
509c2_status_t C2SoftApvEnc::releaseEncoder() {
510 for (int32_t i = 0; i < MAX_NUM_FRMS; i++) {
511 if (mInputFrames.frm[i].imgb != nullptr) {
512 imgb_release(mInputFrames.frm[i].imgb);
513 }
514 }
515
516 if (mBitstreamBuf) {
517 std::free(mBitstreamBuf);
518 mBitstreamBuf = nullptr;
519 }
520 return C2_OK;
521}
522
523c2_status_t C2SoftApvEnc::drain(uint32_t drainMode, const std::shared_ptr<C2BlockPool>& pool) {
524 return drainInternal(drainMode, pool, nullptr);
525}
526
527void C2SoftApvEnc::showEncoderParams(oapve_cdesc_t* cdsc) {
528 std::string title = "APV encoder params:";
529 ALOGD("%s width = %d, height = %d", title.c_str(), cdsc->param[0].w, cdsc->param[0].h);
530 ALOGD("%s FrameRate = %f", title.c_str(),
531 (double)cdsc->param[0].fps_num / cdsc->param[0].fps_den);
532 ALOGD("%s BitRate = %d Kbps", title.c_str(), cdsc->param[0].bitrate);
533 ALOGD("%s QP = %d", title.c_str(), cdsc->param[0].qp);
534 ALOGD("%s profile_idc = %d, level_idc = %d, band_idc = %d", title.c_str(),
535 cdsc->param[0].profile_idc, cdsc->param[0].level_idc / 3, cdsc->param[0].band_idc);
536 ALOGD("%s Bitrate Mode: %d", title.c_str(), cdsc->param[0].rc_type);
537 ALOGD("%s mColorAspects primaries: %d, transfer: %d, matrix: %d, range: %d", title.c_str(),
538 mColorAspects->primaries, mColorAspects->transfer, mColorAspects->matrix,
539 mColorAspects->range);
540 ALOGD("%s mCodedColorAspects primaries: %d, transfer: %d, matrix: %d, range: %d", title.c_str(),
541 mCodedColorAspects->primaries, mCodedColorAspects->transfer, mCodedColorAspects->matrix,
542 mCodedColorAspects->range);
543 ALOGD("%s Input color format: %s", title.c_str(),
544 mColorFormat == OAPV_CF_YCBCR422 ? "YUV422P10LE" : "P210");
545 ALOGD("%s max_num_frms: %d", title.c_str(), cdsc->max_num_frms);
546}
547
548c2_status_t C2SoftApvEnc::initEncoder() {
549 if (mInitEncoder) {
550 return C2_OK;
551 }
552 ALOGV("initEncoder");
553
554 mSize = mIntf->getSize_l();
555 mFrameRate = mIntf->getFrameRate_l();
556 mBitrate = mIntf->getBitrate_l();
557 mQuality = mIntf->getQuality_l();
558 mColorAspects = mIntf->getColorAspects_l();
559 mCodedColorAspects = mIntf->getCodedColorAspects_l();
560 mProfileLevel = mIntf->getProfileLevel_l();
561 mPixelFormat = mIntf->getPixelFormat_l();
562
563 mCodecDesc = std::make_unique<oapve_cdesc_t>();
564 if (mCodecDesc == nullptr) {
565 ALOGE("Allocate ctx failed");
566 return C2_NO_INIT;
567 }
568 mCodecDesc->max_bs_buf_size = kMaxBitstreamBufSize;
569 mCodecDesc->max_num_frms = MAX_NUM_FRMS;
570 // TODO: Bound parameters to CPU count
571 mCodecDesc->threads = 4;
572
573 int32_t ret = C2_OK;
574 /* set params */
575 for (int32_t i = 0; i < mMaxFrames; i++) {
576 oapve_param_t* param = &mCodecDesc->param[i];
577 ret = oapve_param_default(param);
578 if (OAPV_FAILED(ret)) {
579 ALOGE("cannot set default parameter");
580 return C2_NO_INIT;
581 }
582 setParams(*param);
583 }
584
585 showEncoderParams(mCodecDesc.get());
586
587 /* create encoder */
588 mEncoderId = oapve_create(mCodecDesc.get(), NULL);
589 if (mEncoderId == NULL) {
590 ALOGE("cannot create APV encoder");
591 return C2_CORRUPTED;
592 }
593
594 /* create metadata */
595 mMetaId = oapvm_create(&ret);
596 if (mMetaId == NULL) {
597 ALOGE("cannot create APV encoder");
598 return C2_NO_MEMORY;
599 }
600
601 /* create image buffers */
602 for (int32_t i = 0; i < mMaxFrames; i++) {
603 if (mBitDepth == 10) {
604 mInputFrames.frm[i].imgb = imgb_create(mCodecDesc->param[0].w, mCodecDesc->param[0].h,
605 OAPV_CS_SET(mColorFormat, mBitDepth, 0));
606 mReconFrames.frm[i].imgb = nullptr;
607 } else {
608 mInputFrames.frm[i].imgb = imgb_create(mCodecDesc->param[0].w, mCodecDesc->param[0].h,
609 OAPV_CS_SET(mColorFormat, 10, 0));
610 mReconFrames.frm[i].imgb = nullptr;
611 }
612 }
613
614 /* allocate bitstream buffer */
615 mBitstreamBuf = new unsigned char[kMaxBitstreamBufSize];
616 if (mBitstreamBuf == nullptr) {
617 ALOGE("cannot allocate bitstream buffer, size= %d", kMaxBitstreamBufSize);
618 return C2_NO_MEMORY;
619 }
620
621 /* Calculate SDR to HDR mapping values */
622 mSdrToHdrMapping.clear();
623 for (int32_t i = 0; i < 256; i++) {
624 mSdrToHdrMapping.push_back((uint16_t)(i * 1023 / 255 + 0.5));
625 }
626
627 mStarted = true;
628 mInitEncoder = true;
629 return C2_OK;
630}
631
632void C2SoftApvEnc::setParams(oapve_param_t& param) {
633 param.w = mSize->width;
634 param.h = mSize->height;
635 param.fps_num = (int)(mFrameRate->value * 100);
636 param.fps_den = 100;
637 param.bitrate = mBitrate->value / 1000;
638 param.rc_type = mIntf->getBitrateMode_l();
639
640 int ApvQP = kApvDefaultQP;
641 if (param.rc_type == OAPV_RC_CQP) {
642 ApvQP = getQpFromQuality(mQuality->value);
643 ALOGI("Bitrate mode is CQ, so QP value is derived from Quality. Quality is %d, QP is %d",
644 mQuality->value, ApvQP);
645 }
646 param.qp = ApvQP;
647 param.band_idc = 0; // TODO: Get from the Level setting
648 param.profile_idc = mIntf->getProfile_l();
649 C2Config::level_t level = decisionApvLevel(
650 param.w, param.h, (int)(param.fps_num / param.fps_den), param.bitrate, param.band_idc);
651 if (mProfileLevel->level != level) {
652 mProfileLevel->level = level;
653 ALOGI("Need to update level to %d", mIntf->getLevel_l());
654 }
655 param.level_idc = mIntf->getLevel_l();
656}
657
658c2_status_t C2SoftApvEnc::setEncodeArgs(oapv_frms_t* inputFrames, const C2GraphicView* const input,
659 uint64_t workIndex) {
660 if (input->width() < mSize->width || input->height() < mSize->height) {
661 /* Expect width height to be configured */
662 ALOGW("unexpected Capacity Aspect %d(%d) x %d(%d)", input->width(), mSize->width,
663 input->height(), mSize->height);
664 return C2_BAD_VALUE;
665 }
666 const C2PlanarLayout& layout = input->layout();
667 uint8_t* yPlane = const_cast<uint8_t*>(input->data()[C2PlanarLayout::PLANE_Y]);
668 uint8_t* uPlane = const_cast<uint8_t*>(input->data()[C2PlanarLayout::PLANE_U]);
669 uint8_t* vPlane = const_cast<uint8_t*>(input->data()[C2PlanarLayout::PLANE_V]);
670 int32_t yStride = layout.planes[C2PlanarLayout::PLANE_Y].rowInc;
671 int32_t uStride = layout.planes[C2PlanarLayout::PLANE_U].rowInc;
672 int32_t vStride = layout.planes[C2PlanarLayout::PLANE_V].rowInc;
673
674 uint32_t width = mSize->width;
675 uint32_t height = mSize->height;
676
677 /* width and height must be even */
678 if (width & 1u || height & 1u) {
679 ALOGW("height(%u) and width(%u) must both be even", height, width);
680 return C2_BAD_VALUE;
681 }
682
683 /* Set num frames */
684 inputFrames->num_frms = MAX_NUM_FRMS;
685 inputFrames->frm[mReceivedFrames].group_id = 1;
686 inputFrames->frm[mReceivedFrames].pbu_type = OAPV_PBU_TYPE_PRIMARY_FRAME;
687
688 switch (layout.type) {
689 case C2PlanarLayout::TYPE_RGB:
690 [[fallthrough]];
691 case C2PlanarLayout::TYPE_RGBA: {
692 // TODO: Add RGBA1010102 support
693 ALOGE("Not supported RGB color format");
694 return C2_BAD_VALUE;
695 }
696 case C2PlanarLayout::TYPE_YUV: {
697 if (IsP010(*input)) {
698 if (mColorFormat == OAPV_CF_YCBCR422) {
699 ColorConvertP010ToYUV422P10le(input, inputFrames->frm[0].imgb);
700 } else if (mColorFormat == OAPV_CF_PLANAR2) {
701 ColorConvertP010ToP210(input, inputFrames->frm[0].imgb);
702 } else {
703 ALOGE("Not supported color format. %d", mColorFormat);
704 return C2_BAD_VALUE;
705 }
706 } else if (IsNV12(*input)) {
707 ColorConvertNv12ToP210(input, inputFrames->frm[0].imgb);
708 } else if (IsNV21(*input)) {
709 ColorConvertNv12ToP210(input, inputFrames->frm[0].imgb);
710 } else if (IsYUV420(*input)) {
711 return C2_BAD_VALUE;
712 } else if (IsI420(*input)) {
713 return C2_BAD_VALUE;
714 } else {
715 ALOGE("Not supported color format. %d", mColorFormat);
716 return C2_BAD_VALUE;
717 }
718 break;
719 }
720
721 default:
722 ALOGE("Unrecognized plane type: %d", layout.type);
723 return C2_BAD_VALUE;
724 }
725
726 return C2_OK;
727}
728
729void C2SoftApvEnc::ColorConvertNv12ToP210(const C2GraphicView* const input, oapv_imgb_t* imgb) {
730 auto width = input->width();
731 auto height = input->height();
732
733 auto* yPlane = (uint8_t*)input->data()[0];
734 auto* uvPlane = (uint8_t*)input->data()[1];
735
736 auto* dst = (uint16_t*)imgb->a[0];
737 int32_t lumaOffset = 0;
738 for (int32_t y = 0; y < height; ++y) {
739 for (int32_t x = 0; x < width; ++x) {
740 lumaOffset = y * width + x;
741 dst[lumaOffset] = (mSdrToHdrMapping[yPlane[lumaOffset]] << 6) |
742 ((mSdrToHdrMapping[yPlane[lumaOffset]] & 0x300) >> 3);
743 }
744 }
745
746 auto* dst_uv = (uint16_t*)imgb->a[1];
747 uint32_t uvDstStride = width;
748 int32_t srcOffset = 0;
749 int32_t dstOffset1 = 0, dstOffset2 = 0;
750 int32_t tmp1 = 0, tmp2 = 0;
751 for (int32_t y = 0; y < height / 2; ++y) {
752 for (int32_t x = 0; x < width; x += 2) {
753 srcOffset = y * width + x;
754 dstOffset1 = (y * 2) * width + x;
755 dstOffset2 = ((y * 2) + 1) * width + x;
756
757 tmp1 = (mSdrToHdrMapping[uvPlane[srcOffset]] << 6) |
758 ((mSdrToHdrMapping[uvPlane[srcOffset]] & 0x300) >> 3);
759 tmp2 = (mSdrToHdrMapping[uvPlane[srcOffset + 1]] << 6) |
760 ((mSdrToHdrMapping[uvPlane[srcOffset + 1]] & 0x300) >> 3);
761 dst_uv[dstOffset1] = (uint16_t)tmp1;
762 dst_uv[dstOffset1 + 1] = (uint16_t)tmp2;
763 dst_uv[dstOffset2] = (uint16_t)tmp1;
764 dst_uv[dstOffset2 + 1] = (uint16_t)tmp2;
765 }
766 }
767}
768
769C2Config::level_t C2SoftApvEnc::decisionApvLevel(int32_t width, int32_t height, int32_t fps,
770 int32_t bitrate, int32_t band) {
771 C2Config::level_t level = C2Config::LEVEL_APV_1_BAND_0;
772
773 struct LevelLimits {
774 C2Config::level_t level;
775 uint64_t samplesPerSec;
776 uint32_t bitratesOfBand;
777 };
778
779 constexpr LevelLimits kLimitsBand0[] = {
780 {LEVEL_APV_1_BAND_0, 3'041'280, 7'000},
781 {LEVEL_APV_1_1_BAND_0, 6'082'560, 14'000},
782 {LEVEL_APV_2_BAND_0, 15'667'200, 36'000},
783 {LEVEL_APV_2_1_BAND_0, 31'334'400, 71'000},
784 {LEVEL_APV_3_BAND_0, 66'846'720, 101'000},
785 {LEVEL_APV_3_1_BAND_0, 133'693'440, 201'000},
786 {LEVEL_APV_4_BAND_0, 265'420'800, 401'000},
787 {LEVEL_APV_4_1_BAND_0, 530'841'600, 780'000},
788 {LEVEL_APV_5_BAND_0, 1'061'683'200, 1'560'000},
789 {LEVEL_APV_5_1_BAND_0, 2'123'366'400, 3'324'000},
790 {LEVEL_APV_6_BAND_0, 4'777'574'400, 6'648'000},
791 {LEVEL_APV_6_1_BAND_0, 8'493'465'600, 13'296'000},
792 {LEVEL_APV_7_BAND_0, 16'986'931'200, 26'592'000},
793 {LEVEL_APV_7_1_BAND_0, 33'973'862'400, 53'184'000},
794 };
795
796 constexpr LevelLimits kLimitsBand1[] = {
797 {LEVEL_APV_1_BAND_1, 3'041'280, 11'000},
798 {LEVEL_APV_1_1_BAND_1, 6'082'560, 21'000},
799 {LEVEL_APV_2_BAND_1, 15'667'200, 53'000},
800 {LEVEL_APV_2_1_BAND_1, 31'334'400, 106'00},
801 {LEVEL_APV_3_BAND_1, 66'846'720, 151'000},
802 {LEVEL_APV_3_1_BAND_1, 133'693'440, 301'000},
803 {LEVEL_APV_4_BAND_1, 265'420'800, 602'000},
804 {LEVEL_APV_4_1_BAND_1, 530'841'600, 1'170'000},
805 {LEVEL_APV_5_BAND_1, 1'061'683'200, 2'340'000},
806 {LEVEL_APV_5_1_BAND_1, 2'123'366'400, 4'986'000},
807 {LEVEL_APV_6_BAND_1, 4'777'574'400, 9'972'000},
808 {LEVEL_APV_6_1_BAND_1, 8'493'465'600, 19'944'000},
809 {LEVEL_APV_7_BAND_1, 16'986'931'200, 39'888'000},
810 {LEVEL_APV_7_1_BAND_1, 33'973'862'400, 79'776'000},
811 };
812
813 constexpr LevelLimits kLimitsBand2[] = {
814 {LEVEL_APV_1_BAND_2, 3'041'280, 14'000},
815 {LEVEL_APV_1_1_BAND_2, 6'082'560, 28'000},
816 {LEVEL_APV_2_BAND_2, 15'667'200, 71'000},
817 {LEVEL_APV_2_1_BAND_2, 31'334'400, 141'000},
818 {LEVEL_APV_3_BAND_2, 66'846'720, 201'000},
819 {LEVEL_APV_3_1_BAND_2, 133'693'440, 401'000},
820 {LEVEL_APV_4_BAND_2, 265'420'800, 780'000},
821 {LEVEL_APV_4_1_BAND_2, 530'841'600, 1'560'000},
822 {LEVEL_APV_5_BAND_2, 1'061'683'200, 3'324'000},
823 {LEVEL_APV_5_1_BAND_2, 2'123'366'400, 6'648'000},
824 {LEVEL_APV_6_BAND_2, 4'777'574'400, 13'296'000},
825 {LEVEL_APV_6_1_BAND_2, 8'493'465'600, 26'592'000},
826 {LEVEL_APV_7_BAND_2, 16'986'931'200, 53'184'000},
827 {LEVEL_APV_7_1_BAND_2, 33'973'862'400, 106'368'000},
828 };
829
830 constexpr LevelLimits kLimitsBand3[] = {
831 {LEVEL_APV_1_BAND_3, 3'041'280, 21'000},
832 {LEVEL_APV_1_1_BAND_3, 6'082'560, 42'000},
833 {LEVEL_APV_2_BAND_3, 15'667'200, 106'000},
834 {LEVEL_APV_2_1_BAND_3, 31'334'400, 212'000},
835 {LEVEL_APV_3_BAND_3, 66'846'720, 301'000},
836 {LEVEL_APV_3_1_BAND_3, 133'693'440, 602'000},
837 {LEVEL_APV_4_BAND_3, 265'420'800, 1'170'000},
838 {LEVEL_APV_4_1_BAND_3, 530'841'600, 2'340'000},
839 {LEVEL_APV_5_BAND_3, 1'061'683'200, 4'986'000},
840 {LEVEL_APV_5_1_BAND_3, 2'123'366'400, 9'972'000},
841 {LEVEL_APV_6_BAND_3, 4'777'574'400, 19'944'000},
842 {LEVEL_APV_6_1_BAND_3, 8'493'465'600, 39'888'000},
843 {LEVEL_APV_7_BAND_3, 16'986'931'200, 79'776'000},
844 {LEVEL_APV_7_1_BAND_3, 33'973'862'400, 159'552'000},
845 };
846
847 uint64_t samplesPerSec = width * height * fps;
848 if (band == 0) {
849 for (const LevelLimits& limit : kLimitsBand0) {
850 if (samplesPerSec <= limit.samplesPerSec && bitrate <= limit.bitratesOfBand) {
851 level = limit.level;
852 break;
853 }
854 }
855 } else if (band == 1) {
856 for (const LevelLimits& limit : kLimitsBand1) {
857 if (samplesPerSec <= limit.samplesPerSec && bitrate <= limit.bitratesOfBand) {
858 level = limit.level;
859 break;
860 }
861 }
862 } else if (band == 2) {
863 for (const LevelLimits& limit : kLimitsBand2) {
864 if (samplesPerSec <= limit.samplesPerSec && bitrate <= limit.bitratesOfBand) {
865 level = limit.level;
866 break;
867 }
868 }
869 } else if (band == 3) {
870 for (const LevelLimits& limit : kLimitsBand3) {
871 if (samplesPerSec <= limit.samplesPerSec && bitrate <= limit.bitratesOfBand) {
872 level = limit.level;
873 break;
874 }
875 }
876 } else {
877 ALOGE("Invalid band_idc on calculte level");
878 }
879
880 return level;
881}
882
883void C2SoftApvEnc::ColorConvertP010ToP210(const C2GraphicView* const input, oapv_imgb_t* imgb) {
884 auto width = input->width();
885 auto height = input->height();
886
887 auto* yPlane = (uint8_t*)input->data()[0];
888 auto* uvPlane = (uint8_t*)input->data()[1];
889 uint32_t uvStride = width * 2;
890
891 auto* src = yPlane;
892 auto* dst = (uint8_t*)imgb->a[0];
893 std::memcpy(dst, src, width * height * 2);
894
895 auto* dst_uv = (uint8_t*)imgb->a[1];
896 int32_t offset1 = 0, offset2 = 0;
897 for (int32_t y = 0; y < height / 2; ++y) {
898 offset1 = (y * 2) * uvStride;
899 offset2 = (y * 2 + 1) * uvStride;
900 src = uvPlane + (y * uvStride);
901
902 std::memcpy(dst_uv + offset1, src, uvStride);
903 std::memcpy(dst_uv + offset2, src, uvStride);
904 }
905}
906
907void C2SoftApvEnc::ColorConvertP010ToYUV422P10le(const C2GraphicView* const input,
908 oapv_imgb_t* imgb) {
909 uint32_t width = input->width();
910 uint32_t height = input->height();
911
912 uint8_t* yPlane = (uint8_t*)input->data()[0];
913 auto* uvPlane = (uint8_t*)input->data()[1];
914 uint32_t stride[3];
915 stride[0] = width * 2;
916 stride[1] = stride[2] = width;
917
918 uint8_t *dst, *src;
919 uint16_t tmp;
920 for (int32_t y = 0; y < height; ++y) {
921 src = yPlane + y * stride[0];
922 dst = (uint8_t*)imgb->a[0] + y * stride[0];
923 for (int32_t x = 0; x < stride[0]; x += 2) {
924 tmp = (src[x + 1] << 2) | (src[x] >> 6);
925 dst[x] = tmp & 0xFF;
926 dst[x + 1] = tmp >> 8;
927 }
928 }
929
930 uint8_t *dst_u, *dst_v;
931 for (int32_t y = 0; y < height / 2; ++y) {
932 src = uvPlane + y * stride[1] * 2;
933 dst_u = (uint8_t*)imgb->a[1] + (y * 2) * stride[1];
934 dst_v = (uint8_t*)imgb->a[2] + (y * 2) * stride[2];
935 for (int32_t x = 0; x < stride[1] * 2; x += 4) {
936 tmp = (src[x + 1] << 2) | (src[x] >> 6); // cb
937 dst_u[x / 2] = tmp & 0xFF;
938 dst_u[x / 2 + 1] = tmp >> 8;
939 dst_u[x / 2 + stride[1]] = dst_u[x / 2];
940 dst_u[x / 2 + stride[1] + 1] = dst_u[x / 2 + 1];
941
942 tmp = (src[x + 3] << 2) | (src[x + 2] >> 6); // cr
943 dst_v[x / 2] = tmp & 0xFF;
944 dst_v[x / 2 + 1] = tmp >> 8;
945 dst_v[x / 2 + stride[2]] = dst_v[x / 2];
946 dst_v[x / 2 + stride[2] + 1] = dst_v[x / 2 + 1];
947 }
948 }
949}
950
951void C2SoftApvEnc::finishWork(uint64_t workIndex, const std::unique_ptr<C2Work>& work,
952 const std::shared_ptr<C2BlockPool>& pool, oapv_bitb_t* bitb,
953 oapve_stat_t* stat) {
954 std::shared_ptr<C2LinearBlock> block;
955 C2MemoryUsage usage = {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
956 c2_status_t status = pool->fetchLinearBlock(stat->write, usage, &block);
957 if (C2_OK != status) {
958 ALOGE("fetchLinearBlock for Output failed with status 0x%x", status);
959 mSignalledError = true;
960 work->result = status;
961 work->workletsProcessed = 1u;
962 return;
963 }
964
965 C2WriteView wView = block->map().get();
966 if (C2_OK != wView.error()) {
967 ALOGE("write view map failed with status 0x%x", wView.error());
968 mSignalledError = true;
969 work->result = wView.error();
970 work->workletsProcessed = 1u;
971 return;
972 }
973 if ((!mReceivedFirstFrame)) {
974 createCsdData(work, bitb, stat->write);
975 mReceivedFirstFrame = true;
976 }
977
978 memcpy(wView.data(), bitb->addr, stat->write);
979 std::shared_ptr<C2Buffer> buffer = createLinearBuffer(block, 0, stat->write);
980
981 /* All frames are SYNC FRAME */
982 buffer->setInfo(std::make_shared<C2StreamPictureTypeMaskInfo::output>(0u /* stream id */,
983 C2Config::SYNC_FRAME));
984
985 auto fillWork = [buffer](const std::unique_ptr<C2Work>& work) {
986 work->worklets.front()->output.flags = (C2FrameData::flags_t)0;
987 work->worklets.front()->output.buffers.clear();
988 work->worklets.front()->output.buffers.push_back(buffer);
989 work->worklets.front()->output.ordinal = work->input.ordinal;
990 work->workletsProcessed = 1u;
991 };
992 if (work && c2_cntr64_t(workIndex) == work->input.ordinal.frameIndex) {
993 fillWork(work);
994 if (mSignalledEos) {
995 work->worklets.front()->output.flags = C2FrameData::FLAG_END_OF_STREAM;
996 }
997 } else {
998 finish(workIndex, fillWork);
999 }
1000}
1001void C2SoftApvEnc::createCsdData(const std::unique_ptr<C2Work>& work, oapv_bitb_t* bitb,
1002 uint32_t encodedSize) {
1003 uint32_t csdStart = 0, csdEnd = 0;
1004 uint32_t bitOffset = 0;
1005 uint8_t* buf = (uint8_t*)bitb->addr + csdStart;
1006
1007 if (encodedSize == 0) {
1008 ALOGE("the first frame size is zero, so no csd data will be created.");
1009 return;
1010 }
1011 ABitReader reader(buf, encodedSize);
1012
1013 /* pbu_header() */
1014 reader.skipBits(32);
1015 bitOffset += 32; // pbu_size
1016 reader.skipBits(32);
1017 bitOffset += 32; // currReadSize
1018 csdStart = bitOffset / 8;
1019
1020 int32_t pbu_type = reader.getBits(8);
1021 bitOffset += 8; // pbu_type
1022 reader.skipBits(16);
1023 bitOffset += 16; // group_id
1024 reader.skipBits(8);
1025 bitOffset += 8; // reserved_zero_8bits
1026
1027 /* frame info() */
1028 int32_t profile_idc = reader.getBits(8);
1029 bitOffset += 8; // profile_idc
1030 int32_t level_idc = reader.getBits(8);
1031 bitOffset += 8; // level_idc
1032 int32_t band_idc = reader.getBits(3);
1033 bitOffset += 3; // band_idc
1034 reader.skipBits(5);
1035 bitOffset += 5; // reserved_zero_5bits
1036 int32_t width = reader.getBits(32);
1037 bitOffset += 32; // width
1038 int32_t height = reader.getBits(32);
1039 bitOffset += 32; // height
1040 int32_t chroma_idc = reader.getBits(4);
1041 bitOffset += 4; // chroma_format_idc
1042 reader.skipBits(4);
1043 bitOffset += 4; // bit_depth
1044 reader.skipBits(8);
1045 bitOffset += 8; // capture_time_distance
1046 reader.skipBits(8);
1047 bitOffset += 8; // reserved_zero_8bits
1048
1049 /* frame header() */
1050 reader.skipBits(8);
1051 bitOffset += 8; // reserved_zero_8bit
1052 bool color_description_present_flag = reader.getBits(1);
1053 bitOffset += 1; // color_description_present_flag
1054 if (color_description_present_flag) {
1055 reader.skipBits(8);
1056 bitOffset += 8; // color_primaries
1057 reader.skipBits(8);
1058 bitOffset += 8; // transfer_characteristics
1059 reader.skipBits(8);
1060 bitOffset += 8; // matrix_coefficients
1061 }
1062 bool use_q_matrix = reader.getBits(1);
1063 bitOffset += 1; // use_q_matrix
1064 if (use_q_matrix) {
1065 /* quantization_matrix() */
1066 int32_t numComp = chroma_idc == 0 ? 1
1067 : chroma_idc == 2 ? 3
1068 : chroma_idc == 3 ? 3
1069 : chroma_idc == 4 ? 4
1070 : -1;
1071 int32_t needBitsForQ = 64 * 8 * numComp;
1072 reader.skipBits(needBitsForQ);
1073 bitOffset += needBitsForQ;
1074 }
1075
1076 /* tile_info() */
1077 int32_t tile_width_in_mbs_minus1 = reader.getBits(28);
1078 bitOffset += 28;
1079 int32_t tile_height_in_mbs_minus1 = reader.getBits(28);
1080 bitOffset += 28;
1081 bool tile_size_present_in_fh_flag = reader.getBits(1);
1082 bitOffset += 1;
1083 if (tile_size_present_in_fh_flag) {
1084 int32_t numTiles = ceil((double)width / (double)tile_width_in_mbs_minus1) *
1085 ceil((double)height / (double)tile_height_in_mbs_minus1);
1086 reader.skipBits(32 * numTiles);
1087 bitOffset += (32 * numTiles);
1088 }
1089
1090 reader.skipBits(8);
1091 bitOffset += 8; // reserved_zero_8bits
1092
1093 /* byte_alignmenet() */
1094 while (bitOffset % 8) {
1095 reader.skipBits(1);
1096 bitOffset += 1;
1097 }
1098 csdEnd = bitOffset / 8;
1099 int32_t csdSize = csdEnd - csdStart + 1;
1100
1101 std::unique_ptr<C2StreamInitDataInfo::output> csd =
1102 C2StreamInitDataInfo::output::AllocUnique(csdSize, 0u);
1103 if (!csd) {
1104 ALOGE("CSD allocation failed");
1105 mSignalledError = true;
1106 work->result = C2_NO_MEMORY;
1107 work->workletsProcessed = 1u;
1108 return;
1109 }
1110
1111 buf = buf + csdStart;
1112 memcpy(csd->m.value, buf, csdSize);
1113 work->worklets.front()->output.configUpdate.push_back(std::move(csd));
1114}
1115c2_status_t C2SoftApvEnc::drainInternal(uint32_t drainMode,
1116 const std::shared_ptr<C2BlockPool>& pool,
1117 const std::unique_ptr<C2Work>& work) {
1118 fillEmptyWork(work);
1119 return C2_OK;
1120}
1121
1122void C2SoftApvEnc::process(const std::unique_ptr<C2Work>& work,
1123 const std::shared_ptr<C2BlockPool>& pool) {
1124 c2_status_t error;
1125 work->result = C2_OK;
1126 work->workletsProcessed = 0u;
1127 work->worklets.front()->output.flags = work->input.flags;
1128
1129 nsecs_t timeDelay = 0;
1130 uint64_t workIndex = work->input.ordinal.frameIndex.peekull();
1131
1132 mSignalledEos = false;
1133 mOutBlock = nullptr;
1134
1135 if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
1136 ALOGV("Got FLAG_END_OF_STREAM");
1137 mSignalledEos = true;
1138 }
1139
1140 /* Initialize encoder if not already initialized */
1141 if (initEncoder() != C2_OK) {
1142 ALOGE("Failed to initialize encoder");
1143 mSignalledError = true;
1144 work->result = C2_CORRUPTED;
1145 work->workletsProcessed = 1u;
1146 ALOGE("[%s] Failed to make Codec context", __func__);
1147 return;
1148 }
1149 if (mSignalledError) {
1150 ALOGE("[%s] Received signalled error", __func__);
1151 return;
1152 }
1153
1154 if (mSignalledEos) {
1155 drainInternal(DRAIN_COMPONENT_WITH_EOS, pool, work);
1156 return;
1157 }
1158
1159 if (work->input.buffers.empty()) {
1160 return;
1161 }
1162
1163 std::shared_ptr<C2GraphicView> view;
1164 std::shared_ptr<C2Buffer> inputBuffer = nullptr;
1165 if (!work->input.buffers.empty()) {
1166 inputBuffer = work->input.buffers[0];
1167 view = std::make_shared<C2GraphicView>(
1168 inputBuffer->data().graphicBlocks().front().map().get());
1169 if (view->error() != C2_OK) {
1170 ALOGE("graphic view map err = %d", view->error());
1171 work->workletsProcessed = 1u;
1172 return;
1173 }
1174 }
1175 if (!inputBuffer) {
1176 fillEmptyWork(work);
1177 return;
1178 }
1179
1180 oapve_stat_t stat;
1181 auto outBufferSize =
1182 mCodecDesc->param[mReceivedFrames].w * mCodecDesc->param[mReceivedFrames].h * 4;
1183 if (!mOutBlock) {
1184 C2MemoryUsage usage = {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
1185 c2_status_t err = pool->fetchLinearBlock(outBufferSize, usage, &mOutBlock);
1186 if (err != C2_OK) {
1187 work->result = err;
1188 work->workletsProcessed = 1u;
1189 ALOGE("fetchLinearBlock has failed. err = %d", err);
1190 return;
1191 }
1192 }
1193
1194 C2WriteView wView = mOutBlock->map().get();
1195 if (wView.error() != C2_OK) {
1196 work->result = wView.error();
1197 work->workletsProcessed = 1u;
1198 return;
1199 }
1200
1201 error = setEncodeArgs(&mInputFrames, view.get(), workIndex);
1202 if (error != C2_OK) {
1203 mSignalledError = true;
1204 work->result = error;
1205 work->workletsProcessed = 1u;
1206 return;
1207 }
1208
1209 if (++mReceivedFrames < mMaxFrames) {
1210 return;
1211 }
1212 mReceivedFrames = 0;
1213
1214 std::shared_ptr<oapv_bitb_t> bits = std::make_shared<oapv_bitb_t>();
1215 std::memset(mBitstreamBuf, 0, kMaxBitstreamBufSize);
1216 bits->addr = mBitstreamBuf;
1217 bits->bsize = kMaxBitstreamBufSize;
1218 bits->err = C2_OK;
1219
1220 if (mInputFrames.frm[0].imgb) {
1221 int32_t status =
1222 oapve_encode(mEncoderId, &mInputFrames, mMetaId, bits.get(), &stat, &mReconFrames);
1223 if (status != C2_OK) {
1224 mSignalledError = true;
1225 work->result = C2_CORRUPTED;
1226 work->workletsProcessed = 1u;
1227 return;
1228 }
1229 } else if (!mSignalledEos) {
1230 fillEmptyWork(work);
1231 }
1232 finishWork(workIndex, work, pool, bits.get(), &stat);
1233}
1234
1235class C2SoftApvEncFactory : public C2ComponentFactory {
1236 public:
1237 C2SoftApvEncFactory()
1238 : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
1239 GetCodec2PlatformComponentStore()->getParamReflector())) {}
1240
1241 virtual c2_status_t createComponent(c2_node_id_t id,
1242 std::shared_ptr<C2Component>* const component,
1243 std::function<void(C2Component*)> deleter) override {
1244 *component = std::shared_ptr<C2Component>(
1245 new C2SoftApvEnc(COMPONENT_NAME, id,
1246 std::make_shared<C2SoftApvEnc::IntfImpl>(mHelper)),
1247 deleter);
1248 return C2_OK;
1249 }
1250
1251 c2_status_t createInterface(c2_node_id_t id,
1252 std::shared_ptr<C2ComponentInterface>* const interface,
1253 std::function<void(C2ComponentInterface*)> deleter) override {
1254 *interface = std::shared_ptr<C2ComponentInterface>(
1255 new SimpleInterface<C2SoftApvEnc::IntfImpl>(
1256 COMPONENT_NAME, id, std::make_shared<C2SoftApvEnc::IntfImpl>(mHelper)),
1257 deleter);
1258 return C2_OK;
1259 }
1260
1261 ~C2SoftApvEncFactory() override = default;
1262
1263 private:
1264 std::shared_ptr<C2ReflectorHelper> mHelper;
1265};
1266
1267} // namespace android
1268
1269__attribute__((cfi_canonical_jump_table)) extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
1270 return new ::android::C2SoftApvEncFactory();
1271}
1272
1273__attribute__((cfi_canonical_jump_table)) extern "C" void DestroyCodec2Factory(
1274 ::C2ComponentFactory* factory) {
1275 delete factory;
1276}