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 #include "subtitle_sink.h"
17
18 #include "common/log.h"
19 #include "syspara/parameters.h"
20 #include "meta/format.h"
21
22 namespace {
23 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_DOMAIN_SYSTEM_PLAYER, "SubtitleSink" };
24 }
25
26 namespace OHOS {
27 namespace Media {
28 namespace {
29 constexpr bool SUBTITME_LOOP_RUNNING = true;
30 }
31
SubtitleSink()32 SubtitleSink::SubtitleSink()
33 {
34 MEDIA_LOG_I("SubtitleSink ctor");
35 syncerPriority_ = IMediaSynchronizer::SUBTITLE_SINK;
36 }
37
~SubtitleSink()38 SubtitleSink::~SubtitleSink()
39 {
40 MEDIA_LOG_I("SubtitleSink dtor");
41 {
42 std::unique_lock<std::mutex> lock(mutex_);
43 isThreadExit_ = true;
44 }
45 updateCond_.notify_all();
46 if (readThread_ != nullptr && readThread_->joinable()) {
47 readThread_->join();
48 readThread_ = nullptr;
49 }
50
51 if (inputBufferQueueProducer_ != nullptr) {
52 for (auto &buffer : inputBufferVector_) {
53 inputBufferQueueProducer_->DetachBuffer(buffer);
54 }
55 inputBufferVector_.clear();
56 inputBufferQueueProducer_->SetQueueSize(0);
57 }
58 }
59
NotifySeek()60 void SubtitleSink::NotifySeek()
61 {
62 Flush();
63 }
64
GetTargetSubtitleIndex(int64_t currentTime)65 void SubtitleSink::GetTargetSubtitleIndex(int64_t currentTime)
66 {
67 int32_t left = 0;
68 int32_t right = subtitleInfoVec_.size();
69 while (left < right) {
70 int32_t mid = (left + right) / 2;
71 int64_t startTime = subtitleInfoVec_[mid].pts_;
72 int64_t endTime = subtitleInfoVec_[mid].duration_ + startTime;
73 if (startTime > currentTime) {
74 right = mid;
75 continue;
76 } else if (endTime < currentTime) {
77 left = mid + 1;
78 continue;
79 } else {
80 left = mid;
81 break;
82 }
83 }
84 currentInfoIndex_ = left;
85 }
86
Init(std::shared_ptr<Meta> & meta,const std::shared_ptr<Pipeline::EventReceiver> & receiver)87 Status SubtitleSink::Init(std::shared_ptr<Meta> &meta, const std::shared_ptr<Pipeline::EventReceiver> &receiver)
88 {
89 state_ = Pipeline::FilterState::INITIALIZED;
90 if (meta != nullptr) {
91 meta->SetData(Tag::APP_PID, appPid_);
92 meta->SetData(Tag::APP_UID, appUid_);
93 }
94 return Status::OK;
95 }
96
GetBufferQueueProducer()97 sptr<AVBufferQueueProducer> SubtitleSink::GetBufferQueueProducer()
98 {
99 if (state_ != Pipeline::FilterState::READY) {
100 return nullptr;
101 }
102 return inputBufferQueueProducer_;
103 }
104
GetBufferQueueConsumer()105 sptr<AVBufferQueueConsumer> SubtitleSink::GetBufferQueueConsumer()
106 {
107 if (state_ != Pipeline::FilterState::READY) {
108 return nullptr;
109 }
110 return inputBufferQueueConsumer_;
111 }
112
SetParameter(const std::shared_ptr<Meta> & meta)113 Status SubtitleSink::SetParameter(const std::shared_ptr<Meta> &meta)
114 {
115 return Status::OK;
116 }
117
GetParameter(std::shared_ptr<Meta> & meta)118 Status SubtitleSink::GetParameter(std::shared_ptr<Meta> &meta)
119 {
120 return Status::OK;
121 }
122
Prepare()123 Status SubtitleSink::Prepare()
124 {
125 state_ = Pipeline::FilterState::PREPARING;
126 Status ret = PrepareInputBufferQueue();
127 if (ret != Status::OK) {
128 state_ = Pipeline::FilterState::INITIALIZED;
129 return ret;
130 }
131 state_ = Pipeline::FilterState::READY;
132 return ret;
133 }
134
Start()135 Status SubtitleSink::Start()
136 {
137 isEos_ = false;
138 state_ = Pipeline::FilterState::RUNNING;
139 readThread_ = std::make_unique<std::thread>(&SubtitleSink::RenderLoop, this);
140 pthread_setname_np(readThread_->native_handle(), "SubtitleRenderLoop");
141 return Status::OK;
142 }
143
Stop()144 Status SubtitleSink::Stop()
145 {
146 updateCond_.notify_all();
147 state_ = Pipeline::FilterState::INITIALIZED;
148 return Status::OK;
149 }
150
Pause()151 Status SubtitleSink::Pause()
152 {
153 state_ = Pipeline::FilterState::PAUSED;
154 return Status::OK;
155 }
156
Resume()157 Status SubtitleSink::Resume()
158 {
159 {
160 std::unique_lock<std::mutex> lock(mutex_);
161 isEos_ = false;
162 state_ = Pipeline::FilterState::RUNNING;
163 }
164 updateCond_.notify_all();
165 return Status::OK;
166 }
167
Flush()168 Status SubtitleSink::Flush()
169 {
170 if (inputBufferQueueConsumer_ != nullptr) {
171 {
172 std::unique_lock<std::mutex> lock(mutex_);
173 shouldUpdate_ = true;
174 while (!subtitleInfoVec_.empty()) {
175 inputBufferQueueConsumer_->ReleaseBuffer(subtitleInfoVec_.front().buffer_);
176 subtitleInfoVec_.pop_front();
177 }
178 }
179 uint32_t queueSize = inputBufferQueueConsumer_->GetQueueSize();
180 std::shared_ptr<AVBuffer> filledOutputBuffer;
181 for (uint32_t i = 0; i < queueSize; i++) {
182 Status ret = inputBufferQueueConsumer_->AcquireBuffer(filledOutputBuffer);
183 if (ret != Status::OK || filledOutputBuffer == nullptr) {
184 break;
185 }
186 inputBufferQueueConsumer_->ReleaseBuffer(filledOutputBuffer);
187 }
188 }
189 isFlush_.store(true);
190 updateCond_.notify_all();
191 return Status::OK;
192 }
193
Release()194 Status SubtitleSink::Release()
195 {
196 return Status::OK;
197 }
198
SetIsTransitent(bool isTransitent)199 Status SubtitleSink::SetIsTransitent(bool isTransitent)
200 {
201 isTransitent_ = isTransitent;
202 return Status::OK;
203 }
204
PrepareInputBufferQueue()205 Status SubtitleSink::PrepareInputBufferQueue()
206 {
207 if (inputBufferQueue_ != nullptr && inputBufferQueue_->GetQueueSize() > 0) {
208 MEDIA_LOG_I("InputBufferQueue already create");
209 return Status::ERROR_INVALID_OPERATION;
210 }
211 int32_t inputBufferNum = 2;
212 int32_t capacity = 1024;
213 MemoryType memoryType = MemoryType::SHARED_MEMORY;
214 #ifndef MEDIA_OHOS
215 memoryType = MemoryType::VIRTUAL_MEMORY;
216 #endif
217 MEDIA_LOG_I("PrepareInputBufferQueue");
218 if (inputBufferQueue_ == nullptr) {
219 inputBufferQueue_ = AVBufferQueue::Create(inputBufferNum, memoryType, INPUT_BUFFER_QUEUE_NAME);
220 }
221 FALSE_RETURN_V_MSG_E(inputBufferQueue_ != nullptr, Status::ERROR_UNKNOWN, "inputBufferQueue_ is nullptr");
222
223 inputBufferQueueProducer_ = inputBufferQueue_->GetProducer();
224 inputBufferQueueConsumer_ = inputBufferQueue_->GetConsumer();
225
226 for (int i = 0; i < inputBufferNum; i++) {
227 std::shared_ptr<AVAllocator> avAllocator;
228 #ifndef MEDIA_OHOS
229 MEDIA_LOG_D("CreateVirtualAllocator,i=%{public}d capacity=%{public}d", i, capacity);
230 avAllocator = AVAllocatorFactory::CreateVirtualAllocator();
231 #else
232 MEDIA_LOG_D("CreateSharedAllocator,i=%{public}d capacity=%{public}d", i, capacity);
233 avAllocator = AVAllocatorFactory::CreateSharedAllocator(MemoryFlag::MEMORY_READ_WRITE);
234 #endif
235 std::shared_ptr<AVBuffer> inputBuffer = AVBuffer::CreateAVBuffer(avAllocator, capacity);
236 FALSE_RETURN_V_MSG_E(inputBuffer != nullptr, Status::ERROR_UNKNOWN,
237 "inputBuffer is nullptr");
238 FALSE_RETURN_V_MSG_E(inputBufferQueueProducer_ != nullptr, Status::ERROR_UNKNOWN,
239 "inputBufferQueueProducer_ is nullptr");
240 inputBufferQueueProducer_->AttachBuffer(inputBuffer, false);
241 MEDIA_LOG_I("Attach intput buffer. index: %{public}d, bufferId: %{public}" PRIu64,
242 i, inputBuffer->GetUniqueId());
243 inputBufferVector_.push_back(inputBuffer);
244 }
245 FALSE_RETURN_V_NOLOG(playerEventReceiver_ != nullptr, Status::OK);
246 playerEventReceiver_->OnMemoryUsageEvent({"SUBTITLE_BQ",
247 DfxEventType::DFX_INFO_MEMORY_USAGE, inputBufferQueue_->GetMemoryUsage()});
248 return Status::OK;
249 }
250
DrainOutputBuffer(bool flushed)251 void SubtitleSink::DrainOutputBuffer(bool flushed)
252 {
253 Status ret;
254 FALSE_RETURN(inputBufferQueueConsumer_ != nullptr);
255 FALSE_RETURN(!isEos_.load());
256 std::shared_ptr<AVBuffer> filledOutputBuffer;
257 ret = inputBufferQueueConsumer_->AcquireBuffer(filledOutputBuffer);
258 if (ret != Status::OK || filledOutputBuffer == nullptr || filledOutputBuffer->memory_ == nullptr) {
259 return;
260 }
261 if (filledOutputBuffer->flag_ & BUFFER_FLAG_EOS) {
262 isEos_ = true;
263 }
264 std::string subtitleText(reinterpret_cast<const char *>(filledOutputBuffer->memory_->GetAddr()),
265 filledOutputBuffer->memory_->GetSize());
266 SubtitleInfo subtitleInfo{ subtitleText, filledOutputBuffer->pts_, filledOutputBuffer->duration_,
267 filledOutputBuffer };
268 {
269 std::unique_lock<std::mutex> lock(mutex_);
270 subtitleInfoVec_.push_back(subtitleInfo);
271 }
272 updateCond_.notify_all();
273 }
274
RenderLoop()275 void SubtitleSink::RenderLoop()
276 {
277 while (SUBTITME_LOOP_RUNNING) {
278 std::unique_lock<std::mutex> lock(mutex_);
279 updateCond_.wait(lock, [this] {
280 return isThreadExit_.load() ||
281 (!subtitleInfoVec_.empty() && state_ == Pipeline::FilterState::RUNNING);
282 });
283 if (isFlush_) {
284 MEDIA_LOG_I("SubtitleSink RenderLoop flush");
285 isFlush_.store(false);
286 continue;
287 }
288 FALSE_RETURN(!isThreadExit_.load());
289 // wait timeout, seek or stop
290 SubtitleInfo subtitleInfo = subtitleInfoVec_.front();
291 int64_t waitTime = CalcWaitTime(subtitleInfo);
292 updateCond_.wait_for(lock, std::chrono::microseconds(waitTime),
293 [this] { return isThreadExit_.load() || shouldUpdate_; });
294 MEDIA_LOG_I("SubtitleSink NotifyRender buffer. pts = " PUBLIC_LOG_D64 " waitTime: " PUBLIC_LOG_D64,
295 subtitleInfo.pts_, waitTime);
296 if (isFlush_) {
297 MEDIA_LOG_I("SubtitleSink RenderLoop flush");
298 isFlush_.store(false);
299 continue;
300 }
301 FALSE_RETURN(!isThreadExit_.load());
302 auto actionToDo = ActionToDo(subtitleInfo);
303 if (actionToDo == SubtitleBufferState::DROP) {
304 subtitleInfoVec_.pop_front();
305 inputBufferQueueConsumer_->ReleaseBuffer(subtitleInfo.buffer_);
306 continue;
307 } else if (actionToDo == SubtitleBufferState::WAIT) {
308 continue;
309 } else {}
310 NotifyRender(subtitleInfo);
311 subtitleInfoVec_.pop_front();
312 inputBufferQueueConsumer_->ReleaseBuffer(subtitleInfo.buffer_);
313 }
314 }
315
ResetSyncInfo()316 void SubtitleSink::ResetSyncInfo()
317 {
318 auto syncCenter = syncCenter_.lock();
319 if (syncCenter) {
320 syncCenter->Reset();
321 }
322 lastReportedClockTime_ = HST_TIME_NONE;
323 }
324
CalcWaitTime(SubtitleInfo & subtitleInfo)325 uint64_t SubtitleSink::CalcWaitTime(SubtitleInfo &subtitleInfo)
326 {
327 int64_t curTime;
328 if (shouldUpdate_.load()) {
329 shouldUpdate_ = false;
330 }
331 curTime = GetMediaTime();
332 if (subtitleInfo.pts_ < curTime) {
333 return 0;
334 }
335 return (subtitleInfo.pts_ - curTime) / speed_;
336 }
337
ActionToDo(SubtitleInfo & subtitleInfo)338 uint32_t SubtitleSink::ActionToDo(SubtitleInfo &subtitleInfo)
339 {
340 auto curTime = GetMediaTime();
341 if (shouldUpdate_ || subtitleInfo.pts_ + subtitleInfo.duration_ < curTime) {
342 MEDIA_LOG_D("SubtitleInfo pts " PUBLIC_LOG_D64 " duration " PUBLIC_LOG_D64 " drop",
343 subtitleInfo.pts_, subtitleInfo.duration_);
344 return SubtitleBufferState::DROP;
345 }
346 if (subtitleInfo.pts_ > curTime || state_ != Pipeline::FilterState::RUNNING) {
347 MEDIA_LOG_D("SubtitleInfo pts " PUBLIC_LOG_D64 " duration " PUBLIC_LOG_D64 " wait",
348 subtitleInfo.pts_, subtitleInfo.duration_);
349 return SubtitleBufferState::WAIT;
350 }
351 subtitleInfo.duration_ -= curTime - subtitleInfo.pts_;
352 MEDIA_LOG_D("SubtitleInfo pts " PUBLIC_LOG_D64 " duration " PUBLIC_LOG_D64 " show",
353 subtitleInfo.pts_, subtitleInfo.duration_);
354 return SubtitleBufferState::SHOW;
355 }
356
DoSyncWrite(const std::shared_ptr<OHOS::Media::AVBuffer> & buffer)357 int64_t SubtitleSink::DoSyncWrite(const std::shared_ptr<OHOS::Media::AVBuffer> &buffer)
358 {
359 (void)buffer;
360 return 0;
361 }
362
NotifyRender(SubtitleInfo & subtitleInfo)363 void SubtitleSink::NotifyRender(SubtitleInfo &subtitleInfo)
364 {
365 Format format;
366 (void)format.PutStringValue(Tag::SUBTITLE_TEXT, subtitleInfo.text_);
367 (void)format.PutIntValue(Tag::SUBTITLE_PTS, Plugins::Us2Ms(subtitleInfo.pts_));
368 (void)format.PutIntValue(Tag::SUBTITLE_DURATION, Plugins::Us2Ms(subtitleInfo.duration_));
369 Event event{ .srcFilter = "SubtitleSink", .type = EventType::EVENT_SUBTITLE_TEXT_UPDATE, .param = format };
370 FALSE_RETURN(playerEventReceiver_ != nullptr);
371 playerEventReceiver_->OnEvent(event);
372 }
373
OnInterrupted(bool isInterruptNeeded)374 void SubtitleSink::OnInterrupted(bool isInterruptNeeded)
375 {
376 MEDIA_LOG_I("onInterrupted %{public}d", isInterruptNeeded);
377 std::unique_lock<std::mutex> lock(mutex_);
378 isInterruptNeeded_ = isInterruptNeeded;
379 isThreadExit_ = true;
380 updateCond_.notify_all();
381 }
382
SetEventReceiver(const std::shared_ptr<Pipeline::EventReceiver> & receiver)383 void SubtitleSink::SetEventReceiver(const std::shared_ptr<Pipeline::EventReceiver> &receiver)
384 {
385 FALSE_RETURN(receiver != nullptr);
386 playerEventReceiver_ = receiver;
387 }
388
SetSyncCenter(std::shared_ptr<Pipeline::MediaSyncManager> syncCenter)389 void SubtitleSink::SetSyncCenter(std::shared_ptr<Pipeline::MediaSyncManager> syncCenter)
390 {
391 syncCenter_ = syncCenter;
392 MediaSynchronousSink::Init();
393 }
394
SetSpeed(float speed)395 Status SubtitleSink::SetSpeed(float speed)
396 {
397 FALSE_RETURN_V_MSG_W(speed > 0, Status::OK, "Invalid speed %{public}f", speed);
398 {
399 std::unique_lock<std::mutex> lock(mutex_);
400 speed_ = speed;
401 shouldUpdate_ = true;
402 }
403 updateCond_.notify_all();
404 return Status::OK;
405 }
406
GetMediaTime()407 int64_t SubtitleSink::GetMediaTime()
408 {
409 auto syncCenter = syncCenter_.lock();
410 if (!syncCenter) {
411 return 0;
412 }
413 return syncCenter->GetMediaTimeNow();
414 }
415 } // namespace MEDIA
416 } // namespace OHOS