1 /*
2 * Copyright (c) 2023-2025 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 #define MEDIA_PIPELINE
17
18 #include "decoder_surface_filter.h"
19 #include <sys/time.h>
20 #include "filter/filter_factory.h"
21 #include "plugin/plugin_time.h"
22 #include "avcodec_errors.h"
23 #include "common/log.h"
24 #include "common/media_core.h"
25 #include "avcodec_info.h"
26 #include "avcodec_common.h"
27 #include "avcodec_list.h"
28 #include "osal/utils/util.h"
29 #include "parameters.h"
30 #include "scope_guard.h"
31 #ifdef SUPPORT_DRM
32 #include "i_keysession_service.h"
33 #endif
34
35 namespace {
36 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_DOMAIN_SYSTEM_PLAYER, "DecoderSurfaceFilter" };
37 }
38
39 namespace OHOS {
40 namespace Media {
41 namespace Pipeline {
42 static const int64_t PLAY_RANGE_DEFAULT_VALUE = -1;
43 static const int64_t MICROSECONDS_CONVERT_UNIT = 1000; // ms change to us
44 static const int64_t NS_PER_US = 1000; // us change to ns
45 static const uint32_t PREROLL_WAIT_TIME = 1000; // Lock wait for 1000ms.
46 static const uint32_t TASK_DELAY_TOLERANCE = 5 * 1000 * 1000; // task delay tolerance 5_000_000ns also 5ms
47 static const int64_t MAX_DEBUG_LOG = 10;
48 static const int32_t MAX_ADVANCE_US = 80000; // max advance us at render time
49
50 static AutoRegisterFilter<DecoderSurfaceFilter> g_registerDecoderSurfaceFilter("builtin.player.videodecoder",
__anon9c2e0f1f0202(const std::string& name, const FilterType type) 51 FilterType::FILTERTYPE_VDEC, [](const std::string& name, const FilterType type) {
52 return std::make_shared<DecoderSurfaceFilter>(name, FilterType::FILTERTYPE_VDEC);
53 });
54
55 static const bool IS_FILTER_ASYNC = system::GetParameter("persist.media_service.async_filter", "1") == "1";
56
57 static const std::string VIDEO_INPUT_BUFFER_QUEUE_NAME = "VideoDecoderInputBufferQueue";
58
59 class DecoderSurfaceFilterLinkCallback : public FilterLinkCallback {
60 public:
DecoderSurfaceFilterLinkCallback(std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter)61 explicit DecoderSurfaceFilterLinkCallback(std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter)
62 : decoderSurfaceFilter_(decoderSurfaceFilter) {}
63
64 ~DecoderSurfaceFilterLinkCallback() = default;
65
OnLinkedResult(const sptr<AVBufferQueueProducer> & queue,std::shared_ptr<Meta> & meta)66 void OnLinkedResult(const sptr<AVBufferQueueProducer> &queue, std::shared_ptr<Meta> &meta) override
67 {
68 MEDIA_LOG_I("OnLinkedResult");
69 decoderSurfaceFilter_->OnLinkedResult(queue, meta);
70 }
71
OnUnlinkedResult(std::shared_ptr<Meta> & meta)72 void OnUnlinkedResult(std::shared_ptr<Meta> &meta) override
73 {
74 decoderSurfaceFilter_->OnUnlinkedResult(meta);
75 }
76
OnUpdatedResult(std::shared_ptr<Meta> & meta)77 void OnUpdatedResult(std::shared_ptr<Meta> &meta) override
78 {
79 decoderSurfaceFilter_->OnUpdatedResult(meta);
80 }
81 private:
82 std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter_;
83 };
84
85 const std::unordered_map<VideoScaleType, OHOS::ScalingMode> SCALEMODE_MAP = {
86 { VideoScaleType::VIDEO_SCALE_TYPE_FIT, OHOS::SCALING_MODE_SCALE_TO_WINDOW },
87 { VideoScaleType::VIDEO_SCALE_TYPE_FIT_CROP, OHOS::SCALING_MODE_SCALE_CROP},
88 };
89
90 class FilterVideoPostProcessorCallback : public PostProcessorCallback {
91 public:
FilterVideoPostProcessorCallback(std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter)92 explicit FilterVideoPostProcessorCallback(std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter)
93 : decoderSurfaceFilter_(decoderSurfaceFilter) {}
94
95 ~FilterVideoPostProcessorCallback() = default;
96
OnError(int32_t errorCode)97 void OnError(int32_t errorCode) override
98 {
99 if (auto decoderSurfaceFilter = decoderSurfaceFilter_.lock()) {
100 decoderSurfaceFilter->PostProcessorOnError(errorCode);
101 } else {
102 MEDIA_LOG_I("invalid decoderSurfaceFilter");
103 }
104 }
105
OnOutputFormatChanged(const Format & format)106 void OnOutputFormatChanged(const Format &format) override
107 {
108 }
109
OnInputBufferAvailable(uint32_t index,std::shared_ptr<AVBuffer> buffer)110 void OnInputBufferAvailable(uint32_t index, std::shared_ptr<AVBuffer> buffer) override
111 {
112 }
113
OnOutputBufferAvailable(uint32_t index,std::shared_ptr<AVBuffer> buffer)114 void OnOutputBufferAvailable(uint32_t index, std::shared_ptr<AVBuffer> buffer) override
115 {
116 if (auto decoderSurfaceFilter = decoderSurfaceFilter_.lock()) {
117 decoderSurfaceFilter->DrainOutputBuffer(index, buffer);
118 } else {
119 MEDIA_LOG_I("invalid decoderSurfaceFilter");
120 }
121 }
122 private:
123 std::weak_ptr<DecoderSurfaceFilter> decoderSurfaceFilter_;
124 };
125
126 class FilterMediaCodecCallbackWithPostProcessor : public OHOS::MediaAVCodec::MediaCodecCallback {
127 public:
FilterMediaCodecCallbackWithPostProcessor(std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter)128 explicit FilterMediaCodecCallbackWithPostProcessor(std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter)
129 : decoderSurfaceFilter_(decoderSurfaceFilter) {}
130
131 ~FilterMediaCodecCallbackWithPostProcessor() = default;
132
OnError(MediaAVCodec::AVCodecErrorType errorType,int32_t errorCode)133 void OnError(MediaAVCodec::AVCodecErrorType errorType, int32_t errorCode) override
134 {
135 if (auto decoderSurfaceFilter = decoderSurfaceFilter_.lock()) {
136 decoderSurfaceFilter->OnError(errorType, errorCode);
137 } else {
138 MEDIA_LOG_I("invalid decoderSurfaceFilter");
139 }
140 }
141
OnOutputFormatChanged(const MediaAVCodec::Format & format)142 void OnOutputFormatChanged(const MediaAVCodec::Format &format) override
143 {
144 if (auto decoderSurfaceFilter = decoderSurfaceFilter_.lock()) {
145 decoderSurfaceFilter->OnOutputFormatChanged(format);
146 } else {
147 MEDIA_LOG_I("invalid decoderSurfaceFilter");
148 }
149 }
150
OnInputBufferAvailable(uint32_t index,std::shared_ptr<AVBuffer> buffer)151 void OnInputBufferAvailable(uint32_t index, std::shared_ptr<AVBuffer> buffer) override
152 {
153 }
154
OnOutputBufferAvailable(uint32_t index,std::shared_ptr<AVBuffer> buffer)155 void OnOutputBufferAvailable(uint32_t index, std::shared_ptr<AVBuffer> buffer) override
156 {
157 if (auto decoderSurfaceFilter = decoderSurfaceFilter_.lock()) {
158 decoderSurfaceFilter->DecoderDrainOutputBuffer(index, buffer);
159 } else {
160 MEDIA_LOG_I("invalid decoderSurfaceFilter");
161 }
162 }
163
164 private:
165 std::weak_ptr<DecoderSurfaceFilter> decoderSurfaceFilter_;
166 };
167
168 class FilterMediaCodecCallback : public OHOS::MediaAVCodec::MediaCodecCallback {
169 public:
FilterMediaCodecCallback(std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter)170 explicit FilterMediaCodecCallback(std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter)
171 : decoderSurfaceFilter_(decoderSurfaceFilter) {}
172
173 ~FilterMediaCodecCallback() = default;
174
OnError(MediaAVCodec::AVCodecErrorType errorType,int32_t errorCode)175 void OnError(MediaAVCodec::AVCodecErrorType errorType, int32_t errorCode) override
176 {
177 auto decoderSurfaceFilter = decoderSurfaceFilter_.lock();
178 FALSE_RETURN_MSG(decoderSurfaceFilter != nullptr, "invalid decoderSurfaceFilter");
179 decoderSurfaceFilter->OnError(errorType, errorCode);
180 }
181
OnOutputFormatChanged(const MediaAVCodec::Format & format)182 void OnOutputFormatChanged(const MediaAVCodec::Format &format) override
183 {
184 auto decoderSurfaceFilter = decoderSurfaceFilter_.lock();
185 FALSE_RETURN_MSG(decoderSurfaceFilter != nullptr, "invalid decoderSurfaceFilter");
186 decoderSurfaceFilter->OnOutputFormatChanged(format);
187 }
188
OnInputBufferAvailable(uint32_t index,std::shared_ptr<AVBuffer> buffer)189 void OnInputBufferAvailable(uint32_t index, std::shared_ptr<AVBuffer> buffer) override
190 {
191 }
192
OnOutputBufferAvailable(uint32_t index,std::shared_ptr<AVBuffer> buffer)193 void OnOutputBufferAvailable(uint32_t index, std::shared_ptr<AVBuffer> buffer) override
194 {
195 auto decoderSurfaceFilter = decoderSurfaceFilter_.lock();
196 FALSE_RETURN_MSG(decoderSurfaceFilter != nullptr, "invalid decoderSurfaceFilter");
197 decoderSurfaceFilter->DrainOutputBuffer(index, buffer);
198 }
199
200 private:
201 std::weak_ptr<DecoderSurfaceFilter> decoderSurfaceFilter_;
202 };
203
204
205 class AVBufferAvailableListener : public OHOS::Media::IConsumerListener {
206 public:
AVBufferAvailableListener(std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter)207 explicit AVBufferAvailableListener(std::shared_ptr<DecoderSurfaceFilter> decoderSurfaceFilter)
208 {
209 decoderSurfaceFilter_ = decoderSurfaceFilter;
210 }
211 ~AVBufferAvailableListener() = default;
212
OnBufferAvailable()213 void OnBufferAvailable()
214 {
215 auto decoderSurfaceFilter = decoderSurfaceFilter_.lock();
216 FALSE_RETURN_MSG(decoderSurfaceFilter != nullptr, "invalid decoderSurfaceFilter");
217 decoderSurfaceFilter->HandleInputBuffer();
218 }
219
220 private:
221 std::weak_ptr<DecoderSurfaceFilter> decoderSurfaceFilter_;
222 };
223
DecoderSurfaceFilter(const std::string & name,FilterType type)224 DecoderSurfaceFilter::DecoderSurfaceFilter(const std::string& name, FilterType type)
225 : Filter(name, type, IS_FILTER_ASYNC)
226 {
227 videoDecoder_ = std::make_shared<VideoDecoderAdapter>();
228 videoSink_ = std::make_shared<VideoSink>();
229 filterType_ = type;
230 enableRenderAtTime_ = system::GetParameter("debug.media_service.enable_renderattime", "1") == "1";
231 renderTimeMaxAdvanceUs_ = static_cast<int64_t>
232 (system::GetIntParameter("debug.media_service.renderattime_advance", MAX_ADVANCE_US));
233 enableRenderAtTimeDfx_ = system::GetParameter("debug.media_service.enable_renderattime_dfx", "0") == "1";
234 }
235
~DecoderSurfaceFilter()236 DecoderSurfaceFilter::~DecoderSurfaceFilter()
237 {
238 MEDIA_LOG_I("~DecoderSurfaceFilter()");
239 ON_SCOPE_EXIT(0) {
240 DoRelease();
241 MEDIA_LOG_I("~DecoderSurfaceFilter() exit.");
242 };
243 FALSE_RETURN(!IS_FILTER_ASYNC && !isThreadExit_);
244 isThreadExit_ = true;
245 condBufferAvailable_.notify_all();
246 FALSE_RETURN(readThread_ != nullptr && readThread_->joinable());
247 readThread_->join();
248 readThread_ = nullptr;
249 }
250
OnError(MediaAVCodec::AVCodecErrorType errorType,int32_t errorCode)251 void DecoderSurfaceFilter::OnError(MediaAVCodec::AVCodecErrorType errorType, int32_t errorCode)
252 {
253 MEDIA_LOG_E("AVCodec error happened. ErrorType: %{public}d, errorCode: %{public}d",
254 static_cast<int32_t>(errorType), errorCode);
255 FALSE_RETURN(eventReceiver_ != nullptr);
256 eventReceiver_->OnEvent({"DecoderSurfaceFilter", EventType::EVENT_ERROR, MSERR_EXT_API9_IO});
257 }
258
PostProcessorOnError(int32_t errorCode)259 void DecoderSurfaceFilter::PostProcessorOnError(int32_t errorCode)
260 {
261 MEDIA_LOG_E("Post processor error happened. ErrorCode: %{public}d", errorCode);
262 FALSE_RETURN(eventReceiver_ != nullptr);
263 eventReceiver_->OnEvent({"DecoderSurfaceFilter", EventType::EVENT_ERROR, MSERR_EXT_API9_IO});
264 }
265
Init(const std::shared_ptr<EventReceiver> & receiver,const std::shared_ptr<FilterCallback> & callback)266 void DecoderSurfaceFilter::Init(const std::shared_ptr<EventReceiver> &receiver,
267 const std::shared_ptr<FilterCallback> &callback)
268 {
269 MEDIA_LOG_I("Init");
270 eventReceiver_ = receiver;
271 filterCallback_ = callback;
272 videoSink_->SetEventReceiver(eventReceiver_);
273 FALSE_RETURN(videoDecoder_ != nullptr);
274 videoDecoder_->SetEventReceiver(eventReceiver_);
275 }
276
Configure(const std::shared_ptr<Meta> & parameter)277 Status DecoderSurfaceFilter::Configure(const std::shared_ptr<Meta> ¶meter)
278 {
279 MEDIA_LOG_I("Configure");
280 configureParameter_ = parameter;
281 configFormat_.SetMeta(configureParameter_);
282 Status ret = videoDecoder_->Configure(configFormat_);
283
284 std::shared_ptr<MediaAVCodec::MediaCodecCallback> mediaCodecCallback = nullptr;
285 if (postProcessor_ != nullptr) {
286 mediaCodecCallback = std::make_shared<FilterMediaCodecCallbackWithPostProcessor>(shared_from_this());
287 std::shared_ptr<PostProcessorCallback> postProcessorCallback
288 = std::make_shared<FilterVideoPostProcessorCallback>(shared_from_this());
289 postProcessor_->SetCallback(postProcessorCallback);
290 } else {
291 mediaCodecCallback = std::make_shared<FilterMediaCodecCallback>(shared_from_this());
292 }
293 videoDecoder_->SetCallback(mediaCodecCallback);
294 return ret;
295 }
296
DoInitAfterLink()297 Status DecoderSurfaceFilter::DoInitAfterLink()
298 {
299 Status ret;
300 // create secure decoder for drm.
301 MEDIA_LOG_I("DoInit enter the codecMimeType_ is %{public}s", codecMimeType_.c_str());
302 if (videoDecoder_ != nullptr) {
303 videoDecoder_->SetCallingInfo(appUid_, appPid_, bundleName_, instanceId_);
304 } else {
305 return Status::ERROR_UNKNOWN;
306 }
307 videoDecoder_->SetCallingInfo(appUid_, appPid_, bundleName_, instanceId_);
308 if (isDrmProtected_ && svpFlag_) {
309 MEDIA_LOG_D("DecoderSurfaceFilter will create secure decoder for drm-protected videos");
310 std::string baseName = GetCodecName(codecMimeType_);
311 FALSE_RETURN_V_MSG(!baseName.empty(),
312 Status::ERROR_INVALID_PARAMETER, "get name by mime failed.");
313 std::string secureDecoderName = baseName + ".secure";
314 MEDIA_LOG_D("DecoderSurfaceFilter will create secure decoder %{public}s", secureDecoderName.c_str());
315 ret = videoDecoder_->Init(MediaAVCodec::AVCodecType::AVCODEC_TYPE_VIDEO_DECODER, false, secureDecoderName);
316 } else {
317 ret = videoDecoder_->Init(MediaAVCodec::AVCodecType::AVCODEC_TYPE_VIDEO_DECODER, true, codecMimeType_);
318 }
319
320 if (ret != Status::OK && eventReceiver_ != nullptr) {
321 MEDIA_LOG_E("Init decoder fail ret = %{public}d", ret);
322 eventReceiver_->OnEvent({"decoderSurface", EventType::EVENT_ERROR, MSERR_UNSUPPORT_VID_DEC_TYPE});
323 return Status::ERROR_UNSUPPORTED_FORMAT;
324 }
325
326 ret = Configure(meta_);
327 if (ret != Status::OK) {
328 eventReceiver_->OnEvent({"decoderSurface", EventType::EVENT_ERROR, MSERR_UNSUPPORT_VID_SRC_TYPE});
329 return Status::ERROR_UNSUPPORTED_FORMAT;
330 }
331 ParseDecodeRateLimit();
332 videoDecoder_->SetOutputSurface(decoderOutputSurface_);
333 if (isDrmProtected_) {
334 #ifdef SUPPORT_DRM
335 videoDecoder_->SetDecryptConfig(keySessionServiceProxy_, svpFlag_);
336 #endif
337 }
338
339 ret = InitPostProcessor();
340 FALSE_RETURN_V(ret == Status::OK, ret);
341
342 videoSink_->SetParameter(meta_);
343 eosTask_ = std::make_unique<Task>("OS_EOSv", groupId_, TaskType::VIDEO, TaskPriority::HIGH, false);
344 return Status::OK;
345 }
346
DoPrepare()347 Status DecoderSurfaceFilter::DoPrepare()
348 {
349 MEDIA_LOG_I("Prepare");
350 if (onLinkedResultCallback_ != nullptr) {
351 videoDecoder_->PrepareInputBufferQueue();
352 sptr<IConsumerListener> listener = new AVBufferAvailableListener(shared_from_this());
353 sptr<Media::AVBufferQueueConsumer> inputBufferQueueConsumer = videoDecoder_->GetBufferQueueConsumer();
354 inputBufferQueueConsumer->SetBufferAvailableListener(listener);
355 onLinkedResultCallback_->OnLinkedResult(videoDecoder_->GetBufferQueueProducer(), meta_);
356 if (seiMessageCbStatus_) {
357 inputBufferQueueProducer_ = videoDecoder_->GetBufferQueueProducer();
358 }
359 }
360 isRenderStarted_ = false;
361 return Status::OK;
362 }
363
HandleInputBuffer()364 Status DecoderSurfaceFilter::HandleInputBuffer()
365 {
366 ProcessInputBuffer();
367 return Status::OK;
368 }
369
DoStart()370 Status DecoderSurfaceFilter::DoStart()
371 {
372 MEDIA_LOG_I("Start");
373 if (isPaused_.load()) {
374 MEDIA_LOG_I("DoStart after pause to execute resume.");
375 return DoResume();
376 }
377 if (!IS_FILTER_ASYNC) {
378 isThreadExit_ = false;
379 isPaused_ = false;
380 readThread_ = std::make_unique<std::thread>(&DecoderSurfaceFilter::RenderLoop, this);
381 pthread_setname_np(readThread_->native_handle(), "RenderLoop");
382 }
383 auto ret = videoDecoder_->Start();
384 FALSE_RETURN_V(ret == Status::OK, ret);
385 if (postProcessor_) {
386 ret = postProcessor_->Start();
387 }
388 return ret;
389 }
390
DoPause()391 Status DecoderSurfaceFilter::DoPause()
392 {
393 MEDIA_LOG_I("Pause");
394 isPaused_ = true;
395 isFirstFrameAfterResume_ = false;
396 if (!IS_FILTER_ASYNC) {
397 condBufferAvailable_.notify_all();
398 }
399 videoSink_->ResetSyncInfo();
400 latestPausedTime_ = latestBufferTime_;
401 return Status::OK;
402 }
403
DoPauseDragging()404 Status DecoderSurfaceFilter::DoPauseDragging()
405 {
406 MEDIA_LOG_I("DoPauseDragging enter.");
407 DoPause();
408 lastRenderTimeNs_ = GetSystimeTimeNs();
409 {
410 std::unique_lock<std::mutex> lock(mutex_);
411 if (!outputBufferMap_.empty()) {
412 MEDIA_LOG_E("DoPauseDragging outputBufferMap_ size = %{public}zu", outputBufferMap_.size());
413 for (auto it = outputBufferMap_.begin(); it != outputBufferMap_.end(); ++it) {
414 DoReleaseOutputBuffer(it->first, false);
415 }
416 outputBufferMap_.clear();
417 }
418 }
419 return Status::OK;
420 }
421
DoResume()422 Status DecoderSurfaceFilter::DoResume()
423 {
424 MEDIA_LOG_I("Resume");
425 refreshTotalPauseTime_ = true;
426 isPaused_ = false;
427 isFirstFrameAfterResume_ = true;
428 if (!IS_FILTER_ASYNC) {
429 condBufferAvailable_.notify_all();
430 }
431 videoDecoder_->Start();
432 if (postProcessor_) {
433 postProcessor_->Start();
434 }
435 return Status::OK;
436 }
437
DoResumeDragging()438 Status DecoderSurfaceFilter::DoResumeDragging()
439 {
440 MEDIA_LOG_I("DoResumeDragging enter.");
441 refreshTotalPauseTime_ = true;
442 isPaused_ = false;
443 lastRenderTimeNs_ = HST_TIME_NONE;
444 if (!IS_FILTER_ASYNC) {
445 condBufferAvailable_.notify_all();
446 }
447 videoDecoder_->Start();
448 if (postProcessor_) {
449 postProcessor_->Start();
450 }
451 return Status::OK;
452 }
453
DoStop()454 Status DecoderSurfaceFilter::DoStop()
455 {
456 MEDIA_LOG_I("Stop");
457 latestBufferTime_ = HST_TIME_NONE;
458 latestPausedTime_ = HST_TIME_NONE;
459 totalPausedTime_ = 0;
460 refreshTotalPauseTime_ = false;
461 isPaused_ = false;
462 lastRenderTimeNs_ = HST_TIME_NONE;
463 playRangeStartTime_ = PLAY_RANGE_DEFAULT_VALUE;
464 playRangeEndTime_ = PLAY_RANGE_DEFAULT_VALUE;
465
466 timeval tv;
467 gettimeofday(&tv, 0);
468 stopTime_ = (int64_t)tv.tv_sec * 1000000 + (int64_t)tv.tv_usec; // 1000000 means transfering from s to us.
469 videoSink_->ResetSyncInfo();
470 auto ret = videoDecoder_->Stop();
471 Status ret2 = Status::OK;
472 if (postProcessor_) {
473 ret2 = postProcessor_->Stop();
474 }
475 if (!IS_FILTER_ASYNC && !isThreadExit_.load()) {
476 isThreadExit_ = true;
477 condBufferAvailable_.notify_all();
478 FALSE_RETURN_V(readThread_ != nullptr && readThread_->joinable(), ret);
479 readThread_->join();
480 readThread_ = nullptr;
481 }
482 FALSE_RETURN_V(ret == Status::OK, ret);
483 return ret2;
484 }
485
DoFlush()486 Status DecoderSurfaceFilter::DoFlush()
487 {
488 MEDIA_LOG_I("Flush");
489 lastRenderTimeNs_ = HST_TIME_NONE;
490 videoDecoder_->Flush();
491 if (postProcessor_) {
492 postProcessor_->Flush();
493 }
494 {
495 std::lock_guard<std::mutex> lock(mutex_);
496 MEDIA_LOG_I("Flush");
497 outputBuffers_.clear();
498 outputBufferMap_.clear();
499 }
500 videoSink_->ResetSyncInfo();
501 return Status::OK;
502 }
503
DoRelease()504 Status DecoderSurfaceFilter::DoRelease()
505 {
506 MEDIA_LOG_I("Release");
507 videoDecoder_->Release();
508 if (postProcessor_) {
509 postProcessor_->Release();
510 }
511 return Status::OK;
512 }
513
DoPreroll()514 Status DecoderSurfaceFilter::DoPreroll()
515 {
516 MEDIA_LOG_I("DoPreroll enter.");
517 std::lock_guard<std::mutex> lock(prerollMutex_);
518 Status ret = Status::OK;
519 FALSE_RETURN_V_MSG(!inPreroll_.load(), Status::OK, "DoPreroll in preroll now.");
520 inPreroll_.store(true);
521 prerollDone_.store(false);
522 eosNext_.store(false);
523 if (isPaused_.load()) {
524 ret = DoResume();
525 } else {
526 ret = DoStart();
527 }
528 if (ret != Status::OK) {
529 MEDIA_LOG_E("video decoder start failed, ret = %{public}d", ret);
530 eventReceiver_->OnEvent({"decoderSurface", EventType::EVENT_ERROR,
531 MSERR_VID_DEC_FAILED});
532 }
533 Filter::StartFilterTask();
534 return ret;
535 }
536
DoWaitPrerollDone(bool render)537 Status DecoderSurfaceFilter::DoWaitPrerollDone(bool render)
538 {
539 MEDIA_LOG_I("DoWaitPrerollDone enter.");
540 std::unique_lock<std::mutex> lock(prerollMutex_);
541 FALSE_RETURN_V(inPreroll_.load(), Status::OK);
542 if (prerollDone_.load() || isInterruptNeeded_.load()) {
543 MEDIA_LOG_I("Receive preroll frame before DoWaitPrerollDone.");
544 } else {
545 prerollDoneCond_.wait_for(lock, std::chrono::milliseconds(PREROLL_WAIT_TIME),
546 [this] () { return prerollDone_.load() || isInterruptNeeded_.load(); });
547 }
548 Filter::PauseFilterTask();
549 DoPause();
550 if (!prerollDone_.load()) {
551 MEDIA_LOG_E("No preroll frame received!");
552 inPreroll_.store(false);
553 prerollDone_.store(true);
554 eosNext_.store(false);
555 return Status::OK;
556 }
557 std::unique_lock<std::mutex> bufferLock(mutex_);
558 if (render && !eosNext_.load() && !outputBuffers_.empty()) {
559 std::pair<int, std::shared_ptr<AVBuffer>> nextTask = std::move(outputBuffers_.front());
560 outputBuffers_.pop_front();
561 DoReleaseOutputBuffer(nextTask.first, true);
562 }
563 eosNext_.store(false);
564 if (!outputBuffers_.empty()) {
565 Filter::ProcessOutputBuffer(1, 0);
566 }
567 inPreroll_.store(false);
568 return Status::OK;
569 }
570
DoSetPerfRecEnabled(bool isPerfRecEnabled)571 Status DecoderSurfaceFilter::DoSetPerfRecEnabled(bool isPerfRecEnabled)
572 {
573 isPerfRecEnabled_ = isPerfRecEnabled;
574 Status res = Status::OK;
575 if (videoSink_ != nullptr) {
576 res = videoSink_->SetPerfRecEnabled(isPerfRecEnabled);
577 }
578 if (videoDecoder_ != nullptr) {
579 res = videoDecoder_->SetPerfRecEnabled(isPerfRecEnabled);
580 }
581 return res;
582 }
583
DoSetPlayRange(int64_t start,int64_t end)584 Status DecoderSurfaceFilter::DoSetPlayRange(int64_t start, int64_t end)
585 {
586 MEDIA_LOG_I("DoSetPlayRange");
587 playRangeStartTime_ = start;
588 playRangeEndTime_ = end;
589 return Status::OK;
590 }
591
ConvertMediaScaleType(VideoScaleType scaleType)592 static OHOS::ScalingMode ConvertMediaScaleType(VideoScaleType scaleType)
593 {
594 if (SCALEMODE_MAP.find(scaleType) == SCALEMODE_MAP.end()) {
595 return OHOS::SCALING_MODE_SCALE_CROP;
596 }
597 return SCALEMODE_MAP.at(scaleType);
598 }
599
SetParameter(const std::shared_ptr<Meta> & parameter)600 void DecoderSurfaceFilter::SetParameter(const std::shared_ptr<Meta> ¶meter)
601 {
602 MEDIA_LOG_I("SetParameter %{public}i", parameter != nullptr);
603 Format format;
604 if (parameter->Find(Tag::VIDEO_SCALE_TYPE) != parameter->end()) {
605 int32_t scaleType;
606 parameter->Get<Tag::VIDEO_SCALE_TYPE>(scaleType);
607 int32_t codecScalingMode = static_cast<int32_t>(ConvertMediaScaleType(static_cast<VideoScaleType>(scaleType)));
608 format.PutIntValue(Tag::VIDEO_SCALE_TYPE, codecScalingMode);
609 configFormat_.PutIntValue(Tag::VIDEO_SCALE_TYPE, codecScalingMode);
610 }
611 if (parameter->Find(Tag::VIDEO_FRAME_RATE) != parameter->end()) {
612 double rate = 0.0;
613 parameter->Get<Tag::VIDEO_FRAME_RATE>(rate);
614 if (rate < 0) {
615 if (configFormat_.GetDoubleValue(Tag::VIDEO_FRAME_RATE, rate)) {
616 MEDIA_LOG_W("rate is invalid, get frame rate from the original resource: %{public}f", rate);
617 }
618 }
619 if (rate <= 0) {
620 rate = 30.0; // 30.0 is the hisi default frame rate.
621 }
622 format.PutDoubleValue(Tag::VIDEO_FRAME_RATE, rate);
623 }
624 // cannot set parameter when codec at [ CONFIGURED / INITIALIZED ] state
625 auto ret = videoDecoder_->SetParameter(format);
626 if (ret == MediaAVCodec::AVCS_ERR_INVALID_STATE) {
627 MEDIA_LOG_W("SetParameter at invalid state");
628 videoDecoder_->Reset();
629 if (!IS_FILTER_ASYNC && !isThreadExit_.load()) {
630 DoStop();
631 }
632 videoDecoder_->Configure(configFormat_);
633 videoDecoder_->SetOutputSurface(decoderOutputSurface_);
634 if (isDrmProtected_) {
635 #ifdef SUPPORT_DRM
636 videoDecoder_->SetDecryptConfig(keySessionServiceProxy_, svpFlag_);
637 #endif
638 }
639 }
640 videoDecoder_->SetParameter(format);
641 if (postProcessor_) {
642 postProcessor_->SetParameter(format);
643 }
644 }
645
GetLagInfo(int32_t & lagTimes,int32_t & maxLagDuration,int32_t & avgLagDuration)646 Status DecoderSurfaceFilter::GetLagInfo(int32_t& lagTimes, int32_t& maxLagDuration, int32_t& avgLagDuration)
647 {
648 FALSE_RETURN_V(videoSink_ != nullptr, Status::ERROR_INVALID_OPERATION);
649 videoSink_->GetLagInfo(lagTimes, maxLagDuration, avgLagDuration);
650 return Status::OK;
651 }
652
GetParameter(std::shared_ptr<Meta> & parameter)653 void DecoderSurfaceFilter::GetParameter(std::shared_ptr<Meta> ¶meter)
654 {
655 MEDIA_LOG_I("GetParameter enter parameter is valid: %{public}i", parameter != nullptr);
656 }
657
SetCallingInfo(int32_t appUid,int32_t appPid,std::string bundleName,uint64_t instanceId)658 void DecoderSurfaceFilter::SetCallingInfo(int32_t appUid, int32_t appPid, std::string bundleName, uint64_t instanceId)
659 {
660 appUid_ = appUid;
661 appPid_ = appPid;
662 bundleName_ = bundleName;
663 instanceId_ = instanceId;
664 }
665
OnInterrupted(bool isInterruptNeeded)666 void DecoderSurfaceFilter::OnInterrupted(bool isInterruptNeeded)
667 {
668 MEDIA_LOG_D("DecoderSurfaceFilter onInterrupted %{public}d", isInterruptNeeded);
669 std::lock_guard<std::mutex> lock(prerollMutex_);
670 isInterruptNeeded_ = isInterruptNeeded;
671 prerollDoneCond_.notify_all();
672 }
673
LinkNext(const std::shared_ptr<Filter> & nextFilter,StreamType outType)674 Status DecoderSurfaceFilter::LinkNext(const std::shared_ptr<Filter> &nextFilter, StreamType outType)
675 {
676 MEDIA_LOG_I("LinkNext enter, nextFilter is valid: %{public}i, outType: %{public}u",
677 nextFilter != nullptr, static_cast<uint32_t>(outType));
678 return Status::OK;
679 }
680
UpdateNext(const std::shared_ptr<Filter> & nextFilter,StreamType outType)681 Status DecoderSurfaceFilter::UpdateNext(const std::shared_ptr<Filter> &nextFilter, StreamType outType)
682 {
683 return Status::OK;
684 }
685
UnLinkNext(const std::shared_ptr<Filter> & nextFilter,StreamType outType)686 Status DecoderSurfaceFilter::UnLinkNext(const std::shared_ptr<Filter> &nextFilter, StreamType outType)
687 {
688 return Status::OK;
689 }
690
GetFilterType()691 FilterType DecoderSurfaceFilter::GetFilterType()
692 {
693 return filterType_;
694 }
695
GetCodecName(std::string mimeType)696 std::string DecoderSurfaceFilter::GetCodecName(std::string mimeType)
697 {
698 MEDIA_LOG_I("GetCodecName.");
699 std::string codecName;
700 auto codeclist = MediaAVCodec::AVCodecListFactory::CreateAVCodecList();
701 FALSE_RETURN_V_MSG_E(codeclist != nullptr, codecName, "GetCodecName failed due to codeclist nullptr.");
702 MediaAVCodec::Format format;
703 format.PutStringValue("codec_mime", mimeType);
704 codecName = codeclist->FindDecoder(format);
705 return codecName;
706 }
707
IsPostProcessorSupported()708 bool DecoderSurfaceFilter::IsPostProcessorSupported()
709 {
710 MEDIA_LOG_D("IsPostProcessorSupported enter.");
711 return VideoPostProcessorFactory::Instance().IsPostProcessorSupported(postProcessorType_, meta_);
712 }
713
OnLinked(StreamType inType,const std::shared_ptr<Meta> & meta,const std::shared_ptr<FilterLinkCallback> & callback)714 Status DecoderSurfaceFilter::OnLinked(StreamType inType, const std::shared_ptr<Meta> &meta,
715 const std::shared_ptr<FilterLinkCallback> &callback)
716 {
717 MEDIA_LOG_I("OnLinked");
718 meta_ = meta;
719 FALSE_RETURN_V_MSG(meta->GetData(Tag::MIME_TYPE, codecMimeType_),
720 Status::ERROR_INVALID_PARAMETER, "get mime failed.");
721
722 meta_->SetData(Tag::AV_PLAYER_IS_DRM_PROTECTED, isDrmProtected_);
723 isPostProcessorSupported_ = IsPostProcessorSupported();
724 if (!isPostProcessorSupported_ || CreatePostProcessor() == nullptr) {
725 isPostProcessorSupported_ = false;
726 if (postProcessorType_ == VideoPostProcessorType::SUPER_RESOLUTION) {
727 eventReceiver_->OnEvent({"SuperResolutionPostProcessor", EventType::EVENT_SUPER_RESOLUTION_CHANGED, false});
728 }
729 }
730 onLinkedResultCallback_ = callback;
731 return Filter::OnLinked(inType, meta, callback);
732 }
733
OnUpdated(StreamType inType,const std::shared_ptr<Meta> & meta,const std::shared_ptr<FilterLinkCallback> & callback)734 Status DecoderSurfaceFilter::OnUpdated(StreamType inType, const std::shared_ptr<Meta> &meta,
735 const std::shared_ptr<FilterLinkCallback> &callback)
736 {
737 return Status::OK;
738 }
739
OnUnLinked(StreamType inType,const std::shared_ptr<FilterLinkCallback> & callback)740 Status DecoderSurfaceFilter::OnUnLinked(StreamType inType, const std::shared_ptr<FilterLinkCallback>& callback)
741 {
742 return Status::OK;
743 }
744
OnLinkedResult(const sptr<AVBufferQueueProducer> & outputBufferQueue,std::shared_ptr<Meta> & meta)745 void DecoderSurfaceFilter::OnLinkedResult(const sptr<AVBufferQueueProducer> &outputBufferQueue,
746 std::shared_ptr<Meta> &meta)
747 {
748 MEDIA_LOG_I("OnLinkedResult");
749 }
750
OnUpdatedResult(std::shared_ptr<Meta> & meta)751 void DecoderSurfaceFilter::OnUpdatedResult(std::shared_ptr<Meta> &meta)
752 {
753 }
754
OnUnlinkedResult(std::shared_ptr<Meta> & meta)755 void DecoderSurfaceFilter::OnUnlinkedResult(std::shared_ptr<Meta> &meta)
756 {
757 }
758
DoProcessOutputBuffer(int recvArg,bool dropFrame,bool byIdx,uint32_t idx,int64_t renderTime)759 Status DecoderSurfaceFilter::DoProcessOutputBuffer(int recvArg, bool dropFrame, bool byIdx, uint32_t idx,
760 int64_t renderTime)
761 {
762 MEDIA_LOG_D("DoProcessOutputBuffer idx " PUBLIC_LOG_U32 " renderTime " PUBLIC_LOG_D64, idx, renderTime);
763 FALSE_RETURN_V(!dropFrame, Status::OK);
764 uint32_t index = idx;
765 std::shared_ptr<AVBuffer> outputBuffer = nullptr;
766 bool acquireRes = AcquireNextRenderBuffer(byIdx, index, outputBuffer, renderTime);
767 FALSE_RETURN_V(acquireRes, Status::OK);
768 ReleaseOutputBuffer(index, recvArg, outputBuffer, renderTime);
769 return Status::OK;
770 }
771
AcquireNextRenderBuffer(bool byIdx,uint32_t & index,std::shared_ptr<AVBuffer> & outBuffer,int64_t renderTime)772 bool DecoderSurfaceFilter::AcquireNextRenderBuffer(bool byIdx, uint32_t &index, std::shared_ptr<AVBuffer> &outBuffer,
773 int64_t renderTime)
774 {
775 std::unique_lock<std::mutex> lock(mutex_);
776 if (!byIdx) {
777 FALSE_RETURN_V(!outputBuffers_.empty(), false);
778 std::pair<int, std::shared_ptr<AVBuffer>> task = std::move(outputBuffers_.front());
779 outputBuffers_.pop_front();
780 FALSE_RETURN_V(task.first >= 0, false);
781 index = static_cast<uint32_t>(task.first);
782 outBuffer = task.second;
783 if (isFirstFrameAfterResume_) {
784 int64_t curTimeNs = GetSystimeTimeNs();
785 videoSink_->UpdateTimeAnchorActually(outBuffer,
786 (renderTime > 0 && renderTime > curTimeNs) ? renderTime - curTimeNs : 0);
787 isFirstFrameAfterResume_ = false;
788 }
789 if (!outputBuffers_.empty()) {
790 std::pair<int, std::shared_ptr<AVBuffer>> nextTask = outputBuffers_.front();
791 RenderNextOutput(nextTask.first, nextTask.second);
792 }
793 return true;
794 }
795 FALSE_RETURN_V(outputBufferMap_.find(index) != outputBufferMap_.end(), false);
796 outBuffer = outputBufferMap_[index];
797 outputBufferMap_.erase(index);
798 return true;
799 }
800
ReleaseOutputBuffer(int index,bool render,const std::shared_ptr<AVBuffer> & outBuffer,int64_t renderTime)801 Status DecoderSurfaceFilter::ReleaseOutputBuffer(int index, bool render, const std::shared_ptr<AVBuffer> &outBuffer,
802 int64_t renderTime)
803 {
804 if (!isRenderStarted_.load() && render && !(outBuffer->flag_ & static_cast<uint32_t>(Plugins::AVBufferFlag::EOS))
805 && !isInSeekContinous_) {
806 HandleFirstOutput();
807 }
808 if ((playRangeEndTime_ != PLAY_RANGE_DEFAULT_VALUE) &&
809 (outBuffer->pts_ > playRangeEndTime_ * MICROSECONDS_CONVERT_UNIT)) {
810 MEDIA_LOG_I("ReleaseBuffer for eos, SetPlayRange start: " PUBLIC_LOG_D64 ", end: " PUBLIC_LOG_D64,
811 playRangeStartTime_, playRangeEndTime_);
812 HandleEosOutput(index);
813 return Status::OK;
814 }
815
816 if ((outBuffer->flag_ & static_cast<uint32_t>(Plugins::AVBufferFlag::EOS)) && !isInSeekContinous_) {
817 ResetSeekInfo();
818 MEDIA_LOG_I("ReleaseBuffer for eos, index: %{public}u, bufferid: %{public}" PRIu64
819 ", pts: %{public}" PRIu64", flag: %{public}u", index, outBuffer->GetUniqueId(),
820 outBuffer->pts_, outBuffer->flag_);
821 HandleEosOutput(index);
822 return Status::OK;
823 }
824
825 if (outBuffer->pts_ < 0) {
826 MEDIA_LOG_W("Avoid render video frame with pts=" PUBLIC_LOG_D64, outBuffer->pts_);
827 DoReleaseOutputBuffer(index, false);
828 return Status::OK;
829 }
830
831 if (renderTime > 0L && render) {
832 int64_t currentSysTimeNs = GetSystimeTimeNs();
833 int64_t lastRenderTimeNs = lastRenderTimeNs_.load();
834 int64_t minRendererTime = std::max(currentSysTimeNs, lastRenderTimeNs == HST_TIME_NONE ? 0 : lastRenderTimeNs);
835 renderTime = renderTime < minRendererTime ? minRendererTime : renderTime;
836 MEDIA_LOG_D("ReleaseOutputBuffer index " PUBLIC_LOG_U32 " renderTime " PUBLIC_LOG_D64 " curTime " PUBLIC_LOG_D64
837 " lastRenderTimeNs " PUBLIC_LOG_D64, index, renderTime, currentSysTimeNs, lastRenderTimeNs);
838 RenderAtTimeDfx(renderTime, currentSysTimeNs, lastRenderTimeNs);
839 DoRenderOutputBufferAtTime(index, renderTime);
840 if (!isInSeekContinous_) {
841 lastRenderTimeNs_ = renderTime;
842 }
843 } else {
844 MEDIA_LOG_D("ReleaseOutputBuffer index= " PUBLIC_LOG_D32" isRender= " PUBLIC_LOG_U32" pts= " PUBLIC_LOG_D64,
845 index, static_cast<uint32_t>(render), outBuffer->pts_);
846 DoReleaseOutputBuffer(index, render);
847 }
848 if (!isInSeekContinous_) {
849 int64_t renderDelay = renderTime > 0L && render ?
850 (renderTime - GetSystimeTimeNs()) / MICROSECONDS_CONVERT_UNIT : 0;
851 videoSink_->SetLastPts(outBuffer->pts_, renderDelay);
852 }
853 return Status::OK;
854 }
855
DoReleaseOutputBuffer(uint32_t index,bool render)856 void DecoderSurfaceFilter::DoReleaseOutputBuffer(uint32_t index, bool render)
857 {
858 if (postProcessor_) {
859 postProcessor_->ReleaseOutputBuffer(index, render);
860 } else if (videoDecoder_) {
861 videoDecoder_->ReleaseOutputBuffer(index, render);
862 }
863 }
864
DoRenderOutputBufferAtTime(uint32_t index,int64_t renderTime)865 void DecoderSurfaceFilter::DoRenderOutputBufferAtTime(uint32_t index, int64_t renderTime)
866 {
867 if (postProcessor_) {
868 postProcessor_->RenderOutputBufferAtTime(index, renderTime);
869 } else if (videoDecoder_) {
870 videoDecoder_->RenderOutputBufferAtTime(index, renderTime);
871 }
872 }
873
DoProcessInputBuffer(int recvArg,bool dropFrame)874 Status DecoderSurfaceFilter::DoProcessInputBuffer(int recvArg, bool dropFrame)
875 {
876 videoDecoder_->AquireAvailableInputBuffer();
877 return Status::OK;
878 }
879
CalculateNextRender(uint32_t index,std::shared_ptr<AVBuffer> & outputBuffer)880 int64_t DecoderSurfaceFilter::CalculateNextRender(uint32_t index, std::shared_ptr<AVBuffer> &outputBuffer)
881 {
882 (void) index;
883 int64_t waitTime = -1;
884 MEDIA_LOG_D("DrainOutputBuffer not seeking and render. pts: " PUBLIC_LOG_D64, outputBuffer->pts_);
885 videoSink_->SetFirstPts(outputBuffer->pts_);
886 waitTime = videoSink_->DoSyncWrite(outputBuffer);
887 return waitTime;
888 }
889
890 // async filter should call this function
RenderNextOutput(uint32_t index,std::shared_ptr<AVBuffer> & outputBuffer)891 void DecoderSurfaceFilter::RenderNextOutput(uint32_t index, std::shared_ptr<AVBuffer> &outputBuffer)
892 {
893 if (isInSeekContinous_) {
894 Filter::ProcessOutputBuffer(false, 0);
895 return;
896 }
897
898 int64_t waitTime = CalculateNextRender(index, outputBuffer);
899 if (enableRenderAtTime_) {
900 int64_t renderTimeNs = waitTime * NS_PER_US + GetSystimeTimeNs();
901 MEDIA_LOG_D("RenderNextOutput enter. pts: " PUBLIC_LOG_D64 " waitTime: " PUBLIC_LOG_D64
902 " renderTimeNs: " PUBLIC_LOG_D64, outputBuffer->pts_, waitTime, renderTimeNs);
903 // most renderTimeMaxAdvanceUs_ in advance
904 Filter::ProcessOutputBuffer(waitTime >= 0,
905 waitTime > renderTimeMaxAdvanceUs_ ? waitTime - renderTimeMaxAdvanceUs_ : 0, false, 0, renderTimeNs);
906 return;
907 }
908 MEDIA_LOG_D("RenderNextOutput enter. pts: " PUBLIC_LOG_D64" waitTime: " PUBLIC_LOG_D64,
909 outputBuffer->pts_, waitTime);
910 Filter::ProcessOutputBuffer(waitTime >= 0, waitTime);
911 }
912
ConsumeVideoFrame(uint32_t index,bool isRender,int64_t renderTimeNs)913 void DecoderSurfaceFilter::ConsumeVideoFrame(uint32_t index, bool isRender, int64_t renderTimeNs)
914 {
915 MEDIA_LOG_D("ConsumeVideoFrame idx " PUBLIC_LOG_U32 " renderTimeNs " PUBLIC_LOG_D64, index, renderTimeNs);
916 Filter::ProcessOutputBuffer(isRender, 0, true, index, renderTimeNs);
917 }
918
DrainOutputBuffer(uint32_t index,std::shared_ptr<AVBuffer> & outputBuffer)919 void DecoderSurfaceFilter::DrainOutputBuffer(uint32_t index, std::shared_ptr<AVBuffer> &outputBuffer)
920 {
921 MEDIA_LOG_D("DrainOutputBuffer, pts:" PUBLIC_LOG_D64, outputBuffer->pts_);
922 if ((outputBuffer->flag_ & static_cast<uint32_t>(Plugins::AVBufferFlag::EOS))) {
923 MEDIA_LOG_I("DrainOutputBuffer output EOS");
924 }
925 std::unique_lock<std::mutex> lock(mutex_);
926 FALSE_RETURN_NOLOG(!DrainSeekContinuous(index, outputBuffer));
927 FALSE_RETURN_NOLOG(postProcessor_ != nullptr || !DrainSeekClosest(index, outputBuffer));
928 FALSE_RETURN_NOLOG(!DrainPreroll(index, outputBuffer));
929 if (IS_FILTER_ASYNC && outputBuffers_.empty()) {
930 RenderNextOutput(index, outputBuffer);
931 }
932 outputBuffers_.push_back(make_pair(index, outputBuffer));
933 if (!IS_FILTER_ASYNC) {
934 condBufferAvailable_.notify_one();
935 }
936 }
937
DecoderDrainOutputBuffer(uint32_t index,std::shared_ptr<AVBuffer> & outputBuffer)938 void DecoderSurfaceFilter::DecoderDrainOutputBuffer(uint32_t index, std::shared_ptr<AVBuffer> &outputBuffer)
939 {
940 MEDIA_LOG_D("DecoderDrainOutputBuffer pts: " PUBLIC_LOG_D64, outputBuffer->pts_);
941 if (outputBuffer->flag_ & static_cast<uint32_t>(Plugins::AVBufferFlag::EOS)) {
942 MEDIA_LOG_I("Decoder output EOS");
943 postProcessor_->NotifyEos();
944 }
945 FALSE_RETURN_NOLOG(!DrainSeekClosest(index, outputBuffer));
946 videoDecoder_->ReleaseOutputBuffer(index, true);
947 }
948
RenderLoop()949 void DecoderSurfaceFilter::RenderLoop()
950 {
951 while (true) {
952 std::pair<int, std::shared_ptr<AVBuffer>> nextTask;
953 {
954 std::unique_lock<std::mutex> lock(mutex_);
955 condBufferAvailable_.wait(lock, [this] {
956 return (!outputBuffers_.empty() && !isPaused_.load()) || isThreadExit_.load();
957 });
958 if (isThreadExit_) {
959 MEDIA_LOG_I("Exit RenderLoop read thread.");
960 break;
961 }
962 nextTask = std::move(outputBuffers_.front());
963 outputBuffers_.pop_front();
964 }
965 int64_t waitTime = CalculateNextRender(nextTask.first, nextTask.second);
966 MEDIA_LOG_D("RenderLoop pts: " PUBLIC_LOG_D64" waitTime:" PUBLIC_LOG_D64,
967 nextTask.second->pts_, waitTime);
968 if (waitTime > 0) {
969 OSAL::SleepFor(waitTime / 1000); // 1000 convert to ms
970 }
971 ReleaseOutputBuffer(nextTask.first, waitTime >= 0, nextTask.second, -1);
972 }
973 }
974
DrainSeekContinuous(uint32_t index,std::shared_ptr<AVBuffer> & outputBuffer)975 bool DecoderSurfaceFilter::DrainSeekContinuous(uint32_t index, std::shared_ptr<AVBuffer> &outputBuffer)
976 {
977 FALSE_RETURN_V_NOLOG(isInSeekContinous_, false);
978 bool isEOS = outputBuffer->flag_ & static_cast<uint32_t>(Plugins::AVBufferFlag::EOS);
979 FALSE_RETURN_V_NOLOG(!isEOS, false);
980 outputBufferMap_.insert(std::make_pair(index, outputBuffer));
981 std::shared_ptr<VideoFrameReadyCallback> videoFrameReadyCallback = nullptr;
982 {
983 std::unique_lock<std::mutex> draggingLock(draggingMutex_);
984 FALSE_RETURN_V_NOLOG(videoFrameReadyCallback_ != nullptr, false);
985 MEDIA_LOG_D("[drag_debug]DrainSeekContinuous dts: " PUBLIC_LOG_D64 ", pts: " PUBLIC_LOG_D64
986 " bufferIdx: " PUBLIC_LOG_D32,
987 outputBuffer->dts_, outputBuffer->pts_, index);
988 videoFrameReadyCallback = videoFrameReadyCallback_;
989 }
990 FALSE_RETURN_V_NOLOG(videoFrameReadyCallback != nullptr, false);
991 videoFrameReadyCallback->ConsumeVideoFrame(outputBuffer, index);
992 return true;
993 }
994
DrainPreroll(uint32_t index,std::shared_ptr<AVBuffer> & outputBuffer)995 bool DecoderSurfaceFilter::DrainPreroll(uint32_t index, std::shared_ptr<AVBuffer> &outputBuffer)
996 {
997 FALSE_RETURN_V_NOLOG(inPreroll_.load(), false);
998 if (prerollDone_.load()) {
999 outputBuffers_.push_back(make_pair(index, outputBuffer));
1000 return true;
1001 }
1002 std::lock_guard<std::mutex> lock(prerollMutex_);
1003 FALSE_RETURN_V_NOLOG(inPreroll_.load() && !prerollDone_.load(), false);
1004 outputBuffers_.push_back(make_pair(index, outputBuffer));
1005 bool isEOS = outputBuffer->flag_ & static_cast<uint32_t>(Plugins::AVBufferFlag::EOS);
1006 eosNext_.store(isEOS);
1007 prerollDone_.store(true);
1008 MEDIA_LOG_I("receive preroll output, pts: " PUBLIC_LOG_D64 " bufferIdx: " PUBLIC_LOG_D32,
1009 outputBuffer->pts_, index);
1010 prerollDoneCond_.notify_all();
1011 return true;
1012 }
1013
DrainSeekClosest(uint32_t index,std::shared_ptr<AVBuffer> & outputBuffer)1014 bool DecoderSurfaceFilter::DrainSeekClosest(uint32_t index, std::shared_ptr<AVBuffer> &outputBuffer)
1015 {
1016 FALSE_RETURN_V_NOLOG(isSeek_, false);
1017 bool isEOS = outputBuffer->flag_ & static_cast<uint32_t>(Plugins::AVBufferFlag::EOS);
1018 if (outputBuffer->pts_ < seekTimeUs_ && !isEOS) {
1019 videoDecoder_->ReleaseOutputBuffer(index, false);
1020 return true;
1021 }
1022 MEDIA_LOG_I("Seek arrive target video pts: " PUBLIC_LOG_D64, seekTimeUs_);
1023 isSeek_ = false;
1024 return false;
1025 }
1026
SetVideoSurface(sptr<Surface> videoSurface)1027 Status DecoderSurfaceFilter::SetVideoSurface(sptr<Surface> videoSurface)
1028 {
1029 if (!videoSurface) {
1030 MEDIA_LOG_W("videoSurface is null");
1031 return Status::ERROR_INVALID_PARAMETER;
1032 }
1033 videoSurface_ = videoSurface;
1034 if (postProcessor_ != nullptr) {
1035 MEDIA_LOG_I("postProcessor_ SetOutputSurface in");
1036 Status res = postProcessor_->SetOutputSurface(videoSurface_);
1037 if (res != Status::OK) {
1038 MEDIA_LOG_E(" postProcessor_ SetOutputSurface error, result is " PUBLIC_LOG_D32, res);
1039 return Status::ERROR_UNKNOWN;
1040 }
1041 } else {
1042 decoderOutputSurface_ = videoSurface;
1043 }
1044
1045 if (videoDecoder_ != nullptr) {
1046 MEDIA_LOG_I("videoDecoder_ SetOutputSurface in");
1047 int32_t res = videoDecoder_->SetOutputSurface(decoderOutputSurface_);
1048 if (res != OHOS::MediaAVCodec::AVCodecServiceErrCode::AVCS_ERR_OK) {
1049 MEDIA_LOG_E("videoDecoder_ SetOutputSurface error, result is " PUBLIC_LOG_D32, res);
1050 return Status::ERROR_UNKNOWN;
1051 }
1052 }
1053 MEDIA_LOG_I("SetVideoSurface success");
1054 return Status::OK;
1055 }
1056
SetSyncCenter(std::shared_ptr<MediaSyncManager> syncCenter)1057 void DecoderSurfaceFilter::SetSyncCenter(std::shared_ptr<MediaSyncManager> syncCenter)
1058 {
1059 MEDIA_LOG_I("SetSyncCenter enter");
1060 FALSE_RETURN(videoSink_ != nullptr);
1061 videoSink_->SetSyncCenter(syncCenter);
1062 }
1063
SetDecryptConfig(const sptr<DrmStandard::IMediaKeySessionService> & keySessionProxy,bool svp)1064 Status DecoderSurfaceFilter::SetDecryptConfig(const sptr<DrmStandard::IMediaKeySessionService> &keySessionProxy,
1065 bool svp)
1066 {
1067 MEDIA_LOG_I("SetDecryptConfig");
1068 if (keySessionProxy == nullptr) {
1069 MEDIA_LOG_E("SetDecryptConfig keySessionProxy is nullptr.");
1070 return Status::ERROR_INVALID_PARAMETER;
1071 }
1072 isDrmProtected_ = true;
1073 svpFlag_ = svp;
1074 #ifdef SUPPORT_DRM
1075 keySessionServiceProxy_ = keySessionProxy;
1076 #endif
1077 return Status::OK;
1078 }
1079
SetSeekTime(int64_t seekTimeUs)1080 void DecoderSurfaceFilter::SetSeekTime(int64_t seekTimeUs)
1081 {
1082 MEDIA_LOG_I("SetSeekTime");
1083 isSeek_ = true;
1084 seekTimeUs_ = seekTimeUs;
1085 }
1086
ResetSeekInfo()1087 void DecoderSurfaceFilter::ResetSeekInfo()
1088 {
1089 MEDIA_LOG_I("ResetSeekInfo");
1090 isSeek_ = false;
1091 seekTimeUs_ = 0;
1092 }
1093
ParseDecodeRateLimit()1094 void DecoderSurfaceFilter::ParseDecodeRateLimit()
1095 {
1096 MEDIA_LOG_I("ParseDecodeRateLimit entered.");
1097 std::shared_ptr<MediaAVCodec::AVCodecList> codecList = MediaAVCodec::AVCodecListFactory::CreateAVCodecList();
1098 if (codecList == nullptr) {
1099 MEDIA_LOG_E("create avcodeclist failed.");
1100 return;
1101 }
1102 int32_t height = 0;
1103 bool ret = meta_->GetData(Tag::VIDEO_HEIGHT, height);
1104 FALSE_RETURN_MSG(ret || height <= 0, "failed to get video height");
1105 int32_t width = 0;
1106 ret = meta_->GetData(Tag::VIDEO_WIDTH, width);
1107 FALSE_RETURN_MSG(ret || width <= 0, "failed to get video width");
1108
1109 MediaAVCodec::CapabilityData *capabilityData = codecList->GetCapability(codecMimeType_, false,
1110 MediaAVCodec::AVCodecCategory::AVCODEC_NONE);
1111 std::shared_ptr<MediaAVCodec::VideoCaps> videoCap = std::make_shared<MediaAVCodec::VideoCaps>(capabilityData);
1112 FALSE_RETURN_MSG(videoCap != nullptr, "failed to get videoCap instance");
1113 const MediaAVCodec::Range &frameRange = videoCap->GetSupportedFrameRatesFor(width, height);
1114 rateUpperLimit_ = frameRange.maxVal;
1115 if (rateUpperLimit_ > 0) {
1116 meta_->SetData(Tag::VIDEO_DECODER_RATE_UPPER_LIMIT, rateUpperLimit_);
1117 }
1118 }
1119
GetDecRateUpperLimit()1120 int32_t DecoderSurfaceFilter::GetDecRateUpperLimit()
1121 {
1122 return rateUpperLimit_;
1123 }
1124
GetIsSupportSeekWithoutFlush()1125 bool DecoderSurfaceFilter::GetIsSupportSeekWithoutFlush()
1126 {
1127 std::shared_ptr<MediaAVCodec::AVCodecList> codecList = MediaAVCodec::AVCodecListFactory::CreateAVCodecList();
1128 FALSE_RETURN_V_MSG_E(codecList != nullptr, false, "create avcodeclist failed");
1129 MediaAVCodec::CapabilityData *capabilityData = codecList->GetCapability(codecMimeType_, false,
1130 MediaAVCodec::AVCodecCategory::AVCODEC_NONE);
1131 std::shared_ptr<MediaAVCodec::AVCodecInfo> videoCap = std::make_shared<MediaAVCodec::AVCodecInfo>(capabilityData);
1132 FALSE_RETURN_V_MSG_E(videoCap != nullptr, false, "failed to get videoCap instance");
1133 return videoCap->IsFeatureSupported(MediaAVCodec::AVCapabilityFeature::VIDEO_DECODER_SEEK_WITHOUT_FLUSH);
1134 }
1135
OnDumpInfo(int32_t fd)1136 void DecoderSurfaceFilter::OnDumpInfo(int32_t fd)
1137 {
1138 MEDIA_LOG_D("DecoderSurfaceFilter::OnDumpInfo called.");
1139 FALSE_RETURN(videoDecoder_ != nullptr);
1140 videoDecoder_->OnDumpInfo(fd);
1141 }
1142
SetBitrateStart()1143 void DecoderSurfaceFilter::SetBitrateStart()
1144 {
1145 bitrateChange_++;
1146 }
1147
OnOutputFormatChanged(const MediaAVCodec::Format & format)1148 void DecoderSurfaceFilter::OnOutputFormatChanged(const MediaAVCodec::Format &format)
1149 {
1150 AutoLock lock(formatChangeMutex_);
1151 int32_t width = 0;
1152 format.GetIntValue("video_picture_width", width);
1153 int32_t height = 0;
1154 format.GetIntValue("video_picture_height", height);
1155 if (width <= 0 || height <= 0) {
1156 MEDIA_LOG_W("invaild video size");
1157 return;
1158 }
1159 if (surfaceWidth_ == 0 || surfaceWidth_ == 0) {
1160 MEDIA_LOG_I("receive first output Format");
1161 surfaceWidth_ = width;
1162 surfaceHeight_ = height;
1163 return;
1164 }
1165 if (surfaceWidth_ == width && surfaceHeight_ == height) {
1166 MEDIA_LOG_W("receive the same output Format");
1167 return;
1168 } else {
1169 MEDIA_LOG_I("OnOutputFormatChanged curW=" PUBLIC_LOG_D32 " curH=" PUBLIC_LOG_D32 " nextW=" PUBLIC_LOG_D32
1170 " nextH=" PUBLIC_LOG_D32, surfaceWidth_, surfaceHeight_, width, height);
1171 }
1172 surfaceWidth_ = width;
1173 surfaceHeight_ = height;
1174
1175 MEDIA_LOG_I("ReportVideoSizeChange videoWidth: " PUBLIC_LOG_D32 " videoHeight: "
1176 PUBLIC_LOG_D32, surfaceWidth_, surfaceHeight_);
1177 std::pair<int32_t, int32_t> videoSize {surfaceWidth_, surfaceHeight_};
1178 eventReceiver_->OnEvent({"DecoderSurfaceFilter", EventType::EVENT_RESOLUTION_CHANGE, videoSize});
1179 }
1180
RegisterVideoFrameReadyCallback(std::shared_ptr<VideoFrameReadyCallback> & callback)1181 void DecoderSurfaceFilter::RegisterVideoFrameReadyCallback(std::shared_ptr<VideoFrameReadyCallback> &callback)
1182 {
1183 std::unique_lock<std::mutex> draggingLock(draggingMutex_);
1184 isInSeekContinous_ = true;
1185 FALSE_RETURN(callback != nullptr);
1186 videoFrameReadyCallback_ = callback;
1187 }
1188
DeregisterVideoFrameReadyCallback()1189 void DecoderSurfaceFilter::DeregisterVideoFrameReadyCallback()
1190 {
1191 std::unique_lock<std::mutex> draggingLock(draggingMutex_);
1192 isInSeekContinous_ = false;
1193 videoFrameReadyCallback_ = nullptr;
1194 }
1195
StartSeekContinous()1196 Status DecoderSurfaceFilter::StartSeekContinous()
1197 {
1198 isInSeekContinous_ = true;
1199 return Status::OK;
1200 }
1201
StopSeekContinous()1202 Status DecoderSurfaceFilter::StopSeekContinous()
1203 {
1204 isInSeekContinous_ = false;
1205 return Status::OK;
1206 }
1207
GetSystimeTimeNs()1208 int64_t DecoderSurfaceFilter::GetSystimeTimeNs()
1209 {
1210 return std::chrono::duration_cast<std::chrono::nanoseconds>(
1211 std::chrono::steady_clock::now().time_since_epoch()).count();
1212 }
1213
HandleFirstOutput()1214 void DecoderSurfaceFilter::HandleFirstOutput()
1215 {
1216 isRenderStarted_ = true;
1217 FALSE_RETURN_MSG(eventReceiver_ != nullptr, "ReportFirsrFrameEvent without eventReceiver_");
1218 eventReceiver_->OnEvent({"video_sink", EventType::EVENT_VIDEO_RENDERING_START, Status::OK});
1219 }
1220
HandleEosOutput(int index)1221 void DecoderSurfaceFilter::HandleEosOutput(int index)
1222 {
1223 int64_t curTimeNs = GetSystimeTimeNs();
1224 int64_t lastRenderTimeNs = lastRenderTimeNs_.load();
1225 if (lastRenderTimeNs == HST_TIME_NONE || curTimeNs >= lastRenderTimeNs || !eosTask_) {
1226 MEDIA_LOG_I("HandleEosOutput sync");
1227 DoReleaseOutputBuffer(index, false);
1228 ReportEosEvent();
1229 return;
1230 }
1231 std::weak_ptr<DecoderSurfaceFilter> weakPtr(shared_from_this());
1232 eosTask_->SubmitJobOnce([index, weakPtr] {
1233 MEDIA_LOG_I("HandleEosOutput async");
1234 auto strongPtr = weakPtr.lock();
1235 FALSE_RETURN(strongPtr != nullptr);
1236 int64_t lastRenderTimeNs = strongPtr->lastRenderTimeNs_.load();
1237 if (lastRenderTimeNs == HST_TIME_NONE ||
1238 lastRenderTimeNs - strongPtr->GetSystimeTimeNs() > TASK_DELAY_TOLERANCE) { // flush before release EOS
1239 return;
1240 }
1241 strongPtr->DoReleaseOutputBuffer(index, false);
1242 strongPtr->ReportEosEvent();
1243 }, (lastRenderTimeNs - curTimeNs) / MICROSECONDS_CONVERT_UNIT, false);
1244 }
1245
ReportEosEvent()1246 void DecoderSurfaceFilter::ReportEosEvent()
1247 {
1248 MEDIA_LOG_I("ReportEOSEvent");
1249 FALSE_RETURN_MSG(eventReceiver_ != nullptr, "ReportEOSEvent without eventReceiver_");
1250 Event event {
1251 .srcFilter = "VideoSink",
1252 .type = EventType::EVENT_COMPLETE,
1253 };
1254 eventReceiver_->OnEvent(event);
1255 }
1256
RenderAtTimeDfx(int64_t renderTime,int64_t currentTime,int64_t lastRenderTimeNs)1257 void DecoderSurfaceFilter::RenderAtTimeDfx(int64_t renderTime, int64_t currentTime, int64_t lastRenderTimeNs)
1258 {
1259 FALSE_RETURN_NOLOG(enableRenderAtTimeDfx_);
1260 renderTimeQueue_.push_back(renderTime);
1261
1262 auto firstValidIt = std::lower_bound(renderTimeQueue_.begin(), renderTimeQueue_.end(), currentTime);
1263 renderTimeQueue_.erase(renderTimeQueue_.begin(), firstValidIt);
1264 MEDIA_LOG_D("RenderTimeQueue size = %{public}zu", renderTimeQueue_.size());
1265
1266 int32_t count = 0;
1267 for (auto it = renderTimeQueue_.begin(); it != renderTimeQueue_.end(); ++it) {
1268 if (count < MAX_DEBUG_LOG) {
1269 logMessage += std::to_string(*it);
1270 logMessage += ", ";
1271 ++count;
1272 }
1273 }
1274
1275 if (!logMessage.empty()) {
1276 MEDIA_LOG_D("buffer renderTime is %{public}s", logMessage.c_str());
1277 logMessage.clear();
1278 }
1279 }
1280
SetSeiMessageCbStatus(bool status,const std::vector<int32_t> & payloadTypes)1281 Status DecoderSurfaceFilter::SetSeiMessageCbStatus(bool status, const std::vector<int32_t> &payloadTypes)
1282 {
1283 seiMessageCbStatus_ = status;
1284 MEDIA_LOG_I("seiMessageCbStatus_ = " PUBLIC_LOG_D32, seiMessageCbStatus_);
1285 FALSE_RETURN_V_MSG(
1286 inputBufferQueueProducer_ != nullptr, Status::ERROR_NO_MEMORY, "get producer failed");
1287 if (producerListener_ == nullptr) {
1288 producerListener_ =
1289 new SeiParserListener(codecMimeType_, inputBufferQueueProducer_, eventReceiver_, false);
1290 FALSE_RETURN_V_MSG(
1291 producerListener_ != nullptr, Status::ERROR_NO_MEMORY, "sei listener create failed");
1292 }
1293 producerListener_->SetSeiMessageCbStatus(status, payloadTypes);
1294 return Status::OK;
1295 }
1296
InitPostProcessor()1297 Status DecoderSurfaceFilter::InitPostProcessor()
1298 {
1299 FALSE_RETURN_V_NOLOG(postProcessor_ != nullptr, Status::OK);
1300 postProcessor_->SetOutputSurface(videoSurface_);
1301 postProcessor_->SetEventReceiver(eventReceiver_);
1302 postProcessor_->SetVideoWindowSize(postProcessorTargetWidth_, postProcessorTargetHeight_);
1303 postProcessor_->SetPostProcessorOn(isPostProcessorOn_);
1304 auto ret = postProcessor_->Init();
1305 if (ret != Status::OK) {
1306 MEDIA_LOG_E("Init postProcessor fail ret = %{public}d", ret);
1307 eventReceiver_->OnEvent({"decoderSurface", EventType::EVENT_ERROR, MSERR_UNSUPPORT_VID_SRC_TYPE});
1308 return Status::ERROR_UNSUPPORTED_FORMAT;
1309 }
1310 return Status::OK;
1311 }
1312
SetPostProcessorType(VideoPostProcessorType type)1313 void DecoderSurfaceFilter::SetPostProcessorType(VideoPostProcessorType type)
1314 {
1315 postProcessorType_ = type;
1316 }
1317
CreatePostProcessor()1318 std::shared_ptr<BaseVideoPostProcessor> DecoderSurfaceFilter::CreatePostProcessor()
1319 {
1320 MEDIA_LOG_D("CreatePostProcessor In");
1321 FALSE_RETURN_V_MSG(postProcessor_ == nullptr, nullptr, "Post processor is allready created!");
1322 FALSE_RETURN_V_MSG(postProcessorType_ != VideoPostProcessorType::NONE, nullptr, "post processor type is not set");
1323 postProcessor_ =
1324 VideoPostProcessorFactory::Instance().CreateVideoPostProcessor<BaseVideoPostProcessor>(postProcessorType_);
1325 if (postProcessor_ != nullptr) {
1326 decoderOutputSurface_ = postProcessor_->GetInputSurface();
1327 videoDecoder_->SetOutputSurface(decoderOutputSurface_);
1328 postProcessor_->SetOutputSurface(videoSurface_);
1329 }
1330 return postProcessor_;
1331 }
1332
SetPostProcessorOn(bool isPostProcessorOn)1333 Status DecoderSurfaceFilter::SetPostProcessorOn(bool isPostProcessorOn)
1334 {
1335 isPostProcessorOn_ = isPostProcessorOn;
1336 FALSE_RETURN_V(isPostProcessorSupported_, Status::ERROR_UNSUPPORTED_FORMAT);
1337 FALSE_RETURN_V(postProcessor_ != nullptr, Status::OK);
1338
1339 postProcessor_->SetPostProcessorOn(isPostProcessorOn);
1340 return Status::OK;
1341 }
1342
SetVideoWindowSize(int32_t width,int32_t height)1343 Status DecoderSurfaceFilter::SetVideoWindowSize(int32_t width, int32_t height)
1344 {
1345 postProcessorTargetWidth_ = width;
1346 postProcessorTargetHeight_ = height;
1347 FALSE_RETURN_V(isPostProcessorSupported_, Status::ERROR_UNSUPPORTED_FORMAT);
1348 FALSE_RETURN_V(postProcessor_ != nullptr, Status::OK);
1349
1350 return postProcessor_->SetVideoWindowSize(width, height);
1351 }
1352 } // namespace Pipeline
1353 } // namespace MEDIA
1354 } // namespace OHOS
1355