blob: c3c1d0dc47a8446284c4082d8ff710d93af07c46 [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 jitter_estimator_(Clock::GetRealTimeClock()),
37 timing_(Clock::GetRealTimeClock()),
38 frame_buffer_(Clock::GetRealTimeClock(),
39 &jitter_estimator_,
40 &timing_,
philipel844876d2018-04-05 11:02:54 +020041 nullptr),
philipel6847f9b2018-04-20 15:05:37 +020042 next_frame_timestamps_index_(0) {
43 frame_timestamps_.fill({-1, -1, -1});
philipel844876d2018-04-05 11:02:54 +020044 decode_thread_.Start();
45}
philipel2fee4d62018-03-21 16:52:13 +010046
philipel97187112018-03-23 10:43:21 +010047VideoStreamDecoderImpl::~VideoStreamDecoderImpl() {
48 frame_buffer_.Stop();
philipel844876d2018-04-05 11:02:54 +020049 decode_thread_.Stop();
philipel97187112018-03-23 10:43:21 +010050}
philipel2fee4d62018-03-21 16:52:13 +010051
52void VideoStreamDecoderImpl::OnFrame(
philipel97187112018-03-23 10:43:21 +010053 std::unique_ptr<video_coding::EncodedFrame> frame) {
54 if (!bookkeeping_queue_.IsCurrent()) {
Danil Chapovalov471783f2019-03-11 14:26:02 +010055 struct OnFrameTask : QueuedTask {
philipel97187112018-03-23 10:43:21 +010056 OnFrameTask(std::unique_ptr<video_coding::EncodedFrame> frame,
57 VideoStreamDecoderImpl* video_stream_decoder)
58 : frame_(std::move(frame)),
59 video_stream_decoder_(video_stream_decoder) {}
60
Niels Möllerbe682d42018-03-27 08:31:45 +020061 bool Run() override {
philipel97187112018-03-23 10:43:21 +010062 video_stream_decoder_->OnFrame(std::move(frame_));
63 return true;
64 }
65
66 std::unique_ptr<video_coding::EncodedFrame> frame_;
67 VideoStreamDecoderImpl* video_stream_decoder_;
68 };
69
70 bookkeeping_queue_.PostTask(
Karl Wiberg918f50c2018-07-05 11:40:33 +020071 absl::make_unique<OnFrameTask>(std::move(frame), this));
philipel97187112018-03-23 10:43:21 +010072 return;
73 }
74
75 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
76
77 uint64_t continuous_pid = frame_buffer_.InsertFrame(std::move(frame));
78 video_coding::VideoLayerFrameId continuous_id(continuous_pid, 0);
79 if (last_continuous_id_ < continuous_id) {
80 last_continuous_id_ = continuous_id;
81 callbacks_->OnContinuousUntil(last_continuous_id_);
82 }
83}
84
philipel79aab3f2018-03-26 14:31:23 +020085VideoDecoder* VideoStreamDecoderImpl::GetDecoder(int payload_type) {
86 if (current_payload_type_ == payload_type) {
87 RTC_DCHECK(decoder_);
88 return decoder_.get();
89 }
90
91 current_payload_type_.reset();
92 decoder_.reset();
93
94 auto decoder_settings_it = decoder_settings_.find(payload_type);
95 if (decoder_settings_it == decoder_settings_.end()) {
96 RTC_LOG(LS_WARNING) << "Payload type " << payload_type
97 << " not registered.";
98 return nullptr;
99 }
100
101 const SdpVideoFormat& video_format = decoder_settings_it->second.first;
102 std::unique_ptr<VideoDecoder> decoder =
103 decoder_factory_->CreateVideoDecoder(video_format);
104 if (!decoder) {
105 RTC_LOG(LS_WARNING) << "Failed to create decoder for payload type "
106 << payload_type << ".";
107 return nullptr;
108 }
109
110 int num_cores = decoder_settings_it->second.second;
111 int32_t init_result = decoder->InitDecode(nullptr, num_cores);
112 if (init_result != WEBRTC_VIDEO_CODEC_OK) {
113 RTC_LOG(LS_WARNING) << "Failed to initialize decoder for payload type "
114 << payload_type << ".";
115 return nullptr;
116 }
117
118 int32_t register_result = decoder->RegisterDecodeCompleteCallback(this);
119 if (register_result != WEBRTC_VIDEO_CODEC_OK) {
120 RTC_LOG(LS_WARNING) << "Failed to register decode callback.";
121 return nullptr;
122 }
123
124 current_payload_type_.emplace(payload_type);
125 decoder_ = std::move(decoder);
126 return decoder_.get();
127}
128
philipel844876d2018-04-05 11:02:54 +0200129// static
130void VideoStreamDecoderImpl::DecodeLoop(void* ptr) {
131 // TODO(philipel): Remove this and use rtc::Event::kForever when it's
132 // supported by the |frame_buffer_|.
133 static constexpr int kForever = 100000000;
134
135 int max_wait_time_ms = kForever;
136 bool keyframe_required = true;
137 auto* vs_decoder = static_cast<VideoStreamDecoderImpl*>(ptr);
138 while (true) {
139 DecodeResult decode_result =
140 vs_decoder->DecodeNextFrame(max_wait_time_ms, keyframe_required);
141
142 switch (decode_result) {
143 case kOk: {
144 max_wait_time_ms = kForever;
145 keyframe_required = false;
146 break;
147 }
148 case kDecodeFailure: {
149 max_wait_time_ms = 0;
150 keyframe_required = true;
151 break;
152 }
153 case kNoFrame: {
154 max_wait_time_ms = kForever;
155 // If we end up here it means that we got a decoding error and there is
156 // no keyframe available in the |frame_buffer_|.
157 vs_decoder->bookkeeping_queue_.PostTask([vs_decoder]() {
158 RTC_DCHECK_RUN_ON(&vs_decoder->bookkeeping_queue_);
159 vs_decoder->callbacks_->OnNonDecodableState();
160 });
161 break;
162 }
163 case kNoDecoder: {
164 max_wait_time_ms = kForever;
165 break;
166 }
167 case kShutdown: {
168 return;
169 }
170 }
171 }
172}
173
174VideoStreamDecoderImpl::DecodeResult VideoStreamDecoderImpl::DecodeNextFrame(
175 int max_wait_time_ms,
176 bool keyframe_required) {
177 std::unique_ptr<video_coding::EncodedFrame> frame;
178 video_coding::FrameBuffer::ReturnReason res =
179 frame_buffer_.NextFrame(max_wait_time_ms, &frame, keyframe_required);
180
181 if (res == video_coding::FrameBuffer::ReturnReason::kStopped)
182 return kShutdown;
183
184 if (frame) {
185 VideoDecoder* decoder = GetDecoder(frame->PayloadType());
186 if (!decoder) {
187 RTC_LOG(LS_WARNING) << "Failed to get decoder, dropping frame ("
188 << frame->id.picture_id << ":"
189 << frame->id.spatial_layer << ").";
190 return kNoDecoder;
191 }
192
193 int64_t decode_start_time_ms = rtc::TimeMillis();
Niels Möller23775882018-08-16 10:24:12 +0200194 int64_t timestamp = frame->Timestamp();
philipel6847f9b2018-04-20 15:05:37 +0200195 int64_t render_time_us = frame->RenderTimeMs() * 1000;
philipel844876d2018-04-05 11:02:54 +0200196 bookkeeping_queue_.PostTask(
philipel6847f9b2018-04-20 15:05:37 +0200197 [this, decode_start_time_ms, timestamp, render_time_us]() {
philipel844876d2018-04-05 11:02:54 +0200198 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
199 // Saving decode start time this way wont work if we decode spatial
200 // layers sequentially.
philipel6847f9b2018-04-20 15:05:37 +0200201 FrameTimestamps* frame_timestamps =
202 &frame_timestamps_[next_frame_timestamps_index_];
203 frame_timestamps->timestamp = timestamp;
204 frame_timestamps->decode_start_time_ms = decode_start_time_ms;
205 frame_timestamps->render_time_us = render_time_us;
206
207 next_frame_timestamps_index_ =
208 Add<kFrameTimestampsMemory>(next_frame_timestamps_index_, 1);
philipel844876d2018-04-05 11:02:54 +0200209 });
210
Yves Gerey665174f2018-06-19 15:03:05 +0200211 int32_t decode_result = decoder->Decode(frame->EncodedImage(),
212 false, // missing_frame
213 nullptr, // codec specific info
214 frame->RenderTimeMs());
philipel844876d2018-04-05 11:02:54 +0200215
216 return decode_result == WEBRTC_VIDEO_CODEC_OK ? kOk : kDecodeFailure;
217 }
218
219 return kNoFrame;
220}
221
philipel6847f9b2018-04-20 15:05:37 +0200222VideoStreamDecoderImpl::FrameTimestamps*
223VideoStreamDecoderImpl::GetFrameTimestamps(int64_t timestamp) {
224 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
225
226 int start_time_index = next_frame_timestamps_index_;
227 for (int i = 0; i < kFrameTimestampsMemory; ++i) {
228 start_time_index = Subtract<kFrameTimestampsMemory>(start_time_index, 1);
229
230 if (frame_timestamps_[start_time_index].timestamp == timestamp)
231 return &frame_timestamps_[start_time_index];
232 }
233
234 return nullptr;
235}
236
237// VideoDecoder::DecodedImageCallback
238int32_t VideoStreamDecoderImpl::Decoded(VideoFrame& decoded_image) {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200239 Decoded(decoded_image, absl::nullopt, absl::nullopt);
philipel6847f9b2018-04-20 15:05:37 +0200240 return WEBRTC_VIDEO_CODEC_OK;
241}
242
243// VideoDecoder::DecodedImageCallback
244int32_t VideoStreamDecoderImpl::Decoded(VideoFrame& decoded_image,
245 int64_t decode_time_ms) {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200246 Decoded(decoded_image, decode_time_ms, absl::nullopt);
philipel6847f9b2018-04-20 15:05:37 +0200247 return WEBRTC_VIDEO_CODEC_OK;
248}
249
250// VideoDecoder::DecodedImageCallback
251void VideoStreamDecoderImpl::Decoded(VideoFrame& decoded_image,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200252 absl::optional<int32_t> decode_time_ms,
253 absl::optional<uint8_t> qp) {
philipel6847f9b2018-04-20 15:05:37 +0200254 int64_t decode_stop_time_ms = rtc::TimeMillis();
255
256 bookkeeping_queue_.PostTask([this, decode_stop_time_ms, decoded_image,
257 decode_time_ms, qp]() {
258 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
259
260 FrameTimestamps* frame_timestamps =
261 GetFrameTimestamps(decoded_image.timestamp());
262 if (!frame_timestamps) {
263 RTC_LOG(LS_ERROR) << "No frame information found for frame with timestamp"
264 << decoded_image.timestamp();
265 return;
266 }
267
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200268 absl::optional<int> casted_qp;
philipel6847f9b2018-04-20 15:05:37 +0200269 if (qp)
270 casted_qp.emplace(*qp);
271
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200272 absl::optional<int> casted_decode_time_ms(decode_time_ms.value_or(
philipel6847f9b2018-04-20 15:05:37 +0200273 decode_stop_time_ms - frame_timestamps->decode_start_time_ms));
274
275 timing_.StopDecodeTimer(0, *casted_decode_time_ms, decode_stop_time_ms,
276 frame_timestamps->render_time_us / 1000);
277
278 callbacks_->OnDecodedFrame(
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100279 VideoFrame::Builder()
280 .set_video_frame_buffer(decoded_image.video_frame_buffer())
281 .set_rotation(decoded_image.rotation())
282 .set_timestamp_us(frame_timestamps->render_time_us)
Sergey Silkin1daa7e82019-01-10 14:29:46 +0100283 .set_timestamp_rtp(decoded_image.timestamp())
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100284 .set_id(decoded_image.id())
285 .build(),
philipel6847f9b2018-04-20 15:05:37 +0200286 casted_decode_time_ms, casted_qp);
287 });
288}
289
philipel2fee4d62018-03-21 16:52:13 +0100290} // namespace webrtc