blob: d969f2e132d2034b1fa44655793b486acb421517 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "C2SoftVpxDec"
19#include <log/log.h>
20
Wonsik Kimf61206f2019-05-18 16:52:46 -070021#include <algorithm>
Pawin Vongmasa36653902018-11-15 00:10:25 -080022#include <media/stagefright/foundation/AUtils.h>
23#include <media/stagefright/foundation/MediaDefs.h>
24
25#include <C2Debug.h>
26#include <C2PlatformSupport.h>
Harish Mahendrakarf0fa7a22021-12-10 20:36:32 -080027#include <Codec2BufferUtils.h>
Harish Mahendrakarf5dec502022-04-13 15:53:55 -070028#include <Codec2CommonUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <SimpleC2Interface.h>
30
31#include "C2SoftVpxDec.h"
32
33namespace android {
Harish Mahendrakare55c4712019-07-26 12:32:13 -070034constexpr size_t kMinInputBufferSize = 2 * 1024 * 1024;
Pawin Vongmasa36653902018-11-15 00:10:25 -080035#ifdef VP9
36constexpr char COMPONENT_NAME[] = "c2.android.vp9.decoder";
37#else
38constexpr char COMPONENT_NAME[] = "c2.android.vp8.decoder";
39#endif
40
41class C2SoftVpxDec::IntfImpl : public SimpleInterface<void>::BaseParams {
42public:
43 explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
44 : SimpleInterface<void>::BaseParams(
45 helper,
46 COMPONENT_NAME,
47 C2Component::KIND_DECODER,
48 C2Component::DOMAIN_VIDEO,
49#ifdef VP9
50 MEDIA_MIMETYPE_VIDEO_VP9
51#else
52 MEDIA_MIMETYPE_VIDEO_VP8
53#endif
54 ) {
55 noPrivateBuffers(); // TODO: account for our buffers here
56 noInputReferences();
57 noOutputReferences();
58 noInputLatency();
59 noTimeStretch();
60
61 // TODO: output latency and reordering
62
63 addParameter(
64 DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
65 .withConstValue(new C2ComponentAttributesSetting(C2Component::ATTRIB_IS_TEMPORAL))
66 .build());
67
68 addParameter(
69 DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
70 .withDefault(new C2StreamPictureSizeInfo::output(0u, 320, 240))
71 .withFields({
72 C2F(mSize, width).inRange(2, 2048, 2),
73 C2F(mSize, height).inRange(2, 2048, 2),
74 })
75 .withSetter(SizeSetter)
76 .build());
77
78#ifdef VP9
79 // TODO: Add C2Config::PROFILE_VP9_2HDR ??
80 addParameter(
81 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
82 .withDefault(new C2StreamProfileLevelInfo::input(0u,
83 C2Config::PROFILE_VP9_0, C2Config::LEVEL_VP9_5))
84 .withFields({
85 C2F(mProfileLevel, profile).oneOf({
86 C2Config::PROFILE_VP9_0,
87 C2Config::PROFILE_VP9_2}),
88 C2F(mProfileLevel, level).oneOf({
89 C2Config::LEVEL_VP9_1,
90 C2Config::LEVEL_VP9_1_1,
91 C2Config::LEVEL_VP9_2,
92 C2Config::LEVEL_VP9_2_1,
93 C2Config::LEVEL_VP9_3,
94 C2Config::LEVEL_VP9_3_1,
95 C2Config::LEVEL_VP9_4,
96 C2Config::LEVEL_VP9_4_1,
97 C2Config::LEVEL_VP9_5,
98 })
99 })
100 .withSetter(ProfileLevelSetter, mSize)
101 .build());
102
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800103 mHdr10PlusInfoInput = C2StreamHdr10PlusInfo::input::AllocShared(0);
104 addParameter(
105 DefineParam(mHdr10PlusInfoInput, C2_PARAMKEY_INPUT_HDR10_PLUS_INFO)
106 .withDefault(mHdr10PlusInfoInput)
107 .withFields({
108 C2F(mHdr10PlusInfoInput, m.value).any(),
109 })
110 .withSetter(Hdr10PlusInfoInputSetter)
111 .build());
112
113 mHdr10PlusInfoOutput = C2StreamHdr10PlusInfo::output::AllocShared(0);
114 addParameter(
115 DefineParam(mHdr10PlusInfoOutput, C2_PARAMKEY_OUTPUT_HDR10_PLUS_INFO)
116 .withDefault(mHdr10PlusInfoOutput)
117 .withFields({
118 C2F(mHdr10PlusInfoOutput, m.value).any(),
119 })
120 .withSetter(Hdr10PlusInfoOutputSetter)
121 .build());
122
Pawin Vongmasa36653902018-11-15 00:10:25 -0800123#if 0
124 // sample BT.2020 static info
125 mHdrStaticInfo = std::make_shared<C2StreamHdrStaticInfo::output>();
126 mHdrStaticInfo->mastering = {
127 .red = { .x = 0.708, .y = 0.292 },
128 .green = { .x = 0.170, .y = 0.797 },
129 .blue = { .x = 0.131, .y = 0.046 },
130 .white = { .x = 0.3127, .y = 0.3290 },
131 .maxLuminance = 1000,
132 .minLuminance = 0.1,
133 };
134 mHdrStaticInfo->maxCll = 1000;
135 mHdrStaticInfo->maxFall = 120;
136
137 mHdrStaticInfo->maxLuminance = 0; // disable static info
138
139 helper->addStructDescriptors<C2MasteringDisplayColorVolumeStruct, C2ColorXyStruct>();
140 addParameter(
141 DefineParam(mHdrStaticInfo, C2_PARAMKEY_HDR_STATIC_INFO)
142 .withDefault(mHdrStaticInfo)
143 .withFields({
144 C2F(mHdrStaticInfo, mastering.red.x).inRange(0, 1),
145 // TODO
146 })
147 .withSetter(HdrStaticInfoSetter)
148 .build());
149#endif
150#else
151 addParameter(
152 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
Harish Mahendrakar22cb9d02021-08-26 16:35:48 -0700153 .withDefault(new C2StreamProfileLevelInfo::input(0u,
154 C2Config::PROFILE_VP8_0, C2Config::LEVEL_UNUSED))
155 .withFields({
156 C2F(mProfileLevel, profile).equalTo(
157 PROFILE_VP8_0
158 ),
159 C2F(mProfileLevel, level).equalTo(
160 LEVEL_UNUSED),
161 })
162 .withSetter(ProfileLevelSetter, mSize)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800163 .build());
164#endif
165
166 addParameter(
167 DefineParam(mMaxSize, C2_PARAMKEY_MAX_PICTURE_SIZE)
168 .withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 320, 240))
169 .withFields({
170 C2F(mSize, width).inRange(2, 2048, 2),
171 C2F(mSize, height).inRange(2, 2048, 2),
172 })
173 .withSetter(MaxPictureSizeSetter, mSize)
174 .build());
175
176 addParameter(
177 DefineParam(mMaxInputSize, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE)
Harish Mahendrakare55c4712019-07-26 12:32:13 -0700178 .withDefault(new C2StreamMaxBufferSizeInfo::input(0u, kMinInputBufferSize))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800179 .withFields({
180 C2F(mMaxInputSize, value).any(),
181 })
182 .calculatedAs(MaxInputSizeSetter, mMaxSize)
183 .build());
184
185 C2ChromaOffsetStruct locations[1] = { C2ChromaOffsetStruct::ITU_YUV_420_0() };
186 std::shared_ptr<C2StreamColorInfo::output> defaultColorInfo =
187 C2StreamColorInfo::output::AllocShared(
188 1u, 0u, 8u /* bitDepth */, C2Color::YUV_420);
189 memcpy(defaultColorInfo->m.locations, locations, sizeof(locations));
190
191 defaultColorInfo =
192 C2StreamColorInfo::output::AllocShared(
193 { C2ChromaOffsetStruct::ITU_YUV_420_0() },
194 0u, 8u /* bitDepth */, C2Color::YUV_420);
195 helper->addStructDescriptors<C2ChromaOffsetStruct>();
196
197 addParameter(
198 DefineParam(mColorInfo, C2_PARAMKEY_CODED_COLOR_INFO)
199 .withConstValue(defaultColorInfo)
200 .build());
201
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700202 addParameter(
203 DefineParam(mDefaultColorAspects, C2_PARAMKEY_DEFAULT_COLOR_ASPECTS)
204 .withDefault(new C2StreamColorAspectsTuning::output(
205 0u, C2Color::RANGE_UNSPECIFIED, C2Color::PRIMARIES_UNSPECIFIED,
206 C2Color::TRANSFER_UNSPECIFIED, C2Color::MATRIX_UNSPECIFIED))
207 .withFields({
208 C2F(mDefaultColorAspects, range).inRange(
209 C2Color::RANGE_UNSPECIFIED, C2Color::RANGE_OTHER),
210 C2F(mDefaultColorAspects, primaries).inRange(
211 C2Color::PRIMARIES_UNSPECIFIED, C2Color::PRIMARIES_OTHER),
212 C2F(mDefaultColorAspects, transfer).inRange(
213 C2Color::TRANSFER_UNSPECIFIED, C2Color::TRANSFER_OTHER),
214 C2F(mDefaultColorAspects, matrix).inRange(
215 C2Color::MATRIX_UNSPECIFIED, C2Color::MATRIX_OTHER)
216 })
217 .withSetter(DefaultColorAspectsSetter)
218 .build());
219
Pawin Vongmasa36653902018-11-15 00:10:25 -0800220 // TODO: support more formats?
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700221 std::vector<uint32_t> pixelFormats = {HAL_PIXEL_FORMAT_YCBCR_420_888};
222#ifdef VP9
Harish Mahendrakarf5dec502022-04-13 15:53:55 -0700223 if (isHalPixelFormatSupported((AHardwareBuffer_Format)HAL_PIXEL_FORMAT_YCBCR_P010)) {
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700224 pixelFormats.push_back(HAL_PIXEL_FORMAT_YCBCR_P010);
225 }
226#endif
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 addParameter(
228 DefineParam(mPixelFormat, C2_PARAMKEY_PIXEL_FORMAT)
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700229 .withDefault(new C2StreamPixelFormatInfo::output(
230 0u, HAL_PIXEL_FORMAT_YCBCR_420_888))
231 .withFields({C2F(mPixelFormat, value).oneOf(pixelFormats)})
232 .withSetter((Setter<decltype(*mPixelFormat)>::StrictValueWithNoDeps))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 .build());
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700234
Pawin Vongmasa36653902018-11-15 00:10:25 -0800235 }
236
237 static C2R SizeSetter(bool mayBlock, const C2P<C2StreamPictureSizeInfo::output> &oldMe,
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800238 C2P<C2StreamPictureSizeInfo::output> &me) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800239 (void)mayBlock;
240 C2R res = C2R::Ok();
241 if (!me.F(me.v.width).supportsAtAll(me.v.width)) {
242 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.width)));
243 me.set().width = oldMe.v.width;
244 }
245 if (!me.F(me.v.height).supportsAtAll(me.v.height)) {
246 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.height)));
247 me.set().height = oldMe.v.height;
248 }
249 return res;
250 }
251
252 static C2R MaxPictureSizeSetter(bool mayBlock, C2P<C2StreamMaxPictureSizeTuning::output> &me,
253 const C2P<C2StreamPictureSizeInfo::output> &size) {
254 (void)mayBlock;
255 // TODO: get max width/height from the size's field helpers vs. hardcoding
256 me.set().width = c2_min(c2_max(me.v.width, size.v.width), 2048u);
257 me.set().height = c2_min(c2_max(me.v.height, size.v.height), 2048u);
258 return C2R::Ok();
259 }
260
261 static C2R MaxInputSizeSetter(bool mayBlock, C2P<C2StreamMaxBufferSizeInfo::input> &me,
262 const C2P<C2StreamMaxPictureSizeTuning::output> &maxSize) {
263 (void)mayBlock;
264 // assume compression ratio of 2
Harish Mahendrakare55c4712019-07-26 12:32:13 -0700265 me.set().value = c2_max((((maxSize.v.width + 63) / 64)
266 * ((maxSize.v.height + 63) / 64) * 3072), kMinInputBufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800267 return C2R::Ok();
268 }
269
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700270 static C2R DefaultColorAspectsSetter(bool mayBlock, C2P<C2StreamColorAspectsTuning::output> &me) {
271 (void)mayBlock;
272 if (me.v.range > C2Color::RANGE_OTHER) {
273 me.set().range = C2Color::RANGE_OTHER;
274 }
275 if (me.v.primaries > C2Color::PRIMARIES_OTHER) {
276 me.set().primaries = C2Color::PRIMARIES_OTHER;
277 }
278 if (me.v.transfer > C2Color::TRANSFER_OTHER) {
279 me.set().transfer = C2Color::TRANSFER_OTHER;
280 }
281 if (me.v.matrix > C2Color::MATRIX_OTHER) {
282 me.set().matrix = C2Color::MATRIX_OTHER;
283 }
284 return C2R::Ok();
285 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800286
287 static C2R ProfileLevelSetter(bool mayBlock, C2P<C2StreamProfileLevelInfo::input> &me,
288 const C2P<C2StreamPictureSizeInfo::output> &size) {
289 (void)mayBlock;
290 (void)size;
291 (void)me; // TODO: validate
292 return C2R::Ok();
293 }
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700294 std::shared_ptr<C2StreamColorAspectsTuning::output> getDefaultColorAspects_l() {
295 return mDefaultColorAspects;
296 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800297
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800298 static C2R Hdr10PlusInfoInputSetter(bool mayBlock, C2P<C2StreamHdr10PlusInfo::input> &me) {
299 (void)mayBlock;
300 (void)me; // TODO: validate
301 return C2R::Ok();
302 }
303
304 static C2R Hdr10PlusInfoOutputSetter(bool mayBlock, C2P<C2StreamHdr10PlusInfo::output> &me) {
305 (void)mayBlock;
306 (void)me; // TODO: validate
307 return C2R::Ok();
308 }
309
Pawin Vongmasa36653902018-11-15 00:10:25 -0800310private:
311 std::shared_ptr<C2StreamProfileLevelInfo::input> mProfileLevel;
312 std::shared_ptr<C2StreamPictureSizeInfo::output> mSize;
313 std::shared_ptr<C2StreamMaxPictureSizeTuning::output> mMaxSize;
314 std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mMaxInputSize;
315 std::shared_ptr<C2StreamColorInfo::output> mColorInfo;
316 std::shared_ptr<C2StreamPixelFormatInfo::output> mPixelFormat;
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700317 std::shared_ptr<C2StreamColorAspectsTuning::output> mDefaultColorAspects;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800318#ifdef VP9
319#if 0
320 std::shared_ptr<C2StreamHdrStaticInfo::output> mHdrStaticInfo;
321#endif
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800322 std::shared_ptr<C2StreamHdr10PlusInfo::input> mHdr10PlusInfoInput;
323 std::shared_ptr<C2StreamHdr10PlusInfo::output> mHdr10PlusInfoOutput;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800324#endif
325};
326
Wonsik Kimf61206f2019-05-18 16:52:46 -0700327C2SoftVpxDec::ConverterThread::ConverterThread(
328 const std::shared_ptr<Mutexed<ConversionQueue>> &queue)
329 : Thread(false), mQueue(queue) {}
330
331bool C2SoftVpxDec::ConverterThread::threadLoop() {
332 Mutexed<ConversionQueue>::Locked queue(*mQueue);
333 if (queue->entries.empty()) {
334 queue.waitForCondition(queue->cond);
335 if (queue->entries.empty()) {
336 return true;
337 }
338 }
339 std::function<void()> convert = queue->entries.front();
340 queue->entries.pop_front();
341 if (!queue->entries.empty()) {
342 queue->cond.signal();
343 }
344 queue.unlock();
345
346 convert();
347
348 queue.lock();
349 if (--queue->numPending == 0u) {
350 queue->cond.broadcast();
351 }
352 return true;
353}
354
Pawin Vongmasa36653902018-11-15 00:10:25 -0800355C2SoftVpxDec::C2SoftVpxDec(
356 const char *name,
357 c2_node_id_t id,
358 const std::shared_ptr<IntfImpl> &intfImpl)
359 : SimpleC2Component(std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
360 mIntf(intfImpl),
Wonsik Kimf61206f2019-05-18 16:52:46 -0700361 mCodecCtx(nullptr),
362 mCoreCount(1),
363 mQueue(new Mutexed<ConversionQueue>) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800364}
365
366C2SoftVpxDec::~C2SoftVpxDec() {
367 onRelease();
368}
369
370c2_status_t C2SoftVpxDec::onInit() {
371 status_t err = initDecoder();
372 return err == OK ? C2_OK : C2_CORRUPTED;
373}
374
375c2_status_t C2SoftVpxDec::onStop() {
376 mSignalledError = false;
377 mSignalledOutputEos = false;
378
379 return C2_OK;
380}
381
382void C2SoftVpxDec::onReset() {
383 (void)onStop();
384 c2_status_t err = onFlush_sm();
385 if (err != C2_OK)
386 {
387 ALOGW("Failed to flush decoder. Try to hard reset decoder");
388 destroyDecoder();
389 (void)initDecoder();
390 }
391}
392
393void C2SoftVpxDec::onRelease() {
394 destroyDecoder();
395}
396
397c2_status_t C2SoftVpxDec::onFlush_sm() {
398 if (mFrameParallelMode) {
399 // Flush decoder by passing nullptr data ptr and 0 size.
400 // Ideally, this should never fail.
401 if (vpx_codec_decode(mCodecCtx, nullptr, 0, nullptr, 0)) {
402 ALOGE("Failed to flush on2 decoder.");
403 return C2_CORRUPTED;
404 }
405 }
406
407 // Drop all the decoded frames in decoder.
408 vpx_codec_iter_t iter = nullptr;
409 while (vpx_codec_get_frame(mCodecCtx, &iter)) {
410 }
411
412 mSignalledError = false;
413 mSignalledOutputEos = false;
414 return C2_OK;
415}
416
417static int GetCPUCoreCount() {
418 int cpuCoreCount = 1;
419#if defined(_SC_NPROCESSORS_ONLN)
420 cpuCoreCount = sysconf(_SC_NPROCESSORS_ONLN);
421#else
422 // _SC_NPROC_ONLN must be defined...
423 cpuCoreCount = sysconf(_SC_NPROC_ONLN);
424#endif
425 CHECK(cpuCoreCount >= 1);
426 ALOGV("Number of CPU cores: %d", cpuCoreCount);
427 return cpuCoreCount;
428}
429
430status_t C2SoftVpxDec::initDecoder() {
431#ifdef VP9
432 mMode = MODE_VP9;
433#else
434 mMode = MODE_VP8;
435#endif
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700436 mHalPixelFormat = HAL_PIXEL_FORMAT_YV12;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800437 mWidth = 320;
438 mHeight = 240;
439 mFrameParallelMode = false;
440 mSignalledOutputEos = false;
441 mSignalledError = false;
442
443 if (!mCodecCtx) {
444 mCodecCtx = new vpx_codec_ctx_t;
445 }
446 if (!mCodecCtx) {
447 ALOGE("mCodecCtx is null");
448 return NO_MEMORY;
449 }
450
451 vpx_codec_dec_cfg_t cfg;
452 memset(&cfg, 0, sizeof(vpx_codec_dec_cfg_t));
Wonsik Kimf61206f2019-05-18 16:52:46 -0700453 cfg.threads = mCoreCount = GetCPUCoreCount();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800454
455 vpx_codec_flags_t flags;
456 memset(&flags, 0, sizeof(vpx_codec_flags_t));
457 if (mFrameParallelMode) flags |= VPX_CODEC_USE_FRAME_THREADING;
458
459 vpx_codec_err_t vpx_err;
460 if ((vpx_err = vpx_codec_dec_init(
461 mCodecCtx, mMode == MODE_VP8 ? &vpx_codec_vp8_dx_algo : &vpx_codec_vp9_dx_algo,
462 &cfg, flags))) {
463 ALOGE("on2 decoder failed to initialize. (%d)", vpx_err);
464 return UNKNOWN_ERROR;
465 }
466
Wonsik Kimf61206f2019-05-18 16:52:46 -0700467 if (mMode == MODE_VP9) {
468 using namespace std::string_literals;
469 for (int i = 0; i < mCoreCount; ++i) {
470 sp<ConverterThread> thread(new ConverterThread(mQueue));
471 mConverterThreads.push_back(thread);
472 if (thread->run(("vp9conv #"s + std::to_string(i)).c_str(),
473 ANDROID_PRIORITY_AUDIO) != OK) {
474 return UNKNOWN_ERROR;
475 }
476 }
477 }
478
Pawin Vongmasa36653902018-11-15 00:10:25 -0800479 return OK;
480}
481
482status_t C2SoftVpxDec::destroyDecoder() {
483 if (mCodecCtx) {
484 vpx_codec_destroy(mCodecCtx);
485 delete mCodecCtx;
486 mCodecCtx = nullptr;
487 }
Wonsik Kimf61206f2019-05-18 16:52:46 -0700488 bool running = true;
489 for (const sp<ConverterThread> &thread : mConverterThreads) {
490 thread->requestExit();
491 }
492 while (running) {
493 mQueue->lock()->cond.broadcast();
494 running = false;
495 for (const sp<ConverterThread> &thread : mConverterThreads) {
496 if (thread->isRunning()) {
497 running = true;
498 break;
499 }
500 }
501 }
502 mConverterThreads.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800503
504 return OK;
505}
506
507void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
508 uint32_t flags = 0;
509 if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
510 flags |= C2FrameData::FLAG_END_OF_STREAM;
511 ALOGV("signalling eos");
512 }
513 work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
514 work->worklets.front()->output.buffers.clear();
515 work->worklets.front()->output.ordinal = work->input.ordinal;
516 work->workletsProcessed = 1u;
517}
518
519void C2SoftVpxDec::finishWork(uint64_t index, const std::unique_ptr<C2Work> &work,
520 const std::shared_ptr<C2GraphicBlock> &block) {
521 std::shared_ptr<C2Buffer> buffer = createGraphicBuffer(block,
522 C2Rect(mWidth, mHeight));
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800523 auto fillWork = [buffer, index, intf = this->mIntf](
524 const std::unique_ptr<C2Work> &work) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800525 uint32_t flags = 0;
526 if ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) &&
527 (c2_cntr64_t(index) == work->input.ordinal.frameIndex)) {
528 flags |= C2FrameData::FLAG_END_OF_STREAM;
529 ALOGV("signalling eos");
530 }
531 work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
532 work->worklets.front()->output.buffers.clear();
533 work->worklets.front()->output.buffers.push_back(buffer);
534 work->worklets.front()->output.ordinal = work->input.ordinal;
535 work->workletsProcessed = 1u;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800536
537 for (const std::unique_ptr<C2Param> &param: work->input.configUpdate) {
538 if (param) {
539 C2StreamHdr10PlusInfo::input *hdr10PlusInfo =
540 C2StreamHdr10PlusInfo::input::From(param.get());
541
542 if (hdr10PlusInfo != nullptr) {
543 std::vector<std::unique_ptr<C2SettingResult>> failures;
544 std::unique_ptr<C2Param> outParam = C2Param::CopyAsStream(
545 *param.get(), true /*output*/, param->stream());
546 c2_status_t err = intf->config(
547 { outParam.get() }, C2_MAY_BLOCK, &failures);
548 if (err == C2_OK) {
549 work->worklets.front()->output.configUpdate.push_back(
550 C2Param::Copy(*outParam.get()));
551 } else {
552 ALOGE("finishWork: Config update size failed");
553 }
554 break;
555 }
556 }
557 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800558 };
559 if (work && c2_cntr64_t(index) == work->input.ordinal.frameIndex) {
560 fillWork(work);
561 } else {
562 finish(index, fillWork);
563 }
564}
565
566void C2SoftVpxDec::process(
567 const std::unique_ptr<C2Work> &work,
568 const std::shared_ptr<C2BlockPool> &pool) {
569 // Initialize output work
570 work->result = C2_OK;
571 work->workletsProcessed = 0u;
572 work->worklets.front()->output.configUpdate.clear();
573 work->worklets.front()->output.flags = work->input.flags;
574
575 if (mSignalledError || mSignalledOutputEos) {
576 work->result = C2_BAD_VALUE;
577 return;
578 }
579
580 size_t inOffset = 0u;
581 size_t inSize = 0u;
582 C2ReadView rView = mDummyReadView;
583 if (!work->input.buffers.empty()) {
584 rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
585 inSize = rView.capacity();
586 if (inSize && rView.error()) {
587 ALOGE("read view map failed %d", rView.error());
588 work->result = C2_CORRUPTED;
589 return;
590 }
591 }
592
593 bool codecConfig = ((work->input.flags & C2FrameData::FLAG_CODEC_CONFIG) !=0);
594 bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
595
596 ALOGV("in buffer attr. size %zu timestamp %d frameindex %d, flags %x",
597 inSize, (int)work->input.ordinal.timestamp.peeku(),
598 (int)work->input.ordinal.frameIndex.peeku(), work->input.flags);
599
600 // Software VP9 Decoder does not need the Codec Specific Data (CSD)
601 // (specified in http://www.webmproject.org/vp9/profiles/). Ignore it if
602 // it was passed.
603 if (codecConfig) {
604 // Ignore CSD buffer for VP9.
605 if (mMode == MODE_VP9) {
606 fillEmptyWork(work);
607 return;
608 } else {
609 // Tolerate the CSD buffer for VP8. This is a workaround
610 // for b/28689536. continue
611 ALOGW("WARNING: Got CSD buffer for VP8. Continue");
612 }
613 }
614
Pawin Vongmasa36653902018-11-15 00:10:25 -0800615 if (inSize) {
616 uint8_t *bitstream = const_cast<uint8_t *>(rView.data() + inOffset);
617 vpx_codec_err_t err = vpx_codec_decode(
Wonsik Kim377eeab2019-11-03 19:05:59 -0800618 mCodecCtx, bitstream, inSize, &work->input.ordinal.frameIndex, 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800619 if (err != VPX_CODEC_OK) {
620 ALOGE("on2 decoder failed to decode frame. err: %d", err);
621 mSignalledError = true;
622 work->workletsProcessed = 1u;
623 work->result = C2_CORRUPTED;
624 return;
625 }
626 }
627
Wonsik Kim377eeab2019-11-03 19:05:59 -0800628 status_t err = outputBuffer(pool, work);
629 if (err == NOT_ENOUGH_DATA) {
630 if (inSize > 0) {
631 ALOGV("Maybe non-display frame at %lld.",
632 work->input.ordinal.frameIndex.peekll());
633 // send the work back with empty buffer.
634 inSize = 0;
635 }
636 } else if (err != OK) {
637 ALOGD("Error while getting the output frame out");
638 // work->result would be already filled; do fillEmptyWork() below to
639 // send the work back.
640 inSize = 0;
641 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800642
643 if (eos) {
644 drainInternal(DRAIN_COMPONENT_WITH_EOS, pool, work);
645 mSignalledOutputEos = true;
646 } else if (!inSize) {
647 fillEmptyWork(work);
648 }
649}
650
Wonsik Kim377eeab2019-11-03 19:05:59 -0800651status_t C2SoftVpxDec::outputBuffer(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800652 const std::shared_ptr<C2BlockPool> &pool,
653 const std::unique_ptr<C2Work> &work)
654{
Wonsik Kim377eeab2019-11-03 19:05:59 -0800655 if (!(work && pool)) return BAD_VALUE;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800656
657 vpx_codec_iter_t iter = nullptr;
658 vpx_image_t *img = vpx_codec_get_frame(mCodecCtx, &iter);
659
Wonsik Kim377eeab2019-11-03 19:05:59 -0800660 if (!img) return NOT_ENOUGH_DATA;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800661
662 if (img->d_w != mWidth || img->d_h != mHeight) {
663 mWidth = img->d_w;
664 mHeight = img->d_h;
665
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800666 C2StreamPictureSizeInfo::output size(0u, mWidth, mHeight);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800667 std::vector<std::unique_ptr<C2SettingResult>> failures;
668 c2_status_t err = mIntf->config({&size}, C2_MAY_BLOCK, &failures);
669 if (err == C2_OK) {
670 work->worklets.front()->output.configUpdate.push_back(
671 C2Param::Copy(size));
672 } else {
673 ALOGE("Config update size failed");
674 mSignalledError = true;
675 work->workletsProcessed = 1u;
676 work->result = C2_CORRUPTED;
Wonsik Kim377eeab2019-11-03 19:05:59 -0800677 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800678 }
679
680 }
Harish Mahendrakar3fdfaa32019-08-02 15:44:30 -0700681 if(img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_I42016) {
682 ALOGE("img->fmt %d not supported", img->fmt);
683 mSignalledError = true;
684 work->workletsProcessed = 1u;
685 work->result = C2_CORRUPTED;
686 return false;
687 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800688
689 std::shared_ptr<C2GraphicBlock> block;
690 uint32_t format = HAL_PIXEL_FORMAT_YV12;
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700691 if (img->fmt == VPX_IMG_FMT_I42016) {
692 IntfImpl::Lock lock = mIntf->lock();
693 std::shared_ptr<C2StreamColorAspectsTuning::output> defaultColorAspects = mIntf->getDefaultColorAspects_l();
Harish Mahendrakar749a74c2022-01-27 16:47:09 -0800694 bool allowRGBA1010102 = false;
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700695 if (defaultColorAspects->primaries == C2Color::PRIMARIES_BT2020 &&
696 defaultColorAspects->matrix == C2Color::MATRIX_BT2020 &&
697 defaultColorAspects->transfer == C2Color::TRANSFER_ST2084) {
Harish Mahendrakar749a74c2022-01-27 16:47:09 -0800698 allowRGBA1010102 = true;
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700699 }
Harish Mahendrakar749a74c2022-01-27 16:47:09 -0800700 format = getHalPixelFormatForBitDepth10(allowRGBA1010102);
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700701 }
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700702
703 if (mHalPixelFormat != format) {
704 C2StreamPixelFormatInfo::output pixelFormat(0u, format);
705 std::vector<std::unique_ptr<C2SettingResult>> failures;
706 c2_status_t err = mIntf->config({&pixelFormat }, C2_MAY_BLOCK, &failures);
707 if (err == C2_OK) {
708 work->worklets.front()->output.configUpdate.push_back(
709 C2Param::Copy(pixelFormat));
710 } else {
711 ALOGE("Config update pixelFormat failed");
712 mSignalledError = true;
713 work->workletsProcessed = 1u;
714 work->result = C2_CORRUPTED;
715 return UNKNOWN_ERROR;
716 }
717 mHalPixelFormat = format;
718 }
719
Pawin Vongmasa36653902018-11-15 00:10:25 -0800720 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700721 c2_status_t err = pool->fetchGraphicBlock(align(mWidth, 16), mHeight, format, usage, &block);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800722 if (err != C2_OK) {
723 ALOGE("fetchGraphicBlock for Output failed with status %d", err);
724 work->result = err;
Wonsik Kim377eeab2019-11-03 19:05:59 -0800725 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800726 }
727
728 C2GraphicView wView = block->map().get();
729 if (wView.error()) {
730 ALOGE("graphic view map failed %d", wView.error());
731 work->result = C2_CORRUPTED;
Wonsik Kim377eeab2019-11-03 19:05:59 -0800732 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800733 }
734
Wonsik Kim377eeab2019-11-03 19:05:59 -0800735 ALOGV("provided (%dx%d) required (%dx%d), out frameindex %lld",
736 block->width(), block->height(), mWidth, mHeight,
737 ((c2_cntr64_t *)img->user_priv)->peekll());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800738
ming.zhouac19c3d2019-10-11 11:14:07 +0800739 uint8_t *dstY = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
740 uint8_t *dstU = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_U]);
741 uint8_t *dstV = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_V]);
742
Pawin Vongmasa36653902018-11-15 00:10:25 -0800743 size_t srcYStride = img->stride[VPX_PLANE_Y];
744 size_t srcUStride = img->stride[VPX_PLANE_U];
745 size_t srcVStride = img->stride[VPX_PLANE_V];
Harish Mahendrakardfa3f5a2019-05-02 12:10:24 -0700746 C2PlanarLayout layout = wView.layout();
747 size_t dstYStride = layout.planes[C2PlanarLayout::PLANE_Y].rowInc;
748 size_t dstUVStride = layout.planes[C2PlanarLayout::PLANE_U].rowInc;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700750 if (img->fmt == VPX_IMG_FMT_I42016) {
751 const uint16_t *srcY = (const uint16_t *)img->planes[VPX_PLANE_Y];
752 const uint16_t *srcU = (const uint16_t *)img->planes[VPX_PLANE_U];
753 const uint16_t *srcV = (const uint16_t *)img->planes[VPX_PLANE_V];
754
755 if (format == HAL_PIXEL_FORMAT_RGBA_1010102) {
Wonsik Kimf61206f2019-05-18 16:52:46 -0700756 Mutexed<ConversionQueue>::Locked queue(*mQueue);
757 size_t i = 0;
758 constexpr size_t kHeight = 64;
759 for (; i < mHeight; i += kHeight) {
760 queue->entries.push_back(
ming.zhouac19c3d2019-10-11 11:14:07 +0800761 [dstY, srcY, srcU, srcV,
Wonsik Kimf61206f2019-05-18 16:52:46 -0700762 srcYStride, srcUStride, srcVStride, dstYStride,
763 width = mWidth, height = std::min(mHeight - i, kHeight)] {
Harish Mahendrakar5c467652022-04-28 19:47:28 -0700764 convertYUV420Planar16ToY410OrRGBA1010102(
ming.zhouac19c3d2019-10-11 11:14:07 +0800765 (uint32_t *)dstY, srcY, srcU, srcV, srcYStride / 2,
Wonsik Kimf61206f2019-05-18 16:52:46 -0700766 srcUStride / 2, srcVStride / 2, dstYStride / sizeof(uint32_t),
767 width, height);
768 });
769 srcY += srcYStride / 2 * kHeight;
770 srcU += srcUStride / 2 * (kHeight / 2);
771 srcV += srcVStride / 2 * (kHeight / 2);
ming.zhouac19c3d2019-10-11 11:14:07 +0800772 dstY += dstYStride * kHeight;
Wonsik Kimf61206f2019-05-18 16:52:46 -0700773 }
774 CHECK_EQ(0u, queue->numPending);
775 queue->numPending = queue->entries.size();
776 while (queue->numPending > 0) {
777 queue->cond.signal();
778 queue.waitForCondition(queue->cond);
779 }
Harish Mahendrakar1b1aef22021-12-30 19:12:51 -0800780 } else if (format == HAL_PIXEL_FORMAT_YCBCR_P010) {
781 convertYUV420Planar16ToP010((uint16_t *)dstY, (uint16_t *)dstU, srcY, srcU, srcV,
782 srcYStride / 2, srcUStride / 2, srcVStride / 2,
783 dstYStride / 2, dstUVStride / 2, mWidth, mHeight);
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700784 } else {
Harish Mahendrakar1b1aef22021-12-30 19:12:51 -0800785 convertYUV420Planar16ToYV12(dstY, dstU, dstV, srcY, srcU, srcV, srcYStride / 2,
786 srcUStride / 2, srcVStride / 2, dstYStride, dstUVStride,
787 mWidth, mHeight);
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700788 }
789 } else {
790 const uint8_t *srcY = (const uint8_t *)img->planes[VPX_PLANE_Y];
791 const uint8_t *srcU = (const uint8_t *)img->planes[VPX_PLANE_U];
792 const uint8_t *srcV = (const uint8_t *)img->planes[VPX_PLANE_V];
ming.zhouac19c3d2019-10-11 11:14:07 +0800793
Harish Mahendrakar1b1aef22021-12-30 19:12:51 -0800794 convertYUV420Planar8ToYV12(dstY, dstU, dstV, srcY, srcU, srcV, srcYStride, srcUStride,
795 srcVStride, dstYStride, dstUVStride, mWidth, mHeight);
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700796 }
Wonsik Kim377eeab2019-11-03 19:05:59 -0800797 finishWork(((c2_cntr64_t *)img->user_priv)->peekull(), work, std::move(block));
798 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800799}
800
801c2_status_t C2SoftVpxDec::drainInternal(
802 uint32_t drainMode,
803 const std::shared_ptr<C2BlockPool> &pool,
804 const std::unique_ptr<C2Work> &work) {
805 if (drainMode == NO_DRAIN) {
806 ALOGW("drain with NO_DRAIN: no-op");
807 return C2_OK;
808 }
809 if (drainMode == DRAIN_CHAIN) {
810 ALOGW("DRAIN_CHAIN not supported");
811 return C2_OMITTED;
812 }
813
Wonsik Kim377eeab2019-11-03 19:05:59 -0800814 while (outputBuffer(pool, work) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800815 }
816
817 if (drainMode == DRAIN_COMPONENT_WITH_EOS &&
818 work && work->workletsProcessed == 0u) {
819 fillEmptyWork(work);
820 }
821
822 return C2_OK;
823}
824c2_status_t C2SoftVpxDec::drain(
825 uint32_t drainMode,
826 const std::shared_ptr<C2BlockPool> &pool) {
827 return drainInternal(drainMode, pool, nullptr);
828}
829
830class C2SoftVpxFactory : public C2ComponentFactory {
831public:
832 C2SoftVpxFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
833 GetCodec2PlatformComponentStore()->getParamReflector())) {
834 }
835
836 virtual c2_status_t createComponent(
837 c2_node_id_t id,
838 std::shared_ptr<C2Component>* const component,
839 std::function<void(C2Component*)> deleter) override {
840 *component = std::shared_ptr<C2Component>(
841 new C2SoftVpxDec(COMPONENT_NAME, id,
842 std::make_shared<C2SoftVpxDec::IntfImpl>(mHelper)),
843 deleter);
844 return C2_OK;
845 }
846
847 virtual c2_status_t createInterface(
848 c2_node_id_t id,
849 std::shared_ptr<C2ComponentInterface>* const interface,
850 std::function<void(C2ComponentInterface*)> deleter) override {
851 *interface = std::shared_ptr<C2ComponentInterface>(
852 new SimpleInterface<C2SoftVpxDec::IntfImpl>(
853 COMPONENT_NAME, id,
854 std::make_shared<C2SoftVpxDec::IntfImpl>(mHelper)),
855 deleter);
856 return C2_OK;
857 }
858
859 virtual ~C2SoftVpxFactory() override = default;
860
861private:
862 std::shared_ptr<C2ReflectorHelper> mHelper;
863};
864
865} // namespace android
866
Cindy Zhouf6c0c3c2020-12-02 10:53:40 -0800867__attribute__((cfi_canonical_jump_table))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800868extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
869 ALOGV("in %s", __func__);
870 return new ::android::C2SoftVpxFactory();
871}
872
Cindy Zhouf6c0c3c2020-12-02 10:53:40 -0800873__attribute__((cfi_canonical_jump_table))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800874extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
875 ALOGV("in %s", __func__);
876 delete factory;
877}