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