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