blob: c2ccfa0b4e7fe7b3c11561f3bc5f6ee7257100c6 [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>
Pawin Vongmasa36653902018-11-15 00:10:25 -080028#include <SimpleC2Interface.h>
29
30#include "C2SoftVpxDec.h"
31
32namespace android {
Harish Mahendrakare55c4712019-07-26 12:32:13 -070033constexpr size_t kMinInputBufferSize = 2 * 1024 * 1024;
Pawin Vongmasa36653902018-11-15 00:10:25 -080034#ifdef VP9
35constexpr char COMPONENT_NAME[] = "c2.android.vp9.decoder";
36#else
37constexpr char COMPONENT_NAME[] = "c2.android.vp8.decoder";
38#endif
39
40class C2SoftVpxDec::IntfImpl : public SimpleInterface<void>::BaseParams {
41public:
42 explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
43 : SimpleInterface<void>::BaseParams(
44 helper,
45 COMPONENT_NAME,
46 C2Component::KIND_DECODER,
47 C2Component::DOMAIN_VIDEO,
48#ifdef VP9
49 MEDIA_MIMETYPE_VIDEO_VP9
50#else
51 MEDIA_MIMETYPE_VIDEO_VP8
52#endif
53 ) {
54 noPrivateBuffers(); // TODO: account for our buffers here
55 noInputReferences();
56 noOutputReferences();
57 noInputLatency();
58 noTimeStretch();
59
60 // TODO: output latency and reordering
61
62 addParameter(
63 DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
64 .withConstValue(new C2ComponentAttributesSetting(C2Component::ATTRIB_IS_TEMPORAL))
65 .build());
66
67 addParameter(
68 DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
69 .withDefault(new C2StreamPictureSizeInfo::output(0u, 320, 240))
70 .withFields({
71 C2F(mSize, width).inRange(2, 2048, 2),
72 C2F(mSize, height).inRange(2, 2048, 2),
73 })
74 .withSetter(SizeSetter)
75 .build());
76
77#ifdef VP9
78 // TODO: Add C2Config::PROFILE_VP9_2HDR ??
79 addParameter(
80 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
81 .withDefault(new C2StreamProfileLevelInfo::input(0u,
82 C2Config::PROFILE_VP9_0, C2Config::LEVEL_VP9_5))
83 .withFields({
84 C2F(mProfileLevel, profile).oneOf({
85 C2Config::PROFILE_VP9_0,
86 C2Config::PROFILE_VP9_2}),
87 C2F(mProfileLevel, level).oneOf({
88 C2Config::LEVEL_VP9_1,
89 C2Config::LEVEL_VP9_1_1,
90 C2Config::LEVEL_VP9_2,
91 C2Config::LEVEL_VP9_2_1,
92 C2Config::LEVEL_VP9_3,
93 C2Config::LEVEL_VP9_3_1,
94 C2Config::LEVEL_VP9_4,
95 C2Config::LEVEL_VP9_4_1,
96 C2Config::LEVEL_VP9_5,
97 })
98 })
99 .withSetter(ProfileLevelSetter, mSize)
100 .build());
101
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800102 mHdr10PlusInfoInput = C2StreamHdr10PlusInfo::input::AllocShared(0);
103 addParameter(
104 DefineParam(mHdr10PlusInfoInput, C2_PARAMKEY_INPUT_HDR10_PLUS_INFO)
105 .withDefault(mHdr10PlusInfoInput)
106 .withFields({
107 C2F(mHdr10PlusInfoInput, m.value).any(),
108 })
109 .withSetter(Hdr10PlusInfoInputSetter)
110 .build());
111
112 mHdr10PlusInfoOutput = C2StreamHdr10PlusInfo::output::AllocShared(0);
113 addParameter(
114 DefineParam(mHdr10PlusInfoOutput, C2_PARAMKEY_OUTPUT_HDR10_PLUS_INFO)
115 .withDefault(mHdr10PlusInfoOutput)
116 .withFields({
117 C2F(mHdr10PlusInfoOutput, m.value).any(),
118 })
119 .withSetter(Hdr10PlusInfoOutputSetter)
120 .build());
121
Pawin Vongmasa36653902018-11-15 00:10:25 -0800122#if 0
123 // sample BT.2020 static info
124 mHdrStaticInfo = std::make_shared<C2StreamHdrStaticInfo::output>();
125 mHdrStaticInfo->mastering = {
126 .red = { .x = 0.708, .y = 0.292 },
127 .green = { .x = 0.170, .y = 0.797 },
128 .blue = { .x = 0.131, .y = 0.046 },
129 .white = { .x = 0.3127, .y = 0.3290 },
130 .maxLuminance = 1000,
131 .minLuminance = 0.1,
132 };
133 mHdrStaticInfo->maxCll = 1000;
134 mHdrStaticInfo->maxFall = 120;
135
136 mHdrStaticInfo->maxLuminance = 0; // disable static info
137
138 helper->addStructDescriptors<C2MasteringDisplayColorVolumeStruct, C2ColorXyStruct>();
139 addParameter(
140 DefineParam(mHdrStaticInfo, C2_PARAMKEY_HDR_STATIC_INFO)
141 .withDefault(mHdrStaticInfo)
142 .withFields({
143 C2F(mHdrStaticInfo, mastering.red.x).inRange(0, 1),
144 // TODO
145 })
146 .withSetter(HdrStaticInfoSetter)
147 .build());
148#endif
149#else
150 addParameter(
151 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
Harish Mahendrakar22cb9d02021-08-26 16:35:48 -0700152 .withDefault(new C2StreamProfileLevelInfo::input(0u,
153 C2Config::PROFILE_VP8_0, C2Config::LEVEL_UNUSED))
154 .withFields({
155 C2F(mProfileLevel, profile).equalTo(
156 PROFILE_VP8_0
157 ),
158 C2F(mProfileLevel, level).equalTo(
159 LEVEL_UNUSED),
160 })
161 .withSetter(ProfileLevelSetter, mSize)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800162 .build());
163#endif
164
165 addParameter(
166 DefineParam(mMaxSize, C2_PARAMKEY_MAX_PICTURE_SIZE)
167 .withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 320, 240))
168 .withFields({
169 C2F(mSize, width).inRange(2, 2048, 2),
170 C2F(mSize, height).inRange(2, 2048, 2),
171 })
172 .withSetter(MaxPictureSizeSetter, mSize)
173 .build());
174
175 addParameter(
176 DefineParam(mMaxInputSize, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE)
Harish Mahendrakare55c4712019-07-26 12:32:13 -0700177 .withDefault(new C2StreamMaxBufferSizeInfo::input(0u, kMinInputBufferSize))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800178 .withFields({
179 C2F(mMaxInputSize, value).any(),
180 })
181 .calculatedAs(MaxInputSizeSetter, mMaxSize)
182 .build());
183
184 C2ChromaOffsetStruct locations[1] = { C2ChromaOffsetStruct::ITU_YUV_420_0() };
185 std::shared_ptr<C2StreamColorInfo::output> defaultColorInfo =
186 C2StreamColorInfo::output::AllocShared(
187 1u, 0u, 8u /* bitDepth */, C2Color::YUV_420);
188 memcpy(defaultColorInfo->m.locations, locations, sizeof(locations));
189
190 defaultColorInfo =
191 C2StreamColorInfo::output::AllocShared(
192 { C2ChromaOffsetStruct::ITU_YUV_420_0() },
193 0u, 8u /* bitDepth */, C2Color::YUV_420);
194 helper->addStructDescriptors<C2ChromaOffsetStruct>();
195
196 addParameter(
197 DefineParam(mColorInfo, C2_PARAMKEY_CODED_COLOR_INFO)
198 .withConstValue(defaultColorInfo)
199 .build());
200
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700201 addParameter(
202 DefineParam(mDefaultColorAspects, C2_PARAMKEY_DEFAULT_COLOR_ASPECTS)
203 .withDefault(new C2StreamColorAspectsTuning::output(
204 0u, C2Color::RANGE_UNSPECIFIED, C2Color::PRIMARIES_UNSPECIFIED,
205 C2Color::TRANSFER_UNSPECIFIED, C2Color::MATRIX_UNSPECIFIED))
206 .withFields({
207 C2F(mDefaultColorAspects, range).inRange(
208 C2Color::RANGE_UNSPECIFIED, C2Color::RANGE_OTHER),
209 C2F(mDefaultColorAspects, primaries).inRange(
210 C2Color::PRIMARIES_UNSPECIFIED, C2Color::PRIMARIES_OTHER),
211 C2F(mDefaultColorAspects, transfer).inRange(
212 C2Color::TRANSFER_UNSPECIFIED, C2Color::TRANSFER_OTHER),
213 C2F(mDefaultColorAspects, matrix).inRange(
214 C2Color::MATRIX_UNSPECIFIED, C2Color::MATRIX_OTHER)
215 })
216 .withSetter(DefaultColorAspectsSetter)
217 .build());
218
Pawin Vongmasa36653902018-11-15 00:10:25 -0800219 // TODO: support more formats?
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700220 std::vector<uint32_t> pixelFormats = {HAL_PIXEL_FORMAT_YCBCR_420_888};
221#ifdef VP9
222 if (isAtLeastT()) {
223 pixelFormats.push_back(HAL_PIXEL_FORMAT_YCBCR_P010);
224 }
225#endif
Pawin Vongmasa36653902018-11-15 00:10:25 -0800226 addParameter(
227 DefineParam(mPixelFormat, C2_PARAMKEY_PIXEL_FORMAT)
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700228 .withDefault(new C2StreamPixelFormatInfo::output(
229 0u, HAL_PIXEL_FORMAT_YCBCR_420_888))
230 .withFields({C2F(mPixelFormat, value).oneOf(pixelFormats)})
231 .withSetter((Setter<decltype(*mPixelFormat)>::StrictValueWithNoDeps))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800232 .build());
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700233
Pawin Vongmasa36653902018-11-15 00:10:25 -0800234 }
235
236 static C2R SizeSetter(bool mayBlock, const C2P<C2StreamPictureSizeInfo::output> &oldMe,
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800237 C2P<C2StreamPictureSizeInfo::output> &me) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800238 (void)mayBlock;
239 C2R res = C2R::Ok();
240 if (!me.F(me.v.width).supportsAtAll(me.v.width)) {
241 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.width)));
242 me.set().width = oldMe.v.width;
243 }
244 if (!me.F(me.v.height).supportsAtAll(me.v.height)) {
245 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.height)));
246 me.set().height = oldMe.v.height;
247 }
248 return res;
249 }
250
251 static C2R MaxPictureSizeSetter(bool mayBlock, C2P<C2StreamMaxPictureSizeTuning::output> &me,
252 const C2P<C2StreamPictureSizeInfo::output> &size) {
253 (void)mayBlock;
254 // TODO: get max width/height from the size's field helpers vs. hardcoding
255 me.set().width = c2_min(c2_max(me.v.width, size.v.width), 2048u);
256 me.set().height = c2_min(c2_max(me.v.height, size.v.height), 2048u);
257 return C2R::Ok();
258 }
259
260 static C2R MaxInputSizeSetter(bool mayBlock, C2P<C2StreamMaxBufferSizeInfo::input> &me,
261 const C2P<C2StreamMaxPictureSizeTuning::output> &maxSize) {
262 (void)mayBlock;
263 // assume compression ratio of 2
Harish Mahendrakare55c4712019-07-26 12:32:13 -0700264 me.set().value = c2_max((((maxSize.v.width + 63) / 64)
265 * ((maxSize.v.height + 63) / 64) * 3072), kMinInputBufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800266 return C2R::Ok();
267 }
268
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700269 static C2R DefaultColorAspectsSetter(bool mayBlock, C2P<C2StreamColorAspectsTuning::output> &me) {
270 (void)mayBlock;
271 if (me.v.range > C2Color::RANGE_OTHER) {
272 me.set().range = C2Color::RANGE_OTHER;
273 }
274 if (me.v.primaries > C2Color::PRIMARIES_OTHER) {
275 me.set().primaries = C2Color::PRIMARIES_OTHER;
276 }
277 if (me.v.transfer > C2Color::TRANSFER_OTHER) {
278 me.set().transfer = C2Color::TRANSFER_OTHER;
279 }
280 if (me.v.matrix > C2Color::MATRIX_OTHER) {
281 me.set().matrix = C2Color::MATRIX_OTHER;
282 }
283 return C2R::Ok();
284 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800285
286 static C2R ProfileLevelSetter(bool mayBlock, C2P<C2StreamProfileLevelInfo::input> &me,
287 const C2P<C2StreamPictureSizeInfo::output> &size) {
288 (void)mayBlock;
289 (void)size;
290 (void)me; // TODO: validate
291 return C2R::Ok();
292 }
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700293 std::shared_ptr<C2StreamColorAspectsTuning::output> getDefaultColorAspects_l() {
294 return mDefaultColorAspects;
295 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800296
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800297 static C2R Hdr10PlusInfoInputSetter(bool mayBlock, C2P<C2StreamHdr10PlusInfo::input> &me) {
298 (void)mayBlock;
299 (void)me; // TODO: validate
300 return C2R::Ok();
301 }
302
303 static C2R Hdr10PlusInfoOutputSetter(bool mayBlock, C2P<C2StreamHdr10PlusInfo::output> &me) {
304 (void)mayBlock;
305 (void)me; // TODO: validate
306 return C2R::Ok();
307 }
308
Pawin Vongmasa36653902018-11-15 00:10:25 -0800309private:
310 std::shared_ptr<C2StreamProfileLevelInfo::input> mProfileLevel;
311 std::shared_ptr<C2StreamPictureSizeInfo::output> mSize;
312 std::shared_ptr<C2StreamMaxPictureSizeTuning::output> mMaxSize;
313 std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mMaxInputSize;
314 std::shared_ptr<C2StreamColorInfo::output> mColorInfo;
315 std::shared_ptr<C2StreamPixelFormatInfo::output> mPixelFormat;
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700316 std::shared_ptr<C2StreamColorAspectsTuning::output> mDefaultColorAspects;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800317#ifdef VP9
318#if 0
319 std::shared_ptr<C2StreamHdrStaticInfo::output> mHdrStaticInfo;
320#endif
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800321 std::shared_ptr<C2StreamHdr10PlusInfo::input> mHdr10PlusInfoInput;
322 std::shared_ptr<C2StreamHdr10PlusInfo::output> mHdr10PlusInfoOutput;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800323#endif
324};
325
Wonsik Kimf61206f2019-05-18 16:52:46 -0700326C2SoftVpxDec::ConverterThread::ConverterThread(
327 const std::shared_ptr<Mutexed<ConversionQueue>> &queue)
328 : Thread(false), mQueue(queue) {}
329
330bool C2SoftVpxDec::ConverterThread::threadLoop() {
331 Mutexed<ConversionQueue>::Locked queue(*mQueue);
332 if (queue->entries.empty()) {
333 queue.waitForCondition(queue->cond);
334 if (queue->entries.empty()) {
335 return true;
336 }
337 }
338 std::function<void()> convert = queue->entries.front();
339 queue->entries.pop_front();
340 if (!queue->entries.empty()) {
341 queue->cond.signal();
342 }
343 queue.unlock();
344
345 convert();
346
347 queue.lock();
348 if (--queue->numPending == 0u) {
349 queue->cond.broadcast();
350 }
351 return true;
352}
353
Pawin Vongmasa36653902018-11-15 00:10:25 -0800354C2SoftVpxDec::C2SoftVpxDec(
355 const char *name,
356 c2_node_id_t id,
357 const std::shared_ptr<IntfImpl> &intfImpl)
358 : SimpleC2Component(std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
359 mIntf(intfImpl),
Wonsik Kimf61206f2019-05-18 16:52:46 -0700360 mCodecCtx(nullptr),
361 mCoreCount(1),
362 mQueue(new Mutexed<ConversionQueue>) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800363}
364
365C2SoftVpxDec::~C2SoftVpxDec() {
366 onRelease();
367}
368
369c2_status_t C2SoftVpxDec::onInit() {
370 status_t err = initDecoder();
371 return err == OK ? C2_OK : C2_CORRUPTED;
372}
373
374c2_status_t C2SoftVpxDec::onStop() {
375 mSignalledError = false;
376 mSignalledOutputEos = false;
377
378 return C2_OK;
379}
380
381void C2SoftVpxDec::onReset() {
382 (void)onStop();
383 c2_status_t err = onFlush_sm();
384 if (err != C2_OK)
385 {
386 ALOGW("Failed to flush decoder. Try to hard reset decoder");
387 destroyDecoder();
388 (void)initDecoder();
389 }
390}
391
392void C2SoftVpxDec::onRelease() {
393 destroyDecoder();
394}
395
396c2_status_t C2SoftVpxDec::onFlush_sm() {
397 if (mFrameParallelMode) {
398 // Flush decoder by passing nullptr data ptr and 0 size.
399 // Ideally, this should never fail.
400 if (vpx_codec_decode(mCodecCtx, nullptr, 0, nullptr, 0)) {
401 ALOGE("Failed to flush on2 decoder.");
402 return C2_CORRUPTED;
403 }
404 }
405
406 // Drop all the decoded frames in decoder.
407 vpx_codec_iter_t iter = nullptr;
408 while (vpx_codec_get_frame(mCodecCtx, &iter)) {
409 }
410
411 mSignalledError = false;
412 mSignalledOutputEos = false;
413 return C2_OK;
414}
415
416static int GetCPUCoreCount() {
417 int cpuCoreCount = 1;
418#if defined(_SC_NPROCESSORS_ONLN)
419 cpuCoreCount = sysconf(_SC_NPROCESSORS_ONLN);
420#else
421 // _SC_NPROC_ONLN must be defined...
422 cpuCoreCount = sysconf(_SC_NPROC_ONLN);
423#endif
424 CHECK(cpuCoreCount >= 1);
425 ALOGV("Number of CPU cores: %d", cpuCoreCount);
426 return cpuCoreCount;
427}
428
429status_t C2SoftVpxDec::initDecoder() {
430#ifdef VP9
431 mMode = MODE_VP9;
432#else
433 mMode = MODE_VP8;
434#endif
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700435 mHalPixelFormat = HAL_PIXEL_FORMAT_YV12;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800436 mWidth = 320;
437 mHeight = 240;
438 mFrameParallelMode = false;
439 mSignalledOutputEos = false;
440 mSignalledError = false;
441
442 if (!mCodecCtx) {
443 mCodecCtx = new vpx_codec_ctx_t;
444 }
445 if (!mCodecCtx) {
446 ALOGE("mCodecCtx is null");
447 return NO_MEMORY;
448 }
449
450 vpx_codec_dec_cfg_t cfg;
451 memset(&cfg, 0, sizeof(vpx_codec_dec_cfg_t));
Wonsik Kimf61206f2019-05-18 16:52:46 -0700452 cfg.threads = mCoreCount = GetCPUCoreCount();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800453
454 vpx_codec_flags_t flags;
455 memset(&flags, 0, sizeof(vpx_codec_flags_t));
456 if (mFrameParallelMode) flags |= VPX_CODEC_USE_FRAME_THREADING;
457
458 vpx_codec_err_t vpx_err;
459 if ((vpx_err = vpx_codec_dec_init(
460 mCodecCtx, mMode == MODE_VP8 ? &vpx_codec_vp8_dx_algo : &vpx_codec_vp9_dx_algo,
461 &cfg, flags))) {
462 ALOGE("on2 decoder failed to initialize. (%d)", vpx_err);
463 return UNKNOWN_ERROR;
464 }
465
Wonsik Kimf61206f2019-05-18 16:52:46 -0700466 if (mMode == MODE_VP9) {
467 using namespace std::string_literals;
468 for (int i = 0; i < mCoreCount; ++i) {
469 sp<ConverterThread> thread(new ConverterThread(mQueue));
470 mConverterThreads.push_back(thread);
471 if (thread->run(("vp9conv #"s + std::to_string(i)).c_str(),
472 ANDROID_PRIORITY_AUDIO) != OK) {
473 return UNKNOWN_ERROR;
474 }
475 }
476 }
477
Pawin Vongmasa36653902018-11-15 00:10:25 -0800478 return OK;
479}
480
481status_t C2SoftVpxDec::destroyDecoder() {
482 if (mCodecCtx) {
483 vpx_codec_destroy(mCodecCtx);
484 delete mCodecCtx;
485 mCodecCtx = nullptr;
486 }
Wonsik Kimf61206f2019-05-18 16:52:46 -0700487 bool running = true;
488 for (const sp<ConverterThread> &thread : mConverterThreads) {
489 thread->requestExit();
490 }
491 while (running) {
492 mQueue->lock()->cond.broadcast();
493 running = false;
494 for (const sp<ConverterThread> &thread : mConverterThreads) {
495 if (thread->isRunning()) {
496 running = true;
497 break;
498 }
499 }
500 }
501 mConverterThreads.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800502
503 return OK;
504}
505
506void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
507 uint32_t flags = 0;
508 if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
509 flags |= C2FrameData::FLAG_END_OF_STREAM;
510 ALOGV("signalling eos");
511 }
512 work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
513 work->worklets.front()->output.buffers.clear();
514 work->worklets.front()->output.ordinal = work->input.ordinal;
515 work->workletsProcessed = 1u;
516}
517
518void C2SoftVpxDec::finishWork(uint64_t index, const std::unique_ptr<C2Work> &work,
519 const std::shared_ptr<C2GraphicBlock> &block) {
520 std::shared_ptr<C2Buffer> buffer = createGraphicBuffer(block,
521 C2Rect(mWidth, mHeight));
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800522 auto fillWork = [buffer, index, intf = this->mIntf](
523 const std::unique_ptr<C2Work> &work) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800524 uint32_t flags = 0;
525 if ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) &&
526 (c2_cntr64_t(index) == work->input.ordinal.frameIndex)) {
527 flags |= C2FrameData::FLAG_END_OF_STREAM;
528 ALOGV("signalling eos");
529 }
530 work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
531 work->worklets.front()->output.buffers.clear();
532 work->worklets.front()->output.buffers.push_back(buffer);
533 work->worklets.front()->output.ordinal = work->input.ordinal;
534 work->workletsProcessed = 1u;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800535
536 for (const std::unique_ptr<C2Param> &param: work->input.configUpdate) {
537 if (param) {
538 C2StreamHdr10PlusInfo::input *hdr10PlusInfo =
539 C2StreamHdr10PlusInfo::input::From(param.get());
540
541 if (hdr10PlusInfo != nullptr) {
542 std::vector<std::unique_ptr<C2SettingResult>> failures;
543 std::unique_ptr<C2Param> outParam = C2Param::CopyAsStream(
544 *param.get(), true /*output*/, param->stream());
545 c2_status_t err = intf->config(
546 { outParam.get() }, C2_MAY_BLOCK, &failures);
547 if (err == C2_OK) {
548 work->worklets.front()->output.configUpdate.push_back(
549 C2Param::Copy(*outParam.get()));
550 } else {
551 ALOGE("finishWork: Config update size failed");
552 }
553 break;
554 }
555 }
556 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800557 };
558 if (work && c2_cntr64_t(index) == work->input.ordinal.frameIndex) {
559 fillWork(work);
560 } else {
561 finish(index, fillWork);
562 }
563}
564
565void C2SoftVpxDec::process(
566 const std::unique_ptr<C2Work> &work,
567 const std::shared_ptr<C2BlockPool> &pool) {
568 // Initialize output work
569 work->result = C2_OK;
570 work->workletsProcessed = 0u;
571 work->worklets.front()->output.configUpdate.clear();
572 work->worklets.front()->output.flags = work->input.flags;
573
574 if (mSignalledError || mSignalledOutputEos) {
575 work->result = C2_BAD_VALUE;
576 return;
577 }
578
579 size_t inOffset = 0u;
580 size_t inSize = 0u;
581 C2ReadView rView = mDummyReadView;
582 if (!work->input.buffers.empty()) {
583 rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
584 inSize = rView.capacity();
585 if (inSize && rView.error()) {
586 ALOGE("read view map failed %d", rView.error());
587 work->result = C2_CORRUPTED;
588 return;
589 }
590 }
591
592 bool codecConfig = ((work->input.flags & C2FrameData::FLAG_CODEC_CONFIG) !=0);
593 bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
594
595 ALOGV("in buffer attr. size %zu timestamp %d frameindex %d, flags %x",
596 inSize, (int)work->input.ordinal.timestamp.peeku(),
597 (int)work->input.ordinal.frameIndex.peeku(), work->input.flags);
598
599 // Software VP9 Decoder does not need the Codec Specific Data (CSD)
600 // (specified in http://www.webmproject.org/vp9/profiles/). Ignore it if
601 // it was passed.
602 if (codecConfig) {
603 // Ignore CSD buffer for VP9.
604 if (mMode == MODE_VP9) {
605 fillEmptyWork(work);
606 return;
607 } else {
608 // Tolerate the CSD buffer for VP8. This is a workaround
609 // for b/28689536. continue
610 ALOGW("WARNING: Got CSD buffer for VP8. Continue");
611 }
612 }
613
Pawin Vongmasa36653902018-11-15 00:10:25 -0800614 if (inSize) {
615 uint8_t *bitstream = const_cast<uint8_t *>(rView.data() + inOffset);
616 vpx_codec_err_t err = vpx_codec_decode(
Wonsik Kim377eeab2019-11-03 19:05:59 -0800617 mCodecCtx, bitstream, inSize, &work->input.ordinal.frameIndex, 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800618 if (err != VPX_CODEC_OK) {
619 ALOGE("on2 decoder failed to decode frame. err: %d", err);
620 mSignalledError = true;
621 work->workletsProcessed = 1u;
622 work->result = C2_CORRUPTED;
623 return;
624 }
625 }
626
Wonsik Kim377eeab2019-11-03 19:05:59 -0800627 status_t err = outputBuffer(pool, work);
628 if (err == NOT_ENOUGH_DATA) {
629 if (inSize > 0) {
630 ALOGV("Maybe non-display frame at %lld.",
631 work->input.ordinal.frameIndex.peekll());
632 // send the work back with empty buffer.
633 inSize = 0;
634 }
635 } else if (err != OK) {
636 ALOGD("Error while getting the output frame out");
637 // work->result would be already filled; do fillEmptyWork() below to
638 // send the work back.
639 inSize = 0;
640 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800641
642 if (eos) {
643 drainInternal(DRAIN_COMPONENT_WITH_EOS, pool, work);
644 mSignalledOutputEos = true;
645 } else if (!inSize) {
646 fillEmptyWork(work);
647 }
648}
649
Wonsik Kim377eeab2019-11-03 19:05:59 -0800650status_t C2SoftVpxDec::outputBuffer(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800651 const std::shared_ptr<C2BlockPool> &pool,
652 const std::unique_ptr<C2Work> &work)
653{
Wonsik Kim377eeab2019-11-03 19:05:59 -0800654 if (!(work && pool)) return BAD_VALUE;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800655
656 vpx_codec_iter_t iter = nullptr;
657 vpx_image_t *img = vpx_codec_get_frame(mCodecCtx, &iter);
658
Wonsik Kim377eeab2019-11-03 19:05:59 -0800659 if (!img) return NOT_ENOUGH_DATA;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800660
661 if (img->d_w != mWidth || img->d_h != mHeight) {
662 mWidth = img->d_w;
663 mHeight = img->d_h;
664
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800665 C2StreamPictureSizeInfo::output size(0u, mWidth, mHeight);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800666 std::vector<std::unique_ptr<C2SettingResult>> failures;
667 c2_status_t err = mIntf->config({&size}, C2_MAY_BLOCK, &failures);
668 if (err == C2_OK) {
669 work->worklets.front()->output.configUpdate.push_back(
670 C2Param::Copy(size));
671 } else {
672 ALOGE("Config update size failed");
673 mSignalledError = true;
674 work->workletsProcessed = 1u;
675 work->result = C2_CORRUPTED;
Wonsik Kim377eeab2019-11-03 19:05:59 -0800676 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800677 }
678
679 }
Harish Mahendrakar3fdfaa32019-08-02 15:44:30 -0700680 if(img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_I42016) {
681 ALOGE("img->fmt %d not supported", img->fmt);
682 mSignalledError = true;
683 work->workletsProcessed = 1u;
684 work->result = C2_CORRUPTED;
685 return false;
686 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800687
688 std::shared_ptr<C2GraphicBlock> block;
689 uint32_t format = HAL_PIXEL_FORMAT_YV12;
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700690 if (img->fmt == VPX_IMG_FMT_I42016) {
691 IntfImpl::Lock lock = mIntf->lock();
692 std::shared_ptr<C2StreamColorAspectsTuning::output> defaultColorAspects = mIntf->getDefaultColorAspects_l();
Harish Mahendrakar749a74c2022-01-27 16:47:09 -0800693 bool allowRGBA1010102 = false;
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700694 if (defaultColorAspects->primaries == C2Color::PRIMARIES_BT2020 &&
695 defaultColorAspects->matrix == C2Color::MATRIX_BT2020 &&
696 defaultColorAspects->transfer == C2Color::TRANSFER_ST2084) {
Harish Mahendrakar749a74c2022-01-27 16:47:09 -0800697 allowRGBA1010102 = true;
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700698 }
Harish Mahendrakar749a74c2022-01-27 16:47:09 -0800699 format = getHalPixelFormatForBitDepth10(allowRGBA1010102);
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700700 }
Harish Mahendrakard4bbb762022-03-29 11:53:23 -0700701
702 if (mHalPixelFormat != format) {
703 C2StreamPixelFormatInfo::output pixelFormat(0u, format);
704 std::vector<std::unique_ptr<C2SettingResult>> failures;
705 c2_status_t err = mIntf->config({&pixelFormat }, C2_MAY_BLOCK, &failures);
706 if (err == C2_OK) {
707 work->worklets.front()->output.configUpdate.push_back(
708 C2Param::Copy(pixelFormat));
709 } else {
710 ALOGE("Config update pixelFormat failed");
711 mSignalledError = true;
712 work->workletsProcessed = 1u;
713 work->result = C2_CORRUPTED;
714 return UNKNOWN_ERROR;
715 }
716 mHalPixelFormat = format;
717 }
718
Pawin Vongmasa36653902018-11-15 00:10:25 -0800719 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700720 c2_status_t err = pool->fetchGraphicBlock(align(mWidth, 16), mHeight, format, usage, &block);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800721 if (err != C2_OK) {
722 ALOGE("fetchGraphicBlock for Output failed with status %d", err);
723 work->result = err;
Wonsik Kim377eeab2019-11-03 19:05:59 -0800724 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800725 }
726
727 C2GraphicView wView = block->map().get();
728 if (wView.error()) {
729 ALOGE("graphic view map failed %d", wView.error());
730 work->result = C2_CORRUPTED;
Wonsik Kim377eeab2019-11-03 19:05:59 -0800731 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800732 }
733
Wonsik Kim377eeab2019-11-03 19:05:59 -0800734 ALOGV("provided (%dx%d) required (%dx%d), out frameindex %lld",
735 block->width(), block->height(), mWidth, mHeight,
736 ((c2_cntr64_t *)img->user_priv)->peekll());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800737
ming.zhouac19c3d2019-10-11 11:14:07 +0800738 uint8_t *dstY = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
739 uint8_t *dstU = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_U]);
740 uint8_t *dstV = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_V]);
741
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 size_t srcYStride = img->stride[VPX_PLANE_Y];
743 size_t srcUStride = img->stride[VPX_PLANE_U];
744 size_t srcVStride = img->stride[VPX_PLANE_V];
Harish Mahendrakardfa3f5a2019-05-02 12:10:24 -0700745 C2PlanarLayout layout = wView.layout();
746 size_t dstYStride = layout.planes[C2PlanarLayout::PLANE_Y].rowInc;
747 size_t dstUVStride = layout.planes[C2PlanarLayout::PLANE_U].rowInc;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700749 if (img->fmt == VPX_IMG_FMT_I42016) {
750 const uint16_t *srcY = (const uint16_t *)img->planes[VPX_PLANE_Y];
751 const uint16_t *srcU = (const uint16_t *)img->planes[VPX_PLANE_U];
752 const uint16_t *srcV = (const uint16_t *)img->planes[VPX_PLANE_V];
753
754 if (format == HAL_PIXEL_FORMAT_RGBA_1010102) {
Wonsik Kimf61206f2019-05-18 16:52:46 -0700755 Mutexed<ConversionQueue>::Locked queue(*mQueue);
756 size_t i = 0;
757 constexpr size_t kHeight = 64;
758 for (; i < mHeight; i += kHeight) {
759 queue->entries.push_back(
ming.zhouac19c3d2019-10-11 11:14:07 +0800760 [dstY, srcY, srcU, srcV,
Wonsik Kimf61206f2019-05-18 16:52:46 -0700761 srcYStride, srcUStride, srcVStride, dstYStride,
762 width = mWidth, height = std::min(mHeight - i, kHeight)] {
Harish Mahendrakar5c467652022-04-28 19:47:28 -0700763 convertYUV420Planar16ToY410OrRGBA1010102(
ming.zhouac19c3d2019-10-11 11:14:07 +0800764 (uint32_t *)dstY, srcY, srcU, srcV, srcYStride / 2,
Wonsik Kimf61206f2019-05-18 16:52:46 -0700765 srcUStride / 2, srcVStride / 2, dstYStride / sizeof(uint32_t),
766 width, height);
767 });
768 srcY += srcYStride / 2 * kHeight;
769 srcU += srcUStride / 2 * (kHeight / 2);
770 srcV += srcVStride / 2 * (kHeight / 2);
ming.zhouac19c3d2019-10-11 11:14:07 +0800771 dstY += dstYStride * kHeight;
Wonsik Kimf61206f2019-05-18 16:52:46 -0700772 }
773 CHECK_EQ(0u, queue->numPending);
774 queue->numPending = queue->entries.size();
775 while (queue->numPending > 0) {
776 queue->cond.signal();
777 queue.waitForCondition(queue->cond);
778 }
Harish Mahendrakar1b1aef22021-12-30 19:12:51 -0800779 } else if (format == HAL_PIXEL_FORMAT_YCBCR_P010) {
780 convertYUV420Planar16ToP010((uint16_t *)dstY, (uint16_t *)dstU, srcY, srcU, srcV,
781 srcYStride / 2, srcUStride / 2, srcVStride / 2,
782 dstYStride / 2, dstUVStride / 2, mWidth, mHeight);
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700783 } else {
Harish Mahendrakar1b1aef22021-12-30 19:12:51 -0800784 convertYUV420Planar16ToYV12(dstY, dstU, dstV, srcY, srcU, srcV, srcYStride / 2,
785 srcUStride / 2, srcVStride / 2, dstYStride, dstUVStride,
786 mWidth, mHeight);
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700787 }
788 } else {
789 const uint8_t *srcY = (const uint8_t *)img->planes[VPX_PLANE_Y];
790 const uint8_t *srcU = (const uint8_t *)img->planes[VPX_PLANE_U];
791 const uint8_t *srcV = (const uint8_t *)img->planes[VPX_PLANE_V];
ming.zhouac19c3d2019-10-11 11:14:07 +0800792
Harish Mahendrakar1b1aef22021-12-30 19:12:51 -0800793 convertYUV420Planar8ToYV12(dstY, dstU, dstV, srcY, srcU, srcV, srcYStride, srcUStride,
794 srcVStride, dstYStride, dstUVStride, mWidth, mHeight);
Harish Mahendrakared4e0cd2018-10-11 18:11:49 -0700795 }
Wonsik Kim377eeab2019-11-03 19:05:59 -0800796 finishWork(((c2_cntr64_t *)img->user_priv)->peekull(), work, std::move(block));
797 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800798}
799
800c2_status_t C2SoftVpxDec::drainInternal(
801 uint32_t drainMode,
802 const std::shared_ptr<C2BlockPool> &pool,
803 const std::unique_ptr<C2Work> &work) {
804 if (drainMode == NO_DRAIN) {
805 ALOGW("drain with NO_DRAIN: no-op");
806 return C2_OK;
807 }
808 if (drainMode == DRAIN_CHAIN) {
809 ALOGW("DRAIN_CHAIN not supported");
810 return C2_OMITTED;
811 }
812
Wonsik Kim377eeab2019-11-03 19:05:59 -0800813 while (outputBuffer(pool, work) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800814 }
815
816 if (drainMode == DRAIN_COMPONENT_WITH_EOS &&
817 work && work->workletsProcessed == 0u) {
818 fillEmptyWork(work);
819 }
820
821 return C2_OK;
822}
823c2_status_t C2SoftVpxDec::drain(
824 uint32_t drainMode,
825 const std::shared_ptr<C2BlockPool> &pool) {
826 return drainInternal(drainMode, pool, nullptr);
827}
828
829class C2SoftVpxFactory : public C2ComponentFactory {
830public:
831 C2SoftVpxFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
832 GetCodec2PlatformComponentStore()->getParamReflector())) {
833 }
834
835 virtual c2_status_t createComponent(
836 c2_node_id_t id,
837 std::shared_ptr<C2Component>* const component,
838 std::function<void(C2Component*)> deleter) override {
839 *component = std::shared_ptr<C2Component>(
840 new C2SoftVpxDec(COMPONENT_NAME, id,
841 std::make_shared<C2SoftVpxDec::IntfImpl>(mHelper)),
842 deleter);
843 return C2_OK;
844 }
845
846 virtual c2_status_t createInterface(
847 c2_node_id_t id,
848 std::shared_ptr<C2ComponentInterface>* const interface,
849 std::function<void(C2ComponentInterface*)> deleter) override {
850 *interface = std::shared_ptr<C2ComponentInterface>(
851 new SimpleInterface<C2SoftVpxDec::IntfImpl>(
852 COMPONENT_NAME, id,
853 std::make_shared<C2SoftVpxDec::IntfImpl>(mHelper)),
854 deleter);
855 return C2_OK;
856 }
857
858 virtual ~C2SoftVpxFactory() override = default;
859
860private:
861 std::shared_ptr<C2ReflectorHelper> mHelper;
862};
863
864} // namespace android
865
Cindy Zhouf6c0c3c2020-12-02 10:53:40 -0800866__attribute__((cfi_canonical_jump_table))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800867extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
868 ALOGV("in %s", __func__);
869 return new ::android::C2SoftVpxFactory();
870}
871
Cindy Zhouf6c0c3c2020-12-02 10:53:40 -0800872__attribute__((cfi_canonical_jump_table))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800873extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
874 ALOGV("in %s", __func__);
875 delete factory;
876}