blob: ba77b72d4fc0180b7044f4669bbdaffc25fe27cb [file] [log] [blame]
philipelbe7a9e52016-05-19 12:19:35 +02001/*
2 * Copyright (c) 2016 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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/video_coding/frame_buffer2.h"
philipelbe7a9e52016-05-19 12:19:35 +020012
13#include <algorithm>
Yves Gerey3e707812018-11-28 16:47:49 +010014#include <cstdlib>
15#include <iterator>
philipele0b2f152016-09-28 10:23:49 +020016#include <queue>
Yves Gerey3e707812018-11-28 16:47:49 +010017#include <utility>
philipel798b2822018-06-11 13:10:14 +020018#include <vector>
philipelbe7a9e52016-05-19 12:19:35 +020019
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +020020#include "absl/memory/memory.h"
Yves Gerey3e707812018-11-28 16:47:49 +010021#include "api/video/encoded_image.h"
22#include "api/video/video_timing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "modules/video_coding/include/video_coding_defines.h"
24#include "modules/video_coding/jitter_estimator.h"
25#include "modules/video_coding/timing.h"
26#include "rtc_base/checks.h"
Yves Gerey3e707812018-11-28 16:47:49 +010027#include "rtc_base/experiments/rtt_mult_experiment.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/logging.h"
Yves Gerey3e707812018-11-28 16:47:49 +010029#include "rtc_base/numerics/sequence_number_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/trace_event.h"
31#include "system_wrappers/include/clock.h"
philipel707f2782017-10-02 14:10:28 +020032#include "system_wrappers/include/field_trial.h"
philipelbe7a9e52016-05-19 12:19:35 +020033
34namespace webrtc {
35namespace video_coding {
36
37namespace {
philipele0b2f152016-09-28 10:23:49 +020038// Max number of frames the buffer will hold.
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +010039constexpr size_t kMaxFramesBuffered = 800;
philipelbe7a9e52016-05-19 12:19:35 +020040
philipele0b2f152016-09-28 10:23:49 +020041// Max number of decoded frame info that will be saved.
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +010042constexpr int kMaxFramesHistory = 1 << 13;
philipel65e1f942017-07-24 08:26:53 -070043
Ilya Nikolaevskiy8c4fe162018-02-27 15:49:47 +010044// The time it's allowed for a frame to be late to its rendering prediction and
45// still be rendered.
Ilya Nikolaevskiy7eef0072018-02-28 09:59:26 +010046constexpr int kMaxAllowedFrameDelayMs = 5;
Ilya Nikolaevskiy8c4fe162018-02-27 15:49:47 +010047
philipel65e1f942017-07-24 08:26:53 -070048constexpr int64_t kLogNonDecodedIntervalMs = 5000;
philipelbe7a9e52016-05-19 12:19:35 +020049} // namespace
50
philipelbe7a9e52016-05-19 12:19:35 +020051FrameBuffer::FrameBuffer(Clock* clock,
philipela45102f2017-02-22 05:30:39 -080052 VCMTiming* timing,
53 VCMReceiveStatisticsCallback* stats_callback)
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +010054 : decoded_frames_history_(kMaxFramesHistory),
55 clock_(clock),
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +020056 callback_queue_(nullptr),
Niels Möllerd9c2d942019-04-30 09:16:36 +020057 jitter_estimator_(clock),
philipelbe7a9e52016-05-19 12:19:35 +020058 timing_(timing),
philipel4f6cd6a2016-08-03 10:59:32 +020059 inter_frame_delay_(clock_->TimeInMilliseconds()),
philipel29f730e2017-03-15 08:10:08 -070060 stopped_(false),
philipela45102f2017-02-22 05:30:39 -080061 protection_mode_(kProtectionNack),
philipel65e1f942017-07-24 08:26:53 -070062 stats_callback_(stats_callback),
Elad Alone4b50232019-01-14 18:56:14 +010063 last_log_non_decoded_ms_(-kLogNonDecodedIntervalMs),
64 add_rtt_to_playout_delay_(
“Michaeld3a4ebe2019-06-07 03:55:01 -050065 webrtc::field_trial::IsEnabled("WebRTC-AddRttToPlayoutDelay")),
Tommi430951a2020-05-19 23:27:29 +020066 rtt_mult_settings_(RttMultExperiment::GetRttMultValue()) {
67 callback_checker_.Detach();
68}
philipel266f0a42016-11-28 08:49:07 -080069
Tommi430951a2020-05-19 23:27:29 +020070FrameBuffer::~FrameBuffer() {
71 RTC_DCHECK_RUN_ON(&construction_checker_);
72}
philipelbe7a9e52016-05-19 12:19:35 +020073
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +020074void FrameBuffer::NextFrame(
75 int64_t max_wait_time_ms,
76 bool keyframe_required,
77 rtc::TaskQueue* callback_queue,
78 std::function<void(std::unique_ptr<EncodedFrame>, ReturnReason)> handler) {
Tommi430951a2020-05-19 23:27:29 +020079 RTC_DCHECK_RUN_ON(&callback_checker_);
80 RTC_DCHECK(callback_queue->IsCurrent());
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +020081 TRACE_EVENT0("webrtc", "FrameBuffer::NextFrame");
82 int64_t latest_return_time_ms =
83 clock_->TimeInMilliseconds() + max_wait_time_ms;
Tommi430951a2020-05-19 23:27:29 +020084
Markus Handell6deec382020-07-07 12:17:12 +020085 MutexLock lock(&mutex_);
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +020086 if (stopped_) {
87 return;
88 }
89 latest_return_time_ms_ = latest_return_time_ms;
90 keyframe_required_ = keyframe_required;
91 frame_handler_ = handler;
92 callback_queue_ = callback_queue;
93 StartWaitForNextFrameOnQueue();
94}
95
96void FrameBuffer::StartWaitForNextFrameOnQueue() {
97 RTC_DCHECK(callback_queue_);
98 RTC_DCHECK(!callback_task_.Running());
99 int64_t wait_ms = FindNextFrame(clock_->TimeInMilliseconds());
100 callback_task_ = RepeatingTaskHandle::DelayedStart(
Danil Chapovalov55284022020-02-07 14:53:52 +0100101 callback_queue_->Get(), TimeDelta::Millis(wait_ms), [this] {
Tommi430951a2020-05-19 23:27:29 +0200102 RTC_DCHECK_RUN_ON(&callback_checker_);
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200103 // If this task has not been cancelled, we did not get any new frames
104 // while waiting. Continue with frame delivery.
Markus Handell334b1fd2020-12-14 00:08:11 +0100105 std::unique_ptr<EncodedFrame> frame;
106 std::function<void(std::unique_ptr<EncodedFrame>, ReturnReason)>
107 frame_handler;
108 {
109 MutexLock lock(&mutex_);
110 if (!frames_to_decode_.empty()) {
111 // We have frames, deliver!
112 frame = absl::WrapUnique(GetNextFrame());
Rezaul Barbhuiya82c22482021-08-05 17:54:11 -0700113 timing_->SetLastDecodeScheduledTimestamp(
114 clock_->TimeInMilliseconds());
Markus Handell334b1fd2020-12-14 00:08:11 +0100115 } else if (clock_->TimeInMilliseconds() < latest_return_time_ms_) {
116 // If there's no frames to decode and there is still time left, it
117 // means that the frame buffer was cleared between creation and
118 // execution of this task. Continue waiting for the remaining time.
119 int64_t wait_ms = FindNextFrame(clock_->TimeInMilliseconds());
120 return TimeDelta::Millis(wait_ms);
121 }
122 frame_handler = std::move(frame_handler_);
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200123 CancelCallback();
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200124 }
Markus Handell334b1fd2020-12-14 00:08:11 +0100125 // Deliver frame, if any. Otherwise signal timeout.
126 ReturnReason reason = frame ? kFrameFound : kTimeout;
127 frame_handler(std::move(frame), reason);
128 return TimeDelta::Zero(); // Ignored.
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200129 });
130}
131
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200132int64_t FrameBuffer::FindNextFrame(int64_t now_ms) {
133 int64_t wait_ms = latest_return_time_ms_ - now_ms;
134 frames_to_decode_.clear();
135
136 // |last_continuous_frame_| may be empty below, but nullopt is smaller
137 // than everything else and loop will immediately terminate as expected.
138 for (auto frame_it = frames_.begin();
139 frame_it != frames_.end() && frame_it->first <= last_continuous_frame_;
140 ++frame_it) {
141 if (!frame_it->second.continuous ||
142 frame_it->second.num_missing_decodable > 0) {
143 continue;
144 }
145
146 EncodedFrame* frame = frame_it->second.frame.get();
147
148 if (keyframe_required_ && !frame->is_keyframe())
149 continue;
150
151 auto last_decoded_frame_timestamp =
152 decoded_frames_history_.GetLastDecodedFrameTimestamp();
153
154 // TODO(https://bugs.webrtc.org/9974): consider removing this check
155 // as it may make a stream undecodable after a very long delay between
156 // frames.
157 if (last_decoded_frame_timestamp &&
158 AheadOf(*last_decoded_frame_timestamp, frame->Timestamp())) {
159 continue;
160 }
161
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200162 // Gather all remaining frames for the same superframe.
163 std::vector<FrameMap::iterator> current_superframe;
164 current_superframe.push_back(frame_it);
165 bool last_layer_completed = frame_it->second.frame->is_last_spatial_layer;
166 FrameMap::iterator next_frame_it = frame_it;
philipela65d7852020-11-20 17:49:24 +0100167 while (!last_layer_completed) {
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200168 ++next_frame_it;
philipela65d7852020-11-20 17:49:24 +0100169
170 if (next_frame_it == frames_.end() || !next_frame_it->second.frame) {
171 break;
172 }
173
174 if (next_frame_it->second.frame->Timestamp() != frame->Timestamp() ||
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200175 !next_frame_it->second.continuous) {
176 break;
177 }
philipela65d7852020-11-20 17:49:24 +0100178
179 if (next_frame_it->second.num_missing_decodable > 0) {
philipelcb327d92020-12-10 10:49:20 +0100180 bool has_inter_layer_dependency = false;
181 for (size_t i = 0; i < EncodedFrame::kMaxFrameReferences &&
philipela65d7852020-11-20 17:49:24 +0100182 i < next_frame_it->second.frame->num_references;
183 ++i) {
philipel9aa9b8d2021-02-15 13:31:29 +0100184 if (next_frame_it->second.frame->references[i] >= frame_it->first) {
philipela65d7852020-11-20 17:49:24 +0100185 has_inter_layer_dependency = true;
philipelcb327d92020-12-10 10:49:20 +0100186 break;
philipela65d7852020-11-20 17:49:24 +0100187 }
188 }
189
190 // If the frame has an undecoded dependency that is not within the same
philipelcb327d92020-12-10 10:49:20 +0100191 // temporal unit then this frame is not yet ready to be decoded. If it
philipela65d7852020-11-20 17:49:24 +0100192 // is within the same temporal unit then the not yet decoded dependency
193 // is just a lower spatial frame, which is ok.
194 if (!has_inter_layer_dependency ||
195 next_frame_it->second.num_missing_decodable > 1) {
196 break;
197 }
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200198 }
philipela65d7852020-11-20 17:49:24 +0100199
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200200 current_superframe.push_back(next_frame_it);
201 last_layer_completed = next_frame_it->second.frame->is_last_spatial_layer;
202 }
203 // Check if the current superframe is complete.
204 // TODO(bugs.webrtc.org/10064): consider returning all available to
205 // decode frames even if the superframe is not complete yet.
206 if (!last_layer_completed) {
207 continue;
208 }
209
210 frames_to_decode_ = std::move(current_superframe);
211
212 if (frame->RenderTime() == -1) {
213 frame->SetRenderTime(timing_->RenderTimeMs(frame->Timestamp(), now_ms));
214 }
215 wait_ms = timing_->MaxWaitingTime(frame->RenderTime(), now_ms);
216
217 // This will cause the frame buffer to prefer high framerate rather
218 // than high resolution in the case of the decoder not decoding fast
219 // enough and the stream has multiple spatial and temporal layers.
220 // For multiple temporal layers it may cause non-base layer frames to be
221 // skipped if they are late.
222 if (wait_ms < -kMaxAllowedFrameDelayMs)
223 continue;
224
225 break;
226 }
227 wait_ms = std::min<int64_t>(wait_ms, latest_return_time_ms_ - now_ms);
228 wait_ms = std::max<int64_t>(wait_ms, 0);
229 return wait_ms;
230}
231
232EncodedFrame* FrameBuffer::GetNextFrame() {
Tommi430951a2020-05-19 23:27:29 +0200233 RTC_DCHECK_RUN_ON(&callback_checker_);
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200234 int64_t now_ms = clock_->TimeInMilliseconds();
235 // TODO(ilnik): remove |frames_out| use frames_to_decode_ directly.
236 std::vector<EncodedFrame*> frames_out;
237
238 RTC_DCHECK(!frames_to_decode_.empty());
239 bool superframe_delayed_by_retransmission = false;
240 size_t superframe_size = 0;
241 EncodedFrame* first_frame = frames_to_decode_[0]->second.frame.get();
242 int64_t render_time_ms = first_frame->RenderTime();
243 int64_t receive_time_ms = first_frame->ReceivedTime();
244 // Gracefully handle bad RTP timestamps and render time issues.
245 if (HasBadRenderTiming(*first_frame, now_ms)) {
Niels Möllerd9c2d942019-04-30 09:16:36 +0200246 jitter_estimator_.Reset();
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200247 timing_->Reset();
248 render_time_ms = timing_->RenderTimeMs(first_frame->Timestamp(), now_ms);
249 }
250
251 for (FrameMap::iterator& frame_it : frames_to_decode_) {
252 RTC_DCHECK(frame_it != frames_.end());
253 EncodedFrame* frame = frame_it->second.frame.release();
254
255 frame->SetRenderTime(render_time_ms);
256
257 superframe_delayed_by_retransmission |= frame->delayed_by_retransmission();
258 receive_time_ms = std::max(receive_time_ms, frame->ReceivedTime());
259 superframe_size += frame->size();
260
261 PropagateDecodability(frame_it->second);
262 decoded_frames_history_.InsertDecoded(frame_it->first, frame->Timestamp());
263
264 // Remove decoded frame and all undecoded frames before it.
Johannes Kron0c141c52019-08-26 15:04:43 +0200265 if (stats_callback_) {
philipel9aa9b8d2021-02-15 13:31:29 +0100266 unsigned int dropped_frames =
267 std::count_if(frames_.begin(), frame_it,
268 [](const std::pair<const int64_t, FrameInfo>& frame) {
269 return frame.second.frame != nullptr;
270 });
Johannes Kron0c141c52019-08-26 15:04:43 +0200271 if (dropped_frames > 0) {
272 stats_callback_->OnDroppedFrames(dropped_frames);
273 }
274 }
275
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200276 frames_.erase(frames_.begin(), ++frame_it);
277
278 frames_out.push_back(frame);
279 }
280
281 if (!superframe_delayed_by_retransmission) {
282 int64_t frame_delay;
283
284 if (inter_frame_delay_.CalculateDelay(first_frame->Timestamp(),
285 &frame_delay, receive_time_ms)) {
Niels Möllerd9c2d942019-04-30 09:16:36 +0200286 jitter_estimator_.UpdateEstimate(frame_delay, superframe_size);
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200287 }
288
289 float rtt_mult = protection_mode_ == kProtectionNackFEC ? 0.0 : 1.0;
“Michaeld3a4ebe2019-06-07 03:55:01 -0500290 absl::optional<float> rtt_mult_add_cap_ms = absl::nullopt;
291 if (rtt_mult_settings_.has_value()) {
292 rtt_mult = rtt_mult_settings_->rtt_mult_setting;
293 rtt_mult_add_cap_ms = rtt_mult_settings_->rtt_mult_add_cap_ms;
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200294 }
“Michaele0f37042019-06-04 10:04:12 -0500295 timing_->SetJitterDelay(
296 jitter_estimator_.GetJitterEstimate(rtt_mult, rtt_mult_add_cap_ms));
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200297 timing_->UpdateCurrentDelay(render_time_ms, now_ms);
298 } else {
299 if (RttMultExperiment::RttMultEnabled() || add_rtt_to_playout_delay_)
Niels Möllerd9c2d942019-04-30 09:16:36 +0200300 jitter_estimator_.FrameNacked();
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200301 }
302
303 UpdateJitterDelay();
304 UpdateTimingFrameInfo();
305
306 if (frames_out.size() == 1) {
307 return frames_out[0];
308 } else {
309 return CombineAndDeleteFrames(frames_out);
310 }
311}
312
philipele7c891f2018-02-22 14:35:06 +0100313bool FrameBuffer::HasBadRenderTiming(const EncodedFrame& frame,
314 int64_t now_ms) {
stefan95e97542017-05-23 09:52:18 -0700315 // Assume that render timing errors are due to changes in the video stream.
316 int64_t render_time_ms = frame.RenderTimeMs();
Stefan Holmer812ceaf2018-05-15 13:00:10 +0200317 // Zero render time means render immediately.
318 if (render_time_ms == 0) {
319 return false;
320 }
stefan95e97542017-05-23 09:52:18 -0700321 if (render_time_ms < 0) {
322 return true;
323 }
Stefan Holmer812ceaf2018-05-15 13:00:10 +0200324 const int64_t kMaxVideoDelayMs = 10000;
stefan95e97542017-05-23 09:52:18 -0700325 if (std::abs(render_time_ms - now_ms) > kMaxVideoDelayMs) {
326 int frame_delay = static_cast<int>(std::abs(render_time_ms - now_ms));
Mirko Bonadei675513b2017-11-09 11:09:25 +0100327 RTC_LOG(LS_WARNING)
328 << "A frame about to be decoded is out of the configured "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100329 "delay bounds ("
330 << frame_delay << " > " << kMaxVideoDelayMs
Mirko Bonadei675513b2017-11-09 11:09:25 +0100331 << "). Resetting the video jitter buffer.";
stefan95e97542017-05-23 09:52:18 -0700332 return true;
333 }
334 if (static_cast<int>(timing_->TargetVideoDelay()) > kMaxVideoDelayMs) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100335 RTC_LOG(LS_WARNING) << "The video target delay has grown larger than "
336 << kMaxVideoDelayMs << " ms.";
stefan95e97542017-05-23 09:52:18 -0700337 return true;
338 }
339 return false;
340}
341
philipel4f6cd6a2016-08-03 10:59:32 +0200342void FrameBuffer::SetProtectionMode(VCMVideoProtection mode) {
tommidb23ea62017-03-03 07:21:18 -0800343 TRACE_EVENT0("webrtc", "FrameBuffer::SetProtectionMode");
Markus Handell6deec382020-07-07 12:17:12 +0200344 MutexLock lock(&mutex_);
Henrik Boströmc680c4a2019-04-03 10:27:36 +0000345 protection_mode_ = mode;
philipel4f6cd6a2016-08-03 10:59:32 +0200346}
347
philipel504c47d2016-06-30 17:33:02 +0200348void FrameBuffer::Stop() {
tommidb23ea62017-03-03 07:21:18 -0800349 TRACE_EVENT0("webrtc", "FrameBuffer::Stop");
Markus Handell6deec382020-07-07 12:17:12 +0200350 MutexLock lock(&mutex_);
Tommi430951a2020-05-19 23:27:29 +0200351 if (stopped_)
352 return;
Henrik Boströmc680c4a2019-04-03 10:27:36 +0000353 stopped_ = true;
Tommi430951a2020-05-19 23:27:29 +0200354
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200355 CancelCallback();
philipel504c47d2016-06-30 17:33:02 +0200356}
357
Ilya Nikolaevskiye6a2d942018-11-07 14:32:28 +0100358void FrameBuffer::Clear() {
Markus Handell6deec382020-07-07 12:17:12 +0200359 MutexLock lock(&mutex_);
Henrik Boströmc680c4a2019-04-03 10:27:36 +0000360 ClearFramesAndHistory();
Ilya Nikolaevskiye6a2d942018-11-07 14:32:28 +0100361}
362
Johannes Kron111e9812020-10-26 13:54:40 +0100363int FrameBuffer::Size() {
364 MutexLock lock(&mutex_);
365 return frames_.size();
366}
367
philipele21be1d2017-09-25 06:37:12 -0700368void FrameBuffer::UpdateRtt(int64_t rtt_ms) {
Markus Handell6deec382020-07-07 12:17:12 +0200369 MutexLock lock(&mutex_);
Niels Möllerd9c2d942019-04-30 09:16:36 +0200370 jitter_estimator_.UpdateRtt(rtt_ms);
philipele21be1d2017-09-25 06:37:12 -0700371}
372
philipele7c891f2018-02-22 14:35:06 +0100373bool FrameBuffer::ValidReferences(const EncodedFrame& frame) const {
philipel112adf92017-06-15 09:06:21 -0700374 for (size_t i = 0; i < frame.num_references; ++i) {
philipel9aa9b8d2021-02-15 13:31:29 +0100375 if (frame.references[i] >= frame.Id())
philipel112adf92017-06-15 09:06:21 -0700376 return false;
philipel3b3c9c42017-09-11 09:38:36 -0700377
philipel112adf92017-06-15 09:06:21 -0700378 for (size_t j = i + 1; j < frame.num_references; ++j) {
379 if (frame.references[i] == frame.references[j])
380 return false;
381 }
382 }
383
philipel112adf92017-06-15 09:06:21 -0700384 return true;
385}
386
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200387void FrameBuffer::CancelCallback() {
Tommi430951a2020-05-19 23:27:29 +0200388 // Called from the callback queue or from within Stop().
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200389 frame_handler_ = {};
390 callback_task_.Stop();
391 callback_queue_ = nullptr;
Tommi430951a2020-05-19 23:27:29 +0200392 callback_checker_.Detach();
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200393}
394
philipele7c891f2018-02-22 14:35:06 +0100395int64_t FrameBuffer::InsertFrame(std::unique_ptr<EncodedFrame> frame) {
tommidb23ea62017-03-03 07:21:18 -0800396 TRACE_EVENT0("webrtc", "FrameBuffer::InsertFrame");
philipel93e451b2016-10-06 12:25:13 +0200397 RTC_DCHECK(frame);
tommi0a735642017-03-14 06:23:57 -0700398
Markus Handell6deec382020-07-07 12:17:12 +0200399 MutexLock lock(&mutex_);
philipel29f730e2017-03-15 08:10:08 -0700400
philipel9aa9b8d2021-02-15 13:31:29 +0100401 int64_t last_continuous_frame_id = last_continuous_frame_.value_or(-1);
philipele0b2f152016-09-28 10:23:49 +0200402
philipel112adf92017-06-15 09:06:21 -0700403 if (!ValidReferences(*frame)) {
philipel9aa9b8d2021-02-15 13:31:29 +0100404 RTC_LOG(LS_WARNING) << "Frame " << frame->Id()
philipelf1091932021-02-11 15:25:08 +0100405 << " has invalid frame references, dropping frame.";
philipel9aa9b8d2021-02-15 13:31:29 +0100406 return last_continuous_frame_id;
philipel112adf92017-06-15 09:06:21 -0700407 }
408
Ilya Nikolaevskiy6551faf2019-01-10 15:16:47 +0100409 if (frames_.size() >= kMaxFramesBuffered) {
philipel9771c502018-03-02 11:06:27 +0100410 if (frame->is_keyframe()) {
philipel9aa9b8d2021-02-15 13:31:29 +0100411 RTC_LOG(LS_WARNING) << "Inserting keyframe " << frame->Id()
philipelf1091932021-02-11 15:25:08 +0100412 << " but buffer is full, clearing"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100413 " buffer and inserting the frame.";
philipel9771c502018-03-02 11:06:27 +0100414 ClearFramesAndHistory();
415 } else {
philipel9aa9b8d2021-02-15 13:31:29 +0100416 RTC_LOG(LS_WARNING) << "Frame " << frame->Id()
philipelf1091932021-02-11 15:25:08 +0100417 << " could not be inserted due to the frame "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100418 "buffer being full, dropping frame.";
philipel9aa9b8d2021-02-15 13:31:29 +0100419 return last_continuous_frame_id;
philipel9771c502018-03-02 11:06:27 +0100420 }
philipele0b2f152016-09-28 10:23:49 +0200421 }
422
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +0100423 auto last_decoded_frame = decoded_frames_history_.GetLastDecodedFrameId();
424 auto last_decoded_frame_timestamp =
425 decoded_frames_history_.GetLastDecodedFrameTimestamp();
philipel9aa9b8d2021-02-15 13:31:29 +0100426 if (last_decoded_frame && frame->Id() <= *last_decoded_frame) {
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +0100427 if (AheadOf(frame->Timestamp(), *last_decoded_frame_timestamp) &&
philipel3042c2d2017-08-18 04:55:02 -0700428 frame->is_keyframe()) {
philipel9aa9b8d2021-02-15 13:31:29 +0100429 // If this frame has a newer timestamp but an earlier frame id then we
430 // assume there has been a jump in the frame id due to some encoder
philipelfcc60062017-01-18 05:35:20 -0800431 // reconfiguration or some other reason. Even though this is not according
432 // to spec we can still continue to decode from this frame if it is a
433 // keyframe.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100434 RTC_LOG(LS_WARNING)
philipel9aa9b8d2021-02-15 13:31:29 +0100435 << "A jump in frame id was detected, clearing buffer.";
philipelfcc60062017-01-18 05:35:20 -0800436 ClearFramesAndHistory();
philipel9aa9b8d2021-02-15 13:31:29 +0100437 last_continuous_frame_id = -1;
philipelfcc60062017-01-18 05:35:20 -0800438 } else {
philipel9aa9b8d2021-02-15 13:31:29 +0100439 RTC_LOG(LS_WARNING) << "Frame " << frame->Id() << " inserted after frame "
440 << *last_decoded_frame
philipelf1091932021-02-11 15:25:08 +0100441 << " was handed off for decoding, dropping frame.";
philipel9aa9b8d2021-02-15 13:31:29 +0100442 return last_continuous_frame_id;
philipelfcc60062017-01-18 05:35:20 -0800443 }
philipele0b2f152016-09-28 10:23:49 +0200444 }
445
philipel146a48b2017-04-20 04:04:38 -0700446 // Test if inserting this frame would cause the order of the frames to become
447 // ambiguous (covering more than half the interval of 2^16). This can happen
philipel9aa9b8d2021-02-15 13:31:29 +0100448 // when the frame id make large jumps mid stream.
449 if (!frames_.empty() && frame->Id() < frames_.begin()->first &&
450 frames_.rbegin()->first < frame->Id()) {
451 RTC_LOG(LS_WARNING) << "A jump in frame id was detected, clearing buffer.";
philipel146a48b2017-04-20 04:04:38 -0700452 ClearFramesAndHistory();
philipel9aa9b8d2021-02-15 13:31:29 +0100453 last_continuous_frame_id = -1;
philipel146a48b2017-04-20 04:04:38 -0700454 }
455
philipel9aa9b8d2021-02-15 13:31:29 +0100456 auto info = frames_.emplace(frame->Id(), FrameInfo()).first;
philipele0b2f152016-09-28 10:23:49 +0200457
philipel93e451b2016-10-06 12:25:13 +0200458 if (info->second.frame) {
philipel9aa9b8d2021-02-15 13:31:29 +0100459 return last_continuous_frame_id;
philipele0b2f152016-09-28 10:23:49 +0200460 }
461
philipel93e451b2016-10-06 12:25:13 +0200462 if (!UpdateFrameInfoWithIncomingFrame(*frame, info))
philipel9aa9b8d2021-02-15 13:31:29 +0100463 return last_continuous_frame_id;
Ruslan Burakov493a6502019-02-27 15:32:48 +0100464
465 if (!frame->delayed_by_retransmission())
466 timing_->IncomingTimestamp(frame->Timestamp(), frame->ReceivedTime());
philipel0a9f6de2018-02-28 11:29:47 +0100467
philipel0cb73262020-12-08 17:36:53 +0100468 // It can happen that a frame will be reported as fully received even if a
469 // lower spatial layer frame is missing.
470 if (stats_callback_ && frame->is_last_spatial_layer) {
Johannes Kronb88b44e2019-08-22 13:16:44 +0200471 stats_callback_->OnCompleteFrame(frame->is_keyframe(), frame->size(),
472 frame->contentType());
473 }
474
philipele0b2f152016-09-28 10:23:49 +0200475 info->second.frame = std::move(frame);
philipele0b2f152016-09-28 10:23:49 +0200476
477 if (info->second.num_missing_continuous == 0) {
478 info->second.continuous = true;
479 PropagateContinuity(info);
philipel9aa9b8d2021-02-15 13:31:29 +0100480 last_continuous_frame_id = *last_continuous_frame_;
philipele0b2f152016-09-28 10:23:49 +0200481
482 // Since we now have new continuous frames there might be a better frame
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200483 // to return from NextFrame.
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200484 if (callback_queue_) {
485 callback_queue_->PostTask([this] {
Markus Handell6deec382020-07-07 12:17:12 +0200486 MutexLock lock(&mutex_);
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200487 if (!callback_task_.Running())
488 return;
489 RTC_CHECK(frame_handler_);
490 callback_task_.Stop();
491 StartWaitForNextFrameOnQueue();
492 });
493 }
philipele0b2f152016-09-28 10:23:49 +0200494 }
495
philipel9aa9b8d2021-02-15 13:31:29 +0100496 return last_continuous_frame_id;
philipelbe7a9e52016-05-19 12:19:35 +0200497}
498
philipele0b2f152016-09-28 10:23:49 +0200499void FrameBuffer::PropagateContinuity(FrameMap::iterator start) {
tommidb23ea62017-03-03 07:21:18 -0800500 TRACE_EVENT0("webrtc", "FrameBuffer::PropagateContinuity");
philipele0b2f152016-09-28 10:23:49 +0200501 RTC_DCHECK(start->second.continuous);
philipele0b2f152016-09-28 10:23:49 +0200502
503 std::queue<FrameMap::iterator> continuous_frames;
504 continuous_frames.push(start);
505
506 // A simple BFS to traverse continuous frames.
507 while (!continuous_frames.empty()) {
508 auto frame = continuous_frames.front();
509 continuous_frames.pop();
510
Ilya Nikolaevskiy6551faf2019-01-10 15:16:47 +0100511 if (!last_continuous_frame_ || *last_continuous_frame_ < frame->first) {
512 last_continuous_frame_ = frame->first;
513 }
philipele0b2f152016-09-28 10:23:49 +0200514
515 // Loop through all dependent frames, and if that frame no longer has
516 // any unfulfilled dependencies then that frame is continuous as well.
Elad Alon69321dd2019-01-10 15:02:54 +0100517 for (size_t d = 0; d < frame->second.dependent_frames.size(); ++d) {
philipele0b2f152016-09-28 10:23:49 +0200518 auto frame_ref = frames_.find(frame->second.dependent_frames[d]);
philipel112adf92017-06-15 09:06:21 -0700519 RTC_DCHECK(frame_ref != frames_.end());
philipele0b2f152016-09-28 10:23:49 +0200520
philipel112adf92017-06-15 09:06:21 -0700521 // TODO(philipel): Look into why we've seen this happen.
522 if (frame_ref != frames_.end()) {
523 --frame_ref->second.num_missing_continuous;
524 if (frame_ref->second.num_missing_continuous == 0) {
525 frame_ref->second.continuous = true;
526 continuous_frames.push(frame_ref);
527 }
philipele0b2f152016-09-28 10:23:49 +0200528 }
529 }
530 }
531}
532
533void FrameBuffer::PropagateDecodability(const FrameInfo& info) {
tommidb23ea62017-03-03 07:21:18 -0800534 TRACE_EVENT0("webrtc", "FrameBuffer::PropagateDecodability");
Elad Alon69321dd2019-01-10 15:02:54 +0100535 for (size_t d = 0; d < info.dependent_frames.size(); ++d) {
philipele0b2f152016-09-28 10:23:49 +0200536 auto ref_info = frames_.find(info.dependent_frames[d]);
philipel93e451b2016-10-06 12:25:13 +0200537 RTC_DCHECK(ref_info != frames_.end());
tommie95b78b2017-05-14 07:23:11 -0700538 // TODO(philipel): Look into why we've seen this happen.
539 if (ref_info != frames_.end()) {
540 RTC_DCHECK_GT(ref_info->second.num_missing_decodable, 0U);
541 --ref_info->second.num_missing_decodable;
542 }
philipele0b2f152016-09-28 10:23:49 +0200543 }
544}
545
philipele7c891f2018-02-22 14:35:06 +0100546bool FrameBuffer::UpdateFrameInfoWithIncomingFrame(const EncodedFrame& frame,
philipele0b2f152016-09-28 10:23:49 +0200547 FrameMap::iterator info) {
tommidb23ea62017-03-03 07:21:18 -0800548 TRACE_EVENT0("webrtc", "FrameBuffer::UpdateFrameInfoWithIncomingFrame");
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +0100549 auto last_decoded_frame = decoded_frames_history_.GetLastDecodedFrameId();
550 RTC_DCHECK(!last_decoded_frame || *last_decoded_frame < info->first);
philipele0b2f152016-09-28 10:23:49 +0200551
philipel798b2822018-06-11 13:10:14 +0200552 // In this function we determine how many missing dependencies this |frame|
553 // has to become continuous/decodable. If a frame that this |frame| depend
554 // on has already been decoded then we can ignore that dependency since it has
555 // already been fulfilled.
556 //
557 // For all other frames we will register a backwards reference to this |frame|
558 // so that |num_missing_continuous| and |num_missing_decodable| can be
559 // decremented as frames become continuous/are decoded.
560 struct Dependency {
philipel9aa9b8d2021-02-15 13:31:29 +0100561 int64_t frame_id;
philipel798b2822018-06-11 13:10:14 +0200562 bool continuous;
563 };
564 std::vector<Dependency> not_yet_fulfilled_dependencies;
565
566 // Find all dependencies that have not yet been fulfilled.
philipele0b2f152016-09-28 10:23:49 +0200567 for (size_t i = 0; i < frame.num_references; ++i) {
philipel798b2822018-06-11 13:10:14 +0200568 // Does |frame| depend on a frame earlier than the last decoded one?
philipel9aa9b8d2021-02-15 13:31:29 +0100569 if (last_decoded_frame && frame.references[i] <= *last_decoded_frame) {
philipel798b2822018-06-11 13:10:14 +0200570 // Was that frame decoded? If not, this |frame| will never become
571 // decodable.
philipel9aa9b8d2021-02-15 13:31:29 +0100572 if (!decoded_frames_history_.WasDecoded(frame.references[i])) {
philipel65e1f942017-07-24 08:26:53 -0700573 int64_t now_ms = clock_->TimeInMilliseconds();
574 if (last_log_non_decoded_ms_ + kLogNonDecodedIntervalMs < now_ms) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100575 RTC_LOG(LS_WARNING)
philipel9aa9b8d2021-02-15 13:31:29 +0100576 << "Frame " << frame.Id()
philipelf1091932021-02-11 15:25:08 +0100577 << " depends on a non-decoded frame more previous than the last "
578 "decoded frame, dropping frame.";
philipel65e1f942017-07-24 08:26:53 -0700579 last_log_non_decoded_ms_ = now_ms;
580 }
philipele0b2f152016-09-28 10:23:49 +0200581 return false;
582 }
philipele0b2f152016-09-28 10:23:49 +0200583 } else {
philipel9aa9b8d2021-02-15 13:31:29 +0100584 auto ref_info = frames_.find(frame.references[i]);
philipel798b2822018-06-11 13:10:14 +0200585 bool ref_continuous =
586 ref_info != frames_.end() && ref_info->second.continuous;
philipel9aa9b8d2021-02-15 13:31:29 +0100587 not_yet_fulfilled_dependencies.push_back(
588 {frame.references[i], ref_continuous});
philipele0b2f152016-09-28 10:23:49 +0200589 }
philipelbe7a9e52016-05-19 12:19:35 +0200590 }
591
philipel798b2822018-06-11 13:10:14 +0200592 info->second.num_missing_continuous = not_yet_fulfilled_dependencies.size();
593 info->second.num_missing_decodable = not_yet_fulfilled_dependencies.size();
594
595 for (const Dependency& dep : not_yet_fulfilled_dependencies) {
596 if (dep.continuous)
597 --info->second.num_missing_continuous;
598
philipel9aa9b8d2021-02-15 13:31:29 +0100599 frames_[dep.frame_id].dependent_frames.push_back(frame.Id());
philipel798b2822018-06-11 13:10:14 +0200600 }
philipel93e451b2016-10-06 12:25:13 +0200601
philipelbe7a9e52016-05-19 12:19:35 +0200602 return true;
603}
604
philipelbe742702016-11-30 01:31:40 -0800605void FrameBuffer::UpdateJitterDelay() {
tommidb23ea62017-03-03 07:21:18 -0800606 TRACE_EVENT0("webrtc", "FrameBuffer::UpdateJitterDelay");
philipela45102f2017-02-22 05:30:39 -0800607 if (!stats_callback_)
608 return;
philipelbe742702016-11-30 01:31:40 -0800609
philipela45102f2017-02-22 05:30:39 -0800610 int max_decode_ms;
611 int current_delay_ms;
612 int target_delay_ms;
613 int jitter_buffer_ms;
614 int min_playout_delay_ms;
615 int render_delay_ms;
Johannes Kronbfd343b2019-07-01 10:07:50 +0200616 if (timing_->GetTimings(&max_decode_ms, &current_delay_ms, &target_delay_ms,
617 &jitter_buffer_ms, &min_playout_delay_ms,
618 &render_delay_ms)) {
philipela45102f2017-02-22 05:30:39 -0800619 stats_callback_->OnFrameBufferTimingsUpdated(
Johannes Kronbfd343b2019-07-01 10:07:50 +0200620 max_decode_ms, current_delay_ms, target_delay_ms, jitter_buffer_ms,
621 min_playout_delay_ms, render_delay_ms);
philipelbe742702016-11-30 01:31:40 -0800622 }
philipel266f0a42016-11-28 08:49:07 -0800623}
624
ilnik2edc6842017-07-06 03:06:50 -0700625void FrameBuffer::UpdateTimingFrameInfo() {
626 TRACE_EVENT0("webrtc", "FrameBuffer::UpdateTimingFrameInfo");
Danil Chapovalov0040b662018-06-18 10:48:16 +0200627 absl::optional<TimingFrameInfo> info = timing_->GetTimingFrameInfo();
philipel97187112018-03-23 10:43:21 +0100628 if (info && stats_callback_)
ilnik2edc6842017-07-06 03:06:50 -0700629 stats_callback_->OnTimingFrameInfoUpdated(*info);
630}
631
philipelfcc60062017-01-18 05:35:20 -0800632void FrameBuffer::ClearFramesAndHistory() {
ilnik2edc6842017-07-06 03:06:50 -0700633 TRACE_EVENT0("webrtc", "FrameBuffer::ClearFramesAndHistory");
Johannes Kron0c141c52019-08-26 15:04:43 +0200634 if (stats_callback_) {
philipel9aa9b8d2021-02-15 13:31:29 +0100635 unsigned int dropped_frames =
636 std::count_if(frames_.begin(), frames_.end(),
637 [](const std::pair<const int64_t, FrameInfo>& frame) {
638 return frame.second.frame != nullptr;
639 });
Johannes Kron0c141c52019-08-26 15:04:43 +0200640 if (dropped_frames > 0) {
641 stats_callback_->OnDroppedFrames(dropped_frames);
642 }
643 }
philipelfcc60062017-01-18 05:35:20 -0800644 frames_.clear();
Ilya Nikolaevskiy6551faf2019-01-10 15:16:47 +0100645 last_continuous_frame_.reset();
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100646 frames_to_decode_.clear();
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +0100647 decoded_frames_history_.Clear();
philipelfcc60062017-01-18 05:35:20 -0800648}
649
Niels Möllerff2e2152019-09-27 10:29:30 +0200650// TODO(philipel): Avoid the concatenation of frames here, by replacing
651// NextFrame and GetNextFrame with methods returning multiple frames.
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100652EncodedFrame* FrameBuffer::CombineAndDeleteFrames(
653 const std::vector<EncodedFrame*>& frames) const {
654 RTC_DCHECK(!frames.empty());
Sergey Silkin61832dd2018-12-20 14:32:14 +0100655 EncodedFrame* first_frame = frames[0];
656 EncodedFrame* last_frame = frames.back();
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100657 size_t total_length = 0;
658 for (size_t i = 0; i < frames.size(); ++i) {
659 total_length += frames[i]->size();
660 }
Niels Möllerff2e2152019-09-27 10:29:30 +0200661 auto encoded_image_buffer = EncodedImageBuffer::Create(total_length);
662 uint8_t* buffer = encoded_image_buffer->data();
philipel0cb73262020-12-08 17:36:53 +0100663 first_frame->SetSpatialLayerFrameSize(first_frame->SpatialIndex().value_or(0),
Sergey Silkin2799e632019-05-17 09:51:39 +0200664 first_frame->size());
Niels Möllerff2e2152019-09-27 10:29:30 +0200665 memcpy(buffer, first_frame->data(), first_frame->size());
666 buffer += first_frame->size();
Sergey Silkin2799e632019-05-17 09:51:39 +0200667
Sergey Silkin61832dd2018-12-20 14:32:14 +0100668 // Spatial index of combined frame is set equal to spatial index of its top
669 // spatial layer.
philipel0cb73262020-12-08 17:36:53 +0100670 first_frame->SetSpatialIndex(last_frame->SpatialIndex().value_or(0));
Sergey Silkin61832dd2018-12-20 14:32:14 +0100671
672 first_frame->video_timing_mutable()->network2_timestamp_ms =
673 last_frame->video_timing().network2_timestamp_ms;
674 first_frame->video_timing_mutable()->receive_finish_ms =
675 last_frame->video_timing().receive_finish_ms;
676
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100677 // Append all remaining frames to the first one.
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100678 for (size_t i = 1; i < frames.size(); ++i) {
Sergey Silkin61832dd2018-12-20 14:32:14 +0100679 EncodedFrame* next_frame = frames[i];
philipel0cb73262020-12-08 17:36:53 +0100680 first_frame->SetSpatialLayerFrameSize(
681 next_frame->SpatialIndex().value_or(0), next_frame->size());
Niels Möller9c843902019-01-11 10:21:35 +0100682 memcpy(buffer, next_frame->data(), next_frame->size());
Sergey Silkin61832dd2018-12-20 14:32:14 +0100683 buffer += next_frame->size();
684 delete next_frame;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100685 }
Niels Möllerff2e2152019-09-27 10:29:30 +0200686 first_frame->SetEncodedData(encoded_image_buffer);
Sergey Silkin61832dd2018-12-20 14:32:14 +0100687 return first_frame;
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100688}
689
Niels Möllerbe682d42018-03-27 08:31:45 +0200690FrameBuffer::FrameInfo::FrameInfo() = default;
691FrameBuffer::FrameInfo::FrameInfo(FrameInfo&&) = default;
692FrameBuffer::FrameInfo::~FrameInfo() = default;
693
philipelbe7a9e52016-05-19 12:19:35 +0200694} // namespace video_coding
695} // namespace webrtc