blob: edc87b782203811d87252c59b880a421566dec3c [file] [log] [blame]
philipel2fee4d62018-03-21 16:52:13 +01001/*
2 * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "video/video_stream_decoder_impl.h"
12
Karl Wiberg918f50c2018-07-05 11:40:33 +020013#include "absl/memory/memory.h"
Danil Chapovalov471783f2019-03-11 14:26:02 +010014#include "api/task_queue/queued_task.h"
philipel97187112018-03-23 10:43:21 +010015#include "rtc_base/logging.h"
philipel844876d2018-04-05 11:02:54 +020016#include "rtc_base/numerics/mod_ops.h"
Steve Anton10542f22019-01-11 09:11:00 -080017#include "rtc_base/time_utils.h"
philipel2fee4d62018-03-21 16:52:13 +010018
19namespace webrtc {
philipel97187112018-03-23 10:43:21 +010020
philipel2fee4d62018-03-21 16:52:13 +010021VideoStreamDecoderImpl::VideoStreamDecoderImpl(
Danil Chapovalovb703db92019-04-08 16:59:28 +020022 VideoStreamDecoderInterface::Callbacks* callbacks,
philipel2fee4d62018-03-21 16:52:13 +010023 VideoDecoderFactory* decoder_factory,
Danil Chapovalovb703db92019-04-08 16:59:28 +020024 TaskQueueFactory* task_queue_factory,
philipel2fee4d62018-03-21 16:52:13 +010025 std::map<int, std::pair<SdpVideoFormat, int>> decoder_settings)
26 : callbacks_(callbacks),
27 decoder_factory_(decoder_factory),
philipel97187112018-03-23 10:43:21 +010028 decoder_settings_(std::move(decoder_settings)),
Danil Chapovalovb703db92019-04-08 16:59:28 +020029 bookkeeping_queue_(task_queue_factory->CreateTaskQueue(
30 "video_stream_decoder_bookkeeping_queue",
31 TaskQueueFactory::Priority::NORMAL)),
philipel844876d2018-04-05 11:02:54 +020032 decode_thread_(&DecodeLoop,
33 this,
34 "video_stream_decoder_decode_thread",
35 rtc::kHighestPriority),
philipel97187112018-03-23 10:43:21 +010036 timing_(Clock::GetRealTimeClock()),
37 frame_buffer_(Clock::GetRealTimeClock(),
philipel97187112018-03-23 10:43:21 +010038 &timing_,
philipel844876d2018-04-05 11:02:54 +020039 nullptr),
philipel6847f9b2018-04-20 15:05:37 +020040 next_frame_timestamps_index_(0) {
41 frame_timestamps_.fill({-1, -1, -1});
philipel844876d2018-04-05 11:02:54 +020042 decode_thread_.Start();
43}
philipel2fee4d62018-03-21 16:52:13 +010044
philipel97187112018-03-23 10:43:21 +010045VideoStreamDecoderImpl::~VideoStreamDecoderImpl() {
46 frame_buffer_.Stop();
philipel844876d2018-04-05 11:02:54 +020047 decode_thread_.Stop();
philipel97187112018-03-23 10:43:21 +010048}
philipel2fee4d62018-03-21 16:52:13 +010049
50void VideoStreamDecoderImpl::OnFrame(
philipel97187112018-03-23 10:43:21 +010051 std::unique_ptr<video_coding::EncodedFrame> frame) {
52 if (!bookkeeping_queue_.IsCurrent()) {
Danil Chapovalov471783f2019-03-11 14:26:02 +010053 struct OnFrameTask : QueuedTask {
philipel97187112018-03-23 10:43:21 +010054 OnFrameTask(std::unique_ptr<video_coding::EncodedFrame> frame,
55 VideoStreamDecoderImpl* video_stream_decoder)
56 : frame_(std::move(frame)),
57 video_stream_decoder_(video_stream_decoder) {}
58
Niels Möllerbe682d42018-03-27 08:31:45 +020059 bool Run() override {
philipel97187112018-03-23 10:43:21 +010060 video_stream_decoder_->OnFrame(std::move(frame_));
61 return true;
62 }
63
64 std::unique_ptr<video_coding::EncodedFrame> frame_;
65 VideoStreamDecoderImpl* video_stream_decoder_;
66 };
67
68 bookkeeping_queue_.PostTask(
Karl Wiberg918f50c2018-07-05 11:40:33 +020069 absl::make_unique<OnFrameTask>(std::move(frame), this));
philipel97187112018-03-23 10:43:21 +010070 return;
71 }
72
73 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
74
75 uint64_t continuous_pid = frame_buffer_.InsertFrame(std::move(frame));
76 video_coding::VideoLayerFrameId continuous_id(continuous_pid, 0);
77 if (last_continuous_id_ < continuous_id) {
78 last_continuous_id_ = continuous_id;
79 callbacks_->OnContinuousUntil(last_continuous_id_);
80 }
81}
82
philipel79aab3f2018-03-26 14:31:23 +020083VideoDecoder* VideoStreamDecoderImpl::GetDecoder(int payload_type) {
84 if (current_payload_type_ == payload_type) {
85 RTC_DCHECK(decoder_);
86 return decoder_.get();
87 }
88
89 current_payload_type_.reset();
90 decoder_.reset();
91
92 auto decoder_settings_it = decoder_settings_.find(payload_type);
93 if (decoder_settings_it == decoder_settings_.end()) {
94 RTC_LOG(LS_WARNING) << "Payload type " << payload_type
95 << " not registered.";
96 return nullptr;
97 }
98
99 const SdpVideoFormat& video_format = decoder_settings_it->second.first;
100 std::unique_ptr<VideoDecoder> decoder =
101 decoder_factory_->CreateVideoDecoder(video_format);
102 if (!decoder) {
103 RTC_LOG(LS_WARNING) << "Failed to create decoder for payload type "
104 << payload_type << ".";
105 return nullptr;
106 }
107
108 int num_cores = decoder_settings_it->second.second;
109 int32_t init_result = decoder->InitDecode(nullptr, num_cores);
110 if (init_result != WEBRTC_VIDEO_CODEC_OK) {
111 RTC_LOG(LS_WARNING) << "Failed to initialize decoder for payload type "
112 << payload_type << ".";
113 return nullptr;
114 }
115
116 int32_t register_result = decoder->RegisterDecodeCompleteCallback(this);
117 if (register_result != WEBRTC_VIDEO_CODEC_OK) {
118 RTC_LOG(LS_WARNING) << "Failed to register decode callback.";
119 return nullptr;
120 }
121
122 current_payload_type_.emplace(payload_type);
123 decoder_ = std::move(decoder);
124 return decoder_.get();
125}
126
philipel844876d2018-04-05 11:02:54 +0200127// static
128void VideoStreamDecoderImpl::DecodeLoop(void* ptr) {
129 // TODO(philipel): Remove this and use rtc::Event::kForever when it's
130 // supported by the |frame_buffer_|.
131 static constexpr int kForever = 100000000;
132
133 int max_wait_time_ms = kForever;
134 bool keyframe_required = true;
135 auto* vs_decoder = static_cast<VideoStreamDecoderImpl*>(ptr);
136 while (true) {
137 DecodeResult decode_result =
138 vs_decoder->DecodeNextFrame(max_wait_time_ms, keyframe_required);
139
140 switch (decode_result) {
141 case kOk: {
142 max_wait_time_ms = kForever;
143 keyframe_required = false;
144 break;
145 }
146 case kDecodeFailure: {
147 max_wait_time_ms = 0;
148 keyframe_required = true;
149 break;
150 }
151 case kNoFrame: {
152 max_wait_time_ms = kForever;
153 // If we end up here it means that we got a decoding error and there is
154 // no keyframe available in the |frame_buffer_|.
155 vs_decoder->bookkeeping_queue_.PostTask([vs_decoder]() {
156 RTC_DCHECK_RUN_ON(&vs_decoder->bookkeeping_queue_);
157 vs_decoder->callbacks_->OnNonDecodableState();
158 });
159 break;
160 }
161 case kNoDecoder: {
162 max_wait_time_ms = kForever;
163 break;
164 }
165 case kShutdown: {
166 return;
167 }
168 }
169 }
170}
171
172VideoStreamDecoderImpl::DecodeResult VideoStreamDecoderImpl::DecodeNextFrame(
173 int max_wait_time_ms,
174 bool keyframe_required) {
175 std::unique_ptr<video_coding::EncodedFrame> frame;
176 video_coding::FrameBuffer::ReturnReason res =
177 frame_buffer_.NextFrame(max_wait_time_ms, &frame, keyframe_required);
178
179 if (res == video_coding::FrameBuffer::ReturnReason::kStopped)
180 return kShutdown;
181
182 if (frame) {
183 VideoDecoder* decoder = GetDecoder(frame->PayloadType());
184 if (!decoder) {
185 RTC_LOG(LS_WARNING) << "Failed to get decoder, dropping frame ("
186 << frame->id.picture_id << ":"
187 << frame->id.spatial_layer << ").";
188 return kNoDecoder;
189 }
190
191 int64_t decode_start_time_ms = rtc::TimeMillis();
Niels Möller23775882018-08-16 10:24:12 +0200192 int64_t timestamp = frame->Timestamp();
philipel6847f9b2018-04-20 15:05:37 +0200193 int64_t render_time_us = frame->RenderTimeMs() * 1000;
philipel844876d2018-04-05 11:02:54 +0200194 bookkeeping_queue_.PostTask(
philipel6847f9b2018-04-20 15:05:37 +0200195 [this, decode_start_time_ms, timestamp, render_time_us]() {
philipel844876d2018-04-05 11:02:54 +0200196 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
197 // Saving decode start time this way wont work if we decode spatial
198 // layers sequentially.
philipel6847f9b2018-04-20 15:05:37 +0200199 FrameTimestamps* frame_timestamps =
200 &frame_timestamps_[next_frame_timestamps_index_];
201 frame_timestamps->timestamp = timestamp;
202 frame_timestamps->decode_start_time_ms = decode_start_time_ms;
203 frame_timestamps->render_time_us = render_time_us;
204
205 next_frame_timestamps_index_ =
206 Add<kFrameTimestampsMemory>(next_frame_timestamps_index_, 1);
philipel844876d2018-04-05 11:02:54 +0200207 });
208
Yves Gerey665174f2018-06-19 15:03:05 +0200209 int32_t decode_result = decoder->Decode(frame->EncodedImage(),
210 false, // missing_frame
Yves Gerey665174f2018-06-19 15:03:05 +0200211 frame->RenderTimeMs());
philipel844876d2018-04-05 11:02:54 +0200212
213 return decode_result == WEBRTC_VIDEO_CODEC_OK ? kOk : kDecodeFailure;
214 }
215
216 return kNoFrame;
217}
218
philipel6847f9b2018-04-20 15:05:37 +0200219VideoStreamDecoderImpl::FrameTimestamps*
220VideoStreamDecoderImpl::GetFrameTimestamps(int64_t timestamp) {
221 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
222
223 int start_time_index = next_frame_timestamps_index_;
224 for (int i = 0; i < kFrameTimestampsMemory; ++i) {
225 start_time_index = Subtract<kFrameTimestampsMemory>(start_time_index, 1);
226
227 if (frame_timestamps_[start_time_index].timestamp == timestamp)
228 return &frame_timestamps_[start_time_index];
229 }
230
231 return nullptr;
232}
233
234// VideoDecoder::DecodedImageCallback
235int32_t VideoStreamDecoderImpl::Decoded(VideoFrame& decoded_image) {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200236 Decoded(decoded_image, absl::nullopt, absl::nullopt);
philipel6847f9b2018-04-20 15:05:37 +0200237 return WEBRTC_VIDEO_CODEC_OK;
238}
239
240// VideoDecoder::DecodedImageCallback
241int32_t VideoStreamDecoderImpl::Decoded(VideoFrame& decoded_image,
242 int64_t decode_time_ms) {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200243 Decoded(decoded_image, decode_time_ms, absl::nullopt);
philipel6847f9b2018-04-20 15:05:37 +0200244 return WEBRTC_VIDEO_CODEC_OK;
245}
246
247// VideoDecoder::DecodedImageCallback
248void VideoStreamDecoderImpl::Decoded(VideoFrame& decoded_image,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200249 absl::optional<int32_t> decode_time_ms,
250 absl::optional<uint8_t> qp) {
philipel6847f9b2018-04-20 15:05:37 +0200251 int64_t decode_stop_time_ms = rtc::TimeMillis();
252
253 bookkeeping_queue_.PostTask([this, decode_stop_time_ms, decoded_image,
254 decode_time_ms, qp]() {
255 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
256
257 FrameTimestamps* frame_timestamps =
258 GetFrameTimestamps(decoded_image.timestamp());
259 if (!frame_timestamps) {
260 RTC_LOG(LS_ERROR) << "No frame information found for frame with timestamp"
261 << decoded_image.timestamp();
262 return;
263 }
264
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200265 absl::optional<int> casted_qp;
philipel6847f9b2018-04-20 15:05:37 +0200266 if (qp)
267 casted_qp.emplace(*qp);
268
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200269 absl::optional<int> casted_decode_time_ms(decode_time_ms.value_or(
philipel6847f9b2018-04-20 15:05:37 +0200270 decode_stop_time_ms - frame_timestamps->decode_start_time_ms));
271
272 timing_.StopDecodeTimer(0, *casted_decode_time_ms, decode_stop_time_ms,
273 frame_timestamps->render_time_us / 1000);
274
275 callbacks_->OnDecodedFrame(
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100276 VideoFrame::Builder()
277 .set_video_frame_buffer(decoded_image.video_frame_buffer())
278 .set_rotation(decoded_image.rotation())
279 .set_timestamp_us(frame_timestamps->render_time_us)
Sergey Silkin1daa7e82019-01-10 14:29:46 +0100280 .set_timestamp_rtp(decoded_image.timestamp())
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100281 .set_id(decoded_image.id())
282 .build(),
philipel6847f9b2018-04-20 15:05:37 +0200283 casted_decode_time_ms, casted_qp);
284 });
285}
286
philipel2fee4d62018-03-21 16:52:13 +0100287} // namespace webrtc