1 /*
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
21 #include <algorithm>
22
23 #include <media/stagefright/foundation/AUtils.h>
24 #include <media/stagefright/foundation/MediaDefs.h>
25
26 #include <C2Debug.h>
27 #include <C2PlatformSupport.h>
28 #include <SimpleC2Interface.h>
29
30 #include "C2SoftVpxDec.h"
31
32 namespace android {
33
34 #ifdef VP9
35 constexpr char COMPONENT_NAME[] = "c2.android.vp9.decoder";
36 #else
37 constexpr char COMPONENT_NAME[] = "c2.android.vp8.decoder";
38 #endif
39
40 class C2SoftVpxDec::IntfImpl : public SimpleInterface<void>::BaseParams {
41 public:
IntfImpl(const std::shared_ptr<C2ReflectorHelper> & helper)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
102 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
122 #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)
152 .withConstValue(new C2StreamProfileLevelInfo::input(0u,
153 C2Config::PROFILE_UNUSED, C2Config::LEVEL_UNUSED))
154 .build());
155 #endif
156
157 addParameter(
158 DefineParam(mMaxSize, C2_PARAMKEY_MAX_PICTURE_SIZE)
159 .withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 320, 240))
160 .withFields({
161 C2F(mSize, width).inRange(2, 2048, 2),
162 C2F(mSize, height).inRange(2, 2048, 2),
163 })
164 .withSetter(MaxPictureSizeSetter, mSize)
165 .build());
166
167 addParameter(
168 DefineParam(mMaxInputSize, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE)
169 .withDefault(new C2StreamMaxBufferSizeInfo::input(0u, 320 * 240 * 3 / 4))
170 .withFields({
171 C2F(mMaxInputSize, value).any(),
172 })
173 .calculatedAs(MaxInputSizeSetter, mMaxSize)
174 .build());
175
176 C2ChromaOffsetStruct locations[1] = { C2ChromaOffsetStruct::ITU_YUV_420_0() };
177 std::shared_ptr<C2StreamColorInfo::output> defaultColorInfo =
178 C2StreamColorInfo::output::AllocShared(
179 1u, 0u, 8u /* bitDepth */, C2Color::YUV_420);
180 memcpy(defaultColorInfo->m.locations, locations, sizeof(locations));
181
182 defaultColorInfo =
183 C2StreamColorInfo::output::AllocShared(
184 { C2ChromaOffsetStruct::ITU_YUV_420_0() },
185 0u, 8u /* bitDepth */, C2Color::YUV_420);
186 helper->addStructDescriptors<C2ChromaOffsetStruct>();
187
188 addParameter(
189 DefineParam(mColorInfo, C2_PARAMKEY_CODED_COLOR_INFO)
190 .withConstValue(defaultColorInfo)
191 .build());
192
193 addParameter(
194 DefineParam(mDefaultColorAspects, C2_PARAMKEY_DEFAULT_COLOR_ASPECTS)
195 .withDefault(new C2StreamColorAspectsTuning::output(
196 0u, C2Color::RANGE_UNSPECIFIED, C2Color::PRIMARIES_UNSPECIFIED,
197 C2Color::TRANSFER_UNSPECIFIED, C2Color::MATRIX_UNSPECIFIED))
198 .withFields({
199 C2F(mDefaultColorAspects, range).inRange(
200 C2Color::RANGE_UNSPECIFIED, C2Color::RANGE_OTHER),
201 C2F(mDefaultColorAspects, primaries).inRange(
202 C2Color::PRIMARIES_UNSPECIFIED, C2Color::PRIMARIES_OTHER),
203 C2F(mDefaultColorAspects, transfer).inRange(
204 C2Color::TRANSFER_UNSPECIFIED, C2Color::TRANSFER_OTHER),
205 C2F(mDefaultColorAspects, matrix).inRange(
206 C2Color::MATRIX_UNSPECIFIED, C2Color::MATRIX_OTHER)
207 })
208 .withSetter(DefaultColorAspectsSetter)
209 .build());
210
211 // TODO: support more formats?
212 addParameter(
213 DefineParam(mPixelFormat, C2_PARAMKEY_PIXEL_FORMAT)
214 .withConstValue(new C2StreamPixelFormatInfo::output(
215 0u, HAL_PIXEL_FORMAT_YCBCR_420_888))
216 .build());
217 }
218
SizeSetter(bool mayBlock,const C2P<C2StreamPictureSizeInfo::output> & oldMe,C2P<C2StreamPictureSizeInfo::output> & me)219 static C2R SizeSetter(bool mayBlock, const C2P<C2StreamPictureSizeInfo::output> &oldMe,
220 C2P<C2StreamPictureSizeInfo::output> &me) {
221 (void)mayBlock;
222 C2R res = C2R::Ok();
223 if (!me.F(me.v.width).supportsAtAll(me.v.width)) {
224 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.width)));
225 me.set().width = oldMe.v.width;
226 }
227 if (!me.F(me.v.height).supportsAtAll(me.v.height)) {
228 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.height)));
229 me.set().height = oldMe.v.height;
230 }
231 return res;
232 }
233
MaxPictureSizeSetter(bool mayBlock,C2P<C2StreamMaxPictureSizeTuning::output> & me,const C2P<C2StreamPictureSizeInfo::output> & size)234 static C2R MaxPictureSizeSetter(bool mayBlock, C2P<C2StreamMaxPictureSizeTuning::output> &me,
235 const C2P<C2StreamPictureSizeInfo::output> &size) {
236 (void)mayBlock;
237 // TODO: get max width/height from the size's field helpers vs. hardcoding
238 me.set().width = c2_min(c2_max(me.v.width, size.v.width), 2048u);
239 me.set().height = c2_min(c2_max(me.v.height, size.v.height), 2048u);
240 return C2R::Ok();
241 }
242
MaxInputSizeSetter(bool mayBlock,C2P<C2StreamMaxBufferSizeInfo::input> & me,const C2P<C2StreamMaxPictureSizeTuning::output> & maxSize)243 static C2R MaxInputSizeSetter(bool mayBlock, C2P<C2StreamMaxBufferSizeInfo::input> &me,
244 const C2P<C2StreamMaxPictureSizeTuning::output> &maxSize) {
245 (void)mayBlock;
246 // assume compression ratio of 2
247 me.set().value = (((maxSize.v.width + 63) / 64) * ((maxSize.v.height + 63) / 64) * 3072);
248 return C2R::Ok();
249 }
250
DefaultColorAspectsSetter(bool mayBlock,C2P<C2StreamColorAspectsTuning::output> & me)251 static C2R DefaultColorAspectsSetter(bool mayBlock, C2P<C2StreamColorAspectsTuning::output> &me) {
252 (void)mayBlock;
253 if (me.v.range > C2Color::RANGE_OTHER) {
254 me.set().range = C2Color::RANGE_OTHER;
255 }
256 if (me.v.primaries > C2Color::PRIMARIES_OTHER) {
257 me.set().primaries = C2Color::PRIMARIES_OTHER;
258 }
259 if (me.v.transfer > C2Color::TRANSFER_OTHER) {
260 me.set().transfer = C2Color::TRANSFER_OTHER;
261 }
262 if (me.v.matrix > C2Color::MATRIX_OTHER) {
263 me.set().matrix = C2Color::MATRIX_OTHER;
264 }
265 return C2R::Ok();
266 }
267
ProfileLevelSetter(bool mayBlock,C2P<C2StreamProfileLevelInfo::input> & me,const C2P<C2StreamPictureSizeInfo::output> & size)268 static C2R ProfileLevelSetter(bool mayBlock, C2P<C2StreamProfileLevelInfo::input> &me,
269 const C2P<C2StreamPictureSizeInfo::output> &size) {
270 (void)mayBlock;
271 (void)size;
272 (void)me; // TODO: validate
273 return C2R::Ok();
274 }
getDefaultColorAspects_l()275 std::shared_ptr<C2StreamColorAspectsTuning::output> getDefaultColorAspects_l() {
276 return mDefaultColorAspects;
277 }
278
Hdr10PlusInfoInputSetter(bool mayBlock,C2P<C2StreamHdr10PlusInfo::input> & me)279 static C2R Hdr10PlusInfoInputSetter(bool mayBlock, C2P<C2StreamHdr10PlusInfo::input> &me) {
280 (void)mayBlock;
281 (void)me; // TODO: validate
282 return C2R::Ok();
283 }
284
Hdr10PlusInfoOutputSetter(bool mayBlock,C2P<C2StreamHdr10PlusInfo::output> & me)285 static C2R Hdr10PlusInfoOutputSetter(bool mayBlock, C2P<C2StreamHdr10PlusInfo::output> &me) {
286 (void)mayBlock;
287 (void)me; // TODO: validate
288 return C2R::Ok();
289 }
290
291 private:
292 std::shared_ptr<C2StreamProfileLevelInfo::input> mProfileLevel;
293 std::shared_ptr<C2StreamPictureSizeInfo::output> mSize;
294 std::shared_ptr<C2StreamMaxPictureSizeTuning::output> mMaxSize;
295 std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mMaxInputSize;
296 std::shared_ptr<C2StreamColorInfo::output> mColorInfo;
297 std::shared_ptr<C2StreamPixelFormatInfo::output> mPixelFormat;
298 std::shared_ptr<C2StreamColorAspectsTuning::output> mDefaultColorAspects;
299 #ifdef VP9
300 #if 0
301 std::shared_ptr<C2StreamHdrStaticInfo::output> mHdrStaticInfo;
302 #endif
303 std::shared_ptr<C2StreamHdr10PlusInfo::input> mHdr10PlusInfoInput;
304 std::shared_ptr<C2StreamHdr10PlusInfo::output> mHdr10PlusInfoOutput;
305 #endif
306 };
307
ConverterThread(const std::shared_ptr<Mutexed<ConversionQueue>> & queue)308 C2SoftVpxDec::ConverterThread::ConverterThread(
309 const std::shared_ptr<Mutexed<ConversionQueue>> &queue)
310 : Thread(false), mQueue(queue) {}
311
threadLoop()312 bool C2SoftVpxDec::ConverterThread::threadLoop() {
313 Mutexed<ConversionQueue>::Locked queue(*mQueue);
314 if (queue->entries.empty()) {
315 queue.waitForCondition(queue->cond);
316 if (queue->entries.empty()) {
317 return true;
318 }
319 }
320 std::function<void()> convert = queue->entries.front();
321 queue->entries.pop_front();
322 if (!queue->entries.empty()) {
323 queue->cond.signal();
324 }
325 queue.unlock();
326
327 convert();
328
329 queue.lock();
330 if (--queue->numPending == 0u) {
331 queue->cond.broadcast();
332 }
333 return true;
334 }
335
C2SoftVpxDec(const char * name,c2_node_id_t id,const std::shared_ptr<IntfImpl> & intfImpl)336 C2SoftVpxDec::C2SoftVpxDec(
337 const char *name,
338 c2_node_id_t id,
339 const std::shared_ptr<IntfImpl> &intfImpl)
340 : SimpleC2Component(std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
341 mIntf(intfImpl),
342 mCodecCtx(nullptr),
343 mCoreCount(1),
344 mQueue(new Mutexed<ConversionQueue>) {
345 }
346
~C2SoftVpxDec()347 C2SoftVpxDec::~C2SoftVpxDec() {
348 onRelease();
349 }
350
onInit()351 c2_status_t C2SoftVpxDec::onInit() {
352 status_t err = initDecoder();
353 return err == OK ? C2_OK : C2_CORRUPTED;
354 }
355
onStop()356 c2_status_t C2SoftVpxDec::onStop() {
357 mSignalledError = false;
358 mSignalledOutputEos = false;
359
360 return C2_OK;
361 }
362
onReset()363 void C2SoftVpxDec::onReset() {
364 (void)onStop();
365 c2_status_t err = onFlush_sm();
366 if (err != C2_OK)
367 {
368 ALOGW("Failed to flush decoder. Try to hard reset decoder");
369 destroyDecoder();
370 (void)initDecoder();
371 }
372 }
373
onRelease()374 void C2SoftVpxDec::onRelease() {
375 destroyDecoder();
376 }
377
onFlush_sm()378 c2_status_t C2SoftVpxDec::onFlush_sm() {
379 if (mFrameParallelMode) {
380 // Flush decoder by passing nullptr data ptr and 0 size.
381 // Ideally, this should never fail.
382 if (vpx_codec_decode(mCodecCtx, nullptr, 0, nullptr, 0)) {
383 ALOGE("Failed to flush on2 decoder.");
384 return C2_CORRUPTED;
385 }
386 }
387
388 // Drop all the decoded frames in decoder.
389 vpx_codec_iter_t iter = nullptr;
390 while (vpx_codec_get_frame(mCodecCtx, &iter)) {
391 }
392
393 mSignalledError = false;
394 mSignalledOutputEos = false;
395 return C2_OK;
396 }
397
GetCPUCoreCount()398 static int GetCPUCoreCount() {
399 int cpuCoreCount = 1;
400 #if defined(_SC_NPROCESSORS_ONLN)
401 cpuCoreCount = sysconf(_SC_NPROCESSORS_ONLN);
402 #else
403 // _SC_NPROC_ONLN must be defined...
404 cpuCoreCount = sysconf(_SC_NPROC_ONLN);
405 #endif
406 CHECK(cpuCoreCount >= 1);
407 ALOGV("Number of CPU cores: %d", cpuCoreCount);
408 return cpuCoreCount;
409 }
410
initDecoder()411 status_t C2SoftVpxDec::initDecoder() {
412 #ifdef VP9
413 mMode = MODE_VP9;
414 #else
415 mMode = MODE_VP8;
416 #endif
417
418 mWidth = 320;
419 mHeight = 240;
420 mFrameParallelMode = false;
421 mSignalledOutputEos = false;
422 mSignalledError = false;
423
424 if (!mCodecCtx) {
425 mCodecCtx = new vpx_codec_ctx_t;
426 }
427 if (!mCodecCtx) {
428 ALOGE("mCodecCtx is null");
429 return NO_MEMORY;
430 }
431
432 vpx_codec_dec_cfg_t cfg;
433 memset(&cfg, 0, sizeof(vpx_codec_dec_cfg_t));
434 cfg.threads = mCoreCount = GetCPUCoreCount();
435
436 vpx_codec_flags_t flags;
437 memset(&flags, 0, sizeof(vpx_codec_flags_t));
438 if (mFrameParallelMode) flags |= VPX_CODEC_USE_FRAME_THREADING;
439
440 vpx_codec_err_t vpx_err;
441 if ((vpx_err = vpx_codec_dec_init(
442 mCodecCtx, mMode == MODE_VP8 ? &vpx_codec_vp8_dx_algo : &vpx_codec_vp9_dx_algo,
443 &cfg, flags))) {
444 ALOGE("on2 decoder failed to initialize. (%d)", vpx_err);
445 return UNKNOWN_ERROR;
446 }
447
448 if (mMode == MODE_VP9) {
449 using namespace std::string_literals;
450 for (int i = 0; i < mCoreCount; ++i) {
451 sp<ConverterThread> thread(new ConverterThread(mQueue));
452 mConverterThreads.push_back(thread);
453 if (thread->run(("vp9conv #"s + std::to_string(i)).c_str(),
454 ANDROID_PRIORITY_AUDIO) != OK) {
455 return UNKNOWN_ERROR;
456 }
457 }
458 }
459
460 return OK;
461 }
462
destroyDecoder()463 status_t C2SoftVpxDec::destroyDecoder() {
464 if (mCodecCtx) {
465 vpx_codec_destroy(mCodecCtx);
466 delete mCodecCtx;
467 mCodecCtx = nullptr;
468 }
469 bool running = true;
470 for (const sp<ConverterThread> &thread : mConverterThreads) {
471 thread->requestExit();
472 }
473 while (running) {
474 mQueue->lock()->cond.broadcast();
475 running = false;
476 for (const sp<ConverterThread> &thread : mConverterThreads) {
477 if (thread->isRunning()) {
478 running = true;
479 break;
480 }
481 }
482 }
483 mConverterThreads.clear();
484
485 return OK;
486 }
487
fillEmptyWork(const std::unique_ptr<C2Work> & work)488 void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
489 uint32_t flags = 0;
490 if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
491 flags |= C2FrameData::FLAG_END_OF_STREAM;
492 ALOGV("signalling eos");
493 }
494 work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
495 work->worklets.front()->output.buffers.clear();
496 work->worklets.front()->output.ordinal = work->input.ordinal;
497 work->workletsProcessed = 1u;
498 }
499
finishWork(uint64_t index,const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2GraphicBlock> & block)500 void C2SoftVpxDec::finishWork(uint64_t index, const std::unique_ptr<C2Work> &work,
501 const std::shared_ptr<C2GraphicBlock> &block) {
502 std::shared_ptr<C2Buffer> buffer = createGraphicBuffer(block,
503 C2Rect(mWidth, mHeight));
504 auto fillWork = [buffer, index, intf = this->mIntf](
505 const std::unique_ptr<C2Work> &work) {
506 uint32_t flags = 0;
507 if ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) &&
508 (c2_cntr64_t(index) == work->input.ordinal.frameIndex)) {
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.buffers.push_back(buffer);
515 work->worklets.front()->output.ordinal = work->input.ordinal;
516 work->workletsProcessed = 1u;
517
518 for (const std::unique_ptr<C2Param> ¶m: work->input.configUpdate) {
519 if (param) {
520 C2StreamHdr10PlusInfo::input *hdr10PlusInfo =
521 C2StreamHdr10PlusInfo::input::From(param.get());
522
523 if (hdr10PlusInfo != nullptr) {
524 std::vector<std::unique_ptr<C2SettingResult>> failures;
525 std::unique_ptr<C2Param> outParam = C2Param::CopyAsStream(
526 *param.get(), true /*output*/, param->stream());
527 c2_status_t err = intf->config(
528 { outParam.get() }, C2_MAY_BLOCK, &failures);
529 if (err == C2_OK) {
530 work->worklets.front()->output.configUpdate.push_back(
531 C2Param::Copy(*outParam.get()));
532 } else {
533 ALOGE("finishWork: Config update size failed");
534 }
535 break;
536 }
537 }
538 }
539 };
540 if (work && c2_cntr64_t(index) == work->input.ordinal.frameIndex) {
541 fillWork(work);
542 } else {
543 finish(index, fillWork);
544 }
545 }
546
process(const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2BlockPool> & pool)547 void C2SoftVpxDec::process(
548 const std::unique_ptr<C2Work> &work,
549 const std::shared_ptr<C2BlockPool> &pool) {
550 // Initialize output work
551 work->result = C2_OK;
552 work->workletsProcessed = 0u;
553 work->worklets.front()->output.configUpdate.clear();
554 work->worklets.front()->output.flags = work->input.flags;
555
556 if (mSignalledError || mSignalledOutputEos) {
557 work->result = C2_BAD_VALUE;
558 return;
559 }
560
561 size_t inOffset = 0u;
562 size_t inSize = 0u;
563 C2ReadView rView = mDummyReadView;
564 if (!work->input.buffers.empty()) {
565 rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
566 inSize = rView.capacity();
567 if (inSize && rView.error()) {
568 ALOGE("read view map failed %d", rView.error());
569 work->result = C2_CORRUPTED;
570 return;
571 }
572 }
573
574 bool codecConfig = ((work->input.flags & C2FrameData::FLAG_CODEC_CONFIG) !=0);
575 bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
576
577 ALOGV("in buffer attr. size %zu timestamp %d frameindex %d, flags %x",
578 inSize, (int)work->input.ordinal.timestamp.peeku(),
579 (int)work->input.ordinal.frameIndex.peeku(), work->input.flags);
580
581 // Software VP9 Decoder does not need the Codec Specific Data (CSD)
582 // (specified in http://www.webmproject.org/vp9/profiles/). Ignore it if
583 // it was passed.
584 if (codecConfig) {
585 // Ignore CSD buffer for VP9.
586 if (mMode == MODE_VP9) {
587 fillEmptyWork(work);
588 return;
589 } else {
590 // Tolerate the CSD buffer for VP8. This is a workaround
591 // for b/28689536. continue
592 ALOGW("WARNING: Got CSD buffer for VP8. Continue");
593 }
594 }
595
596 int64_t frameIndex = work->input.ordinal.frameIndex.peekll();
597
598 if (inSize) {
599 uint8_t *bitstream = const_cast<uint8_t *>(rView.data() + inOffset);
600 vpx_codec_err_t err = vpx_codec_decode(
601 mCodecCtx, bitstream, inSize, &frameIndex, 0);
602 if (err != VPX_CODEC_OK) {
603 ALOGE("on2 decoder failed to decode frame. err: %d", err);
604 mSignalledError = true;
605 work->workletsProcessed = 1u;
606 work->result = C2_CORRUPTED;
607 return;
608 }
609 }
610
611 (void)outputBuffer(pool, work);
612
613 if (eos) {
614 drainInternal(DRAIN_COMPONENT_WITH_EOS, pool, work);
615 mSignalledOutputEos = true;
616 } else if (!inSize) {
617 fillEmptyWork(work);
618 }
619 }
620
copyOutputBufferToYuvPlanarFrame(uint8_t * dst,const uint8_t * srcY,const uint8_t * srcU,const uint8_t * srcV,size_t srcYStride,size_t srcUStride,size_t srcVStride,size_t dstYStride,size_t dstUVStride,uint32_t width,uint32_t height)621 static void copyOutputBufferToYuvPlanarFrame(
622 uint8_t *dst, const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV,
623 size_t srcYStride, size_t srcUStride, size_t srcVStride,
624 size_t dstYStride, size_t dstUVStride,
625 uint32_t width, uint32_t height) {
626 uint8_t *dstStart = dst;
627
628 for (size_t i = 0; i < height; ++i) {
629 memcpy(dst, srcY, width);
630 srcY += srcYStride;
631 dst += dstYStride;
632 }
633
634 dst = dstStart + dstYStride * height;
635 for (size_t i = 0; i < height / 2; ++i) {
636 memcpy(dst, srcV, width / 2);
637 srcV += srcVStride;
638 dst += dstUVStride;
639 }
640
641 dst = dstStart + (dstYStride * height) + (dstUVStride * height / 2);
642 for (size_t i = 0; i < height / 2; ++i) {
643 memcpy(dst, srcU, width / 2);
644 srcU += srcUStride;
645 dst += dstUVStride;
646 }
647 }
648
convertYUV420Planar16ToY410(uint32_t * dst,const uint16_t * srcY,const uint16_t * srcU,const uint16_t * srcV,size_t srcYStride,size_t srcUStride,size_t srcVStride,size_t dstStride,size_t width,size_t height)649 static void convertYUV420Planar16ToY410(uint32_t *dst,
650 const uint16_t *srcY, const uint16_t *srcU, const uint16_t *srcV,
651 size_t srcYStride, size_t srcUStride, size_t srcVStride,
652 size_t dstStride, size_t width, size_t height) {
653
654 // Converting two lines at a time, slightly faster
655 for (size_t y = 0; y < height; y += 2) {
656 uint32_t *dstTop = (uint32_t *) dst;
657 uint32_t *dstBot = (uint32_t *) (dst + dstStride);
658 uint16_t *ySrcTop = (uint16_t*) srcY;
659 uint16_t *ySrcBot = (uint16_t*) (srcY + srcYStride);
660 uint16_t *uSrc = (uint16_t*) srcU;
661 uint16_t *vSrc = (uint16_t*) srcV;
662
663 uint32_t u01, v01, y01, y23, y45, y67, uv0, uv1;
664 size_t x = 0;
665 for (; x < width - 3; x += 4) {
666
667 u01 = *((uint32_t*)uSrc); uSrc += 2;
668 v01 = *((uint32_t*)vSrc); vSrc += 2;
669
670 y01 = *((uint32_t*)ySrcTop); ySrcTop += 2;
671 y23 = *((uint32_t*)ySrcTop); ySrcTop += 2;
672 y45 = *((uint32_t*)ySrcBot); ySrcBot += 2;
673 y67 = *((uint32_t*)ySrcBot); ySrcBot += 2;
674
675 uv0 = (u01 & 0x3FF) | ((v01 & 0x3FF) << 20);
676 uv1 = (u01 >> 16) | ((v01 >> 16) << 20);
677
678 *dstTop++ = 3 << 30 | ((y01 & 0x3FF) << 10) | uv0;
679 *dstTop++ = 3 << 30 | ((y01 >> 16) << 10) | uv0;
680 *dstTop++ = 3 << 30 | ((y23 & 0x3FF) << 10) | uv1;
681 *dstTop++ = 3 << 30 | ((y23 >> 16) << 10) | uv1;
682
683 *dstBot++ = 3 << 30 | ((y45 & 0x3FF) << 10) | uv0;
684 *dstBot++ = 3 << 30 | ((y45 >> 16) << 10) | uv0;
685 *dstBot++ = 3 << 30 | ((y67 & 0x3FF) << 10) | uv1;
686 *dstBot++ = 3 << 30 | ((y67 >> 16) << 10) | uv1;
687 }
688
689 // There should be at most 2 more pixels to process. Note that we don't
690 // need to consider odd case as the buffer is always aligned to even.
691 if (x < width) {
692 u01 = *uSrc;
693 v01 = *vSrc;
694 y01 = *((uint32_t*)ySrcTop);
695 y45 = *((uint32_t*)ySrcBot);
696 uv0 = (u01 & 0x3FF) | ((v01 & 0x3FF) << 20);
697 *dstTop++ = ((y01 & 0x3FF) << 10) | uv0;
698 *dstTop++ = ((y01 >> 16) << 10) | uv0;
699 *dstBot++ = ((y45 & 0x3FF) << 10) | uv0;
700 *dstBot++ = ((y45 >> 16) << 10) | uv0;
701 }
702
703 srcY += srcYStride * 2;
704 srcU += srcUStride;
705 srcV += srcVStride;
706 dst += dstStride * 2;
707 }
708
709 return;
710 }
711
convertYUV420Planar16ToYUV420Planar(uint8_t * dst,const uint16_t * srcY,const uint16_t * srcU,const uint16_t * srcV,size_t srcYStride,size_t srcUStride,size_t srcVStride,size_t dstYStride,size_t dstUVStride,size_t width,size_t height)712 static void convertYUV420Planar16ToYUV420Planar(uint8_t *dst,
713 const uint16_t *srcY, const uint16_t *srcU, const uint16_t *srcV,
714 size_t srcYStride, size_t srcUStride, size_t srcVStride,
715 size_t dstYStride, size_t dstUVStride, size_t width, size_t height) {
716
717 uint8_t *dstY = (uint8_t *)dst;
718 size_t dstYSize = dstYStride * height;
719 size_t dstUVSize = dstUVStride * height / 2;
720 uint8_t *dstV = dstY + dstYSize;
721 uint8_t *dstU = dstV + dstUVSize;
722
723 for (size_t y = 0; y < height; ++y) {
724 for (size_t x = 0; x < width; ++x) {
725 dstY[x] = (uint8_t)(srcY[x] >> 2);
726 }
727
728 srcY += srcYStride;
729 dstY += dstYStride;
730 }
731
732 for (size_t y = 0; y < (height + 1) / 2; ++y) {
733 for (size_t x = 0; x < (width + 1) / 2; ++x) {
734 dstU[x] = (uint8_t)(srcU[x] >> 2);
735 dstV[x] = (uint8_t)(srcV[x] >> 2);
736 }
737
738 srcU += srcUStride;
739 srcV += srcVStride;
740 dstU += dstUVStride;
741 dstV += dstUVStride;
742 }
743 return;
744 }
outputBuffer(const std::shared_ptr<C2BlockPool> & pool,const std::unique_ptr<C2Work> & work)745 bool C2SoftVpxDec::outputBuffer(
746 const std::shared_ptr<C2BlockPool> &pool,
747 const std::unique_ptr<C2Work> &work)
748 {
749 if (!(work && pool)) return false;
750
751 vpx_codec_iter_t iter = nullptr;
752 vpx_image_t *img = vpx_codec_get_frame(mCodecCtx, &iter);
753
754 if (!img) return false;
755
756 if (img->d_w != mWidth || img->d_h != mHeight) {
757 mWidth = img->d_w;
758 mHeight = img->d_h;
759
760 C2StreamPictureSizeInfo::output size(0u, mWidth, mHeight);
761 std::vector<std::unique_ptr<C2SettingResult>> failures;
762 c2_status_t err = mIntf->config({&size}, C2_MAY_BLOCK, &failures);
763 if (err == C2_OK) {
764 work->worklets.front()->output.configUpdate.push_back(
765 C2Param::Copy(size));
766 } else {
767 ALOGE("Config update size failed");
768 mSignalledError = true;
769 work->workletsProcessed = 1u;
770 work->result = C2_CORRUPTED;
771 return false;
772 }
773
774 }
775 CHECK(img->fmt == VPX_IMG_FMT_I420 || img->fmt == VPX_IMG_FMT_I42016);
776
777 std::shared_ptr<C2GraphicBlock> block;
778 uint32_t format = HAL_PIXEL_FORMAT_YV12;
779 if (img->fmt == VPX_IMG_FMT_I42016) {
780 IntfImpl::Lock lock = mIntf->lock();
781 std::shared_ptr<C2StreamColorAspectsTuning::output> defaultColorAspects = mIntf->getDefaultColorAspects_l();
782
783 if (defaultColorAspects->primaries == C2Color::PRIMARIES_BT2020 &&
784 defaultColorAspects->matrix == C2Color::MATRIX_BT2020 &&
785 defaultColorAspects->transfer == C2Color::TRANSFER_ST2084) {
786 format = HAL_PIXEL_FORMAT_RGBA_1010102;
787 }
788 }
789 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
790 c2_status_t err = pool->fetchGraphicBlock(align(mWidth, 16), mHeight, format, usage, &block);
791 if (err != C2_OK) {
792 ALOGE("fetchGraphicBlock for Output failed with status %d", err);
793 work->result = err;
794 return false;
795 }
796
797 C2GraphicView wView = block->map().get();
798 if (wView.error()) {
799 ALOGE("graphic view map failed %d", wView.error());
800 work->result = C2_CORRUPTED;
801 return false;
802 }
803
804 ALOGV("provided (%dx%d) required (%dx%d), out frameindex %d",
805 block->width(), block->height(), mWidth, mHeight, (int)*(int64_t *)img->user_priv);
806
807 uint8_t *dst = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
808 size_t srcYStride = img->stride[VPX_PLANE_Y];
809 size_t srcUStride = img->stride[VPX_PLANE_U];
810 size_t srcVStride = img->stride[VPX_PLANE_V];
811 C2PlanarLayout layout = wView.layout();
812 size_t dstYStride = layout.planes[C2PlanarLayout::PLANE_Y].rowInc;
813 size_t dstUVStride = layout.planes[C2PlanarLayout::PLANE_U].rowInc;
814
815 if (img->fmt == VPX_IMG_FMT_I42016) {
816 const uint16_t *srcY = (const uint16_t *)img->planes[VPX_PLANE_Y];
817 const uint16_t *srcU = (const uint16_t *)img->planes[VPX_PLANE_U];
818 const uint16_t *srcV = (const uint16_t *)img->planes[VPX_PLANE_V];
819
820 if (format == HAL_PIXEL_FORMAT_RGBA_1010102) {
821 Mutexed<ConversionQueue>::Locked queue(*mQueue);
822 size_t i = 0;
823 constexpr size_t kHeight = 64;
824 for (; i < mHeight; i += kHeight) {
825 queue->entries.push_back(
826 [dst, srcY, srcU, srcV,
827 srcYStride, srcUStride, srcVStride, dstYStride,
828 width = mWidth, height = std::min(mHeight - i, kHeight)] {
829 convertYUV420Planar16ToY410(
830 (uint32_t *)dst, srcY, srcU, srcV, srcYStride / 2,
831 srcUStride / 2, srcVStride / 2, dstYStride / sizeof(uint32_t),
832 width, height);
833 });
834 srcY += srcYStride / 2 * kHeight;
835 srcU += srcUStride / 2 * (kHeight / 2);
836 srcV += srcVStride / 2 * (kHeight / 2);
837 dst += dstYStride * kHeight;
838 }
839 CHECK_EQ(0u, queue->numPending);
840 queue->numPending = queue->entries.size();
841 while (queue->numPending > 0) {
842 queue->cond.signal();
843 queue.waitForCondition(queue->cond);
844 }
845 } else {
846 convertYUV420Planar16ToYUV420Planar(dst, srcY, srcU, srcV, srcYStride / 2,
847 srcUStride / 2, srcVStride / 2,
848 dstYStride, dstUVStride,
849 mWidth, mHeight);
850 }
851 } else {
852 const uint8_t *srcY = (const uint8_t *)img->planes[VPX_PLANE_Y];
853 const uint8_t *srcU = (const uint8_t *)img->planes[VPX_PLANE_U];
854 const uint8_t *srcV = (const uint8_t *)img->planes[VPX_PLANE_V];
855 copyOutputBufferToYuvPlanarFrame(
856 dst, srcY, srcU, srcV,
857 srcYStride, srcUStride, srcVStride,
858 dstYStride, dstUVStride,
859 mWidth, mHeight);
860 }
861 finishWork(*(int64_t *)img->user_priv, work, std::move(block));
862 return true;
863 }
864
drainInternal(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool,const std::unique_ptr<C2Work> & work)865 c2_status_t C2SoftVpxDec::drainInternal(
866 uint32_t drainMode,
867 const std::shared_ptr<C2BlockPool> &pool,
868 const std::unique_ptr<C2Work> &work) {
869 if (drainMode == NO_DRAIN) {
870 ALOGW("drain with NO_DRAIN: no-op");
871 return C2_OK;
872 }
873 if (drainMode == DRAIN_CHAIN) {
874 ALOGW("DRAIN_CHAIN not supported");
875 return C2_OMITTED;
876 }
877
878 while ((outputBuffer(pool, work))) {
879 }
880
881 if (drainMode == DRAIN_COMPONENT_WITH_EOS &&
882 work && work->workletsProcessed == 0u) {
883 fillEmptyWork(work);
884 }
885
886 return C2_OK;
887 }
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)888 c2_status_t C2SoftVpxDec::drain(
889 uint32_t drainMode,
890 const std::shared_ptr<C2BlockPool> &pool) {
891 return drainInternal(drainMode, pool, nullptr);
892 }
893
894 class C2SoftVpxFactory : public C2ComponentFactory {
895 public:
C2SoftVpxFactory()896 C2SoftVpxFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
897 GetCodec2PlatformComponentStore()->getParamReflector())) {
898 }
899
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)900 virtual c2_status_t createComponent(
901 c2_node_id_t id,
902 std::shared_ptr<C2Component>* const component,
903 std::function<void(C2Component*)> deleter) override {
904 *component = std::shared_ptr<C2Component>(
905 new C2SoftVpxDec(COMPONENT_NAME, id,
906 std::make_shared<C2SoftVpxDec::IntfImpl>(mHelper)),
907 deleter);
908 return C2_OK;
909 }
910
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)911 virtual c2_status_t createInterface(
912 c2_node_id_t id,
913 std::shared_ptr<C2ComponentInterface>* const interface,
914 std::function<void(C2ComponentInterface*)> deleter) override {
915 *interface = std::shared_ptr<C2ComponentInterface>(
916 new SimpleInterface<C2SoftVpxDec::IntfImpl>(
917 COMPONENT_NAME, id,
918 std::make_shared<C2SoftVpxDec::IntfImpl>(mHelper)),
919 deleter);
920 return C2_OK;
921 }
922
923 virtual ~C2SoftVpxFactory() override = default;
924
925 private:
926 std::shared_ptr<C2ReflectorHelper> mHelper;
927 };
928
929 } // namespace android
930
CreateCodec2Factory()931 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
932 ALOGV("in %s", __func__);
933 return new ::android::C2SoftVpxFactory();
934 }
935
DestroyCodec2Factory(::C2ComponentFactory * factory)936 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
937 ALOGV("in %s", __func__);
938 delete factory;
939 }
940