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