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 <media/stagefright/foundation/AUtils.h>
22 #include <media/stagefright/foundation/MediaDefs.h>
23
24 #include <C2Debug.h>
25 #include <C2PlatformSupport.h>
26 #include <SimpleC2Interface.h>
27
28 #include "C2SoftVpxDec.h"
29
30 namespace android {
31
32 #ifdef VP9
33 constexpr char COMPONENT_NAME[] = "c2.android.vp9.decoder";
34 #else
35 constexpr char COMPONENT_NAME[] = "c2.android.vp8.decoder";
36 #endif
37
38 class C2SoftVpxDec::IntfImpl : public SimpleInterface<void>::BaseParams {
39 public:
IntfImpl(const std::shared_ptr<C2ReflectorHelper> & helper)40 explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
41 : SimpleInterface<void>::BaseParams(
42 helper,
43 COMPONENT_NAME,
44 C2Component::KIND_DECODER,
45 C2Component::DOMAIN_VIDEO,
46 #ifdef VP9
47 MEDIA_MIMETYPE_VIDEO_VP9
48 #else
49 MEDIA_MIMETYPE_VIDEO_VP8
50 #endif
51 ) {
52 noPrivateBuffers(); // TODO: account for our buffers here
53 noInputReferences();
54 noOutputReferences();
55 noInputLatency();
56 noTimeStretch();
57
58 // TODO: output latency and reordering
59
60 addParameter(
61 DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
62 .withConstValue(new C2ComponentAttributesSetting(C2Component::ATTRIB_IS_TEMPORAL))
63 .build());
64
65 addParameter(
66 DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
67 .withDefault(new C2StreamPictureSizeInfo::output(0u, 320, 240))
68 .withFields({
69 C2F(mSize, width).inRange(2, 2048, 2),
70 C2F(mSize, height).inRange(2, 2048, 2),
71 })
72 .withSetter(SizeSetter)
73 .build());
74
75 #ifdef VP9
76 // TODO: Add C2Config::PROFILE_VP9_2HDR ??
77 addParameter(
78 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
79 .withDefault(new C2StreamProfileLevelInfo::input(0u,
80 C2Config::PROFILE_VP9_0, C2Config::LEVEL_VP9_5))
81 .withFields({
82 C2F(mProfileLevel, profile).oneOf({
83 C2Config::PROFILE_VP9_0,
84 C2Config::PROFILE_VP9_2}),
85 C2F(mProfileLevel, level).oneOf({
86 C2Config::LEVEL_VP9_1,
87 C2Config::LEVEL_VP9_1_1,
88 C2Config::LEVEL_VP9_2,
89 C2Config::LEVEL_VP9_2_1,
90 C2Config::LEVEL_VP9_3,
91 C2Config::LEVEL_VP9_3_1,
92 C2Config::LEVEL_VP9_4,
93 C2Config::LEVEL_VP9_4_1,
94 C2Config::LEVEL_VP9_5,
95 })
96 })
97 .withSetter(ProfileLevelSetter, mSize)
98 .build());
99 #else
100 addParameter(
101 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
102 .withConstValue(new C2StreamProfileLevelInfo::input(0u,
103 C2Config::PROFILE_UNUSED, C2Config::LEVEL_UNUSED))
104 .build());
105 #endif
106
107 C2ChromaOffsetStruct locations[1] = { C2ChromaOffsetStruct::ITU_YUV_420_0() };
108 std::shared_ptr<C2StreamColorInfo::output> defaultColorInfo =
109 C2StreamColorInfo::output::AllocShared(
110 1u, 0u, 8u /* bitDepth */, C2Color::YUV_420);
111 memcpy(defaultColorInfo->m.locations, locations, sizeof(locations));
112
113 defaultColorInfo =
114 C2StreamColorInfo::output::AllocShared(
115 { C2ChromaOffsetStruct::ITU_YUV_420_0() },
116 0u, 8u /* bitDepth */, C2Color::YUV_420);
117 helper->addStructDescriptors<C2ChromaOffsetStruct>();
118
119 addParameter(
120 DefineParam(mColorInfo, C2_PARAMKEY_CODED_COLOR_INFO)
121 .withConstValue(defaultColorInfo)
122 .build());
123
124 // TODO: support more formats?
125 addParameter(
126 DefineParam(mPixelFormat, C2_PARAMKEY_PIXEL_FORMAT)
127 .withConstValue(new C2StreamPixelFormatInfo::output(
128 0u, HAL_PIXEL_FORMAT_YCBCR_420_888))
129 .build());
130 }
131
SizeSetter(bool mayBlock,const C2P<C2VideoSizeStreamInfo::output> & oldMe,C2P<C2VideoSizeStreamInfo::output> & me)132 static C2R SizeSetter(bool mayBlock, const C2P<C2VideoSizeStreamInfo::output> &oldMe,
133 C2P<C2VideoSizeStreamInfo::output> &me) {
134 (void)mayBlock;
135 C2R res = C2R::Ok();
136 if (!me.F(me.v.width).supportsAtAll(me.v.width)) {
137 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.width)));
138 me.set().width = oldMe.v.width;
139 }
140 if (!me.F(me.v.height).supportsAtAll(me.v.height)) {
141 res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.height)));
142 me.set().height = oldMe.v.height;
143 }
144 return res;
145 }
146
ProfileLevelSetter(bool mayBlock,C2P<C2StreamProfileLevelInfo::input> & me,const C2P<C2StreamPictureSizeInfo::output> & size)147 static C2R ProfileLevelSetter(bool mayBlock, C2P<C2StreamProfileLevelInfo::input> &me,
148 const C2P<C2StreamPictureSizeInfo::output> &size) {
149 (void)mayBlock;
150 (void)size;
151 (void)me; // TODO: validate
152 return C2R::Ok();
153 }
154
155 private:
156 std::shared_ptr<C2StreamProfileLevelInfo::input> mProfileLevel;
157 std::shared_ptr<C2VideoSizeStreamInfo::output> mSize;
158 std::shared_ptr<C2StreamColorInfo::output> mColorInfo;
159 std::shared_ptr<C2StreamPixelFormatInfo::output> mPixelFormat;
160 };
161
C2SoftVpxDec(const char * name,c2_node_id_t id,const std::shared_ptr<IntfImpl> & intfImpl)162 C2SoftVpxDec::C2SoftVpxDec(
163 const char *name,
164 c2_node_id_t id,
165 const std::shared_ptr<IntfImpl> &intfImpl)
166 : SimpleC2Component(std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
167 mIntf(intfImpl),
168 mCodecCtx(nullptr) {
169 }
170
~C2SoftVpxDec()171 C2SoftVpxDec::~C2SoftVpxDec() {
172 onRelease();
173 }
174
onInit()175 c2_status_t C2SoftVpxDec::onInit() {
176 status_t err = initDecoder();
177 return err == OK ? C2_OK : C2_CORRUPTED;
178 }
179
onStop()180 c2_status_t C2SoftVpxDec::onStop() {
181 mSignalledError = false;
182 mSignalledOutputEos = false;
183
184 return C2_OK;
185 }
186
onReset()187 void C2SoftVpxDec::onReset() {
188 (void)onStop();
189 c2_status_t err = onFlush_sm();
190 if (err != C2_OK)
191 {
192 ALOGW("Failed to flush decoder. Try to hard reset decoder");
193 destroyDecoder();
194 (void)initDecoder();
195 }
196 }
197
onRelease()198 void C2SoftVpxDec::onRelease() {
199 destroyDecoder();
200 }
201
onFlush_sm()202 c2_status_t C2SoftVpxDec::onFlush_sm() {
203 if (mFrameParallelMode) {
204 // Flush decoder by passing nullptr data ptr and 0 size.
205 // Ideally, this should never fail.
206 if (vpx_codec_decode(mCodecCtx, nullptr, 0, nullptr, 0)) {
207 ALOGE("Failed to flush on2 decoder.");
208 return C2_CORRUPTED;
209 }
210 }
211
212 // Drop all the decoded frames in decoder.
213 vpx_codec_iter_t iter = nullptr;
214 while (vpx_codec_get_frame(mCodecCtx, &iter)) {
215 }
216
217 mSignalledError = false;
218 mSignalledOutputEos = false;
219 return C2_OK;
220 }
221
GetCPUCoreCount()222 static int GetCPUCoreCount() {
223 int cpuCoreCount = 1;
224 #if defined(_SC_NPROCESSORS_ONLN)
225 cpuCoreCount = sysconf(_SC_NPROCESSORS_ONLN);
226 #else
227 // _SC_NPROC_ONLN must be defined...
228 cpuCoreCount = sysconf(_SC_NPROC_ONLN);
229 #endif
230 CHECK(cpuCoreCount >= 1);
231 ALOGV("Number of CPU cores: %d", cpuCoreCount);
232 return cpuCoreCount;
233 }
234
initDecoder()235 status_t C2SoftVpxDec::initDecoder() {
236 #ifdef VP9
237 mMode = MODE_VP9;
238 #else
239 mMode = MODE_VP8;
240 #endif
241
242 mWidth = 320;
243 mHeight = 240;
244 mFrameParallelMode = false;
245 mSignalledOutputEos = false;
246 mSignalledError = false;
247
248 if (!mCodecCtx) {
249 mCodecCtx = new vpx_codec_ctx_t;
250 }
251
252 vpx_codec_dec_cfg_t cfg;
253 memset(&cfg, 0, sizeof(vpx_codec_dec_cfg_t));
254 cfg.threads = GetCPUCoreCount();
255
256 vpx_codec_flags_t flags;
257 memset(&flags, 0, sizeof(vpx_codec_flags_t));
258 if (mFrameParallelMode) flags |= VPX_CODEC_USE_FRAME_THREADING;
259
260 vpx_codec_err_t vpx_err;
261 if ((vpx_err = vpx_codec_dec_init(
262 mCodecCtx, mMode == MODE_VP8 ? &vpx_codec_vp8_dx_algo : &vpx_codec_vp9_dx_algo,
263 &cfg, flags))) {
264 ALOGE("on2 decoder failed to initialize. (%d)", vpx_err);
265 return UNKNOWN_ERROR;
266 }
267
268 return OK;
269 }
270
destroyDecoder()271 status_t C2SoftVpxDec::destroyDecoder() {
272 if (mCodecCtx) {
273 vpx_codec_destroy(mCodecCtx);
274 delete mCodecCtx;
275 mCodecCtx = nullptr;
276 }
277
278 return OK;
279 }
280
fillEmptyWork(const std::unique_ptr<C2Work> & work)281 void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
282 uint32_t flags = 0;
283 if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
284 flags |= C2FrameData::FLAG_END_OF_STREAM;
285 ALOGV("signalling eos");
286 }
287 work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
288 work->worklets.front()->output.buffers.clear();
289 work->worklets.front()->output.ordinal = work->input.ordinal;
290 work->workletsProcessed = 1u;
291 }
292
finishWork(uint64_t index,const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2GraphicBlock> & block)293 void C2SoftVpxDec::finishWork(uint64_t index, const std::unique_ptr<C2Work> &work,
294 const std::shared_ptr<C2GraphicBlock> &block) {
295 std::shared_ptr<C2Buffer> buffer = createGraphicBuffer(block,
296 C2Rect(mWidth, mHeight));
297 auto fillWork = [buffer, index](const std::unique_ptr<C2Work> &work) {
298 uint32_t flags = 0;
299 if ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) &&
300 (c2_cntr64_t(index) == work->input.ordinal.frameIndex)) {
301 flags |= C2FrameData::FLAG_END_OF_STREAM;
302 ALOGV("signalling eos");
303 }
304 work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
305 work->worklets.front()->output.buffers.clear();
306 work->worklets.front()->output.buffers.push_back(buffer);
307 work->worklets.front()->output.ordinal = work->input.ordinal;
308 work->workletsProcessed = 1u;
309 };
310 if (work && c2_cntr64_t(index) == work->input.ordinal.frameIndex) {
311 fillWork(work);
312 } else {
313 finish(index, fillWork);
314 }
315 }
316
process(const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2BlockPool> & pool)317 void C2SoftVpxDec::process(
318 const std::unique_ptr<C2Work> &work,
319 const std::shared_ptr<C2BlockPool> &pool) {
320 work->result = C2_OK;
321 work->workletsProcessed = 0u;
322 work->worklets.front()->output.configUpdate.clear();
323 if (mSignalledError || mSignalledOutputEos) {
324 work->result = C2_BAD_VALUE;
325 return;
326 }
327
328 size_t inOffset = 0u;
329 size_t inSize = 0u;
330 C2ReadView rView = mDummyReadView;
331 if (!work->input.buffers.empty()) {
332 rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
333 inSize = rView.capacity();
334 if (inSize && rView.error()) {
335 ALOGE("read view map failed %d", rView.error());
336 work->result = C2_CORRUPTED;
337 return;
338 }
339 }
340
341 bool codecConfig = ((work->input.flags & C2FrameData::FLAG_CODEC_CONFIG) !=0);
342 bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
343
344 ALOGV("in buffer attr. size %zu timestamp %d frameindex %d, flags %x",
345 inSize, (int)work->input.ordinal.timestamp.peeku(),
346 (int)work->input.ordinal.frameIndex.peeku(), work->input.flags);
347
348 // Software VP9 Decoder does not need the Codec Specific Data (CSD)
349 // (specified in http://www.webmproject.org/vp9/profiles/). Ignore it if
350 // it was passed.
351 if (codecConfig) {
352 // Ignore CSD buffer for VP9.
353 if (mMode == MODE_VP9) {
354 fillEmptyWork(work);
355 return;
356 } else {
357 // Tolerate the CSD buffer for VP8. This is a workaround
358 // for b/28689536. continue
359 ALOGW("WARNING: Got CSD buffer for VP8. Continue");
360 }
361 }
362
363 int64_t frameIndex = work->input.ordinal.frameIndex.peekll();
364
365 if (inSize) {
366 uint8_t *bitstream = const_cast<uint8_t *>(rView.data() + inOffset);
367 vpx_codec_err_t err = vpx_codec_decode(
368 mCodecCtx, bitstream, inSize, &frameIndex, 0);
369 if (err != VPX_CODEC_OK) {
370 ALOGE("on2 decoder failed to decode frame. err: %d", err);
371 work->result = C2_CORRUPTED;
372 mSignalledError = true;
373 return;
374 }
375 }
376
377 (void)outputBuffer(pool, work);
378
379 if (eos) {
380 drainInternal(DRAIN_COMPONENT_WITH_EOS, pool, work);
381 mSignalledOutputEos = true;
382 } else if (!inSize) {
383 fillEmptyWork(work);
384 }
385 }
386
copyOutputBufferToYV12Frame(uint8_t * dst,const uint8_t * srcY,const uint8_t * srcU,const uint8_t * srcV,size_t srcYStride,size_t srcUStride,size_t srcVStride,uint32_t width,uint32_t height,int32_t bpp)387 static void copyOutputBufferToYV12Frame(uint8_t *dst,
388 const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV,
389 size_t srcYStride, size_t srcUStride, size_t srcVStride,
390 uint32_t width, uint32_t height, int32_t bpp) {
391 size_t dstYStride = align(width, 16) * bpp ;
392 size_t dstUVStride = align(dstYStride / 2, 16);
393 uint8_t *dstStart = dst;
394
395 for (size_t i = 0; i < height; ++i) {
396 memcpy(dst, srcY, width * bpp);
397 srcY += srcYStride;
398 dst += dstYStride;
399 }
400
401 dst = dstStart + dstYStride * height;
402 for (size_t i = 0; i < height / 2; ++i) {
403 memcpy(dst, srcV, width / 2 * bpp);
404 srcV += srcVStride;
405 dst += dstUVStride;
406 }
407
408 dst = dstStart + (dstYStride * height) + (dstUVStride * height / 2);
409 for (size_t i = 0; i < height / 2; ++i) {
410 memcpy(dst, srcU, width / 2 * bpp);
411 srcU += srcUStride;
412 dst += dstUVStride;
413 }
414 }
415
outputBuffer(const std::shared_ptr<C2BlockPool> & pool,const std::unique_ptr<C2Work> & work)416 bool C2SoftVpxDec::outputBuffer(
417 const std::shared_ptr<C2BlockPool> &pool,
418 const std::unique_ptr<C2Work> &work)
419 {
420 if (!(work && pool)) return false;
421
422 vpx_codec_iter_t iter = nullptr;
423 vpx_image_t *img = vpx_codec_get_frame(mCodecCtx, &iter);
424
425 if (!img) return false;
426
427 if (img->d_w != mWidth || img->d_h != mHeight) {
428 mWidth = img->d_w;
429 mHeight = img->d_h;
430
431 C2VideoSizeStreamInfo::output size(0u, mWidth, mHeight);
432 std::vector<std::unique_ptr<C2SettingResult>> failures;
433 c2_status_t err = mIntf->config({&size}, C2_MAY_BLOCK, &failures);
434 if (err == C2_OK) {
435 work->worklets.front()->output.configUpdate.push_back(
436 C2Param::Copy(size));
437 } else {
438 ALOGE("Config update size failed");
439 mSignalledError = true;
440 work->result = C2_CORRUPTED;
441 return false;
442 }
443
444 }
445 CHECK(img->fmt == VPX_IMG_FMT_I420 || img->fmt == VPX_IMG_FMT_I42016);
446 int32_t bpp = 1;
447 if (img->fmt == VPX_IMG_FMT_I42016) {
448 bpp = 2;
449 }
450
451 std::shared_ptr<C2GraphicBlock> block;
452 uint32_t format = HAL_PIXEL_FORMAT_YV12;
453 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
454 c2_status_t err = pool->fetchGraphicBlock(align(mWidth, 16) * bpp, mHeight, format, usage, &block);
455 if (err != C2_OK) {
456 ALOGE("fetchGraphicBlock for Output failed with status %d", err);
457 work->result = err;
458 return false;
459 }
460
461 C2GraphicView wView = block->map().get();
462 if (wView.error()) {
463 ALOGE("graphic view map failed %d", wView.error());
464 work->result = C2_CORRUPTED;
465 return false;
466 }
467
468 ALOGV("provided (%dx%d) required (%dx%d), out frameindex %d",
469 block->width(), block->height(), mWidth, mHeight, (int)*(int64_t *)img->user_priv);
470
471 uint8_t *dst = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
472 size_t srcYStride = img->stride[VPX_PLANE_Y];
473 size_t srcUStride = img->stride[VPX_PLANE_U];
474 size_t srcVStride = img->stride[VPX_PLANE_V];
475 const uint8_t *srcY = (const uint8_t *)img->planes[VPX_PLANE_Y];
476 const uint8_t *srcU = (const uint8_t *)img->planes[VPX_PLANE_U];
477 const uint8_t *srcV = (const uint8_t *)img->planes[VPX_PLANE_V];
478 copyOutputBufferToYV12Frame(dst, srcY, srcU, srcV,
479 srcYStride, srcUStride, srcVStride, mWidth, mHeight, bpp);
480
481 finishWork(*(int64_t *)img->user_priv, work, std::move(block));
482 return true;
483 }
484
drainInternal(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool,const std::unique_ptr<C2Work> & work)485 c2_status_t C2SoftVpxDec::drainInternal(
486 uint32_t drainMode,
487 const std::shared_ptr<C2BlockPool> &pool,
488 const std::unique_ptr<C2Work> &work) {
489 if (drainMode == NO_DRAIN) {
490 ALOGW("drain with NO_DRAIN: no-op");
491 return C2_OK;
492 }
493 if (drainMode == DRAIN_CHAIN) {
494 ALOGW("DRAIN_CHAIN not supported");
495 return C2_OMITTED;
496 }
497
498 while ((outputBuffer(pool, work))) {
499 }
500
501 if (drainMode == DRAIN_COMPONENT_WITH_EOS &&
502 work && work->workletsProcessed == 0u) {
503 fillEmptyWork(work);
504 }
505
506 return C2_OK;
507 }
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)508 c2_status_t C2SoftVpxDec::drain(
509 uint32_t drainMode,
510 const std::shared_ptr<C2BlockPool> &pool) {
511 return drainInternal(drainMode, pool, nullptr);
512 }
513
514 class C2SoftVpxFactory : public C2ComponentFactory {
515 public:
C2SoftVpxFactory()516 C2SoftVpxFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
517 GetCodec2PlatformComponentStore()->getParamReflector())) {
518 }
519
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)520 virtual c2_status_t createComponent(
521 c2_node_id_t id,
522 std::shared_ptr<C2Component>* const component,
523 std::function<void(C2Component*)> deleter) override {
524 *component = std::shared_ptr<C2Component>(
525 new C2SoftVpxDec(COMPONENT_NAME, id,
526 std::make_shared<C2SoftVpxDec::IntfImpl>(mHelper)),
527 deleter);
528 return C2_OK;
529 }
530
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)531 virtual c2_status_t createInterface(
532 c2_node_id_t id,
533 std::shared_ptr<C2ComponentInterface>* const interface,
534 std::function<void(C2ComponentInterface*)> deleter) override {
535 *interface = std::shared_ptr<C2ComponentInterface>(
536 new SimpleInterface<C2SoftVpxDec::IntfImpl>(
537 COMPONENT_NAME, id,
538 std::make_shared<C2SoftVpxDec::IntfImpl>(mHelper)),
539 deleter);
540 return C2_OK;
541 }
542
543 virtual ~C2SoftVpxFactory() override = default;
544
545 private:
546 std::shared_ptr<C2ReflectorHelper> mHelper;
547 };
548
549 } // namespace android
550
CreateCodec2Factory()551 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
552 ALOGV("in %s", __func__);
553 return new ::android::C2SoftVpxFactory();
554 }
555
DestroyCodec2Factory(::C2ComponentFactory * factory)556 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
557 ALOGV("in %s", __func__);
558 delete factory;
559 }
560