blob: 48733ecca443992e9fdcb04e963b574b012c6804 [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()),
Jonas Olssona4d87372019-07-05 19:08:33 +020037 frame_buffer_(Clock::GetRealTimeClock(), &timing_, nullptr),
philipel6847f9b2018-04-20 15:05:37 +020038 next_frame_timestamps_index_(0) {
39 frame_timestamps_.fill({-1, -1, -1});
philipel844876d2018-04-05 11:02:54 +020040 decode_thread_.Start();
41}
philipel2fee4d62018-03-21 16:52:13 +010042
philipel97187112018-03-23 10:43:21 +010043VideoStreamDecoderImpl::~VideoStreamDecoderImpl() {
44 frame_buffer_.Stop();
philipel844876d2018-04-05 11:02:54 +020045 decode_thread_.Stop();
philipel97187112018-03-23 10:43:21 +010046}
philipel2fee4d62018-03-21 16:52:13 +010047
48void VideoStreamDecoderImpl::OnFrame(
philipel97187112018-03-23 10:43:21 +010049 std::unique_ptr<video_coding::EncodedFrame> frame) {
50 if (!bookkeeping_queue_.IsCurrent()) {
Danil Chapovalov471783f2019-03-11 14:26:02 +010051 struct OnFrameTask : QueuedTask {
philipel97187112018-03-23 10:43:21 +010052 OnFrameTask(std::unique_ptr<video_coding::EncodedFrame> frame,
53 VideoStreamDecoderImpl* video_stream_decoder)
54 : frame_(std::move(frame)),
55 video_stream_decoder_(video_stream_decoder) {}
56
Niels Möllerbe682d42018-03-27 08:31:45 +020057 bool Run() override {
philipel97187112018-03-23 10:43:21 +010058 video_stream_decoder_->OnFrame(std::move(frame_));
59 return true;
60 }
61
62 std::unique_ptr<video_coding::EncodedFrame> frame_;
63 VideoStreamDecoderImpl* video_stream_decoder_;
64 };
65
66 bookkeeping_queue_.PostTask(
Karl Wiberg918f50c2018-07-05 11:40:33 +020067 absl::make_unique<OnFrameTask>(std::move(frame), this));
philipel97187112018-03-23 10:43:21 +010068 return;
69 }
70
71 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
72
73 uint64_t continuous_pid = frame_buffer_.InsertFrame(std::move(frame));
74 video_coding::VideoLayerFrameId continuous_id(continuous_pid, 0);
75 if (last_continuous_id_ < continuous_id) {
76 last_continuous_id_ = continuous_id;
77 callbacks_->OnContinuousUntil(last_continuous_id_);
78 }
79}
80
philipel781653c2019-06-04 17:10:37 +020081void VideoStreamDecoderImpl::SetMinPlayoutDelay(TimeDelta min_delay) {
82 timing_.set_min_playout_delay(min_delay.ms());
83}
84
85void VideoStreamDecoderImpl::SetMaxPlayoutDelay(TimeDelta max_delay) {
86 timing_.set_max_playout_delay(max_delay.ms());
87}
88
philipel79aab3f2018-03-26 14:31:23 +020089VideoDecoder* VideoStreamDecoderImpl::GetDecoder(int payload_type) {
90 if (current_payload_type_ == payload_type) {
91 RTC_DCHECK(decoder_);
92 return decoder_.get();
93 }
94
95 current_payload_type_.reset();
96 decoder_.reset();
97
98 auto decoder_settings_it = decoder_settings_.find(payload_type);
99 if (decoder_settings_it == decoder_settings_.end()) {
100 RTC_LOG(LS_WARNING) << "Payload type " << payload_type
101 << " not registered.";
102 return nullptr;
103 }
104
105 const SdpVideoFormat& video_format = decoder_settings_it->second.first;
106 std::unique_ptr<VideoDecoder> decoder =
107 decoder_factory_->CreateVideoDecoder(video_format);
108 if (!decoder) {
109 RTC_LOG(LS_WARNING) << "Failed to create decoder for payload type "
110 << payload_type << ".";
111 return nullptr;
112 }
113
114 int num_cores = decoder_settings_it->second.second;
115 int32_t init_result = decoder->InitDecode(nullptr, num_cores);
116 if (init_result != WEBRTC_VIDEO_CODEC_OK) {
117 RTC_LOG(LS_WARNING) << "Failed to initialize decoder for payload type "
118 << payload_type << ".";
119 return nullptr;
120 }
121
122 int32_t register_result = decoder->RegisterDecodeCompleteCallback(this);
123 if (register_result != WEBRTC_VIDEO_CODEC_OK) {
124 RTC_LOG(LS_WARNING) << "Failed to register decode callback.";
125 return nullptr;
126 }
127
128 current_payload_type_.emplace(payload_type);
129 decoder_ = std::move(decoder);
130 return decoder_.get();
131}
132
philipel844876d2018-04-05 11:02:54 +0200133// static
134void VideoStreamDecoderImpl::DecodeLoop(void* ptr) {
135 // TODO(philipel): Remove this and use rtc::Event::kForever when it's
136 // supported by the |frame_buffer_|.
137 static constexpr int kForever = 100000000;
138
139 int max_wait_time_ms = kForever;
140 bool keyframe_required = true;
141 auto* vs_decoder = static_cast<VideoStreamDecoderImpl*>(ptr);
142 while (true) {
143 DecodeResult decode_result =
144 vs_decoder->DecodeNextFrame(max_wait_time_ms, keyframe_required);
145
146 switch (decode_result) {
147 case kOk: {
148 max_wait_time_ms = kForever;
149 keyframe_required = false;
150 break;
151 }
152 case kDecodeFailure: {
153 max_wait_time_ms = 0;
154 keyframe_required = true;
155 break;
156 }
157 case kNoFrame: {
158 max_wait_time_ms = kForever;
159 // If we end up here it means that we got a decoding error and there is
160 // no keyframe available in the |frame_buffer_|.
161 vs_decoder->bookkeeping_queue_.PostTask([vs_decoder]() {
162 RTC_DCHECK_RUN_ON(&vs_decoder->bookkeeping_queue_);
163 vs_decoder->callbacks_->OnNonDecodableState();
164 });
165 break;
166 }
167 case kNoDecoder: {
168 max_wait_time_ms = kForever;
169 break;
170 }
171 case kShutdown: {
172 return;
173 }
174 }
175 }
176}
177
178VideoStreamDecoderImpl::DecodeResult VideoStreamDecoderImpl::DecodeNextFrame(
179 int max_wait_time_ms,
180 bool keyframe_required) {
181 std::unique_ptr<video_coding::EncodedFrame> frame;
182 video_coding::FrameBuffer::ReturnReason res =
183 frame_buffer_.NextFrame(max_wait_time_ms, &frame, keyframe_required);
184
185 if (res == video_coding::FrameBuffer::ReturnReason::kStopped)
186 return kShutdown;
187
188 if (frame) {
189 VideoDecoder* decoder = GetDecoder(frame->PayloadType());
190 if (!decoder) {
191 RTC_LOG(LS_WARNING) << "Failed to get decoder, dropping frame ("
192 << frame->id.picture_id << ":"
193 << frame->id.spatial_layer << ").";
194 return kNoDecoder;
195 }
196
197 int64_t decode_start_time_ms = rtc::TimeMillis();
Niels Möller23775882018-08-16 10:24:12 +0200198 int64_t timestamp = frame->Timestamp();
philipel6847f9b2018-04-20 15:05:37 +0200199 int64_t render_time_us = frame->RenderTimeMs() * 1000;
philipel844876d2018-04-05 11:02:54 +0200200 bookkeeping_queue_.PostTask(
philipel6847f9b2018-04-20 15:05:37 +0200201 [this, decode_start_time_ms, timestamp, render_time_us]() {
philipel844876d2018-04-05 11:02:54 +0200202 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
203 // Saving decode start time this way wont work if we decode spatial
204 // layers sequentially.
philipel6847f9b2018-04-20 15:05:37 +0200205 FrameTimestamps* frame_timestamps =
206 &frame_timestamps_[next_frame_timestamps_index_];
207 frame_timestamps->timestamp = timestamp;
208 frame_timestamps->decode_start_time_ms = decode_start_time_ms;
209 frame_timestamps->render_time_us = render_time_us;
210
211 next_frame_timestamps_index_ =
212 Add<kFrameTimestampsMemory>(next_frame_timestamps_index_, 1);
philipel844876d2018-04-05 11:02:54 +0200213 });
214
Yves Gerey665174f2018-06-19 15:03:05 +0200215 int32_t decode_result = decoder->Decode(frame->EncodedImage(),
Jonas Olssona4d87372019-07-05 19:08:33 +0200216 false, // missing_frame
Yves Gerey665174f2018-06-19 15:03:05 +0200217 frame->RenderTimeMs());
philipel844876d2018-04-05 11:02:54 +0200218
219 return decode_result == WEBRTC_VIDEO_CODEC_OK ? kOk : kDecodeFailure;
220 }
221
222 return kNoFrame;
223}
224
philipel6847f9b2018-04-20 15:05:37 +0200225VideoStreamDecoderImpl::FrameTimestamps*
226VideoStreamDecoderImpl::GetFrameTimestamps(int64_t timestamp) {
227 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
228
229 int start_time_index = next_frame_timestamps_index_;
230 for (int i = 0; i < kFrameTimestampsMemory; ++i) {
231 start_time_index = Subtract<kFrameTimestampsMemory>(start_time_index, 1);
232
233 if (frame_timestamps_[start_time_index].timestamp == timestamp)
234 return &frame_timestamps_[start_time_index];
235 }
236
237 return nullptr;
238}
239
240// VideoDecoder::DecodedImageCallback
241int32_t VideoStreamDecoderImpl::Decoded(VideoFrame& decoded_image) {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200242 Decoded(decoded_image, absl::nullopt, absl::nullopt);
philipel6847f9b2018-04-20 15:05:37 +0200243 return WEBRTC_VIDEO_CODEC_OK;
244}
245
246// VideoDecoder::DecodedImageCallback
247int32_t VideoStreamDecoderImpl::Decoded(VideoFrame& decoded_image,
248 int64_t decode_time_ms) {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200249 Decoded(decoded_image, decode_time_ms, absl::nullopt);
philipel6847f9b2018-04-20 15:05:37 +0200250 return WEBRTC_VIDEO_CODEC_OK;
251}
252
253// VideoDecoder::DecodedImageCallback
254void VideoStreamDecoderImpl::Decoded(VideoFrame& decoded_image,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200255 absl::optional<int32_t> decode_time_ms,
256 absl::optional<uint8_t> qp) {
philipel6847f9b2018-04-20 15:05:37 +0200257 int64_t decode_stop_time_ms = rtc::TimeMillis();
258
259 bookkeeping_queue_.PostTask([this, decode_stop_time_ms, decoded_image,
260 decode_time_ms, qp]() {
261 RTC_DCHECK_RUN_ON(&bookkeeping_queue_);
262
263 FrameTimestamps* frame_timestamps =
264 GetFrameTimestamps(decoded_image.timestamp());
265 if (!frame_timestamps) {
266 RTC_LOG(LS_ERROR) << "No frame information found for frame with timestamp"
267 << decoded_image.timestamp();
268 return;
269 }
270
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200271 absl::optional<int> casted_qp;
philipel6847f9b2018-04-20 15:05:37 +0200272 if (qp)
273 casted_qp.emplace(*qp);
274
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200275 absl::optional<int> casted_decode_time_ms(decode_time_ms.value_or(
philipel6847f9b2018-04-20 15:05:37 +0200276 decode_stop_time_ms - frame_timestamps->decode_start_time_ms));
277
Johannes Kronbfd343b2019-07-01 10:07:50 +0200278 timing_.StopDecodeTimer(*casted_decode_time_ms, decode_stop_time_ms);
philipel6847f9b2018-04-20 15:05:37 +0200279
Ilya Nikolaevskiy4fc08552019-06-05 15:59:12 +0200280 VideoFrame copy = decoded_image;
281 copy.set_timestamp_us(frame_timestamps->render_time_us);
282 callbacks_->OnDecodedFrame(copy, casted_decode_time_ms, casted_qp);
philipel6847f9b2018-04-20 15:05:37 +0200283 });
284}
285
philipel2fee4d62018-03-21 16:52:13 +0100286} // namespace webrtc