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> &param: 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     if (inSize) {
597         uint8_t *bitstream = const_cast<uint8_t *>(rView.data() + inOffset);
598         vpx_codec_err_t err = vpx_codec_decode(
599                 mCodecCtx, bitstream, inSize, &work->input.ordinal.frameIndex, 0);
600         if (err != VPX_CODEC_OK) {
601             ALOGE("on2 decoder failed to decode frame. err: %d", err);
602             mSignalledError = true;
603             work->workletsProcessed = 1u;
604             work->result = C2_CORRUPTED;
605             return;
606         }
607     }
608 
609     status_t err = outputBuffer(pool, work);
610     if (err == NOT_ENOUGH_DATA) {
611         if (inSize > 0) {
612             ALOGV("Maybe non-display frame at %lld.",
613                   work->input.ordinal.frameIndex.peekll());
614             // send the work back with empty buffer.
615             inSize = 0;
616         }
617     } else if (err != OK) {
618         ALOGD("Error while getting the output frame out");
619         // work->result would be already filled; do fillEmptyWork() below to
620         // send the work back.
621         inSize = 0;
622     }
623 
624     if (eos) {
625         drainInternal(DRAIN_COMPONENT_WITH_EOS, pool, work);
626         mSignalledOutputEos = true;
627     } else if (!inSize) {
628         fillEmptyWork(work);
629     }
630 }
631 
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)632 static void copyOutputBufferToYuvPlanarFrame(
633         uint8_t *dst, const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV,
634         size_t srcYStride, size_t srcUStride, size_t srcVStride,
635         size_t dstYStride, size_t dstUVStride,
636         uint32_t width, uint32_t height) {
637     uint8_t *dstStart = dst;
638 
639     for (size_t i = 0; i < height; ++i) {
640          memcpy(dst, srcY, width);
641          srcY += srcYStride;
642          dst += dstYStride;
643     }
644 
645     dst = dstStart + dstYStride * height;
646     for (size_t i = 0; i < height / 2; ++i) {
647          memcpy(dst, srcV, width / 2);
648          srcV += srcVStride;
649          dst += dstUVStride;
650     }
651 
652     dst = dstStart + (dstYStride * height) + (dstUVStride * height / 2);
653     for (size_t i = 0; i < height / 2; ++i) {
654          memcpy(dst, srcU, width / 2);
655          srcU += srcUStride;
656          dst += dstUVStride;
657     }
658 }
659 
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)660 static void convertYUV420Planar16ToY410(uint32_t *dst,
661         const uint16_t *srcY, const uint16_t *srcU, const uint16_t *srcV,
662         size_t srcYStride, size_t srcUStride, size_t srcVStride,
663         size_t dstStride, size_t width, size_t height) {
664 
665     // Converting two lines at a time, slightly faster
666     for (size_t y = 0; y < height; y += 2) {
667         uint32_t *dstTop = (uint32_t *) dst;
668         uint32_t *dstBot = (uint32_t *) (dst + dstStride);
669         uint16_t *ySrcTop = (uint16_t*) srcY;
670         uint16_t *ySrcBot = (uint16_t*) (srcY + srcYStride);
671         uint16_t *uSrc = (uint16_t*) srcU;
672         uint16_t *vSrc = (uint16_t*) srcV;
673 
674         uint32_t u01, v01, y01, y23, y45, y67, uv0, uv1;
675         size_t x = 0;
676         for (; x < width - 3; x += 4) {
677 
678             u01 = *((uint32_t*)uSrc); uSrc += 2;
679             v01 = *((uint32_t*)vSrc); vSrc += 2;
680 
681             y01 = *((uint32_t*)ySrcTop); ySrcTop += 2;
682             y23 = *((uint32_t*)ySrcTop); ySrcTop += 2;
683             y45 = *((uint32_t*)ySrcBot); ySrcBot += 2;
684             y67 = *((uint32_t*)ySrcBot); ySrcBot += 2;
685 
686             uv0 = (u01 & 0x3FF) | ((v01 & 0x3FF) << 20);
687             uv1 = (u01 >> 16) | ((v01 >> 16) << 20);
688 
689             *dstTop++ = 3 << 30 | ((y01 & 0x3FF) << 10) | uv0;
690             *dstTop++ = 3 << 30 | ((y01 >> 16) << 10) | uv0;
691             *dstTop++ = 3 << 30 | ((y23 & 0x3FF) << 10) | uv1;
692             *dstTop++ = 3 << 30 | ((y23 >> 16) << 10) | uv1;
693 
694             *dstBot++ = 3 << 30 | ((y45 & 0x3FF) << 10) | uv0;
695             *dstBot++ = 3 << 30 | ((y45 >> 16) << 10) | uv0;
696             *dstBot++ = 3 << 30 | ((y67 & 0x3FF) << 10) | uv1;
697             *dstBot++ = 3 << 30 | ((y67 >> 16) << 10) | uv1;
698         }
699 
700         // There should be at most 2 more pixels to process. Note that we don't
701         // need to consider odd case as the buffer is always aligned to even.
702         if (x < width) {
703             u01 = *uSrc;
704             v01 = *vSrc;
705             y01 = *((uint32_t*)ySrcTop);
706             y45 = *((uint32_t*)ySrcBot);
707             uv0 = (u01 & 0x3FF) | ((v01 & 0x3FF) << 20);
708             *dstTop++ = ((y01 & 0x3FF) << 10) | uv0;
709             *dstTop++ = ((y01 >> 16) << 10) | uv0;
710             *dstBot++ = ((y45 & 0x3FF) << 10) | uv0;
711             *dstBot++ = ((y45 >> 16) << 10) | uv0;
712         }
713 
714         srcY += srcYStride * 2;
715         srcU += srcUStride;
716         srcV += srcVStride;
717         dst += dstStride * 2;
718     }
719 
720     return;
721 }
722 
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)723 static void convertYUV420Planar16ToYUV420Planar(uint8_t *dst,
724         const uint16_t *srcY, const uint16_t *srcU, const uint16_t *srcV,
725         size_t srcYStride, size_t srcUStride, size_t srcVStride,
726         size_t dstYStride, size_t dstUVStride, size_t width, size_t height) {
727 
728     uint8_t *dstY = (uint8_t *)dst;
729     size_t dstYSize = dstYStride * height;
730     size_t dstUVSize = dstUVStride * height / 2;
731     uint8_t *dstV = dstY + dstYSize;
732     uint8_t *dstU = dstV + dstUVSize;
733 
734     for (size_t y = 0; y < height; ++y) {
735         for (size_t x = 0; x < width; ++x) {
736             dstY[x] = (uint8_t)(srcY[x] >> 2);
737         }
738 
739         srcY += srcYStride;
740         dstY += dstYStride;
741     }
742 
743     for (size_t y = 0; y < (height + 1) / 2; ++y) {
744         for (size_t x = 0; x < (width + 1) / 2; ++x) {
745             dstU[x] = (uint8_t)(srcU[x] >> 2);
746             dstV[x] = (uint8_t)(srcV[x] >> 2);
747         }
748 
749         srcU += srcUStride;
750         srcV += srcVStride;
751         dstU += dstUVStride;
752         dstV += dstUVStride;
753     }
754     return;
755 }
outputBuffer(const std::shared_ptr<C2BlockPool> & pool,const std::unique_ptr<C2Work> & work)756 status_t C2SoftVpxDec::outputBuffer(
757         const std::shared_ptr<C2BlockPool> &pool,
758         const std::unique_ptr<C2Work> &work)
759 {
760     if (!(work && pool)) return BAD_VALUE;
761 
762     vpx_codec_iter_t iter = nullptr;
763     vpx_image_t *img = vpx_codec_get_frame(mCodecCtx, &iter);
764 
765     if (!img) return NOT_ENOUGH_DATA;
766 
767     if (img->d_w != mWidth || img->d_h != mHeight) {
768         mWidth = img->d_w;
769         mHeight = img->d_h;
770 
771         C2StreamPictureSizeInfo::output size(0u, mWidth, mHeight);
772         std::vector<std::unique_ptr<C2SettingResult>> failures;
773         c2_status_t err = mIntf->config({&size}, C2_MAY_BLOCK, &failures);
774         if (err == C2_OK) {
775             work->worklets.front()->output.configUpdate.push_back(
776                 C2Param::Copy(size));
777         } else {
778             ALOGE("Config update size failed");
779             mSignalledError = true;
780             work->workletsProcessed = 1u;
781             work->result = C2_CORRUPTED;
782             return UNKNOWN_ERROR;
783         }
784 
785     }
786     if(img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_I42016) {
787         ALOGE("img->fmt %d not supported", img->fmt);
788         mSignalledError = true;
789         work->workletsProcessed = 1u;
790         work->result = C2_CORRUPTED;
791         return false;
792     }
793 
794     std::shared_ptr<C2GraphicBlock> block;
795     uint32_t format = HAL_PIXEL_FORMAT_YV12;
796     if (img->fmt == VPX_IMG_FMT_I42016) {
797         IntfImpl::Lock lock = mIntf->lock();
798         std::shared_ptr<C2StreamColorAspectsTuning::output> defaultColorAspects = mIntf->getDefaultColorAspects_l();
799 
800         if (defaultColorAspects->primaries == C2Color::PRIMARIES_BT2020 &&
801             defaultColorAspects->matrix == C2Color::MATRIX_BT2020 &&
802             defaultColorAspects->transfer == C2Color::TRANSFER_ST2084) {
803             format = HAL_PIXEL_FORMAT_RGBA_1010102;
804         }
805     }
806     C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
807     c2_status_t err = pool->fetchGraphicBlock(align(mWidth, 16), mHeight, format, usage, &block);
808     if (err != C2_OK) {
809         ALOGE("fetchGraphicBlock for Output failed with status %d", err);
810         work->result = err;
811         return UNKNOWN_ERROR;
812     }
813 
814     C2GraphicView wView = block->map().get();
815     if (wView.error()) {
816         ALOGE("graphic view map failed %d", wView.error());
817         work->result = C2_CORRUPTED;
818         return UNKNOWN_ERROR;
819     }
820 
821     ALOGV("provided (%dx%d) required (%dx%d), out frameindex %lld",
822            block->width(), block->height(), mWidth, mHeight,
823            ((c2_cntr64_t *)img->user_priv)->peekll());
824 
825     uint8_t *dst = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
826     size_t srcYStride = img->stride[VPX_PLANE_Y];
827     size_t srcUStride = img->stride[VPX_PLANE_U];
828     size_t srcVStride = img->stride[VPX_PLANE_V];
829     C2PlanarLayout layout = wView.layout();
830     size_t dstYStride = layout.planes[C2PlanarLayout::PLANE_Y].rowInc;
831     size_t dstUVStride = layout.planes[C2PlanarLayout::PLANE_U].rowInc;
832 
833     if (img->fmt == VPX_IMG_FMT_I42016) {
834         const uint16_t *srcY = (const uint16_t *)img->planes[VPX_PLANE_Y];
835         const uint16_t *srcU = (const uint16_t *)img->planes[VPX_PLANE_U];
836         const uint16_t *srcV = (const uint16_t *)img->planes[VPX_PLANE_V];
837 
838         if (format == HAL_PIXEL_FORMAT_RGBA_1010102) {
839             Mutexed<ConversionQueue>::Locked queue(*mQueue);
840             size_t i = 0;
841             constexpr size_t kHeight = 64;
842             for (; i < mHeight; i += kHeight) {
843                 queue->entries.push_back(
844                         [dst, srcY, srcU, srcV,
845                          srcYStride, srcUStride, srcVStride, dstYStride,
846                          width = mWidth, height = std::min(mHeight - i, kHeight)] {
847                             convertYUV420Planar16ToY410(
848                                     (uint32_t *)dst, srcY, srcU, srcV, srcYStride / 2,
849                                     srcUStride / 2, srcVStride / 2, dstYStride / sizeof(uint32_t),
850                                     width, height);
851                         });
852                 srcY += srcYStride / 2 * kHeight;
853                 srcU += srcUStride / 2 * (kHeight / 2);
854                 srcV += srcVStride / 2 * (kHeight / 2);
855                 dst += dstYStride * kHeight;
856             }
857             CHECK_EQ(0u, queue->numPending);
858             queue->numPending = queue->entries.size();
859             while (queue->numPending > 0) {
860                 queue->cond.signal();
861                 queue.waitForCondition(queue->cond);
862             }
863         } else {
864             convertYUV420Planar16ToYUV420Planar(dst, srcY, srcU, srcV, srcYStride / 2,
865                                                 srcUStride / 2, srcVStride / 2,
866                                                 dstYStride, dstUVStride,
867                                                 mWidth, mHeight);
868         }
869     } else {
870         const uint8_t *srcY = (const uint8_t *)img->planes[VPX_PLANE_Y];
871         const uint8_t *srcU = (const uint8_t *)img->planes[VPX_PLANE_U];
872         const uint8_t *srcV = (const uint8_t *)img->planes[VPX_PLANE_V];
873         copyOutputBufferToYuvPlanarFrame(
874                 dst, srcY, srcU, srcV,
875                 srcYStride, srcUStride, srcVStride,
876                 dstYStride, dstUVStride,
877                 mWidth, mHeight);
878     }
879     finishWork(((c2_cntr64_t *)img->user_priv)->peekull(), work, std::move(block));
880     return OK;
881 }
882 
drainInternal(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool,const std::unique_ptr<C2Work> & work)883 c2_status_t C2SoftVpxDec::drainInternal(
884         uint32_t drainMode,
885         const std::shared_ptr<C2BlockPool> &pool,
886         const std::unique_ptr<C2Work> &work) {
887     if (drainMode == NO_DRAIN) {
888         ALOGW("drain with NO_DRAIN: no-op");
889         return C2_OK;
890     }
891     if (drainMode == DRAIN_CHAIN) {
892         ALOGW("DRAIN_CHAIN not supported");
893         return C2_OMITTED;
894     }
895 
896     while (outputBuffer(pool, work) == OK) {
897     }
898 
899     if (drainMode == DRAIN_COMPONENT_WITH_EOS &&
900             work && work->workletsProcessed == 0u) {
901         fillEmptyWork(work);
902     }
903 
904     return C2_OK;
905 }
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)906 c2_status_t C2SoftVpxDec::drain(
907         uint32_t drainMode,
908         const std::shared_ptr<C2BlockPool> &pool) {
909     return drainInternal(drainMode, pool, nullptr);
910 }
911 
912 class C2SoftVpxFactory : public C2ComponentFactory {
913 public:
C2SoftVpxFactory()914     C2SoftVpxFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
915         GetCodec2PlatformComponentStore()->getParamReflector())) {
916     }
917 
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)918     virtual c2_status_t createComponent(
919             c2_node_id_t id,
920             std::shared_ptr<C2Component>* const component,
921             std::function<void(C2Component*)> deleter) override {
922         *component = std::shared_ptr<C2Component>(
923             new C2SoftVpxDec(COMPONENT_NAME, id,
924                           std::make_shared<C2SoftVpxDec::IntfImpl>(mHelper)),
925             deleter);
926         return C2_OK;
927     }
928 
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)929     virtual c2_status_t createInterface(
930             c2_node_id_t id,
931             std::shared_ptr<C2ComponentInterface>* const interface,
932             std::function<void(C2ComponentInterface*)> deleter) override {
933         *interface = std::shared_ptr<C2ComponentInterface>(
934             new SimpleInterface<C2SoftVpxDec::IntfImpl>(
935                 COMPONENT_NAME, id,
936                 std::make_shared<C2SoftVpxDec::IntfImpl>(mHelper)),
937             deleter);
938         return C2_OK;
939     }
940 
941     virtual ~C2SoftVpxFactory() override = default;
942 
943 private:
944     std::shared_ptr<C2ReflectorHelper> mHelper;
945 };
946 
947 }  // namespace android
948 
CreateCodec2Factory()949 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
950     ALOGV("in %s", __func__);
951     return new ::android::C2SoftVpxFactory();
952 }
953 
DestroyCodec2Factory(::C2ComponentFactory * factory)954 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
955     ALOGV("in %s", __func__);
956     delete factory;
957 }
958