blob: 3ba480a31e5a3d5e310a86a7649750b7b2b1776a [file] [log] [blame]
Vignesh Venkatasubramanian46e06392019-06-10 15:11:58 -07001/*
2 * Copyright (C) 2019 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 "C2SoftGav1Dec"
19#include "C2SoftGav1Dec.h"
20
21#include <C2Debug.h>
22#include <C2PlatformSupport.h>
23#include <SimpleC2Interface.h>
24#include <log/log.h>
25#include <media/stagefright/foundation/AUtils.h>
26#include <media/stagefright/foundation/MediaDefs.h>
27
28namespace android {
29
30// TODO(vigneshv): This will be changed to c2.android.av1.decoder once this
31// component is fully functional.
32constexpr char COMPONENT_NAME[] = "c2.android.gav1.decoder";
33
34class C2SoftGav1Dec::IntfImpl : public SimpleInterface<void>::BaseParams {
35 public:
36 explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
37 : SimpleInterface<void>::BaseParams(
38 helper, COMPONENT_NAME, C2Component::KIND_DECODER,
39 C2Component::DOMAIN_VIDEO, MEDIA_MIMETYPE_VIDEO_AV1) {
40 noPrivateBuffers(); // TODO: account for our buffers here.
41 noInputReferences();
42 noOutputReferences();
43 noInputLatency();
44 noTimeStretch();
45
46 addParameter(DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
47 .withConstValue(new C2ComponentAttributesSetting(
48 C2Component::ATTRIB_IS_TEMPORAL))
49 .build());
50
51 addParameter(
52 DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
53 .withDefault(new C2StreamPictureSizeInfo::output(0u, 320, 240))
54 .withFields({
55 C2F(mSize, width).inRange(2, 2048, 2),
56 C2F(mSize, height).inRange(2, 2048, 2),
57 })
58 .withSetter(SizeSetter)
59 .build());
60
61 addParameter(DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
62 .withDefault(new C2StreamProfileLevelInfo::input(
63 0u, C2Config::PROFILE_AV1_0, C2Config::LEVEL_AV1_2_1))
64 .withFields({C2F(mProfileLevel, profile)
65 .oneOf({C2Config::PROFILE_AV1_0,
66 C2Config::PROFILE_AV1_1}),
67 C2F(mProfileLevel, level)
68 .oneOf({
69 C2Config::LEVEL_AV1_2,
70 C2Config::LEVEL_AV1_2_1,
71 C2Config::LEVEL_AV1_2_2,
72 C2Config::LEVEL_AV1_3,
73 C2Config::LEVEL_AV1_3_1,
74 C2Config::LEVEL_AV1_3_2,
75 })})
76 .withSetter(ProfileLevelSetter, mSize)
77 .build());
78
79 mHdr10PlusInfoInput = C2StreamHdr10PlusInfo::input::AllocShared(0);
80 addParameter(
81 DefineParam(mHdr10PlusInfoInput, C2_PARAMKEY_INPUT_HDR10_PLUS_INFO)
82 .withDefault(mHdr10PlusInfoInput)
83 .withFields({
84 C2F(mHdr10PlusInfoInput, m.value).any(),
85 })
86 .withSetter(Hdr10PlusInfoInputSetter)
87 .build());
88
89 mHdr10PlusInfoOutput = C2StreamHdr10PlusInfo::output::AllocShared(0);
90 addParameter(
91 DefineParam(mHdr10PlusInfoOutput, C2_PARAMKEY_OUTPUT_HDR10_PLUS_INFO)
92 .withDefault(mHdr10PlusInfoOutput)
93 .withFields({
94 C2F(mHdr10PlusInfoOutput, m.value).any(),
95 })
96 .withSetter(Hdr10PlusInfoOutputSetter)
97 .build());
98
99 addParameter(
100 DefineParam(mMaxSize, C2_PARAMKEY_MAX_PICTURE_SIZE)
101 .withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 320, 240))
102 .withFields({
103 C2F(mSize, width).inRange(2, 2048, 2),
104 C2F(mSize, height).inRange(2, 2048, 2),
105 })
106 .withSetter(MaxPictureSizeSetter, mSize)
107 .build());
108
109 addParameter(DefineParam(mMaxInputSize, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE)
110 .withDefault(new C2StreamMaxBufferSizeInfo::input(
111 0u, 320 * 240 * 3 / 4))
112 .withFields({
113 C2F(mMaxInputSize, value).any(),
114 })
115 .calculatedAs(MaxInputSizeSetter, mMaxSize)
116 .build());
117
118 C2ChromaOffsetStruct locations[1] = {C2ChromaOffsetStruct::ITU_YUV_420_0()};
119 std::shared_ptr<C2StreamColorInfo::output> defaultColorInfo =
120 C2StreamColorInfo::output::AllocShared(1u, 0u, 8u /* bitDepth */,
121 C2Color::YUV_420);
122 memcpy(defaultColorInfo->m.locations, locations, sizeof(locations));
123
124 defaultColorInfo = C2StreamColorInfo::output::AllocShared(
125 {C2ChromaOffsetStruct::ITU_YUV_420_0()}, 0u, 8u /* bitDepth */,
126 C2Color::YUV_420);
127 helper->addStructDescriptors<C2ChromaOffsetStruct>();
128
129 addParameter(DefineParam(mColorInfo, C2_PARAMKEY_CODED_COLOR_INFO)
130 .withConstValue(defaultColorInfo)
131 .build());
132
133 addParameter(
134 DefineParam(mDefaultColorAspects, C2_PARAMKEY_DEFAULT_COLOR_ASPECTS)
135 .withDefault(new C2StreamColorAspectsTuning::output(
136 0u, C2Color::RANGE_UNSPECIFIED, C2Color::PRIMARIES_UNSPECIFIED,
137 C2Color::TRANSFER_UNSPECIFIED, C2Color::MATRIX_UNSPECIFIED))
138 .withFields(
139 {C2F(mDefaultColorAspects, range)
140 .inRange(C2Color::RANGE_UNSPECIFIED, C2Color::RANGE_OTHER),
141 C2F(mDefaultColorAspects, primaries)
142 .inRange(C2Color::PRIMARIES_UNSPECIFIED,
143 C2Color::PRIMARIES_OTHER),
144 C2F(mDefaultColorAspects, transfer)
145 .inRange(C2Color::TRANSFER_UNSPECIFIED,
146 C2Color::TRANSFER_OTHER),
147 C2F(mDefaultColorAspects, matrix)
148 .inRange(C2Color::MATRIX_UNSPECIFIED,
149 C2Color::MATRIX_OTHER)})
150 .withSetter(DefaultColorAspectsSetter)
151 .build());
152
153 // TODO: support more formats?
154 addParameter(DefineParam(mPixelFormat, C2_PARAMKEY_PIXEL_FORMAT)
155 .withConstValue(new C2StreamPixelFormatInfo::output(
156 0u, HAL_PIXEL_FORMAT_YCBCR_420_888))
157 .build());
158 }
159
160 static C2R SizeSetter(bool mayBlock,
161 const C2P<C2StreamPictureSizeInfo::output> &oldMe,
162 C2P<C2StreamPictureSizeInfo::output> &me) {
163 (void)mayBlock;
164 C2R res = C2R::Ok();
165 if (!me.F(me.v.width).supportsAtAll(me.v.width)) {
166 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.width)));
167 me.set().width = oldMe.v.width;
168 }
169 if (!me.F(me.v.height).supportsAtAll(me.v.height)) {
170 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.height)));
171 me.set().height = oldMe.v.height;
172 }
173 return res;
174 }
175
176 static C2R MaxPictureSizeSetter(
177 bool mayBlock, C2P<C2StreamMaxPictureSizeTuning::output> &me,
178 const C2P<C2StreamPictureSizeInfo::output> &size) {
179 (void)mayBlock;
180 // TODO: get max width/height from the size's field helpers vs.
181 // hardcoding
182 me.set().width = c2_min(c2_max(me.v.width, size.v.width), 4096u);
183 me.set().height = c2_min(c2_max(me.v.height, size.v.height), 4096u);
184 return C2R::Ok();
185 }
186
187 static C2R MaxInputSizeSetter(
188 bool mayBlock, C2P<C2StreamMaxBufferSizeInfo::input> &me,
189 const C2P<C2StreamMaxPictureSizeTuning::output> &maxSize) {
190 (void)mayBlock;
191 // assume compression ratio of 2
192 me.set().value =
193 (((maxSize.v.width + 63) / 64) * ((maxSize.v.height + 63) / 64) * 3072);
194 return C2R::Ok();
195 }
196
197 static C2R DefaultColorAspectsSetter(
198 bool mayBlock, C2P<C2StreamColorAspectsTuning::output> &me) {
199 (void)mayBlock;
200 if (me.v.range > C2Color::RANGE_OTHER) {
201 me.set().range = C2Color::RANGE_OTHER;
202 }
203 if (me.v.primaries > C2Color::PRIMARIES_OTHER) {
204 me.set().primaries = C2Color::PRIMARIES_OTHER;
205 }
206 if (me.v.transfer > C2Color::TRANSFER_OTHER) {
207 me.set().transfer = C2Color::TRANSFER_OTHER;
208 }
209 if (me.v.matrix > C2Color::MATRIX_OTHER) {
210 me.set().matrix = C2Color::MATRIX_OTHER;
211 }
212 return C2R::Ok();
213 }
214
215 static C2R ProfileLevelSetter(
216 bool mayBlock, C2P<C2StreamProfileLevelInfo::input> &me,
217 const C2P<C2StreamPictureSizeInfo::output> &size) {
218 (void)mayBlock;
219 (void)size;
220 (void)me; // TODO: validate
221 return C2R::Ok();
222 }
223
224 std::shared_ptr<C2StreamColorAspectsTuning::output>
225 getDefaultColorAspects_l() {
226 return mDefaultColorAspects;
227 }
228
229 static C2R Hdr10PlusInfoInputSetter(bool mayBlock,
230 C2P<C2StreamHdr10PlusInfo::input> &me) {
231 (void)mayBlock;
232 (void)me; // TODO: validate
233 return C2R::Ok();
234 }
235
236 static C2R Hdr10PlusInfoOutputSetter(bool mayBlock,
237 C2P<C2StreamHdr10PlusInfo::output> &me) {
238 (void)mayBlock;
239 (void)me; // TODO: validate
240 return C2R::Ok();
241 }
242
243 private:
244 std::shared_ptr<C2StreamProfileLevelInfo::input> mProfileLevel;
245 std::shared_ptr<C2StreamPictureSizeInfo::output> mSize;
246 std::shared_ptr<C2StreamMaxPictureSizeTuning::output> mMaxSize;
247 std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mMaxInputSize;
248 std::shared_ptr<C2StreamColorInfo::output> mColorInfo;
249 std::shared_ptr<C2StreamPixelFormatInfo::output> mPixelFormat;
250 std::shared_ptr<C2StreamColorAspectsTuning::output> mDefaultColorAspects;
251 std::shared_ptr<C2StreamHdr10PlusInfo::input> mHdr10PlusInfoInput;
252 std::shared_ptr<C2StreamHdr10PlusInfo::output> mHdr10PlusInfoOutput;
253};
254
255C2SoftGav1Dec::C2SoftGav1Dec(const char *name, c2_node_id_t id,
256 const std::shared_ptr<IntfImpl> &intfImpl)
257 : SimpleC2Component(
258 std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
Vignesh Venkatasubramanian87f6ede2019-06-17 16:21:36 -0700259 mIntf(intfImpl),
260 mCodecCtx(nullptr) {
261 gettimeofday(&mTimeStart, nullptr);
262 gettimeofday(&mTimeEnd, nullptr);
263}
Vignesh Venkatasubramanian46e06392019-06-10 15:11:58 -0700264
Vignesh Venkatasubramanian87f6ede2019-06-17 16:21:36 -0700265C2SoftGav1Dec::~C2SoftGav1Dec() { onRelease(); }
266
267c2_status_t C2SoftGav1Dec::onInit() {
268 return initDecoder() ? C2_OK : C2_CORRUPTED;
269}
270
271c2_status_t C2SoftGav1Dec::onStop() {
272 mSignalledError = false;
273 mSignalledOutputEos = false;
Vignesh Venkatasubramanian46e06392019-06-10 15:11:58 -0700274 return C2_OK;
275}
276
Vignesh Venkatasubramanian87f6ede2019-06-17 16:21:36 -0700277void C2SoftGav1Dec::onReset() {
278 (void)onStop();
279 c2_status_t err = onFlush_sm();
280 if (err != C2_OK) {
281 ALOGW("Failed to flush the av1 decoder. Trying to hard reset.");
282 destroyDecoder();
283 if (!initDecoder()) {
284 ALOGE("Hard reset failed.");
285 }
286 }
287}
288
289void C2SoftGav1Dec::onRelease() { destroyDecoder(); }
290
291c2_status_t C2SoftGav1Dec::onFlush_sm() {
292 Libgav1StatusCode status =
293 mCodecCtx->EnqueueFrame(/*data=*/nullptr, /*size=*/0,
294 /*user_private_data=*/0);
295 if (status != kLibgav1StatusOk) {
296 ALOGE("Failed to flush av1 decoder. status: %d.", status);
297 return C2_CORRUPTED;
298 }
299
300 // Dequeue frame (if any) that was enqueued previously.
301 const libgav1::DecoderBuffer *buffer;
302 status = mCodecCtx->DequeueFrame(&buffer);
303 if (status != kLibgav1StatusOk) {
304 ALOGE("Failed to dequeue frame after flushing the av1 decoder. status: %d",
305 status);
306 return C2_CORRUPTED;
307 }
308
309 mSignalledError = false;
310 mSignalledOutputEos = false;
311
312 return C2_OK;
313}
314
315static int GetCPUCoreCount() {
316 int cpuCoreCount = 1;
317#if defined(_SC_NPROCESSORS_ONLN)
318 cpuCoreCount = sysconf(_SC_NPROCESSORS_ONLN);
319#else
320 // _SC_NPROC_ONLN must be defined...
321 cpuCoreCount = sysconf(_SC_NPROC_ONLN);
322#endif
323 CHECK(cpuCoreCount >= 1);
324 ALOGV("Number of CPU cores: %d", cpuCoreCount);
325 return cpuCoreCount;
326}
327
328bool C2SoftGav1Dec::initDecoder() {
329 mSignalledError = false;
330 mSignalledOutputEos = false;
331 mCodecCtx.reset(new libgav1::Decoder());
332
333 if (mCodecCtx == nullptr) {
334 ALOGE("mCodecCtx is null");
335 return false;
336 }
337
338 libgav1::DecoderSettings settings = {};
339 settings.threads = GetCPUCoreCount();
340
341 Libgav1StatusCode status = mCodecCtx->Init(&settings);
342 if (status != kLibgav1StatusOk) {
343 ALOGE("av1 decoder failed to initialize. status: %d.", status);
344 return false;
345 }
346
347 return true;
348}
349
350void C2SoftGav1Dec::destroyDecoder() { mCodecCtx = nullptr; }
351
352void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
353 uint32_t flags = 0;
354 if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
355 flags |= C2FrameData::FLAG_END_OF_STREAM;
356 ALOGV("signalling eos");
357 }
358 work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
359 work->worklets.front()->output.buffers.clear();
360 work->worklets.front()->output.ordinal = work->input.ordinal;
361 work->workletsProcessed = 1u;
362}
363
364void C2SoftGav1Dec::finishWork(uint64_t index,
365 const std::unique_ptr<C2Work> &work,
366 const std::shared_ptr<C2GraphicBlock> &block) {
367 std::shared_ptr<C2Buffer> buffer =
368 createGraphicBuffer(block, C2Rect(mWidth, mHeight));
369 auto fillWork = [buffer, index](const std::unique_ptr<C2Work> &work) {
370 uint32_t flags = 0;
371 if ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) &&
372 (c2_cntr64_t(index) == work->input.ordinal.frameIndex)) {
373 flags |= C2FrameData::FLAG_END_OF_STREAM;
374 ALOGV("signalling eos");
375 }
376 work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
377 work->worklets.front()->output.buffers.clear();
378 work->worklets.front()->output.buffers.push_back(buffer);
379 work->worklets.front()->output.ordinal = work->input.ordinal;
380 work->workletsProcessed = 1u;
381 };
382 if (work && c2_cntr64_t(index) == work->input.ordinal.frameIndex) {
383 fillWork(work);
384 } else {
385 finish(index, fillWork);
386 }
387}
388
389void C2SoftGav1Dec::process(const std::unique_ptr<C2Work> &work,
390 const std::shared_ptr<C2BlockPool> &pool) {
391 work->result = C2_OK;
392 work->workletsProcessed = 0u;
393 work->worklets.front()->output.configUpdate.clear();
394 work->worklets.front()->output.flags = work->input.flags;
395 if (mSignalledError || mSignalledOutputEos) {
396 work->result = C2_BAD_VALUE;
397 return;
398 }
399
400 size_t inOffset = 0u;
401 size_t inSize = 0u;
402 C2ReadView rView = mDummyReadView;
403 if (!work->input.buffers.empty()) {
404 rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
405 inSize = rView.capacity();
406 if (inSize && rView.error()) {
407 ALOGE("read view map failed %d", rView.error());
408 work->result = C2_CORRUPTED;
409 return;
410 }
411 }
412
413 bool codecConfig =
414 ((work->input.flags & C2FrameData::FLAG_CODEC_CONFIG) != 0);
415 bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
416
417 ALOGV("in buffer attr. size %zu timestamp %d frameindex %d, flags %x", inSize,
418 (int)work->input.ordinal.timestamp.peeku(),
419 (int)work->input.ordinal.frameIndex.peeku(), work->input.flags);
420
421 if (codecConfig) {
422 fillEmptyWork(work);
423 return;
424 }
425
426 int64_t frameIndex = work->input.ordinal.frameIndex.peekll();
427 if (inSize) {
428 uint8_t *bitstream = const_cast<uint8_t *>(rView.data() + inOffset);
429 int32_t decodeTime = 0;
430 int32_t delay = 0;
431
432 GETTIME(&mTimeStart, nullptr);
433 TIME_DIFF(mTimeEnd, mTimeStart, delay);
434
435 const Libgav1StatusCode status =
436 mCodecCtx->EnqueueFrame(bitstream, inSize, frameIndex);
437
438 GETTIME(&mTimeEnd, nullptr);
439 TIME_DIFF(mTimeStart, mTimeEnd, decodeTime);
440 ALOGV("decodeTime=%4d delay=%4d\n", decodeTime, delay);
441
442 if (status != kLibgav1StatusOk) {
443 ALOGE("av1 decoder failed to decode frame. status: %d.", status);
444 work->result = C2_CORRUPTED;
445 work->workletsProcessed = 1u;
446 mSignalledError = true;
447 return;
448 }
449
450 } else {
451 const Libgav1StatusCode status =
452 mCodecCtx->EnqueueFrame(/*data=*/nullptr, /*size=*/0,
453 /*user_private_data=*/0);
454 if (status != kLibgav1StatusOk) {
455 ALOGE("Failed to flush av1 decoder. status: %d.", status);
456 work->result = C2_CORRUPTED;
457 work->workletsProcessed = 1u;
458 mSignalledError = true;
459 return;
460 }
461 }
462
463 (void)outputBuffer(pool, work);
464
465 if (eos) {
466 drainInternal(DRAIN_COMPONENT_WITH_EOS, pool, work);
467 mSignalledOutputEos = true;
468 } else if (!inSize) {
469 fillEmptyWork(work);
470 }
471}
472
473static void copyOutputBufferToYV12Frame(uint8_t *dst, const uint8_t *srcY,
474 const uint8_t *srcU,
475 const uint8_t *srcV, size_t srcYStride,
476 size_t srcUStride, size_t srcVStride,
477 uint32_t width, uint32_t height) {
478 const size_t dstYStride = align(width, 16);
479 const size_t dstUVStride = align(dstYStride / 2, 16);
480 uint8_t *const dstStart = dst;
481
482 for (size_t i = 0; i < height; ++i) {
483 memcpy(dst, srcY, width);
484 srcY += srcYStride;
485 dst += dstYStride;
486 }
487
488 dst = dstStart + dstYStride * height;
489 for (size_t i = 0; i < height / 2; ++i) {
490 memcpy(dst, srcV, width / 2);
491 srcV += srcVStride;
492 dst += dstUVStride;
493 }
494
495 dst = dstStart + (dstYStride * height) + (dstUVStride * height / 2);
496 for (size_t i = 0; i < height / 2; ++i) {
497 memcpy(dst, srcU, width / 2);
498 srcU += srcUStride;
499 dst += dstUVStride;
500 }
501}
502
503static void convertYUV420Planar16ToY410(uint32_t *dst, const uint16_t *srcY,
504 const uint16_t *srcU,
505 const uint16_t *srcV, size_t srcYStride,
506 size_t srcUStride, size_t srcVStride,
507 size_t dstStride, size_t width,
508 size_t height) {
509 // Converting two lines at a time, slightly faster
510 for (size_t y = 0; y < height; y += 2) {
511 uint32_t *dstTop = (uint32_t *)dst;
512 uint32_t *dstBot = (uint32_t *)(dst + dstStride);
513 uint16_t *ySrcTop = (uint16_t *)srcY;
514 uint16_t *ySrcBot = (uint16_t *)(srcY + srcYStride);
515 uint16_t *uSrc = (uint16_t *)srcU;
516 uint16_t *vSrc = (uint16_t *)srcV;
517
518 uint32_t u01, v01, y01, y23, y45, y67, uv0, uv1;
519 size_t x = 0;
520 for (; x < width - 3; x += 4) {
521 u01 = *((uint32_t *)uSrc);
522 uSrc += 2;
523 v01 = *((uint32_t *)vSrc);
524 vSrc += 2;
525
526 y01 = *((uint32_t *)ySrcTop);
527 ySrcTop += 2;
528 y23 = *((uint32_t *)ySrcTop);
529 ySrcTop += 2;
530 y45 = *((uint32_t *)ySrcBot);
531 ySrcBot += 2;
532 y67 = *((uint32_t *)ySrcBot);
533 ySrcBot += 2;
534
535 uv0 = (u01 & 0x3FF) | ((v01 & 0x3FF) << 20);
536 uv1 = (u01 >> 16) | ((v01 >> 16) << 20);
537
538 *dstTop++ = 3 << 30 | ((y01 & 0x3FF) << 10) | uv0;
539 *dstTop++ = 3 << 30 | ((y01 >> 16) << 10) | uv0;
540 *dstTop++ = 3 << 30 | ((y23 & 0x3FF) << 10) | uv1;
541 *dstTop++ = 3 << 30 | ((y23 >> 16) << 10) | uv1;
542
543 *dstBot++ = 3 << 30 | ((y45 & 0x3FF) << 10) | uv0;
544 *dstBot++ = 3 << 30 | ((y45 >> 16) << 10) | uv0;
545 *dstBot++ = 3 << 30 | ((y67 & 0x3FF) << 10) | uv1;
546 *dstBot++ = 3 << 30 | ((y67 >> 16) << 10) | uv1;
547 }
548
549 // There should be at most 2 more pixels to process. Note that we don't
550 // need to consider odd case as the buffer is always aligned to even.
551 if (x < width) {
552 u01 = *uSrc;
553 v01 = *vSrc;
554 y01 = *((uint32_t *)ySrcTop);
555 y45 = *((uint32_t *)ySrcBot);
556 uv0 = (u01 & 0x3FF) | ((v01 & 0x3FF) << 20);
557 *dstTop++ = ((y01 & 0x3FF) << 10) | uv0;
558 *dstTop++ = ((y01 >> 16) << 10) | uv0;
559 *dstBot++ = ((y45 & 0x3FF) << 10) | uv0;
560 *dstBot++ = ((y45 >> 16) << 10) | uv0;
561 }
562
563 srcY += srcYStride * 2;
564 srcU += srcUStride;
565 srcV += srcVStride;
566 dst += dstStride * 2;
567 }
568}
569
570static void convertYUV420Planar16ToYUV420Planar(
571 uint8_t *dst, const uint16_t *srcY, const uint16_t *srcU,
572 const uint16_t *srcV, size_t srcYStride, size_t srcUStride,
573 size_t srcVStride, size_t dstStride, size_t width, size_t height) {
574 uint8_t *dstY = (uint8_t *)dst;
575 size_t dstYSize = dstStride * height;
576 size_t dstUVStride = align(dstStride / 2, 16);
577 size_t dstUVSize = dstUVStride * height / 2;
578 uint8_t *dstV = dstY + dstYSize;
579 uint8_t *dstU = dstV + dstUVSize;
580
581 for (size_t y = 0; y < height; ++y) {
582 for (size_t x = 0; x < width; ++x) {
583 dstY[x] = (uint8_t)(srcY[x] >> 2);
584 }
585
586 srcY += srcYStride;
587 dstY += dstStride;
588 }
589
590 for (size_t y = 0; y < (height + 1) / 2; ++y) {
591 for (size_t x = 0; x < (width + 1) / 2; ++x) {
592 dstU[x] = (uint8_t)(srcU[x] >> 2);
593 dstV[x] = (uint8_t)(srcV[x] >> 2);
594 }
595
596 srcU += srcUStride;
597 srcV += srcVStride;
598 dstU += dstUVStride;
599 dstV += dstUVStride;
600 }
601}
602
603bool C2SoftGav1Dec::outputBuffer(const std::shared_ptr<C2BlockPool> &pool,
604 const std::unique_ptr<C2Work> &work) {
605 if (!(work && pool)) return false;
606
607 const libgav1::DecoderBuffer *buffer;
608 const Libgav1StatusCode status = mCodecCtx->DequeueFrame(&buffer);
609
610 if (status != kLibgav1StatusOk) {
611 ALOGE("av1 decoder DequeueFrame failed. status: %d.", status);
612 return false;
613 }
614
615 // |buffer| can be NULL if status was equal to kLibgav1StatusOk. This is not
616 // an error. This could mean one of two things:
617 // - The EnqueueFrame() call was either a flush (called with nullptr).
618 // - The enqueued frame did not have any displayable frames.
619 if (!buffer) {
620 return false;
621 }
622
623 const int width = buffer->displayed_width[0];
624 const int height = buffer->displayed_height[0];
625 if (width != mWidth || height != mHeight) {
626 mWidth = width;
627 mHeight = height;
628
629 C2StreamPictureSizeInfo::output size(0u, mWidth, mHeight);
630 std::vector<std::unique_ptr<C2SettingResult>> failures;
631 c2_status_t err = mIntf->config({&size}, C2_MAY_BLOCK, &failures);
632 if (err == C2_OK) {
633 work->worklets.front()->output.configUpdate.push_back(
634 C2Param::Copy(size));
635 } else {
636 ALOGE("Config update size failed");
637 mSignalledError = true;
638 work->result = C2_CORRUPTED;
639 work->workletsProcessed = 1u;
640 return false;
641 }
642 }
643
644 // TODO(vigneshv): Add support for monochrome videos since AV1 supports it.
645 CHECK(buffer->image_format == libgav1::kImageFormatYuv420);
646
647 std::shared_ptr<C2GraphicBlock> block;
648 uint32_t format = HAL_PIXEL_FORMAT_YV12;
649 if (buffer->bitdepth == 10) {
650 IntfImpl::Lock lock = mIntf->lock();
651 std::shared_ptr<C2StreamColorAspectsTuning::output> defaultColorAspects =
652 mIntf->getDefaultColorAspects_l();
653
654 if (defaultColorAspects->primaries == C2Color::PRIMARIES_BT2020 &&
655 defaultColorAspects->matrix == C2Color::MATRIX_BT2020 &&
656 defaultColorAspects->transfer == C2Color::TRANSFER_ST2084) {
657 format = HAL_PIXEL_FORMAT_RGBA_1010102;
658 }
659 }
660 C2MemoryUsage usage = {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
661
662 c2_status_t err = pool->fetchGraphicBlock(align(mWidth, 16), mHeight, format,
663 usage, &block);
664
665 if (err != C2_OK) {
666 ALOGE("fetchGraphicBlock for Output failed with status %d", err);
667 work->result = err;
668 return false;
669 }
670
671 C2GraphicView wView = block->map().get();
672
673 if (wView.error()) {
674 ALOGE("graphic view map failed %d", wView.error());
675 work->result = C2_CORRUPTED;
676 return false;
677 }
678
679 ALOGV("provided (%dx%d) required (%dx%d), out frameindex %d", block->width(),
680 block->height(), mWidth, mHeight, (int)buffer->user_private_data);
681
682 uint8_t *dst = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
683 size_t srcYStride = buffer->stride[0];
684 size_t srcUStride = buffer->stride[1];
685 size_t srcVStride = buffer->stride[2];
686
687 if (buffer->bitdepth == 10) {
688 const uint16_t *srcY = (const uint16_t *)buffer->plane[0];
689 const uint16_t *srcU = (const uint16_t *)buffer->plane[1];
690 const uint16_t *srcV = (const uint16_t *)buffer->plane[2];
691
692 if (format == HAL_PIXEL_FORMAT_RGBA_1010102) {
693 convertYUV420Planar16ToY410(
694 (uint32_t *)dst, srcY, srcU, srcV, srcYStride / 2, srcUStride / 2,
695 srcVStride / 2, align(mWidth, 16), mWidth, mHeight);
696 } else {
697 convertYUV420Planar16ToYUV420Planar(dst, srcY, srcU, srcV, srcYStride / 2,
698 srcUStride / 2, srcVStride / 2,
699 align(mWidth, 16), mWidth, mHeight);
700 }
701 } else {
702 const uint8_t *srcY = (const uint8_t *)buffer->plane[0];
703 const uint8_t *srcU = (const uint8_t *)buffer->plane[1];
704 const uint8_t *srcV = (const uint8_t *)buffer->plane[2];
705 copyOutputBufferToYV12Frame(dst, srcY, srcU, srcV, srcYStride, srcUStride,
706 srcVStride, mWidth, mHeight);
707 }
708 finishWork(buffer->user_private_data, work, std::move(block));
709 block = nullptr;
710 return true;
711}
712
713c2_status_t C2SoftGav1Dec::drainInternal(
714 uint32_t drainMode, const std::shared_ptr<C2BlockPool> &pool,
715 const std::unique_ptr<C2Work> &work) {
716 if (drainMode == NO_DRAIN) {
717 ALOGW("drain with NO_DRAIN: no-op");
718 return C2_OK;
719 }
720 if (drainMode == DRAIN_CHAIN) {
721 ALOGW("DRAIN_CHAIN not supported");
722 return C2_OMITTED;
723 }
724
725 Libgav1StatusCode status =
726 mCodecCtx->EnqueueFrame(/*data=*/nullptr, /*size=*/0,
727 /*user_private_data=*/0);
728 if (status != kLibgav1StatusOk) {
729 ALOGE("Failed to flush av1 decoder. status: %d.", status);
730 return C2_CORRUPTED;
731 }
732
733 while (outputBuffer(pool, work)) {
734 }
735
736 if (drainMode == DRAIN_COMPONENT_WITH_EOS && work &&
737 work->workletsProcessed == 0u) {
738 fillEmptyWork(work);
739 }
740
741 return C2_OK;
742}
743
744c2_status_t C2SoftGav1Dec::drain(uint32_t drainMode,
745 const std::shared_ptr<C2BlockPool> &pool) {
746 return drainInternal(drainMode, pool, nullptr);
747}
748
Vignesh Venkatasubramanian46e06392019-06-10 15:11:58 -0700749class C2SoftGav1Factory : public C2ComponentFactory {
750 public:
751 C2SoftGav1Factory()
752 : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
753 GetCodec2PlatformComponentStore()->getParamReflector())) {}
754
755 virtual c2_status_t createComponent(
756 c2_node_id_t id, std::shared_ptr<C2Component> *const component,
757 std::function<void(C2Component *)> deleter) override {
758 *component = std::shared_ptr<C2Component>(
759 new C2SoftGav1Dec(COMPONENT_NAME, id,
760 std::make_shared<C2SoftGav1Dec::IntfImpl>(mHelper)),
761 deleter);
762 return C2_OK;
763 }
764
765 virtual c2_status_t createInterface(
766 c2_node_id_t id, std::shared_ptr<C2ComponentInterface> *const interface,
767 std::function<void(C2ComponentInterface *)> deleter) override {
768 *interface = std::shared_ptr<C2ComponentInterface>(
769 new SimpleInterface<C2SoftGav1Dec::IntfImpl>(
770 COMPONENT_NAME, id,
771 std::make_shared<C2SoftGav1Dec::IntfImpl>(mHelper)),
772 deleter);
773 return C2_OK;
774 }
775
776 virtual ~C2SoftGav1Factory() override = default;
777
778 private:
779 std::shared_ptr<C2ReflectorHelper> mHelper;
780};
781
782} // namespace android
783
784extern "C" ::C2ComponentFactory *CreateCodec2Factory() {
785 ALOGV("in %s", __func__);
786 return new ::android::C2SoftGav1Factory();
787}
788
789extern "C" void DestroyCodec2Factory(::C2ComponentFactory *factory) {
790 ALOGV("in %s", __func__);
791 delete factory;
792}