• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifdef VIDEO_SUPPORT
17 
18 #define HST_LOG_TAG "FfmpegVideoDecoderPlugin"
19 
20 #include "video_ffmpeg_decoder_plugin.h"
21 #include <cstring>
22 #include <map>
23 #include <set>
24 #include "plugin/common/plugin_caps_builder.h"
25 #include "plugin/common/surface_memory.h"
26 #include "plugins/ffmpeg_adapter/utils/ffmpeg_utils.h"
27 
28 namespace {
29 // register plugins
30 using namespace OHOS::Media::Plugin;
31 using namespace Ffmpeg;
32 void UpdatePluginDefinition(const AVCodec* codec, CodecPluginDef& definition);
33 
34 std::map<std::string, std::shared_ptr<const AVCodec>> codecMap;
35 
36 constexpr size_t BUFFER_QUEUE_SIZE = 8;
37 constexpr int32_t STRIDE_ALIGN = 16;
38 
39 std::set<AVCodecID> supportedCodec = {AV_CODEC_ID_H264};
40 
VideoFfmpegDecoderCreator(const std::string & name)41 std::shared_ptr<CodecPlugin> VideoFfmpegDecoderCreator(const std::string& name)
42 {
43     return std::make_shared<VideoFfmpegDecoderPlugin>(name);
44 }
45 
RegisterVideoDecoderPlugins(const std::shared_ptr<Register> & reg)46 Status RegisterVideoDecoderPlugins(const std::shared_ptr<Register>& reg)
47 {
48     const AVCodec* codec = nullptr;
49     void* iter = nullptr;
50     MEDIA_LOG_I("registering video decoders");
51     while ((codec = av_codec_iterate(&iter))) {
52         if (!av_codec_is_decoder(codec) || codec->type != AVMEDIA_TYPE_VIDEO) {
53             continue;
54         }
55         if (supportedCodec.find(codec->id) == supportedCodec.end()) {
56             MEDIA_LOG_DD("codec " PUBLIC_LOG_S "(" PUBLIC_LOG_S ") is not supported right now",
57                          codec->name, codec->long_name);
58             continue;
59         }
60         CodecPluginDef definition;
61         definition.name = "videodecoder_" + std::string(codec->name);
62         definition.pluginType = PluginType::VIDEO_DECODER;
63         definition.rank = 100; // 100
64         definition.creator = VideoFfmpegDecoderCreator;
65         UpdatePluginDefinition(codec, definition);
66         // do not delete the codec in the deleter
67         codecMap[definition.name] = std::shared_ptr<AVCodec>(const_cast<AVCodec*>(codec), [](void* ptr) {});
68         if (reg->AddPlugin(definition) != Status::OK) {
69             MEDIA_LOG_W("register plugin " PUBLIC_LOG_S "(" PUBLIC_LOG_S ") failed",
70                         codec->name, codec->long_name);
71         }
72     }
73     return Status::OK;
74 }
75 
UnRegisterVideoDecoderPlugins()76 void UnRegisterVideoDecoderPlugins()
77 {
78     codecMap.clear();
79 }
80 
UpdateInCaps(const AVCodec * codec,CodecPluginDef & definition)81 void UpdateInCaps(const AVCodec* codec, CodecPluginDef& definition)
82 {
83     CapabilityBuilder incapBuilder;
84     switch (codec->id) {
85         case AV_CODEC_ID_H264:
86             incapBuilder.SetMime(OHOS::Media::MEDIA_MIME_VIDEO_H264);
87             incapBuilder.SetVideoBitStreamFormatList({VideoBitStreamFormat::AVC1, VideoBitStreamFormat::ANNEXB});
88             break;
89         default:
90             incapBuilder.SetMime("video/unknown");
91             MEDIA_LOG_I("codec is not supported right now");
92             break;
93     }
94     definition.inCaps.push_back(incapBuilder.Build());
95 }
96 
UpdateOutCaps(const AVCodec * codec,CodecPluginDef & definition)97 void UpdateOutCaps(const AVCodec* codec, CodecPluginDef& definition)
98 {
99     CapabilityBuilder outcapBuilder;
100     outcapBuilder.SetMime(OHOS::Media::MEDIA_MIME_VIDEO_RAW);
101     if (codec->pix_fmts != nullptr) {
102         DiscreteCapability<VideoPixelFormat> values;
103         size_t index = 0;
104         for (index = 0; codec->pix_fmts[index] != 0; ++index) {
105             auto supportFormat = ConvertPixelFormatFromFFmpeg(codec->pix_fmts[index]);
106             if (supportFormat != VideoPixelFormat::UNKNOWN) {
107                 values.push_back(supportFormat);
108             }
109         }
110         if (index) {
111             outcapBuilder.SetVideoPixelFormatList(values);
112         }
113     }
114     definition.outCaps.push_back(outcapBuilder.Build());
115 }
116 
UpdatePluginDefinition(const AVCodec * codec,CodecPluginDef & definition)117 void UpdatePluginDefinition(const AVCodec* codec, CodecPluginDef& definition)
118 {
119     UpdateInCaps(codec, definition);
120     UpdateOutCaps(codec, definition);
121 }
122 } // namespace
123 
124 PLUGIN_DEFINITION(FFmpegVideoDecoders, LicenseType::LGPL, RegisterVideoDecoderPlugins, UnRegisterVideoDecoderPlugins);
125 
126 namespace OHOS {
127 namespace Media {
128 namespace Plugin {
VideoFfmpegDecoderPlugin(std::string name)129 VideoFfmpegDecoderPlugin::VideoFfmpegDecoderPlugin(std::string name)
130     : CodecPlugin(std::move(name)), outBufferQ_("vdecPluginQueue", BUFFER_QUEUE_SIZE)
131 {
132     for (int32_t i = 0; i < AV_NUM_DATA_POINTERS; i++) {
133         scaleData_[i] = nullptr;
134         scaleLineSize_[i] = 0;
135     }
136     isAllocScaleData_ = false;
137 }
138 
Init()139 Status VideoFfmpegDecoderPlugin::Init()
140 {
141     OSAL::ScopedLock l(avMutex_);
142     auto iter = codecMap.find(pluginName_);
143     if (iter == codecMap.end()) {
144         MEDIA_LOG_W("cannot find codec with name " PUBLIC_LOG_S, pluginName_.c_str());
145         return Status::ERROR_UNSUPPORTED_FORMAT;
146     }
147     avCodec_ = iter->second;
148     cachedFrame_ = std::shared_ptr<AVFrame>(av_frame_alloc(), [](AVFrame* fp) { av_frame_free(&fp); });
149     videoDecParams_[Tag::REQUIRED_OUT_BUFFER_CNT] = (uint32_t)BUFFER_QUEUE_SIZE;
150     if (!decodeTask_) {
151         decodeTask_ = std::make_shared<OHOS::Media::OSAL::Task>("videoFfmpegDecThread");
152         decodeTask_->RegisterHandler([this] { ReceiveFrameBuffer(); });
153     }
154     state_ = State::INITIALIZED;
155     MEDIA_LOG_I("Init success");
156     return Status::OK;
157 }
158 
Deinit()159 Status VideoFfmpegDecoderPlugin::Deinit()
160 {
161     OSAL::ScopedLock l(avMutex_);
162     avCodec_.reset();
163     cachedFrame_.reset();
164     ResetLocked();
165     if (decodeTask_) {
166         decodeTask_->Stop();
167         decodeTask_.reset();
168     }
169     if (scale_) {
170         scale_.reset();
171     }
172     state_ = State::DESTROYED;
173     return Status::OK;
174 }
175 
SetParameter(Tag tag,const ValueType & value)176 Status VideoFfmpegDecoderPlugin::SetParameter(Tag tag, const ValueType& value)
177 {
178     OSAL::ScopedLock l(avMutex_);
179     if (videoDecParams_.count(tag)) {
180         videoDecParams_[tag] = value;
181     } else {
182         videoDecParams_.insert(std::make_pair(tag, value));
183     }
184     return Status::OK;
185 }
186 
GetParameter(Tag tag,ValueType & value)187 Status VideoFfmpegDecoderPlugin::GetParameter(Tag tag, ValueType& value)
188 {
189     OSAL::ScopedLock l(avMutex_);
190     auto res = videoDecParams_.find(tag);
191     if (res != videoDecParams_.end()) {
192         value = res->second;
193         return Status::OK;
194     }
195     return Status::ERROR_INVALID_PARAMETER;
196 }
197 
198 template <typename T>
FindInParameterMapThenAssignLocked(Tag tag,T & assign)199 void VideoFfmpegDecoderPlugin::FindInParameterMapThenAssignLocked(Tag tag, T& assign)
200 {
201     auto iter = videoDecParams_.find(tag);
202     if (iter != videoDecParams_.end() && iter->second.SameTypeWith(typeid(T))) {
203         assign = Plugin::AnyCast<T>(iter->second);
204     } else {
205         MEDIA_LOG_W("parameter " PUBLIC_LOG_D32 " is not found or type mismatch", static_cast<int32_t>(tag));
206     }
207 }
208 
CreateCodecContext()209 Status VideoFfmpegDecoderPlugin::CreateCodecContext()
210 {
211     auto context = avcodec_alloc_context3(avCodec_.get());
212     if (context == nullptr) {
213         MEDIA_LOG_E("cannot allocate codec context");
214         return Status::ERROR_UNKNOWN;
215     }
216     avCodecContext_ = std::shared_ptr<AVCodecContext>(context, [](AVCodecContext* ptr) {
217         if (ptr != nullptr) {
218             if (ptr->extradata) {
219                 av_free(ptr->extradata);
220                 ptr->extradata = nullptr;
221             }
222             avcodec_free_context(&ptr);
223         }
224     });
225     MEDIA_LOG_I("CreateCodecContext success");
226     return Status::OK;
227 }
228 
InitCodecContext()229 void VideoFfmpegDecoderPlugin::InitCodecContext()
230 {
231     avCodecContext_->codec_type = AVMEDIA_TYPE_VIDEO;
232     FindInParameterMapThenAssignLocked<int64_t>(Tag::MEDIA_BITRATE, avCodecContext_->bit_rate);
233     FindInParameterMapThenAssignLocked<std::uint32_t>(Tag::VIDEO_WIDTH, width_);
234     FindInParameterMapThenAssignLocked<std::uint32_t>(Tag::VIDEO_HEIGHT, height_);
235     FindInParameterMapThenAssignLocked<Plugin::VideoPixelFormat>(Tag::VIDEO_PIXEL_FORMAT, pixelFormat_);
236     MEDIA_LOG_D("bitRate: " PUBLIC_LOG_D64 ", width: " PUBLIC_LOG_U32 ", height: " PUBLIC_LOG_U32
237                 ", pixelFormat: " PUBLIC_LOG_U32, avCodecContext_->bit_rate, width_, height_, pixelFormat_);
238     SetCodecExtraData();
239     // Reset coded_width/_height to prevent it being reused from last time when
240     // the codec is opened again, causing a mismatch and possible segfault/corruption.
241     avCodecContext_->coded_width = 0;
242     avCodecContext_->coded_height = 0;
243     avCodecContext_->workaround_bugs |= FF_BUG_AUTODETECT;
244     avCodecContext_->err_recognition = 1;
245 }
246 
DeinitCodecContext()247 void VideoFfmpegDecoderPlugin::DeinitCodecContext()
248 {
249     if (avCodecContext_ == nullptr) {
250         return;
251     }
252     if (avCodecContext_->extradata) {
253         av_free(avCodecContext_->extradata);
254         avCodecContext_->extradata = nullptr;
255     }
256     avCodecContext_->extradata_size = 0;
257     avCodecContext_->opaque = nullptr;
258     avCodecContext_->width = 0;
259     avCodecContext_->height = 0;
260     avCodecContext_->coded_width = 0;
261     avCodecContext_->coded_height = 0;
262     avCodecContext_->time_base.den = 0;
263     avCodecContext_->time_base.num = 0;
264     avCodecContext_->ticks_per_frame = 0;
265     avCodecContext_->sample_aspect_ratio.num = 0;
266     avCodecContext_->sample_aspect_ratio.den = 0;
267     avCodecContext_->get_buffer2 = nullptr;
268 }
269 
SetCodecExtraData()270 void VideoFfmpegDecoderPlugin::SetCodecExtraData()
271 {
272     auto iter = videoDecParams_.find(Tag::MEDIA_CODEC_CONFIG);
273     if (iter == videoDecParams_.end() || !iter->second.SameTypeWith(typeid(std::vector<uint8_t>))) {
274         return;
275     }
276     auto codecConfig = Plugin::AnyCast<std::vector<uint8_t>>(iter->second);
277     int configSize = codecConfig.size();
278     if (configSize > 0) {
279         auto allocSize = AlignUp(configSize + AV_INPUT_BUFFER_PADDING_SIZE, STRIDE_ALIGN);
280         avCodecContext_->extradata = static_cast<uint8_t*>(av_mallocz(allocSize));
281         (void)memcpy_s(avCodecContext_->extradata, configSize, codecConfig.data(), configSize);
282         avCodecContext_->extradata_size = configSize;
283         MEDIA_LOG_I("SetCodecExtraData success");
284     }
285 }
286 
OpenCodecContext()287 Status VideoFfmpegDecoderPlugin::OpenCodecContext()
288 {
289     AVCodec* vdec = avcodec_find_decoder(avCodecContext_->codec_id);
290     if (vdec == nullptr) {
291         MEDIA_LOG_E("Codec: " PUBLIC_LOG_D32 " is not found", static_cast<int32_t>(avCodecContext_->codec_id));
292         DeinitCodecContext();
293         return Status::ERROR_INVALID_PARAMETER;
294     }
295     auto res = avcodec_open2(avCodecContext_.get(), avCodec_.get(), nullptr);
296     if (res != 0) {
297         MEDIA_LOG_E("avcodec open error " PUBLIC_LOG_S " when start decoder ", AVStrError(res).c_str());
298         DeinitCodecContext();
299         return Status::ERROR_UNKNOWN;
300     }
301     MEDIA_LOG_I("OpenCodecContext success");
302     return Status::OK;
303 }
304 
CloseCodecContext()305 Status VideoFfmpegDecoderPlugin::CloseCodecContext()
306 {
307     Status ret = Status::OK;
308     if (avCodecContext_ != nullptr) {
309         auto res = avcodec_close(avCodecContext_.get());
310         if (res != 0) {
311             DeinitCodecContext();
312             MEDIA_LOG_E("avcodec close error " PUBLIC_LOG_S " when stop decoder", AVStrError(res).c_str());
313             ret = Status::ERROR_UNKNOWN;
314         }
315         avCodecContext_.reset();
316     }
317     return ret;
318 }
319 
Prepare()320 Status VideoFfmpegDecoderPlugin::Prepare()
321 {
322     {
323         OSAL::ScopedLock l(avMutex_);
324         if (state_ != State::INITIALIZED && state_ != State::PREPARED) {
325             return Status::ERROR_WRONG_STATE;
326         }
327         if (CreateCodecContext() != Status::OK) {
328             MEDIA_LOG_E("Create codec context fail");
329             return Status::ERROR_UNKNOWN;
330         }
331         InitCodecContext();
332 #ifdef DUMP_RAW_DATA
333         dumpFd_ = std::fopen("./vdec_out.yuv", "wb");
334 #endif
335         state_ = State::PREPARED;
336     }
337     avPacket_ = std::shared_ptr<AVPacket>(av_packet_alloc(), [](AVPacket* ptr) {
338         av_packet_free(&ptr);
339     });
340     outBufferQ_.SetActive(true);
341     MEDIA_LOG_I("Prepare success");
342     return Status::OK;
343 }
344 
ResetLocked()345 Status VideoFfmpegDecoderPlugin::ResetLocked()
346 {
347     videoDecParams_.clear();
348     avCodecContext_.reset();
349     outBufferQ_.Clear();
350     if (scaleData_[0] != nullptr) {
351         if (isAllocScaleData_) {
352             av_free(scaleData_[0]);
353             isAllocScaleData_ = false;
354         }
355         for (int32_t i = 0; i < AV_NUM_DATA_POINTERS; i++) {
356             scaleData_[i] = nullptr;
357             scaleLineSize_[i] = 0;
358         }
359     }
360 #ifdef DUMP_RAW_DATA
361     if (dumpFd_) {
362         std::fclose(dumpFd_);
363         dumpFd_ = nullptr;
364     }
365 #endif
366     state_ = State::INITIALIZED;
367     return Status::OK;
368 }
369 
Reset()370 Status VideoFfmpegDecoderPlugin::Reset()
371 {
372     OSAL::ScopedLock l(avMutex_);
373     return ResetLocked();
374 }
375 
Start()376 Status VideoFfmpegDecoderPlugin::Start()
377 {
378     {
379         OSAL::ScopedLock l(avMutex_);
380         if (state_ != State::PREPARED) {
381             return Status::ERROR_WRONG_STATE;
382         }
383         if (OpenCodecContext() != Status::OK) {
384             MEDIA_LOG_E("Open codec context fail");
385             return Status::ERROR_UNKNOWN;
386         }
387         state_ = State::RUNNING;
388     }
389     outBufferQ_.SetActive(true);
390     decodeTask_->Start();
391     MEDIA_LOG_I("Start success");
392     return Status::OK;
393 }
394 
Stop()395 Status VideoFfmpegDecoderPlugin::Stop()
396 {
397     Status ret = Status::OK;
398     {
399         OSAL::ScopedLock l(avMutex_);
400         ret = CloseCodecContext();
401 #ifdef DUMP_RAW_DATA
402         if (dumpFd_) {
403             std::fclose(dumpFd_);
404             dumpFd_ = nullptr;
405         }
406 #endif
407         state_ = State::INITIALIZED;
408     }
409     outBufferQ_.SetActive(false);
410     decodeTask_->Stop();
411     MEDIA_LOG_I("Stop success");
412     return ret;
413 }
414 
QueueOutputBuffer(const std::shared_ptr<Buffer> & outputBuffer,int32_t timeoutMs)415 Status VideoFfmpegDecoderPlugin::QueueOutputBuffer(const std::shared_ptr<Buffer>& outputBuffer, int32_t timeoutMs)
416 {
417     outBufferQ_.Push(outputBuffer);
418     MEDIA_LOG_DD("QueueOutputBuffer success");
419     return Status::OK;
420 }
421 
Flush()422 Status VideoFfmpegDecoderPlugin::Flush()
423 {
424     OSAL::ScopedLock l(avMutex_);
425     if (avCodecContext_ != nullptr) {
426         avcodec_flush_buffers(avCodecContext_.get());
427     }
428     return Status::OK;
429 }
430 
QueueInputBuffer(const std::shared_ptr<Buffer> & inputBuffer,int32_t timeoutMs)431 Status VideoFfmpegDecoderPlugin::QueueInputBuffer(const std::shared_ptr<Buffer>& inputBuffer, int32_t timeoutMs)
432 {
433     if (inputBuffer->IsEmpty() && !(inputBuffer->flag & BUFFER_FLAG_EOS)) {
434         MEDIA_LOG_E("decoder does not support fd buffer");
435         return Status::ERROR_INVALID_DATA;
436     }
437     Status ret = Status::OK;
438     {
439         OSAL::ScopedLock l(avMutex_);
440         ret = SendBufferLocked(inputBuffer);
441     }
442     NotifyInputBufferDone(inputBuffer);
443     MEDIA_LOG_DD("QueueInputBuffer ret: " PUBLIC_LOG_U32, ret);
444     return ret;
445 }
446 
SendBufferLocked(const std::shared_ptr<Buffer> & inputBuffer)447 Status VideoFfmpegDecoderPlugin::SendBufferLocked(const std::shared_ptr<Buffer>& inputBuffer)
448 {
449     if (state_ != State::RUNNING) {
450         MEDIA_LOG_W("SendBufferLocked in wrong state: " PUBLIC_LOG_D32, state_);
451         return Status::ERROR_WRONG_STATE;
452     }
453     if (inputBuffer && !(inputBuffer->flag & BUFFER_FLAG_EOS)) {
454         auto inputMemory = inputBuffer->GetMemory();
455         const uint8_t* ptr = inputMemory->GetReadOnlyData();
456         auto bufferLength = inputMemory->GetSize();
457         size_t bufferEnd = bufferLength;
458         // pad to data if needed
459         if ((bufferLength % AV_INPUT_BUFFER_PADDING_SIZE != 0) &&
460             (bufferLength - bufferEnd + bufferLength % AV_INPUT_BUFFER_PADDING_SIZE < AV_INPUT_BUFFER_PADDING_SIZE)) {
461             if (paddedBufferSize_ < bufferLength + AV_INPUT_BUFFER_PADDING_SIZE) {
462                 paddedBufferSize_ = bufferLength + AV_INPUT_BUFFER_PADDING_SIZE;
463                 paddedBuffer_.reserve(paddedBufferSize_);
464                 MEDIA_LOG_I("increase padded buffer size to " PUBLIC_LOG_ZU, paddedBufferSize_);
465             }
466             paddedBuffer_.assign(ptr, ptr + bufferLength);
467             paddedBuffer_.insert(paddedBuffer_.end(), AV_INPUT_BUFFER_PADDING_SIZE, 0);
468             ptr = paddedBuffer_.data();
469         }
470         avPacket_->data = const_cast<uint8_t*>(ptr);
471         avPacket_->size = static_cast<int32_t>(bufferLength);
472         avPacket_->pts = static_cast<int64_t>(inputBuffer->pts);
473     }
474     auto ret = avcodec_send_packet(avCodecContext_.get(), avPacket_.get());
475     av_packet_unref(avPacket_.get());
476     if (ret < 0) {
477         MEDIA_LOG_DD("send buffer error " PUBLIC_LOG_S, AVStrError(ret).c_str());
478         return Status::ERROR_NO_MEMORY;
479     }
480     return Status::OK;
481 }
482 
483 #ifdef DUMP_RAW_DATA
DumpVideoRawOutData()484 void VideoFfmpegDecoderPlugin::DumpVideoRawOutData()
485 {
486     if (dumpFd_ == nullptr) {
487         return;
488     }
489     if (pixelFormat_ == VideoPixelFormat::YUV420P) {
490         if (scaleData_[0] != nullptr && scaleLineSize_[0] != 0) {
491             std::fwrite(reinterpret_cast<const char*>(scaleData_[0]),
492                         scaleLineSize_[0] * height_, 1, dumpFd_);
493         }
494         if (scaleData_[1] != nullptr && scaleLineSize_[1] != 0) {
495             std::fwrite(reinterpret_cast<const char*>(scaleData_[1]),
496                         scaleLineSize_[1] * height_ / 2, 1, dumpFd_); // 2
497         }
498         if (scaleData_[2] != nullptr && scaleLineSize_[2] != 0) { // 2
499             std::fwrite(reinterpret_cast<const char*>(scaleData_[2]),
500                         scaleLineSize_[2] * height_ / 2, 1, dumpFd_); // 2
501         }
502     } else if (pixelFormat_ == VideoPixelFormat::NV21 || pixelFormat_ == VideoPixelFormat::NV12) {
503         if (scaleData_[0] != nullptr && scaleLineSize_[0] != 0) {
504             std::fwrite(reinterpret_cast<const char*>(scaleData_[0]),
505                         scaleLineSize_[0] * height_, 1, dumpFd_);
506         }
507         if (scaleData_[1] != nullptr && scaleLineSize_[1] != 0) {
508             std::fwrite(reinterpret_cast<const char*>(scaleData_[1]),
509                         scaleLineSize_[1] * height_ / 2, 1, dumpFd_); // 2
510         }
511     } else if (pixelFormat_ == VideoPixelFormat::RGBA || pixelFormat_ == VideoPixelFormat::ARGB ||
512                pixelFormat_ == VideoPixelFormat::ABGR || pixelFormat_ == VideoPixelFormat::BGRA) {
513         if (scaleData_[0] != nullptr && scaleLineSize_[0] != 0) {
514             std::fwrite(reinterpret_cast<const char*>(scaleData_[0]),
515                         scaleLineSize_[0] * height_, 1, dumpFd_);
516         }
517     }
518 }
519 #endif
520 
ScaleVideoFrame()521 Status VideoFfmpegDecoderPlugin::ScaleVideoFrame()
522 {
523     if (ConvertPixelFormatFromFFmpeg(static_cast<AVPixelFormat>(cachedFrame_->format)) == pixelFormat_ &&
524         static_cast<uint32_t>(cachedFrame_->width) == width_ &&
525         static_cast<uint32_t>(cachedFrame_->height) == height_) {
526         for (int32_t i = 0; cachedFrame_->linesize[i] > 0; i++) {
527             scaleData_[i] = cachedFrame_->data[i];
528             scaleLineSize_[i] = cachedFrame_->linesize[i];
529         }
530         return Status::OK;
531     }
532     if (!scale_) {
533         scale_ = std::make_shared<Ffmpeg::Scale>();
534         Ffmpeg::ScalePara scalePara {
535             static_cast<int32_t>(cachedFrame_->width),
536             static_cast<int32_t>(cachedFrame_->height),
537             static_cast<AVPixelFormat>(cachedFrame_->format),
538             static_cast<int32_t>(width_),
539             static_cast<int32_t>(height_),
540             Ffmpeg::ConvertPixelFormatToFFmpeg(pixelFormat_),
541             STRIDE_ALIGN
542         };
543         FALSE_RETURN_V_MSG(scale_->Init(scalePara, scaleData_, scaleLineSize_) == Status::OK,
544             Status::ERROR_UNKNOWN, "Scale init error");
545         isAllocScaleData_ = true;
546     }
547     auto res = scale_->Convert(cachedFrame_->data, cachedFrame_->linesize, scaleData_, scaleLineSize_);
548     FALSE_RETURN_V_MSG_E(res == Status::OK, Status::ERROR_UNKNOWN, "Scale convert fail.");
549     MEDIA_LOG_D("ScaleVideoFrame success");
550     return Status::OK;
551 }
552 
553 #ifndef OHOS_LITE
WriteYuvDataStride(const std::shared_ptr<Buffer> & frameBuffer,int32_t stride)554 Status VideoFfmpegDecoderPlugin::WriteYuvDataStride(const std::shared_ptr<Buffer>& frameBuffer, int32_t stride)
555 {
556     auto frameBufferMem = frameBuffer->GetMemory();
557     size_t srcPos = 0;
558     size_t dstPos = 0;
559     if (pixelFormat_ == VideoPixelFormat::YUV420P) {
560         auto writeSize = scaleLineSize_[0];
561         for (uint32_t colNum = 0; colNum < height_; colNum++) {
562             frameBufferMem->Write(scaleData_[0] + srcPos, writeSize, dstPos);
563             dstPos += stride;
564         }
565         srcPos = 0;
566         writeSize = scaleLineSize_[1];
567         for (uint32_t colNum = 0; colNum < height_; colNum++) {
568             frameBufferMem->Write(scaleData_[1] + srcPos, writeSize, dstPos);
569             dstPos += stride;
570         }
571         srcPos = 0;
572         writeSize = scaleLineSize_[2]; // 2
573         for (uint32_t colNum = 0; colNum < height_; colNum++) {
574             frameBufferMem->Write(scaleData_[2] + srcPos, writeSize, dstPos); // 2
575             dstPos += stride;
576         }
577     } else if ((pixelFormat_ == VideoPixelFormat::NV12) || (pixelFormat_ == VideoPixelFormat::NV21)) {
578         auto writeSize = scaleLineSize_[0];
579         for (uint32_t colNum = 0; colNum < height_; colNum++) {
580             frameBufferMem->Write(scaleData_[0] + srcPos, writeSize, dstPos);
581             dstPos += stride;
582         }
583         srcPos = 0;
584         writeSize = scaleLineSize_[1];
585         for (uint32_t colNum = 0; colNum < height_; colNum++) {
586             frameBufferMem->Write(scaleData_[1] + srcPos, writeSize, dstPos);
587             dstPos += stride;
588         }
589     } else {
590         return Status::ERROR_UNSUPPORTED_FORMAT;
591     }
592     MEDIA_LOG_D("WriteYuvDataStride success");
593     return Status::OK;
594 }
595 
WriteRgbDataStride(const std::shared_ptr<Buffer> & frameBuffer,int32_t stride)596 Status VideoFfmpegDecoderPlugin::WriteRgbDataStride(const std::shared_ptr<Buffer>& frameBuffer, int32_t stride)
597 {
598     auto frameBufferMem = frameBuffer->GetMemory();
599     if (pixelFormat_ == VideoPixelFormat::RGBA || pixelFormat_ == VideoPixelFormat::ARGB ||
600         pixelFormat_ == VideoPixelFormat::ABGR || pixelFormat_ == VideoPixelFormat::BGRA) {
601         size_t srcPos = 0;
602         size_t dstPos = 0;
603         auto writeSize = scaleLineSize_[0];
604         for (uint32_t colNum = 0; colNum < height_; colNum++) {
605             frameBufferMem->Write(scaleData_[0] + srcPos, writeSize, dstPos);
606             dstPos += stride;
607         }
608     } else {
609         return Status::ERROR_UNSUPPORTED_FORMAT;
610     }
611     MEDIA_LOG_D("WriteRgbDataStride success");
612     return Status::OK;
613 }
614 #endif
615 
WriteYuvData(const std::shared_ptr<Buffer> & frameBuffer)616 Status VideoFfmpegDecoderPlugin::WriteYuvData(const std::shared_ptr<Buffer>& frameBuffer)
617 {
618     auto frameBufferMem = frameBuffer->GetMemory();
619 #ifndef OHOS_LITE
620     if (frameBufferMem->GetMemoryType() == Plugin::MemoryType::SURFACE_BUFFER) {
621         std::shared_ptr<Plugin::SurfaceMemory> surfaceMemory =
622                 Plugin::ReinterpretPointerCast<Plugin::SurfaceMemory>(frameBufferMem);
623         auto stride = surfaceMemory->GetSurfaceBufferStride();
624         if (stride % width_) {
625             return WriteYuvDataStride(frameBuffer, stride);
626         }
627     }
628 #endif
629     size_t ySize = static_cast<size_t>(scaleLineSize_[0] * height_);
630     // AV_PIX_FMT_YUV420P: scaleLineSize_[0] = scaleLineSize_[1] * 2 = scaleLineSize_[2] * 2
631     // AV_PIX_FMT_NV12: scaleLineSize_[0] = scaleLineSize_[1]
632     size_t uvSize = static_cast<size_t>(scaleLineSize_[1] * height_ / 2); // 2
633     size_t frameSize = 0;
634     if (pixelFormat_ == VideoPixelFormat::YUV420P) {
635         frameSize = ySize + (uvSize * 2); // 2
636     } else if (pixelFormat_ == VideoPixelFormat::NV21 || pixelFormat_ == VideoPixelFormat::NV12) {
637         frameSize = ySize + uvSize;
638     }
639     FALSE_RETURN_V_MSG_E(frameBufferMem->GetCapacity() >= frameSize, Status::ERROR_NO_MEMORY,
640                          "output buffer size is not enough: real[" PUBLIC_LOG "zu], need[" PUBLIC_LOG "zu]",
641                          frameBufferMem->GetCapacity(), frameSize);
642     if (pixelFormat_ == VideoPixelFormat::YUV420P) {
643         frameBufferMem->Write(scaleData_[0], ySize);
644         frameBufferMem->Write(scaleData_[1], uvSize);
645         frameBufferMem->Write(scaleData_[2], uvSize); // 2
646     } else if ((pixelFormat_ == VideoPixelFormat::NV12) || (pixelFormat_ == VideoPixelFormat::NV21)) {
647         frameBufferMem->Write(scaleData_[0], ySize);
648         frameBufferMem->Write(scaleData_[1], uvSize);
649     } else {
650         return Status::ERROR_UNSUPPORTED_FORMAT;
651     }
652     MEDIA_LOG_DD("WriteYuvData success");
653     return Status::OK;
654 }
655 
WriteRgbData(const std::shared_ptr<Buffer> & frameBuffer)656 Status VideoFfmpegDecoderPlugin::WriteRgbData(const std::shared_ptr<Buffer>& frameBuffer)
657 {
658     auto frameBufferMem = frameBuffer->GetMemory();
659 #ifndef OHOS_LITE
660     if (frameBufferMem->GetMemoryType() == Plugin::MemoryType::SURFACE_BUFFER) {
661         std::shared_ptr<Plugin::SurfaceMemory> surfaceMemory =
662                 Plugin::ReinterpretPointerCast<Plugin::SurfaceMemory>(frameBufferMem);
663         auto stride = surfaceMemory->GetSurfaceBufferStride();
664         if (stride % width_) {
665             return WriteRgbDataStride(frameBuffer, stride);
666         }
667     }
668 #endif
669     size_t frameSize = static_cast<size_t>(scaleLineSize_[0] * height_);
670     FALSE_RETURN_V_MSG_E(frameBufferMem->GetCapacity() >= frameSize, Status::ERROR_NO_MEMORY,
671                          "output buffer size is not enough: real[" PUBLIC_LOG "zu], need[" PUBLIC_LOG "zu]",
672                          frameBufferMem->GetCapacity(), frameSize);
673     if (pixelFormat_ == VideoPixelFormat::RGBA || pixelFormat_ == VideoPixelFormat::ARGB ||
674         pixelFormat_ == VideoPixelFormat::ABGR || pixelFormat_ == VideoPixelFormat::BGRA) {
675         frameBufferMem->Write(scaleData_[0], frameSize);
676     } else {
677         return Status::ERROR_UNSUPPORTED_FORMAT;
678     }
679     MEDIA_LOG_D("WriteRgbData success");
680     return Status::OK;
681 }
682 
FillFrameBuffer(const std::shared_ptr<Buffer> & frameBuffer)683 Status VideoFfmpegDecoderPlugin::FillFrameBuffer(const std::shared_ptr<Buffer>& frameBuffer)
684 {
685     MEDIA_LOG_DD("receive one frame: " PUBLIC_LOG_D32 ", picture type: " PUBLIC_LOG_D32 ", pixel format: "
686                  PUBLIC_LOG_D32 ", packet size: " PUBLIC_LOG_D32, cachedFrame_->key_frame,
687                  static_cast<int32_t>(cachedFrame_->pict_type), cachedFrame_->format, cachedFrame_->pkt_size);
688     FALSE_RETURN_V_MSG_E((cachedFrame_->flags & AV_FRAME_FLAG_CORRUPT) == 0, Status::ERROR_INVALID_DATA,
689                          "decoded frame is corrupt");
690     auto ret = ScaleVideoFrame();
691     FALSE_RETURN_V_MSG_E(ret == Status::OK, ret, "ScaleVideoFrame fail: " PUBLIC_LOG_D32, ret);
692     auto bufferMeta = frameBuffer->GetBufferMeta();
693     if (bufferMeta != nullptr && bufferMeta->GetType() == BufferMetaType::VIDEO) {
694         std::shared_ptr<VideoBufferMeta> videoMeta = ReinterpretPointerCast<VideoBufferMeta>(bufferMeta);
695         videoMeta->videoPixelFormat = pixelFormat_;
696         videoMeta->height = height_;
697         videoMeta->width = width_;
698         for (int i = 0; scaleLineSize_[i] > 0; ++i) {
699             videoMeta->stride.emplace_back(scaleLineSize_[i]);
700         }
701         videoMeta->planes = videoMeta->stride.size();
702     }
703 #ifdef DUMP_RAW_DATA
704     DumpVideoRawOutData();
705 #endif
706     auto newFormat = ConvertPixelFormatToFFmpeg(pixelFormat_);
707     if (IsYuvFormat(newFormat)) {
708         FALSE_RETURN_V_MSG_E(WriteYuvData(frameBuffer) == Status::OK, Status::ERROR_UNSUPPORTED_FORMAT,
709                              "Unsupported pixel format: " PUBLIC_LOG_U32, pixelFormat_);
710     } else if (IsRgbFormat(newFormat)) {
711         FALSE_RETURN_V_MSG_E(WriteRgbData(frameBuffer) == Status::OK, Status::ERROR_UNSUPPORTED_FORMAT,
712                              "Unsupported pixel format: " PUBLIC_LOG_U32, pixelFormat_);
713     } else {
714         MEDIA_LOG_E("Unsupported pixel format: " PUBLIC_LOG_U32, pixelFormat_);
715         return Status::ERROR_UNSUPPORTED_FORMAT;
716     }
717     frameBuffer->pts = static_cast<uint64_t>(cachedFrame_->pts);
718     MEDIA_LOG_DD("FillFrameBuffer success");
719     return Status::OK;
720 }
721 
ReceiveBufferLocked(const std::shared_ptr<Buffer> & frameBuffer)722 Status VideoFfmpegDecoderPlugin::ReceiveBufferLocked(const std::shared_ptr<Buffer>& frameBuffer)
723 {
724     if (state_ != State::RUNNING) {
725         MEDIA_LOG_W("ReceiveBufferLocked in wrong state: " PUBLIC_LOG_D32, state_);
726         return Status::ERROR_WRONG_STATE;
727     }
728     Status status;
729     auto ret = avcodec_receive_frame(avCodecContext_.get(), cachedFrame_.get());
730     if (ret >= 0) {
731         status = FillFrameBuffer(frameBuffer);
732     } else if (ret == AVERROR_EOF) {
733         MEDIA_LOG_I("eos received");
734         frameBuffer->GetMemory()->Reset();
735         frameBuffer->flag |= BUFFER_FLAG_EOS;
736         avcodec_flush_buffers(avCodecContext_.get());
737         status = Status::END_OF_STREAM;
738     } else {
739         MEDIA_LOG_DD("video decoder receive error: " PUBLIC_LOG_S, AVStrError(ret).c_str());
740         status = Status::ERROR_TIMED_OUT;
741     }
742     av_frame_unref(cachedFrame_.get());
743     MEDIA_LOG_DD("ReceiveBufferLocked status: " PUBLIC_LOG_U32, status);
744     return status;
745 }
746 
ReceiveFrameBuffer()747 void VideoFfmpegDecoderPlugin::ReceiveFrameBuffer()
748 {
749     std::shared_ptr<Buffer> frameBuffer = outBufferQ_.Pop();
750     if (frameBuffer == nullptr || frameBuffer->IsEmpty()) {
751         MEDIA_LOG_W("cannot fetch valid buffer to output");
752         return;
753     }
754     auto frameMeta = frameBuffer->GetBufferMeta();
755     if (frameMeta == nullptr || frameMeta->GetType() != BufferMetaType::VIDEO) {
756         MEDIA_LOG_W("output buffer is not video buffer");
757         return;
758     }
759     Status status;
760     {
761         OSAL::ScopedLock l(avMutex_);
762         status = ReceiveBufferLocked(frameBuffer);
763     }
764     if (status == Status::OK || status == Status::END_OF_STREAM) {
765         NotifyOutputBufferDone(frameBuffer);
766     } else {
767         outBufferQ_.Push(frameBuffer);
768     }
769 }
770 
NotifyInputBufferDone(const std::shared_ptr<Buffer> & input)771 void VideoFfmpegDecoderPlugin::NotifyInputBufferDone(const std::shared_ptr<Buffer>& input)
772 {
773     if (dataCb_ != nullptr) {
774         dataCb_->OnInputBufferDone(input);
775     }
776 }
777 
NotifyOutputBufferDone(const std::shared_ptr<Buffer> & output)778 void VideoFfmpegDecoderPlugin::NotifyOutputBufferDone(const std::shared_ptr<Buffer>& output)
779 {
780     if (dataCb_ != nullptr) {
781         dataCb_->OnOutputBufferDone(output);
782     }
783 }
784 
GetAllocator()785 std::shared_ptr<Allocator> VideoFfmpegDecoderPlugin::GetAllocator()
786 {
787     return nullptr;
788 }
789 } // namespace Plugin
790 } // namespace Media
791 } // namespace OHOS
792 #endif
793