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