blob: d7944dbfa73e8e48c6d1e55e06aa4a7503e65d6d [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>
Evan Shrubsole0072c212021-11-10 11:41:14 +010016#include <memory>
philipele0b2f152016-09-28 10:23:49 +020017#include <queue>
Yves Gerey3e707812018-11-28 16:47:49 +010018#include <utility>
philipel798b2822018-06-11 13:10:14 +020019#include <vector>
philipelbe7a9e52016-05-19 12:19:35 +020020
Evan Shrubsolef83d4262021-12-15 15:05:15 +010021#include "absl/container/inlined_vector.h"
Evan Shrubsole13e42a82022-03-07 13:21:51 +010022#include "api/units/data_size.h"
23#include "api/units/time_delta.h"
Yves Gerey3e707812018-11-28 16:47:49 +010024#include "api/video/encoded_image.h"
25#include "api/video/video_timing.h"
Evan Shrubsolef83d4262021-12-15 15:05:15 +010026#include "modules/video_coding/frame_helpers.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "modules/video_coding/include/video_coding_defines.h"
28#include "modules/video_coding/jitter_estimator.h"
29#include "modules/video_coding/timing.h"
30#include "rtc_base/checks.h"
Yves Gerey3e707812018-11-28 16:47:49 +010031#include "rtc_base/experiments/rtt_mult_experiment.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/logging.h"
Yves Gerey3e707812018-11-28 16:47:49 +010033#include "rtc_base/numerics/sequence_number_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/trace_event.h"
35#include "system_wrappers/include/clock.h"
philipel707f2782017-10-02 14:10:28 +020036#include "system_wrappers/include/field_trial.h"
philipelbe7a9e52016-05-19 12:19:35 +020037
38namespace webrtc {
39namespace video_coding {
40
41namespace {
philipele0b2f152016-09-28 10:23:49 +020042// Max number of frames the buffer will hold.
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +010043constexpr size_t kMaxFramesBuffered = 800;
philipelbe7a9e52016-05-19 12:19:35 +020044
Johannes Kron23bfff32021-09-28 21:31:46 +020045// Default value for the maximum decode queue size that is used when the
46// low-latency renderer is used.
47constexpr size_t kZeroPlayoutDelayDefaultMaxDecodeQueueSize = 8;
48
philipele0b2f152016-09-28 10:23:49 +020049// Max number of decoded frame info that will be saved.
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +010050constexpr int kMaxFramesHistory = 1 << 13;
philipel65e1f942017-07-24 08:26:53 -070051
Ilya Nikolaevskiy8c4fe162018-02-27 15:49:47 +010052// The time it's allowed for a frame to be late to its rendering prediction and
53// still be rendered.
Ilya Nikolaevskiy7eef0072018-02-28 09:59:26 +010054constexpr int kMaxAllowedFrameDelayMs = 5;
Ilya Nikolaevskiy8c4fe162018-02-27 15:49:47 +010055
philipel65e1f942017-07-24 08:26:53 -070056constexpr int64_t kLogNonDecodedIntervalMs = 5000;
philipelbe7a9e52016-05-19 12:19:35 +020057} // namespace
58
philipelbe7a9e52016-05-19 12:19:35 +020059FrameBuffer::FrameBuffer(Clock* clock,
philipela45102f2017-02-22 05:30:39 -080060 VCMTiming* timing,
61 VCMReceiveStatisticsCallback* stats_callback)
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +010062 : decoded_frames_history_(kMaxFramesHistory),
63 clock_(clock),
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +020064 callback_queue_(nullptr),
Niels Möllerd9c2d942019-04-30 09:16:36 +020065 jitter_estimator_(clock),
philipelbe7a9e52016-05-19 12:19:35 +020066 timing_(timing),
philipel4f6cd6a2016-08-03 10:59:32 +020067 inter_frame_delay_(clock_->TimeInMilliseconds()),
philipel29f730e2017-03-15 08:10:08 -070068 stopped_(false),
philipela45102f2017-02-22 05:30:39 -080069 protection_mode_(kProtectionNack),
philipel65e1f942017-07-24 08:26:53 -070070 stats_callback_(stats_callback),
Elad Alone4b50232019-01-14 18:56:14 +010071 last_log_non_decoded_ms_(-kLogNonDecodedIntervalMs),
Johannes Kron2ddc39e2021-08-10 16:56:12 +020072 rtt_mult_settings_(RttMultExperiment::GetRttMultValue()),
Johannes Kron23bfff32021-09-28 21:31:46 +020073 zero_playout_delay_max_decode_queue_size_(
74 "max_decode_queue_size",
75 kZeroPlayoutDelayDefaultMaxDecodeQueueSize) {
Johannes Kron2ddc39e2021-08-10 16:56:12 +020076 ParseFieldTrial({&zero_playout_delay_max_decode_queue_size_},
77 field_trial::FindFullName("WebRTC-ZeroPlayoutDelay"));
Tommi430951a2020-05-19 23:27:29 +020078 callback_checker_.Detach();
79}
philipel266f0a42016-11-28 08:49:07 -080080
Tommi430951a2020-05-19 23:27:29 +020081FrameBuffer::~FrameBuffer() {
82 RTC_DCHECK_RUN_ON(&construction_checker_);
83}
philipelbe7a9e52016-05-19 12:19:35 +020084
Evan Shrubsole3d29efd2021-12-07 14:11:45 +010085void FrameBuffer::NextFrame(int64_t max_wait_time_ms,
86 bool keyframe_required,
87 rtc::TaskQueue* callback_queue,
88 NextFrameCallback handler) {
Tommi430951a2020-05-19 23:27:29 +020089 RTC_DCHECK_RUN_ON(&callback_checker_);
90 RTC_DCHECK(callback_queue->IsCurrent());
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +020091 TRACE_EVENT0("webrtc", "FrameBuffer::NextFrame");
92 int64_t latest_return_time_ms =
93 clock_->TimeInMilliseconds() + max_wait_time_ms;
Tommi430951a2020-05-19 23:27:29 +020094
Markus Handell6deec382020-07-07 12:17:12 +020095 MutexLock lock(&mutex_);
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +020096 if (stopped_) {
97 return;
98 }
99 latest_return_time_ms_ = latest_return_time_ms;
100 keyframe_required_ = keyframe_required;
101 frame_handler_ = handler;
102 callback_queue_ = callback_queue;
103 StartWaitForNextFrameOnQueue();
104}
105
106void FrameBuffer::StartWaitForNextFrameOnQueue() {
107 RTC_DCHECK(callback_queue_);
108 RTC_DCHECK(!callback_task_.Running());
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100109 int64_t wait_ms = FindNextFrame(clock_->CurrentTime());
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200110 callback_task_ = RepeatingTaskHandle::DelayedStart(
Henrik Boström4c72f992022-01-25 08:15:50 +0100111 callback_queue_->Get(), TimeDelta::Millis(wait_ms),
112 [this] {
Tommi430951a2020-05-19 23:27:29 +0200113 RTC_DCHECK_RUN_ON(&callback_checker_);
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200114 // If this task has not been cancelled, we did not get any new frames
115 // while waiting. Continue with frame delivery.
Markus Handell334b1fd2020-12-14 00:08:11 +0100116 std::unique_ptr<EncodedFrame> frame;
Evan Shrubsole3d29efd2021-12-07 14:11:45 +0100117 NextFrameCallback frame_handler;
Markus Handell334b1fd2020-12-14 00:08:11 +0100118 {
119 MutexLock lock(&mutex_);
120 if (!frames_to_decode_.empty()) {
121 // We have frames, deliver!
Evan Shrubsole0072c212021-11-10 11:41:14 +0100122 frame = GetNextFrame();
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100123 timing_->SetLastDecodeScheduledTimestamp(clock_->CurrentTime());
Markus Handell334b1fd2020-12-14 00:08:11 +0100124 } else if (clock_->TimeInMilliseconds() < latest_return_time_ms_) {
125 // If there's no frames to decode and there is still time left, it
126 // means that the frame buffer was cleared between creation and
127 // execution of this task. Continue waiting for the remaining time.
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100128 int64_t wait_ms = FindNextFrame(clock_->CurrentTime());
Markus Handell334b1fd2020-12-14 00:08:11 +0100129 return TimeDelta::Millis(wait_ms);
130 }
131 frame_handler = std::move(frame_handler_);
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200132 CancelCallback();
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200133 }
Markus Handell334b1fd2020-12-14 00:08:11 +0100134 // Deliver frame, if any. Otherwise signal timeout.
Evan Shrubsole3d29efd2021-12-07 14:11:45 +0100135 frame_handler(std::move(frame));
Markus Handell334b1fd2020-12-14 00:08:11 +0100136 return TimeDelta::Zero(); // Ignored.
Henrik Boström4c72f992022-01-25 08:15:50 +0100137 },
138 TaskQueueBase::DelayPrecision::kHigh);
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200139}
140
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100141int64_t FrameBuffer::FindNextFrame(Timestamp now) {
142 int64_t wait_ms = latest_return_time_ms_ - now.ms();
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200143 frames_to_decode_.clear();
144
Artem Titovdcd7fc72021-08-09 13:02:57 +0200145 // `last_continuous_frame_` may be empty below, but nullopt is smaller
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200146 // than everything else and loop will immediately terminate as expected.
147 for (auto frame_it = frames_.begin();
148 frame_it != frames_.end() && frame_it->first <= last_continuous_frame_;
149 ++frame_it) {
150 if (!frame_it->second.continuous ||
151 frame_it->second.num_missing_decodable > 0) {
152 continue;
153 }
154
155 EncodedFrame* frame = frame_it->second.frame.get();
156
157 if (keyframe_required_ && !frame->is_keyframe())
158 continue;
159
160 auto last_decoded_frame_timestamp =
161 decoded_frames_history_.GetLastDecodedFrameTimestamp();
162
163 // TODO(https://bugs.webrtc.org/9974): consider removing this check
164 // as it may make a stream undecodable after a very long delay between
165 // frames.
166 if (last_decoded_frame_timestamp &&
167 AheadOf(*last_decoded_frame_timestamp, frame->Timestamp())) {
168 continue;
169 }
170
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200171 // Gather all remaining frames for the same superframe.
172 std::vector<FrameMap::iterator> current_superframe;
173 current_superframe.push_back(frame_it);
174 bool last_layer_completed = frame_it->second.frame->is_last_spatial_layer;
175 FrameMap::iterator next_frame_it = frame_it;
philipela65d7852020-11-20 17:49:24 +0100176 while (!last_layer_completed) {
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200177 ++next_frame_it;
philipela65d7852020-11-20 17:49:24 +0100178
179 if (next_frame_it == frames_.end() || !next_frame_it->second.frame) {
180 break;
181 }
182
183 if (next_frame_it->second.frame->Timestamp() != frame->Timestamp() ||
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200184 !next_frame_it->second.continuous) {
185 break;
186 }
philipela65d7852020-11-20 17:49:24 +0100187
188 if (next_frame_it->second.num_missing_decodable > 0) {
philipelcb327d92020-12-10 10:49:20 +0100189 bool has_inter_layer_dependency = false;
190 for (size_t i = 0; i < EncodedFrame::kMaxFrameReferences &&
philipela65d7852020-11-20 17:49:24 +0100191 i < next_frame_it->second.frame->num_references;
192 ++i) {
philipel9aa9b8d2021-02-15 13:31:29 +0100193 if (next_frame_it->second.frame->references[i] >= frame_it->first) {
philipela65d7852020-11-20 17:49:24 +0100194 has_inter_layer_dependency = true;
philipelcb327d92020-12-10 10:49:20 +0100195 break;
philipela65d7852020-11-20 17:49:24 +0100196 }
197 }
198
199 // If the frame has an undecoded dependency that is not within the same
philipelcb327d92020-12-10 10:49:20 +0100200 // temporal unit then this frame is not yet ready to be decoded. If it
philipela65d7852020-11-20 17:49:24 +0100201 // is within the same temporal unit then the not yet decoded dependency
202 // is just a lower spatial frame, which is ok.
203 if (!has_inter_layer_dependency ||
204 next_frame_it->second.num_missing_decodable > 1) {
205 break;
206 }
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200207 }
philipela65d7852020-11-20 17:49:24 +0100208
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200209 current_superframe.push_back(next_frame_it);
210 last_layer_completed = next_frame_it->second.frame->is_last_spatial_layer;
211 }
212 // Check if the current superframe is complete.
213 // TODO(bugs.webrtc.org/10064): consider returning all available to
214 // decode frames even if the superframe is not complete yet.
215 if (!last_layer_completed) {
216 continue;
217 }
218
219 frames_to_decode_ = std::move(current_superframe);
220
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100221 absl::optional<Timestamp> render_time = frame->RenderTimestamp();
222 if (!render_time) {
223 render_time = timing_->RenderTime(frame->Timestamp(), now);
224 frame->SetRenderTime(render_time->ms());
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200225 }
Johannes Kron2ddc39e2021-08-10 16:56:12 +0200226 bool too_many_frames_queued =
227 frames_.size() > zero_playout_delay_max_decode_queue_size_ ? true
228 : false;
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100229 wait_ms =
230 timing_->MaxWaitingTime(*render_time, now, too_many_frames_queued).ms();
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200231
232 // This will cause the frame buffer to prefer high framerate rather
233 // than high resolution in the case of the decoder not decoding fast
234 // enough and the stream has multiple spatial and temporal layers.
235 // For multiple temporal layers it may cause non-base layer frames to be
236 // skipped if they are late.
237 if (wait_ms < -kMaxAllowedFrameDelayMs)
238 continue;
239
240 break;
241 }
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100242 wait_ms = std::min<int64_t>(wait_ms, latest_return_time_ms_ - now.ms());
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200243 wait_ms = std::max<int64_t>(wait_ms, 0);
244 return wait_ms;
245}
246
Evan Shrubsole0072c212021-11-10 11:41:14 +0100247std::unique_ptr<EncodedFrame> FrameBuffer::GetNextFrame() {
Tommi430951a2020-05-19 23:27:29 +0200248 RTC_DCHECK_RUN_ON(&callback_checker_);
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100249 Timestamp now = clock_->CurrentTime();
Artem Titovdcd7fc72021-08-09 13:02:57 +0200250 // TODO(ilnik): remove `frames_out` use frames_to_decode_ directly.
Evan Shrubsole0072c212021-11-10 11:41:14 +0100251 std::vector<std::unique_ptr<EncodedFrame>> frames_out;
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200252
253 RTC_DCHECK(!frames_to_decode_.empty());
254 bool superframe_delayed_by_retransmission = false;
Evan Shrubsole13e42a82022-03-07 13:21:51 +0100255 DataSize superframe_size = DataSize::Zero();
Evan Shrubsole5b9b9aa2021-11-01 10:28:31 +0100256 const EncodedFrame& first_frame = *frames_to_decode_[0]->second.frame;
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100257 absl::optional<Timestamp> render_time = first_frame.RenderTimestamp();
Evan Shrubsole5b9b9aa2021-11-01 10:28:31 +0100258 int64_t receive_time_ms = first_frame.ReceivedTime();
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200259 // Gracefully handle bad RTP timestamps and render time issues.
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100260 if (!render_time ||
261 FrameHasBadRenderTiming(*render_time, now, timing_->TargetVideoDelay())) {
Niels Möllerd9c2d942019-04-30 09:16:36 +0200262 jitter_estimator_.Reset();
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200263 timing_->Reset();
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100264 render_time = timing_->RenderTime(first_frame.Timestamp(), now);
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200265 }
266
267 for (FrameMap::iterator& frame_it : frames_to_decode_) {
268 RTC_DCHECK(frame_it != frames_.end());
Evan Shrubsole0072c212021-11-10 11:41:14 +0100269 std::unique_ptr<EncodedFrame> frame = std::move(frame_it->second.frame);
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200270
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100271 frame->SetRenderTime(render_time->ms());
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200272
273 superframe_delayed_by_retransmission |= frame->delayed_by_retransmission();
274 receive_time_ms = std::max(receive_time_ms, frame->ReceivedTime());
Evan Shrubsole13e42a82022-03-07 13:21:51 +0100275 superframe_size += DataSize::Bytes(frame->size());
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200276
277 PropagateDecodability(frame_it->second);
278 decoded_frames_history_.InsertDecoded(frame_it->first, frame->Timestamp());
279
280 // Remove decoded frame and all undecoded frames before it.
Johannes Kron0c141c52019-08-26 15:04:43 +0200281 if (stats_callback_) {
philipel9aa9b8d2021-02-15 13:31:29 +0100282 unsigned int dropped_frames =
283 std::count_if(frames_.begin(), frame_it,
284 [](const std::pair<const int64_t, FrameInfo>& frame) {
285 return frame.second.frame != nullptr;
286 });
Johannes Kron0c141c52019-08-26 15:04:43 +0200287 if (dropped_frames > 0) {
288 stats_callback_->OnDroppedFrames(dropped_frames);
289 }
290 }
291
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200292 frames_.erase(frames_.begin(), ++frame_it);
293
Evan Shrubsole0072c212021-11-10 11:41:14 +0100294 frames_out.emplace_back(std::move(frame));
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200295 }
296
297 if (!superframe_delayed_by_retransmission) {
298 int64_t frame_delay;
299
Evan Shrubsole5b9b9aa2021-11-01 10:28:31 +0100300 if (inter_frame_delay_.CalculateDelay(first_frame.Timestamp(), &frame_delay,
301 receive_time_ms)) {
Evan Shrubsole13e42a82022-03-07 13:21:51 +0100302 jitter_estimator_.UpdateEstimate(TimeDelta::Millis(frame_delay),
303 superframe_size);
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200304 }
305
306 float rtt_mult = protection_mode_ == kProtectionNackFEC ? 0.0 : 1.0;
Evan Shrubsole13e42a82022-03-07 13:21:51 +0100307 absl::optional<TimeDelta> rtt_mult_add_cap_ms = absl::nullopt;
“Michaeld3a4ebe2019-06-07 03:55:01 -0500308 if (rtt_mult_settings_.has_value()) {
309 rtt_mult = rtt_mult_settings_->rtt_mult_setting;
Evan Shrubsole13e42a82022-03-07 13:21:51 +0100310 rtt_mult_add_cap_ms =
311 TimeDelta::Millis(rtt_mult_settings_->rtt_mult_add_cap_ms);
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200312 }
Evan Shrubsole13e42a82022-03-07 13:21:51 +0100313 timing_->SetJitterDelay(
314 jitter_estimator_.GetJitterEstimate(rtt_mult, rtt_mult_add_cap_ms));
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100315 timing_->UpdateCurrentDelay(*render_time, now);
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200316 } else {
Evan Shrubsole9146d762021-10-13 11:19:48 +0200317 if (RttMultExperiment::RttMultEnabled())
Niels Möllerd9c2d942019-04-30 09:16:36 +0200318 jitter_estimator_.FrameNacked();
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200319 }
320
321 UpdateJitterDelay();
322 UpdateTimingFrameInfo();
323
324 if (frames_out.size() == 1) {
Evan Shrubsole0072c212021-11-10 11:41:14 +0100325 return std::move(frames_out[0]);
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200326 } else {
Evan Shrubsole0072c212021-11-10 11:41:14 +0100327 return CombineAndDeleteFrames(std::move(frames_out));
Sebastian Jansson1c747f52019-04-04 13:01:39 +0200328 }
329}
330
philipel4f6cd6a2016-08-03 10:59:32 +0200331void FrameBuffer::SetProtectionMode(VCMVideoProtection mode) {
tommidb23ea62017-03-03 07:21:18 -0800332 TRACE_EVENT0("webrtc", "FrameBuffer::SetProtectionMode");
Markus Handell6deec382020-07-07 12:17:12 +0200333 MutexLock lock(&mutex_);
Henrik Boströmc680c4a2019-04-03 10:27:36 +0000334 protection_mode_ = mode;
philipel4f6cd6a2016-08-03 10:59:32 +0200335}
336
philipel504c47d2016-06-30 17:33:02 +0200337void FrameBuffer::Stop() {
tommidb23ea62017-03-03 07:21:18 -0800338 TRACE_EVENT0("webrtc", "FrameBuffer::Stop");
Markus Handell6deec382020-07-07 12:17:12 +0200339 MutexLock lock(&mutex_);
Tommi430951a2020-05-19 23:27:29 +0200340 if (stopped_)
341 return;
Henrik Boströmc680c4a2019-04-03 10:27:36 +0000342 stopped_ = true;
Tommi430951a2020-05-19 23:27:29 +0200343
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200344 CancelCallback();
philipel504c47d2016-06-30 17:33:02 +0200345}
346
Ilya Nikolaevskiye6a2d942018-11-07 14:32:28 +0100347void FrameBuffer::Clear() {
Markus Handell6deec382020-07-07 12:17:12 +0200348 MutexLock lock(&mutex_);
Henrik Boströmc680c4a2019-04-03 10:27:36 +0000349 ClearFramesAndHistory();
Ilya Nikolaevskiye6a2d942018-11-07 14:32:28 +0100350}
351
Johannes Kron111e9812020-10-26 13:54:40 +0100352int FrameBuffer::Size() {
353 MutexLock lock(&mutex_);
354 return frames_.size();
355}
356
philipele21be1d2017-09-25 06:37:12 -0700357void FrameBuffer::UpdateRtt(int64_t rtt_ms) {
Markus Handell6deec382020-07-07 12:17:12 +0200358 MutexLock lock(&mutex_);
Evan Shrubsole13e42a82022-03-07 13:21:51 +0100359 jitter_estimator_.UpdateRtt(TimeDelta::Millis(rtt_ms));
philipele21be1d2017-09-25 06:37:12 -0700360}
361
philipele7c891f2018-02-22 14:35:06 +0100362bool FrameBuffer::ValidReferences(const EncodedFrame& frame) const {
philipel112adf92017-06-15 09:06:21 -0700363 for (size_t i = 0; i < frame.num_references; ++i) {
philipel9aa9b8d2021-02-15 13:31:29 +0100364 if (frame.references[i] >= frame.Id())
philipel112adf92017-06-15 09:06:21 -0700365 return false;
philipel3b3c9c42017-09-11 09:38:36 -0700366
philipel112adf92017-06-15 09:06:21 -0700367 for (size_t j = i + 1; j < frame.num_references; ++j) {
368 if (frame.references[i] == frame.references[j])
369 return false;
370 }
371 }
372
philipel112adf92017-06-15 09:06:21 -0700373 return true;
374}
375
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200376void FrameBuffer::CancelCallback() {
Tommi430951a2020-05-19 23:27:29 +0200377 // Called from the callback queue or from within Stop().
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200378 frame_handler_ = {};
379 callback_task_.Stop();
380 callback_queue_ = nullptr;
Tommi430951a2020-05-19 23:27:29 +0200381 callback_checker_.Detach();
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200382}
383
philipele7c891f2018-02-22 14:35:06 +0100384int64_t FrameBuffer::InsertFrame(std::unique_ptr<EncodedFrame> frame) {
tommidb23ea62017-03-03 07:21:18 -0800385 TRACE_EVENT0("webrtc", "FrameBuffer::InsertFrame");
philipel93e451b2016-10-06 12:25:13 +0200386 RTC_DCHECK(frame);
tommi0a735642017-03-14 06:23:57 -0700387
Markus Handell6deec382020-07-07 12:17:12 +0200388 MutexLock lock(&mutex_);
philipel29f730e2017-03-15 08:10:08 -0700389
philipel9aa9b8d2021-02-15 13:31:29 +0100390 int64_t last_continuous_frame_id = last_continuous_frame_.value_or(-1);
philipele0b2f152016-09-28 10:23:49 +0200391
philipel112adf92017-06-15 09:06:21 -0700392 if (!ValidReferences(*frame)) {
philipel9aa9b8d2021-02-15 13:31:29 +0100393 RTC_LOG(LS_WARNING) << "Frame " << frame->Id()
philipelf1091932021-02-11 15:25:08 +0100394 << " has invalid frame references, dropping frame.";
philipel9aa9b8d2021-02-15 13:31:29 +0100395 return last_continuous_frame_id;
philipel112adf92017-06-15 09:06:21 -0700396 }
397
Ilya Nikolaevskiy6551faf2019-01-10 15:16:47 +0100398 if (frames_.size() >= kMaxFramesBuffered) {
philipel9771c502018-03-02 11:06:27 +0100399 if (frame->is_keyframe()) {
philipel9aa9b8d2021-02-15 13:31:29 +0100400 RTC_LOG(LS_WARNING) << "Inserting keyframe " << frame->Id()
philipelf1091932021-02-11 15:25:08 +0100401 << " but buffer is full, clearing"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100402 " buffer and inserting the frame.";
philipel9771c502018-03-02 11:06:27 +0100403 ClearFramesAndHistory();
404 } else {
philipel9aa9b8d2021-02-15 13:31:29 +0100405 RTC_LOG(LS_WARNING) << "Frame " << frame->Id()
philipelf1091932021-02-11 15:25:08 +0100406 << " could not be inserted due to the frame "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100407 "buffer being full, dropping frame.";
philipel9aa9b8d2021-02-15 13:31:29 +0100408 return last_continuous_frame_id;
philipel9771c502018-03-02 11:06:27 +0100409 }
philipele0b2f152016-09-28 10:23:49 +0200410 }
411
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +0100412 auto last_decoded_frame = decoded_frames_history_.GetLastDecodedFrameId();
413 auto last_decoded_frame_timestamp =
414 decoded_frames_history_.GetLastDecodedFrameTimestamp();
philipel9aa9b8d2021-02-15 13:31:29 +0100415 if (last_decoded_frame && frame->Id() <= *last_decoded_frame) {
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +0100416 if (AheadOf(frame->Timestamp(), *last_decoded_frame_timestamp) &&
philipel3042c2d2017-08-18 04:55:02 -0700417 frame->is_keyframe()) {
philipel9aa9b8d2021-02-15 13:31:29 +0100418 // If this frame has a newer timestamp but an earlier frame id then we
419 // assume there has been a jump in the frame id due to some encoder
philipelfcc60062017-01-18 05:35:20 -0800420 // reconfiguration or some other reason. Even though this is not according
421 // to spec we can still continue to decode from this frame if it is a
422 // keyframe.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100423 RTC_LOG(LS_WARNING)
philipel9aa9b8d2021-02-15 13:31:29 +0100424 << "A jump in frame id was detected, clearing buffer.";
philipelfcc60062017-01-18 05:35:20 -0800425 ClearFramesAndHistory();
philipel9aa9b8d2021-02-15 13:31:29 +0100426 last_continuous_frame_id = -1;
philipelfcc60062017-01-18 05:35:20 -0800427 } else {
philipel9aa9b8d2021-02-15 13:31:29 +0100428 RTC_LOG(LS_WARNING) << "Frame " << frame->Id() << " inserted after frame "
429 << *last_decoded_frame
philipelf1091932021-02-11 15:25:08 +0100430 << " was handed off for decoding, dropping frame.";
philipel9aa9b8d2021-02-15 13:31:29 +0100431 return last_continuous_frame_id;
philipelfcc60062017-01-18 05:35:20 -0800432 }
philipele0b2f152016-09-28 10:23:49 +0200433 }
434
philipel146a48b2017-04-20 04:04:38 -0700435 // Test if inserting this frame would cause the order of the frames to become
436 // ambiguous (covering more than half the interval of 2^16). This can happen
philipel9aa9b8d2021-02-15 13:31:29 +0100437 // when the frame id make large jumps mid stream.
438 if (!frames_.empty() && frame->Id() < frames_.begin()->first &&
439 frames_.rbegin()->first < frame->Id()) {
440 RTC_LOG(LS_WARNING) << "A jump in frame id was detected, clearing buffer.";
philipel146a48b2017-04-20 04:04:38 -0700441 ClearFramesAndHistory();
philipel9aa9b8d2021-02-15 13:31:29 +0100442 last_continuous_frame_id = -1;
philipel146a48b2017-04-20 04:04:38 -0700443 }
444
philipel9aa9b8d2021-02-15 13:31:29 +0100445 auto info = frames_.emplace(frame->Id(), FrameInfo()).first;
philipele0b2f152016-09-28 10:23:49 +0200446
philipel93e451b2016-10-06 12:25:13 +0200447 if (info->second.frame) {
philipel9aa9b8d2021-02-15 13:31:29 +0100448 return last_continuous_frame_id;
philipele0b2f152016-09-28 10:23:49 +0200449 }
450
philipel93e451b2016-10-06 12:25:13 +0200451 if (!UpdateFrameInfoWithIncomingFrame(*frame, info))
philipel9aa9b8d2021-02-15 13:31:29 +0100452 return last_continuous_frame_id;
Ruslan Burakov493a6502019-02-27 15:32:48 +0100453
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100454 // If ReceiveTime is negative then it is not a valid timestamp.
455 if (!frame->delayed_by_retransmission() && frame->ReceivedTime() >= 0)
456 timing_->IncomingTimestamp(frame->Timestamp(),
457 Timestamp::Millis(frame->ReceivedTime()));
philipel0a9f6de2018-02-28 11:29:47 +0100458
philipel0cb73262020-12-08 17:36:53 +0100459 // It can happen that a frame will be reported as fully received even if a
460 // lower spatial layer frame is missing.
461 if (stats_callback_ && frame->is_last_spatial_layer) {
Johannes Kronb88b44e2019-08-22 13:16:44 +0200462 stats_callback_->OnCompleteFrame(frame->is_keyframe(), frame->size(),
463 frame->contentType());
464 }
465
philipele0b2f152016-09-28 10:23:49 +0200466 info->second.frame = std::move(frame);
philipele0b2f152016-09-28 10:23:49 +0200467
468 if (info->second.num_missing_continuous == 0) {
469 info->second.continuous = true;
470 PropagateContinuity(info);
philipel9aa9b8d2021-02-15 13:31:29 +0100471 last_continuous_frame_id = *last_continuous_frame_;
philipele0b2f152016-09-28 10:23:49 +0200472
473 // Since we now have new continuous frames there might be a better frame
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200474 // to return from NextFrame.
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200475 if (callback_queue_) {
476 callback_queue_->PostTask([this] {
Markus Handell6deec382020-07-07 12:17:12 +0200477 MutexLock lock(&mutex_);
Sebastian Jansson11d0d7b2019-04-11 12:39:34 +0200478 if (!callback_task_.Running())
479 return;
480 RTC_CHECK(frame_handler_);
481 callback_task_.Stop();
482 StartWaitForNextFrameOnQueue();
483 });
484 }
philipele0b2f152016-09-28 10:23:49 +0200485 }
486
philipel9aa9b8d2021-02-15 13:31:29 +0100487 return last_continuous_frame_id;
philipelbe7a9e52016-05-19 12:19:35 +0200488}
489
philipele0b2f152016-09-28 10:23:49 +0200490void FrameBuffer::PropagateContinuity(FrameMap::iterator start) {
tommidb23ea62017-03-03 07:21:18 -0800491 TRACE_EVENT0("webrtc", "FrameBuffer::PropagateContinuity");
philipele0b2f152016-09-28 10:23:49 +0200492 RTC_DCHECK(start->second.continuous);
philipele0b2f152016-09-28 10:23:49 +0200493
494 std::queue<FrameMap::iterator> continuous_frames;
495 continuous_frames.push(start);
496
497 // A simple BFS to traverse continuous frames.
498 while (!continuous_frames.empty()) {
499 auto frame = continuous_frames.front();
500 continuous_frames.pop();
501
Ilya Nikolaevskiy6551faf2019-01-10 15:16:47 +0100502 if (!last_continuous_frame_ || *last_continuous_frame_ < frame->first) {
503 last_continuous_frame_ = frame->first;
504 }
philipele0b2f152016-09-28 10:23:49 +0200505
506 // Loop through all dependent frames, and if that frame no longer has
507 // any unfulfilled dependencies then that frame is continuous as well.
Elad Alon69321dd2019-01-10 15:02:54 +0100508 for (size_t d = 0; d < frame->second.dependent_frames.size(); ++d) {
philipele0b2f152016-09-28 10:23:49 +0200509 auto frame_ref = frames_.find(frame->second.dependent_frames[d]);
philipel112adf92017-06-15 09:06:21 -0700510 RTC_DCHECK(frame_ref != frames_.end());
philipele0b2f152016-09-28 10:23:49 +0200511
philipel112adf92017-06-15 09:06:21 -0700512 // TODO(philipel): Look into why we've seen this happen.
513 if (frame_ref != frames_.end()) {
514 --frame_ref->second.num_missing_continuous;
515 if (frame_ref->second.num_missing_continuous == 0) {
516 frame_ref->second.continuous = true;
517 continuous_frames.push(frame_ref);
518 }
philipele0b2f152016-09-28 10:23:49 +0200519 }
520 }
521 }
522}
523
524void FrameBuffer::PropagateDecodability(const FrameInfo& info) {
tommidb23ea62017-03-03 07:21:18 -0800525 TRACE_EVENT0("webrtc", "FrameBuffer::PropagateDecodability");
Elad Alon69321dd2019-01-10 15:02:54 +0100526 for (size_t d = 0; d < info.dependent_frames.size(); ++d) {
philipele0b2f152016-09-28 10:23:49 +0200527 auto ref_info = frames_.find(info.dependent_frames[d]);
philipel93e451b2016-10-06 12:25:13 +0200528 RTC_DCHECK(ref_info != frames_.end());
tommie95b78b2017-05-14 07:23:11 -0700529 // TODO(philipel): Look into why we've seen this happen.
530 if (ref_info != frames_.end()) {
531 RTC_DCHECK_GT(ref_info->second.num_missing_decodable, 0U);
532 --ref_info->second.num_missing_decodable;
533 }
philipele0b2f152016-09-28 10:23:49 +0200534 }
535}
536
philipele7c891f2018-02-22 14:35:06 +0100537bool FrameBuffer::UpdateFrameInfoWithIncomingFrame(const EncodedFrame& frame,
philipele0b2f152016-09-28 10:23:49 +0200538 FrameMap::iterator info) {
tommidb23ea62017-03-03 07:21:18 -0800539 TRACE_EVENT0("webrtc", "FrameBuffer::UpdateFrameInfoWithIncomingFrame");
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +0100540 auto last_decoded_frame = decoded_frames_history_.GetLastDecodedFrameId();
541 RTC_DCHECK(!last_decoded_frame || *last_decoded_frame < info->first);
philipele0b2f152016-09-28 10:23:49 +0200542
Artem Titovdcd7fc72021-08-09 13:02:57 +0200543 // In this function we determine how many missing dependencies this `frame`
544 // has to become continuous/decodable. If a frame that this `frame` depend
philipel798b2822018-06-11 13:10:14 +0200545 // on has already been decoded then we can ignore that dependency since it has
546 // already been fulfilled.
547 //
Artem Titovdcd7fc72021-08-09 13:02:57 +0200548 // For all other frames we will register a backwards reference to this `frame`
549 // so that `num_missing_continuous` and `num_missing_decodable` can be
philipel798b2822018-06-11 13:10:14 +0200550 // decremented as frames become continuous/are decoded.
551 struct Dependency {
philipel9aa9b8d2021-02-15 13:31:29 +0100552 int64_t frame_id;
philipel798b2822018-06-11 13:10:14 +0200553 bool continuous;
554 };
555 std::vector<Dependency> not_yet_fulfilled_dependencies;
556
557 // Find all dependencies that have not yet been fulfilled.
philipele0b2f152016-09-28 10:23:49 +0200558 for (size_t i = 0; i < frame.num_references; ++i) {
Artem Titovdcd7fc72021-08-09 13:02:57 +0200559 // Does `frame` depend on a frame earlier than the last decoded one?
philipel9aa9b8d2021-02-15 13:31:29 +0100560 if (last_decoded_frame && frame.references[i] <= *last_decoded_frame) {
Artem Titovdcd7fc72021-08-09 13:02:57 +0200561 // Was that frame decoded? If not, this `frame` will never become
philipel798b2822018-06-11 13:10:14 +0200562 // decodable.
philipel9aa9b8d2021-02-15 13:31:29 +0100563 if (!decoded_frames_history_.WasDecoded(frame.references[i])) {
philipel65e1f942017-07-24 08:26:53 -0700564 int64_t now_ms = clock_->TimeInMilliseconds();
565 if (last_log_non_decoded_ms_ + kLogNonDecodedIntervalMs < now_ms) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100566 RTC_LOG(LS_WARNING)
philipel9aa9b8d2021-02-15 13:31:29 +0100567 << "Frame " << frame.Id()
philipelf1091932021-02-11 15:25:08 +0100568 << " depends on a non-decoded frame more previous than the last "
569 "decoded frame, dropping frame.";
philipel65e1f942017-07-24 08:26:53 -0700570 last_log_non_decoded_ms_ = now_ms;
571 }
philipele0b2f152016-09-28 10:23:49 +0200572 return false;
573 }
philipele0b2f152016-09-28 10:23:49 +0200574 } else {
philipel9aa9b8d2021-02-15 13:31:29 +0100575 auto ref_info = frames_.find(frame.references[i]);
philipel798b2822018-06-11 13:10:14 +0200576 bool ref_continuous =
577 ref_info != frames_.end() && ref_info->second.continuous;
philipel9aa9b8d2021-02-15 13:31:29 +0100578 not_yet_fulfilled_dependencies.push_back(
579 {frame.references[i], ref_continuous});
philipele0b2f152016-09-28 10:23:49 +0200580 }
philipelbe7a9e52016-05-19 12:19:35 +0200581 }
582
philipel798b2822018-06-11 13:10:14 +0200583 info->second.num_missing_continuous = not_yet_fulfilled_dependencies.size();
584 info->second.num_missing_decodable = not_yet_fulfilled_dependencies.size();
585
586 for (const Dependency& dep : not_yet_fulfilled_dependencies) {
587 if (dep.continuous)
588 --info->second.num_missing_continuous;
589
philipel9aa9b8d2021-02-15 13:31:29 +0100590 frames_[dep.frame_id].dependent_frames.push_back(frame.Id());
philipel798b2822018-06-11 13:10:14 +0200591 }
philipel93e451b2016-10-06 12:25:13 +0200592
philipelbe7a9e52016-05-19 12:19:35 +0200593 return true;
594}
595
philipelbe742702016-11-30 01:31:40 -0800596void FrameBuffer::UpdateJitterDelay() {
tommidb23ea62017-03-03 07:21:18 -0800597 TRACE_EVENT0("webrtc", "FrameBuffer::UpdateJitterDelay");
philipela45102f2017-02-22 05:30:39 -0800598 if (!stats_callback_)
599 return;
philipelbe742702016-11-30 01:31:40 -0800600
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100601 TimeDelta max_decode = TimeDelta::Zero();
602 TimeDelta current_delay = TimeDelta::Zero();
603 TimeDelta target_delay = TimeDelta::Zero();
604 TimeDelta jitter_buffer = TimeDelta::Zero();
605 TimeDelta min_playout_delay = TimeDelta::Zero();
606 TimeDelta render_delay = TimeDelta::Zero();
607 if (timing_->GetTimings(&max_decode, &current_delay, &target_delay,
608 &jitter_buffer, &min_playout_delay, &render_delay)) {
philipela45102f2017-02-22 05:30:39 -0800609 stats_callback_->OnFrameBufferTimingsUpdated(
Evan Shrubsoled6cdf802022-03-02 15:13:55 +0100610 max_decode.ms(), current_delay.ms(), target_delay.ms(),
611 jitter_buffer.ms(), min_playout_delay.ms(), render_delay.ms());
philipelbe742702016-11-30 01:31:40 -0800612 }
philipel266f0a42016-11-28 08:49:07 -0800613}
614
ilnik2edc6842017-07-06 03:06:50 -0700615void FrameBuffer::UpdateTimingFrameInfo() {
616 TRACE_EVENT0("webrtc", "FrameBuffer::UpdateTimingFrameInfo");
Danil Chapovalov0040b662018-06-18 10:48:16 +0200617 absl::optional<TimingFrameInfo> info = timing_->GetTimingFrameInfo();
philipel97187112018-03-23 10:43:21 +0100618 if (info && stats_callback_)
ilnik2edc6842017-07-06 03:06:50 -0700619 stats_callback_->OnTimingFrameInfoUpdated(*info);
620}
621
philipelfcc60062017-01-18 05:35:20 -0800622void FrameBuffer::ClearFramesAndHistory() {
ilnik2edc6842017-07-06 03:06:50 -0700623 TRACE_EVENT0("webrtc", "FrameBuffer::ClearFramesAndHistory");
Johannes Kron0c141c52019-08-26 15:04:43 +0200624 if (stats_callback_) {
philipel9aa9b8d2021-02-15 13:31:29 +0100625 unsigned int dropped_frames =
626 std::count_if(frames_.begin(), frames_.end(),
627 [](const std::pair<const int64_t, FrameInfo>& frame) {
628 return frame.second.frame != nullptr;
629 });
Johannes Kron0c141c52019-08-26 15:04:43 +0200630 if (dropped_frames > 0) {
631 stats_callback_->OnDroppedFrames(dropped_frames);
632 }
633 }
philipelfcc60062017-01-18 05:35:20 -0800634 frames_.clear();
Ilya Nikolaevskiy6551faf2019-01-10 15:16:47 +0100635 last_continuous_frame_.reset();
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100636 frames_to_decode_.clear();
Ilya Nikolaevskiy13717842019-01-14 13:24:22 +0100637 decoded_frames_history_.Clear();
philipelfcc60062017-01-18 05:35:20 -0800638}
639
Niels Möllerff2e2152019-09-27 10:29:30 +0200640// TODO(philipel): Avoid the concatenation of frames here, by replacing
641// NextFrame and GetNextFrame with methods returning multiple frames.
Evan Shrubsole0072c212021-11-10 11:41:14 +0100642std::unique_ptr<EncodedFrame> FrameBuffer::CombineAndDeleteFrames(
643 std::vector<std::unique_ptr<EncodedFrame>> frames) const {
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100644 RTC_DCHECK(!frames.empty());
Evan Shrubsolef83d4262021-12-15 15:05:15 +0100645 absl::InlinedVector<std::unique_ptr<EncodedFrame>, 4> inlined;
646 for (auto& frame : frames) {
647 inlined.push_back(std::move(frame));
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100648 }
Evan Shrubsolef83d4262021-12-15 15:05:15 +0100649 return webrtc::CombineAndDeleteFrames(std::move(inlined));
Ilya Nikolaevskiy5546aef2018-12-04 15:54:52 +0100650}
651
Niels Möllerbe682d42018-03-27 08:31:45 +0200652FrameBuffer::FrameInfo::FrameInfo() = default;
653FrameBuffer::FrameInfo::FrameInfo(FrameInfo&&) = default;
654FrameBuffer::FrameInfo::~FrameInfo() = default;
655
philipelbe7a9e52016-05-19 12:19:35 +0200656} // namespace video_coding
657} // namespace webrtc