blob: 56efca6986091d40ea9243db72d4d228148da803 [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(
22 VideoStreamDecoder::Callbacks* callbacks,
23 VideoDecoderFactory* decoder_factory,
24 std::map<int, std::pair<SdpVideoFormat, int>> decoder_settings)
25 : callbacks_(callbacks),
26 decoder_factory_(decoder_factory),
philipel97187112018-03-23 10:43:21 +010027 decoder_settings_(std::move(decoder_settings)),
28 bookkeeping_queue_("video_stream_decoder_bookkeeping_queue"),
philipel844876d2018-04-05 11:02:54 +020029 decode_thread_(&DecodeLoop,
30 this,
31 "video_stream_decoder_decode_thread",
32 rtc::kHighestPriority),
philipel97187112018-03-23 10:43:21 +010033 jitter_estimator_(Clock::GetRealTimeClock()),
34 timing_(Clock::GetRealTimeClock()),
35 frame_buffer_(Clock::GetRealTimeClock(),
36 &jitter_estimator_,
37 &timing_,
philipel844876d2018-04-05 11:02:54 +020038 nullptr),
philipel6847f9b2018-04-20 15:05:37 +020039 next_frame_timestamps_index_(0) {
40 frame_timestamps_.fill({-1, -1, -1});
philipel844876d2018-04-05 11:02:54 +020041 decode_thread_.Start();
42}
philipel2fee4d62018-03-21 16:52:13 +010043
philipel97187112018-03-23 10:43:21 +010044VideoStreamDecoderImpl::~VideoStreamDecoderImpl() {
45 frame_buffer_.Stop();
philipel844876d2018-04-05 11:02:54 +020046 decode_thread_.Stop();
philipel97187112018-03-23 10:43:21 +010047}
philipel2fee4d62018-03-21 16:52:13 +010048
49void VideoStreamDecoderImpl::OnFrame(
philipel97187112018-03-23 10:43:21 +010050 std::unique_ptr<video_coding::EncodedFrame> frame) {
51 if (!bookkeeping_queue_.IsCurrent()) {
Danil Chapovalov471783f2019-03-11 14:26:02 +010052 struct OnFrameTask : QueuedTask {
philipel97187112018-03-23 10:43:21 +010053 OnFrameTask(std::unique_ptr<video_coding::EncodedFrame> frame,
54 VideoStreamDecoderImpl* video_stream_decoder)
55 : frame_(std::move(frame)),
56 video_stream_decoder_(video_stream_decoder) {}
57
Niels Möllerbe682d42018-03-27 08:31:45 +020058 bool Run() override {
philipel97187112018-03-23 10:43:21 +010059 video_stream_decoder_->OnFrame(std::move(frame_));
60 return true;
61 }
62
63 std::unique_ptr<video_coding::EncodedFrame> frame_;
64 VideoStreamDecoderImpl* video_stream_decoder_;
65 };
66
67 bookkeeping_queue_.PostTask(
Karl Wiberg918f50c2018-07-05 11:40:33 +020068 absl::make_unique<OnFrameTask>(std::move(frame), this));
philipel97187112018-03-23 10:43:21 +010069 return;
70 }
71
72 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
73
74 uint64_t continuous_pid = frame_buffer_.InsertFrame(std::move(frame));
75 video_coding::VideoLayerFrameId continuous_id(continuous_pid, 0);
76 if (last_continuous_id_ < continuous_id) {
77 last_continuous_id_ = continuous_id;
78 callbacks_->OnContinuousUntil(last_continuous_id_);
79 }
80}
81
philipel79aab3f2018-03-26 14:31:23 +020082VideoDecoder* VideoStreamDecoderImpl::GetDecoder(int payload_type) {
83 if (current_payload_type_ == payload_type) {
84 RTC_DCHECK(decoder_);
85 return decoder_.get();
86 }
87
88 current_payload_type_.reset();
89 decoder_.reset();
90
91 auto decoder_settings_it = decoder_settings_.find(payload_type);
92 if (decoder_settings_it == decoder_settings_.end()) {
93 RTC_LOG(LS_WARNING) << "Payload type " << payload_type
94 << " not registered.";
95 return nullptr;
96 }
97
98 const SdpVideoFormat& video_format = decoder_settings_it->second.first;
99 std::unique_ptr<VideoDecoder> decoder =
100 decoder_factory_->CreateVideoDecoder(video_format);
101 if (!decoder) {
102 RTC_LOG(LS_WARNING) << "Failed to create decoder for payload type "
103 << payload_type << ".";
104 return nullptr;
105 }
106
107 int num_cores = decoder_settings_it->second.second;
108 int32_t init_result = decoder->InitDecode(nullptr, num_cores);
109 if (init_result != WEBRTC_VIDEO_CODEC_OK) {
110 RTC_LOG(LS_WARNING) << "Failed to initialize decoder for payload type "
111 << payload_type << ".";
112 return nullptr;
113 }
114
115 int32_t register_result = decoder->RegisterDecodeCompleteCallback(this);
116 if (register_result != WEBRTC_VIDEO_CODEC_OK) {
117 RTC_LOG(LS_WARNING) << "Failed to register decode callback.";
118 return nullptr;
119 }
120
121 current_payload_type_.emplace(payload_type);
122 decoder_ = std::move(decoder);
123 return decoder_.get();
124}
125
philipel844876d2018-04-05 11:02:54 +0200126// static
127void VideoStreamDecoderImpl::DecodeLoop(void* ptr) {
128 // TODO(philipel): Remove this and use rtc::Event::kForever when it's
129 // supported by the |frame_buffer_|.
130 static constexpr int kForever = 100000000;
131
132 int max_wait_time_ms = kForever;
133 bool keyframe_required = true;
134 auto* vs_decoder = static_cast<VideoStreamDecoderImpl*>(ptr);
135 while (true) {
136 DecodeResult decode_result =
137 vs_decoder->DecodeNextFrame(max_wait_time_ms, keyframe_required);
138
139 switch (decode_result) {
140 case kOk: {
141 max_wait_time_ms = kForever;
142 keyframe_required = false;
143 break;
144 }
145 case kDecodeFailure: {
146 max_wait_time_ms = 0;
147 keyframe_required = true;
148 break;
149 }
150 case kNoFrame: {
151 max_wait_time_ms = kForever;
152 // If we end up here it means that we got a decoding error and there is
153 // no keyframe available in the |frame_buffer_|.
154 vs_decoder->bookkeeping_queue_.PostTask([vs_decoder]() {
155 RTC_DCHECK_RUN_ON(&vs_decoder->bookkeeping_queue_);
156 vs_decoder->callbacks_->OnNonDecodableState();
157 });
158 break;
159 }
160 case kNoDecoder: {
161 max_wait_time_ms = kForever;
162 break;
163 }
164 case kShutdown: {
165 return;
166 }
167 }
168 }
169}
170
171VideoStreamDecoderImpl::DecodeResult VideoStreamDecoderImpl::DecodeNextFrame(
172 int max_wait_time_ms,
173 bool keyframe_required) {
174 std::unique_ptr<video_coding::EncodedFrame> frame;
175 video_coding::FrameBuffer::ReturnReason res =
176 frame_buffer_.NextFrame(max_wait_time_ms, &frame, keyframe_required);
177
178 if (res == video_coding::FrameBuffer::ReturnReason::kStopped)
179 return kShutdown;
180
181 if (frame) {
182 VideoDecoder* decoder = GetDecoder(frame->PayloadType());
183 if (!decoder) {
184 RTC_LOG(LS_WARNING) << "Failed to get decoder, dropping frame ("
185 << frame->id.picture_id << ":"
186 << frame->id.spatial_layer << ").";
187 return kNoDecoder;
188 }
189
190 int64_t decode_start_time_ms = rtc::TimeMillis();
Niels Möller23775882018-08-16 10:24:12 +0200191 int64_t timestamp = frame->Timestamp();
philipel6847f9b2018-04-20 15:05:37 +0200192 int64_t render_time_us = frame->RenderTimeMs() * 1000;
philipel844876d2018-04-05 11:02:54 +0200193 bookkeeping_queue_.PostTask(
philipel6847f9b2018-04-20 15:05:37 +0200194 [this, decode_start_time_ms, timestamp, render_time_us]() {
philipel844876d2018-04-05 11:02:54 +0200195 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
196 // Saving decode start time this way wont work if we decode spatial
197 // layers sequentially.
philipel6847f9b2018-04-20 15:05:37 +0200198 FrameTimestamps* frame_timestamps =
199 &frame_timestamps_[next_frame_timestamps_index_];
200 frame_timestamps->timestamp = timestamp;
201 frame_timestamps->decode_start_time_ms = decode_start_time_ms;
202 frame_timestamps->render_time_us = render_time_us;
203
204 next_frame_timestamps_index_ =
205 Add<kFrameTimestampsMemory>(next_frame_timestamps_index_, 1);
philipel844876d2018-04-05 11:02:54 +0200206 });
207
Yves Gerey665174f2018-06-19 15:03:05 +0200208 int32_t decode_result = decoder->Decode(frame->EncodedImage(),
209 false, // missing_frame
210 nullptr, // codec specific info
211 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