blob: 65a445e50b15b5fd321804c88cc141bba538da11 [file] [log] [blame]
pbos@webrtc.org9115cde2014-12-09 10:36:40 +00001/* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
Ilya Nikolaevskiybf352982017-10-02 10:08:25 +02002 *
3 * Use of this source code is governed by a BSD-style license
4 * that can be found in the LICENSE file in the root of the source
5 * tree. An additional intellectual property rights grant can be found
6 * in the file PATENTS. All contributing project authors may
7 * be found in the AUTHORS file in the root of the source tree.
8 */
pbos@webrtc.org9115cde2014-12-09 10:36:40 +00009
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020010#include "modules/video_coding/codecs/vp8/screenshare_layers.h"
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000011
12#include <stdlib.h>
13
philipelcce46fc2015-12-21 03:04:49 -080014#include <algorithm>
Ilya Nikolaevskiybf352982017-10-02 10:08:25 +020015#include <memory>
philipelcce46fc2015-12-21 03:04:49 -080016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "modules/video_coding/include/video_codec_interface.h"
Elad Alon819661a2019-01-29 17:17:09 +010018#include "rtc_base/arraysize.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "rtc_base/checks.h"
Ilya Nikolaevskiy58662912017-10-04 15:07:09 +020020#include "rtc_base/logging.h"
Sebastian Janssone64a6882019-03-01 18:04:07 +010021#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "system_wrappers/include/metrics.h"
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000023
24namespace webrtc {
Erik Språng59021ba2018-10-03 11:05:16 +020025namespace {
Elad Alon411b49b2019-01-29 14:05:55 +010026using BufferFlags = Vp8FrameConfig::BufferFlags;
27
28constexpr BufferFlags kNone = Vp8FrameConfig::BufferFlags::kNone;
29constexpr BufferFlags kReference = Vp8FrameConfig::BufferFlags::kReference;
30constexpr BufferFlags kUpdate = Vp8FrameConfig::BufferFlags::kUpdate;
31constexpr BufferFlags kReferenceAndUpdate =
32 Vp8FrameConfig::BufferFlags::kReferenceAndUpdate;
33
34constexpr int kOneSecond90Khz = 90000;
35constexpr int kMinTimeBetweenSyncs = kOneSecond90Khz * 2;
36constexpr int kMaxTimeBetweenSyncs = kOneSecond90Khz * 4;
37constexpr int kQpDeltaThresholdForSync = 8;
38constexpr int kMinBitrateKbpsForQpBoost = 500;
Erik Språng59021ba2018-10-03 11:05:16 +020039} // namespace
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000040
sprang@webrtc.org70f74f32014-12-17 10:57:10 +000041const double ScreenshareLayers::kMaxTL0FpsReduction = 2.5;
42const double ScreenshareLayers::kAcceptableTargetOvershoot = 2.0;
43
sprang429600d2017-01-26 06:12:26 -080044constexpr int ScreenshareLayers::kMaxNumTemporalLayers;
45
sprangafe1f742016-04-12 02:45:13 -070046// Always emit a frame with certain interval, even if bitrate targets have
sprang916170a2017-05-23 07:47:55 -070047// been exceeded. This prevents needless keyframe requests.
sprang6c4bbfa2017-05-30 10:08:23 -070048const int ScreenshareLayers::kMaxFrameIntervalMs = 2750;
sprangafe1f742016-04-12 02:45:13 -070049
Sebastian Janssone64a6882019-03-01 18:04:07 +010050ScreenshareLayers::ScreenshareLayers(int num_temporal_layers)
51 : number_of_temporal_layers_(
sprang429600d2017-01-26 06:12:26 -080052 std::min(kMaxNumTemporalLayers, num_temporal_layers)),
Erik Språng2c4c9142015-06-24 11:24:44 +020053 active_layer_(-1),
54 last_timestamp_(-1),
55 last_sync_timestamp_(-1),
sprangafe1f742016-04-12 02:45:13 -070056 last_emitted_tl0_timestamp_(-1),
Erik Språng27a457d2018-01-12 11:00:21 +010057 last_frame_time_ms_(-1),
Erik Språng2c4c9142015-06-24 11:24:44 +020058 min_qp_(-1),
59 max_qp_(-1),
60 max_debt_bytes_(0),
sprangac4a90d2016-12-28 05:58:07 -080061 encode_framerate_(1000.0f, 1000.0f), // 1 second window, second scale.
Erik Språng59021ba2018-10-03 11:05:16 +020062 bitrate_updated_(false),
63 checker_(TemporalLayersChecker::CreateTemporalLayersChecker(
Erik Språng4529fbc2018-10-12 10:30:31 +020064 Vp8TemporalLayersType::kBitrateDynamic,
Erik Språng59021ba2018-10-03 11:05:16 +020065 num_temporal_layers)) {
sprang429600d2017-01-26 06:12:26 -080066 RTC_CHECK_GT(number_of_temporal_layers_, 0);
67 RTC_CHECK_LE(number_of_temporal_layers_, kMaxNumTemporalLayers);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000068}
69
sprangb0fdfea2016-03-01 05:51:16 -080070ScreenshareLayers::~ScreenshareLayers() {
71 UpdateHistograms();
72}
73
Elad Aloncde8ab22019-03-20 11:56:20 +010074size_t ScreenshareLayers::StreamCount() const {
75 return 1;
76}
77
78bool ScreenshareLayers::SupportsEncoderFrameDropping(
79 size_t stream_index) const {
80 RTC_DCHECK_LT(stream_index, StreamCount());
Erik Språngfb2a66a2018-09-10 10:48:01 +020081 // Frame dropping is handled internally by this class.
82 return false;
83}
84
Elad Aloncde8ab22019-03-20 11:56:20 +010085Vp8FrameConfig ScreenshareLayers::UpdateLayerConfig(size_t stream_index,
86 uint32_t timestamp) {
87 RTC_DCHECK_LT(stream_index, StreamCount());
88
Erik Språng59021ba2018-10-03 11:05:16 +020089 auto it = pending_frame_configs_.find(timestamp);
90 if (it != pending_frame_configs_.end()) {
91 // Drop and re-encode, reuse the previous config.
philipelb19f27a2019-03-28 16:09:52 +010092 return it->second.frame_config;
Erik Språng59021ba2018-10-03 11:05:16 +020093 }
94
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000095 if (number_of_temporal_layers_ <= 1) {
96 // No flags needed for 1 layer screenshare.
Peter Boström1436c832017-03-27 15:01:49 -040097 // TODO(pbos): Consider updating only last, and not all buffers.
philipelb19f27a2019-03-28 16:09:52 +010098 DependencyInfo dependency_info{
99 "S", {kReferenceAndUpdate, kReferenceAndUpdate, kReferenceAndUpdate}};
100 pending_frame_configs_[timestamp] = dependency_info;
101 return dependency_info.frame_config;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000102 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200103
Sebastian Janssone64a6882019-03-01 18:04:07 +0100104 const int64_t now_ms = rtc::TimeMillis();
sprangb0fdfea2016-03-01 05:51:16 -0800105
Erik Språng2c4c9142015-06-24 11:24:44 +0200106 int64_t unwrapped_timestamp = time_wrap_handler_.Unwrap(timestamp);
sprang916170a2017-05-23 07:47:55 -0700107 int64_t ts_diff;
108 if (last_timestamp_ == -1) {
109 ts_diff = kOneSecond90Khz / capture_framerate_.value_or(*target_framerate_);
110 } else {
111 ts_diff = unwrapped_timestamp - last_timestamp_;
112 }
Erik Språng27a457d2018-01-12 11:00:21 +0100113
114 if (target_framerate_) {
115 // If input frame rate exceeds target frame rate, either over a one second
116 // averaging window, or if frame interval is below 90% of desired value,
117 // drop frame.
Erik Språng27a457d2018-01-12 11:00:21 +0100118 if (encode_framerate_.Rate(now_ms).value_or(0) > *target_framerate_)
Elad Alon411b49b2019-01-29 14:05:55 +0100119 return Vp8FrameConfig(kNone, kNone, kNone);
Erik Språng27a457d2018-01-12 11:00:21 +0100120
Erik Språngdb9e9d52018-01-22 09:23:11 -0800121 // Primarily check if frame interval is too short using frame timestamps,
122 // as if they are correct they won't be affected by queuing in webrtc.
123 const int64_t expected_frame_interval_90khz =
124 kOneSecond90Khz / *target_framerate_;
125 if (last_timestamp_ != -1 && ts_diff > 0) {
126 if (ts_diff < 85 * expected_frame_interval_90khz / 100) {
Elad Alon411b49b2019-01-29 14:05:55 +0100127 return Vp8FrameConfig(kNone, kNone, kNone);
Erik Språngdb9e9d52018-01-22 09:23:11 -0800128 }
129 } else {
130 // Timestamps looks off, use realtime clock here instead.
131 const int64_t expected_frame_interval_ms = 1000 / *target_framerate_;
132 if (last_frame_time_ms_ != -1 &&
133 now_ms - last_frame_time_ms_ <
134 (85 * expected_frame_interval_ms) / 100) {
Elad Alon411b49b2019-01-29 14:05:55 +0100135 return Vp8FrameConfig(kNone, kNone, kNone);
Erik Språngdb9e9d52018-01-22 09:23:11 -0800136 }
Erik Språng27a457d2018-01-12 11:00:21 +0100137 }
138 }
139
140 if (stats_.first_frame_time_ms_ == -1)
141 stats_.first_frame_time_ms_ = now_ms;
142
sprang916170a2017-05-23 07:47:55 -0700143 // Make sure both frame droppers leak out bits.
144 layers_[0].UpdateDebt(ts_diff / 90);
145 layers_[1].UpdateDebt(ts_diff / 90);
146 last_timestamp_ = timestamp;
Erik Språng27a457d2018-01-12 11:00:21 +0100147 last_frame_time_ms_ = now_ms;
sprang916170a2017-05-23 07:47:55 -0700148
149 TemporalLayerState layer_state = TemporalLayerState::kDrop;
150
Erik Språng2c4c9142015-06-24 11:24:44 +0200151 if (active_layer_ == -1 ||
152 layers_[active_layer_].state != TemporalLayer::State::kDropped) {
sprangafe1f742016-04-12 02:45:13 -0700153 if (last_emitted_tl0_timestamp_ != -1 &&
154 (unwrapped_timestamp - last_emitted_tl0_timestamp_) / 90 >
155 kMaxFrameIntervalMs) {
156 // Too long time has passed since the last frame was emitted, cancel
157 // enough debt to allow a single frame.
158 layers_[0].debt_bytes_ = max_debt_bytes_ - 1;
159 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200160 if (layers_[0].debt_bytes_ > max_debt_bytes_) {
161 // Must drop TL0, encode TL1 instead.
162 if (layers_[1].debt_bytes_ > max_debt_bytes_) {
163 // Must drop both TL0 and TL1.
164 active_layer_ = -1;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000165 } else {
Erik Språng2c4c9142015-06-24 11:24:44 +0200166 active_layer_ = 1;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000167 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200168 } else {
169 active_layer_ = 0;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000170 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000171 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200172
173 switch (active_layer_) {
174 case 0:
sprang916170a2017-05-23 07:47:55 -0700175 layer_state = TemporalLayerState::kTl0;
sprangafe1f742016-04-12 02:45:13 -0700176 last_emitted_tl0_timestamp_ = unwrapped_timestamp;
Erik Språng2c4c9142015-06-24 11:24:44 +0200177 break;
178 case 1:
sprangf03ea042017-07-13 03:53:51 -0700179 if (layers_[1].state != TemporalLayer::State::kDropped) {
Erik Språngb75d6b82018-08-13 16:05:33 +0200180 if (TimeToSync(unwrapped_timestamp) ||
181 layers_[1].state == TemporalLayer::State::kKeyFrame) {
sprangf03ea042017-07-13 03:53:51 -0700182 last_sync_timestamp_ = unwrapped_timestamp;
183 layer_state = TemporalLayerState::kTl1Sync;
184 } else {
185 layer_state = TemporalLayerState::kTl1;
186 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200187 } else {
sprangf03ea042017-07-13 03:53:51 -0700188 layer_state = last_sync_timestamp_ == unwrapped_timestamp
189 ? TemporalLayerState::kTl1Sync
190 : TemporalLayerState::kTl1;
Erik Språng2c4c9142015-06-24 11:24:44 +0200191 }
192 break;
193 case -1:
sprang916170a2017-05-23 07:47:55 -0700194 layer_state = TemporalLayerState::kDrop;
sprangb0fdfea2016-03-01 05:51:16 -0800195 ++stats_.num_dropped_frames_;
Erik Språng2c4c9142015-06-24 11:24:44 +0200196 break;
197 default:
Erik Språng2c4c9142015-06-24 11:24:44 +0200198 RTC_NOTREACHED();
199 }
200
philipelb19f27a2019-03-28 16:09:52 +0100201 DependencyInfo dependency_info;
Peter Boström1436c832017-03-27 15:01:49 -0400202 // TODO(pbos): Consider referencing but not updating the 'alt' buffer for all
203 // layers.
204 switch (layer_state) {
sprang916170a2017-05-23 07:47:55 -0700205 case TemporalLayerState::kDrop:
philipelb19f27a2019-03-28 16:09:52 +0100206 dependency_info = {"", {kNone, kNone, kNone}};
pbos51f083c2017-05-04 06:39:04 -0700207 break;
sprang916170a2017-05-23 07:47:55 -0700208 case TemporalLayerState::kTl0:
Peter Boström1436c832017-03-27 15:01:49 -0400209 // TL0 only references and updates 'last'.
philipelb19f27a2019-03-28 16:09:52 +0100210 dependency_info = {"SS", {kReferenceAndUpdate, kNone, kNone}};
211 dependency_info.frame_config.packetizer_temporal_idx = 0;
pbos51f083c2017-05-04 06:39:04 -0700212 break;
sprang916170a2017-05-23 07:47:55 -0700213 case TemporalLayerState::kTl1:
Peter Boström1436c832017-03-27 15:01:49 -0400214 // TL1 references both 'last' and 'golden' but only updates 'golden'.
philipelb19f27a2019-03-28 16:09:52 +0100215 dependency_info = {"-R", {kReference, kReferenceAndUpdate, kNone}};
216 dependency_info.frame_config.packetizer_temporal_idx = 1;
pbos51f083c2017-05-04 06:39:04 -0700217 break;
sprang916170a2017-05-23 07:47:55 -0700218 case TemporalLayerState::kTl1Sync:
Peter Boström1436c832017-03-27 15:01:49 -0400219 // Predict from only TL0 to allow participants to switch to the high
220 // bitrate stream. Updates 'golden' so that TL1 can continue to refer to
221 // and update 'golden' from this point on.
philipelb19f27a2019-03-28 16:09:52 +0100222 dependency_info = {"-S", {kReference, kUpdate, kNone}};
223 dependency_info.frame_config.packetizer_temporal_idx = 1;
224 dependency_info.frame_config.layer_sync = true;
pbos51f083c2017-05-04 06:39:04 -0700225 break;
Peter Boström1436c832017-03-27 15:01:49 -0400226 }
pbos51f083c2017-05-04 06:39:04 -0700227
philipelb19f27a2019-03-28 16:09:52 +0100228 pending_frame_configs_[timestamp] = dependency_info;
229 return dependency_info.frame_config;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000230}
231
Erik Språngbb60a3a2018-03-19 18:25:10 +0100232void ScreenshareLayers::OnRatesUpdated(
Elad Aloncde8ab22019-03-20 11:56:20 +0100233 size_t stream_index,
Erik Språngbb60a3a2018-03-19 18:25:10 +0100234 const std::vector<uint32_t>& bitrates_bps,
235 int framerate_fps) {
Elad Aloncde8ab22019-03-20 11:56:20 +0100236 RTC_DCHECK_LT(stream_index, StreamCount());
Erik Språngbb60a3a2018-03-19 18:25:10 +0100237 RTC_DCHECK_GT(framerate_fps, 0);
238 RTC_DCHECK_GE(bitrates_bps.size(), 1);
239 RTC_DCHECK_LE(bitrates_bps.size(), 2);
240
241 // |bitrates_bps| uses individual rates per layer, but we want to use the
242 // accumulated rate here.
243 uint32_t tl0_kbps = bitrates_bps[0] / 1000;
244 uint32_t tl1_kbps = tl0_kbps;
245 if (bitrates_bps.size() > 1) {
246 tl1_kbps += bitrates_bps[1] / 1000;
247 }
248
sprangac4a90d2016-12-28 05:58:07 -0800249 if (!target_framerate_) {
Erik Språngbb60a3a2018-03-19 18:25:10 +0100250 // First OnRatesUpdated() is called during construction, with the
251 // configured targets as parameters.
252 target_framerate_ = framerate_fps;
sprang0ad0de62017-01-11 05:01:32 -0800253 capture_framerate_ = target_framerate_;
sprangac4a90d2016-12-28 05:58:07 -0800254 bitrate_updated_ = true;
255 } else {
Erik Språnge624d072018-04-11 16:47:27 +0200256 if ((capture_framerate_ &&
257 framerate_fps != static_cast<int>(*capture_framerate_)) ||
258 (tl0_kbps != layers_[0].target_rate_kbps_) ||
259 (tl1_kbps != layers_[1].target_rate_kbps_)) {
260 bitrate_updated_ = true;
261 }
Erik Språngbb60a3a2018-03-19 18:25:10 +0100262
263 if (framerate_fps < 0) {
sprang0ad0de62017-01-11 05:01:32 -0800264 capture_framerate_.reset();
sprangac4a90d2016-12-28 05:58:07 -0800265 } else {
Erik Språngbb60a3a2018-03-19 18:25:10 +0100266 capture_framerate_ = framerate_fps;
sprangac4a90d2016-12-28 05:58:07 -0800267 }
268 }
269
Erik Språngbb60a3a2018-03-19 18:25:10 +0100270 layers_[0].target_rate_kbps_ = tl0_kbps;
271 layers_[1].target_rate_kbps_ = tl1_kbps;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000272}
273
Elad Aloncde8ab22019-03-20 11:56:20 +0100274void ScreenshareLayers::OnEncodeDone(size_t stream_index,
275 uint32_t rtp_timestamp,
Erik Språng59021ba2018-10-03 11:05:16 +0200276 size_t size_bytes,
277 bool is_keyframe,
278 int qp,
philipel9df33532019-03-04 16:37:50 +0100279 CodecSpecificInfo* info) {
Elad Aloncde8ab22019-03-20 11:56:20 +0100280 RTC_DCHECK_LT(stream_index, StreamCount());
281
Erik Språng59021ba2018-10-03 11:05:16 +0200282 if (size_bytes == 0) {
Elad Alon6796ec22019-04-15 10:07:50 +0200283 RTC_LOG(LS_WARNING) << "Empty frame; treating as dropped.";
284 OnFrameDropped(stream_index, rtp_timestamp);
Erik Språng2c4c9142015-06-24 11:24:44 +0200285 return;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000286 }
sprangef7228c2015-08-05 02:01:29 -0700287
philipelb19f27a2019-03-28 16:09:52 +0100288 absl::optional<DependencyInfo> dependency_info;
Erik Språng59021ba2018-10-03 11:05:16 +0200289 auto it = pending_frame_configs_.find(rtp_timestamp);
290 if (it != pending_frame_configs_.end()) {
philipelb19f27a2019-03-28 16:09:52 +0100291 dependency_info = it->second;
Erik Språng59021ba2018-10-03 11:05:16 +0200292 pending_frame_configs_.erase(it);
293
294 if (checker_) {
philipelb19f27a2019-03-28 16:09:52 +0100295 RTC_DCHECK(checker_->CheckTemporalConfig(is_keyframe,
296 dependency_info->frame_config));
Erik Språng59021ba2018-10-03 11:05:16 +0200297 }
298 }
299
philipel9df33532019-03-04 16:37:50 +0100300 CodecSpecificInfoVP8& vp8_info = info->codecSpecific.VP8;
philipelb19f27a2019-03-28 16:09:52 +0100301 GenericFrameInfo& generic_frame_info = info->generic_frame_info.emplace();
302
Erik Språng59021ba2018-10-03 11:05:16 +0200303 if (number_of_temporal_layers_ == 1) {
philipel9df33532019-03-04 16:37:50 +0100304 vp8_info.temporalIdx = kNoTemporalIdx;
305 vp8_info.layerSync = false;
philipelb19f27a2019-03-28 16:09:52 +0100306 generic_frame_info.decode_target_indications =
307 GenericFrameInfo::DecodeTargetInfo("S");
Erik Språng59021ba2018-10-03 11:05:16 +0200308 } else {
309 int64_t unwrapped_timestamp = time_wrap_handler_.Unwrap(rtp_timestamp);
philipelb19f27a2019-03-28 16:09:52 +0100310 if (dependency_info) {
311 vp8_info.temporalIdx =
312 dependency_info->frame_config.packetizer_temporal_idx;
313 vp8_info.layerSync = dependency_info->frame_config.layer_sync;
314 generic_frame_info.decode_target_indications =
315 dependency_info->decode_target_indications;
Erik Språng59021ba2018-10-03 11:05:16 +0200316 } else {
Elad Alon819661a2019-01-29 17:17:09 +0100317 RTC_DCHECK(is_keyframe);
philipelb19f27a2019-03-28 16:09:52 +0100318 generic_frame_info.decode_target_indications =
319 GenericFrameInfo::DecodeTargetInfo("SS");
Erik Språng59021ba2018-10-03 11:05:16 +0200320 }
Elad Alon819661a2019-01-29 17:17:09 +0100321
Erik Språng59021ba2018-10-03 11:05:16 +0200322 if (is_keyframe) {
philipel9df33532019-03-04 16:37:50 +0100323 vp8_info.temporalIdx = 0;
Erik Språng59021ba2018-10-03 11:05:16 +0200324 last_sync_timestamp_ = unwrapped_timestamp;
philipel9df33532019-03-04 16:37:50 +0100325 vp8_info.layerSync = true;
Erik Språng59021ba2018-10-03 11:05:16 +0200326 layers_[0].state = TemporalLayer::State::kKeyFrame;
327 layers_[1].state = TemporalLayer::State::kKeyFrame;
328 active_layer_ = 1;
philipel9df33532019-03-04 16:37:50 +0100329 info->template_structure =
330 GetTemplateStructure(number_of_temporal_layers_);
Erik Språngdb6335e2019-04-01 16:22:57 +0200331 } else if (active_layer_ >= 0 && layers_[active_layer_].state ==
332 TemporalLayer::State::kKeyFrame) {
333 layers_[active_layer_].state = TemporalLayer::State::kNormal;
Erik Språng59021ba2018-10-03 11:05:16 +0200334 }
Elad Alon819661a2019-01-29 17:17:09 +0100335
philipel9df33532019-03-04 16:37:50 +0100336 vp8_info.useExplicitDependencies = true;
337 RTC_DCHECK_EQ(vp8_info.referencedBuffersCount, 0u);
338 RTC_DCHECK_EQ(vp8_info.updatedBuffersCount, 0u);
Elad Alon819661a2019-01-29 17:17:09 +0100339
340 // Note that |frame_config| is not derefernced if |is_keyframe|,
341 // meaning it's never dereferenced if the optional may be unset.
Niels Möller1f44bc12019-04-09 10:27:34 +0200342 for (int i = 0; i < static_cast<int>(Vp8FrameConfig::Buffer::kCount); ++i) {
343 if (!is_keyframe && dependency_info->frame_config.References(
344 static_cast<Vp8FrameConfig::Buffer>(i))) {
philipel9df33532019-03-04 16:37:50 +0100345 RTC_DCHECK_LT(vp8_info.referencedBuffersCount,
Elad Alon819661a2019-01-29 17:17:09 +0100346 arraysize(CodecSpecificInfoVP8::referencedBuffers));
philipel9df33532019-03-04 16:37:50 +0100347 vp8_info.referencedBuffers[vp8_info.referencedBuffersCount++] = i;
Elad Alon819661a2019-01-29 17:17:09 +0100348 }
349
Niels Möller1f44bc12019-04-09 10:27:34 +0200350 if (is_keyframe || dependency_info->frame_config.Updates(
351 static_cast<Vp8FrameConfig::Buffer>(i))) {
philipel9df33532019-03-04 16:37:50 +0100352 RTC_DCHECK_LT(vp8_info.updatedBuffersCount,
Elad Alon819661a2019-01-29 17:17:09 +0100353 arraysize(CodecSpecificInfoVP8::updatedBuffers));
philipel9df33532019-03-04 16:37:50 +0100354 vp8_info.updatedBuffers[vp8_info.updatedBuffersCount++] = i;
Elad Alon819661a2019-01-29 17:17:09 +0100355 }
356 }
Erik Språng59021ba2018-10-03 11:05:16 +0200357 }
358
Sebastian Janssone64a6882019-03-01 18:04:07 +0100359 encode_framerate_.Update(1, rtc::TimeMillis());
Erik Språng59021ba2018-10-03 11:05:16 +0200360
361 if (number_of_temporal_layers_ == 1)
362 return;
363
364 RTC_DCHECK_NE(-1, active_layer_);
Erik Språng2c4c9142015-06-24 11:24:44 +0200365 if (layers_[active_layer_].state == TemporalLayer::State::kDropped) {
366 layers_[active_layer_].state = TemporalLayer::State::kQualityBoost;
367 }
368
369 if (qp != -1)
370 layers_[active_layer_].last_qp = qp;
371
372 if (active_layer_ == 0) {
Erik Språng59021ba2018-10-03 11:05:16 +0200373 layers_[0].debt_bytes_ += size_bytes;
374 layers_[1].debt_bytes_ += size_bytes;
sprangb0fdfea2016-03-01 05:51:16 -0800375 ++stats_.num_tl0_frames_;
376 stats_.tl0_target_bitrate_sum_ += layers_[0].target_rate_kbps_;
377 stats_.tl0_qp_sum_ += qp;
Erik Språng2c4c9142015-06-24 11:24:44 +0200378 } else if (active_layer_ == 1) {
Erik Språng59021ba2018-10-03 11:05:16 +0200379 layers_[1].debt_bytes_ += size_bytes;
sprangb0fdfea2016-03-01 05:51:16 -0800380 ++stats_.num_tl1_frames_;
381 stats_.tl1_target_bitrate_sum_ += layers_[1].target_rate_kbps_;
382 stats_.tl1_qp_sum_ += qp;
Erik Språng2c4c9142015-06-24 11:24:44 +0200383 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000384}
385
Elad Alon6796ec22019-04-15 10:07:50 +0200386void ScreenshareLayers::OnFrameDropped(size_t stream_index,
387 uint32_t rtp_timestamp) {
388 layers_[active_layer_].state = TemporalLayer::State::kDropped;
389 ++stats_.num_overshoots_;
390}
391
Elad Aloncde8ab22019-03-20 11:56:20 +0100392void ScreenshareLayers::OnPacketLossRateUpdate(float packet_loss_rate) {}
393
394void ScreenshareLayers::OnRttUpdate(int64_t rtt_ms) {}
395
Elad Alon6c371ca2019-04-04 12:28:51 +0200396void ScreenshareLayers::OnLossNotification(
397 const VideoEncoder::LossNotification loss_notification) {}
398
philipel9df33532019-03-04 16:37:50 +0100399TemplateStructure ScreenshareLayers::GetTemplateStructure(
400 int num_layers) const {
401 RTC_CHECK_LT(num_layers, 3);
402 RTC_CHECK_GT(num_layers, 0);
403
404 TemplateStructure template_structure;
philipel361855b2019-03-28 14:12:10 +0100405 template_structure.num_decode_targets = num_layers;
philipel9df33532019-03-04 16:37:50 +0100406
407 using Builder = GenericFrameInfo::Builder;
408 switch (num_layers) {
409 case 1: {
410 template_structure.templates = {
411 Builder().T(0).Dtis("S").Build(),
412 Builder().T(0).Dtis("S").Fdiffs({1}).Build(),
413 };
414 return template_structure;
415 }
416 case 2: {
417 template_structure.templates = {
418 Builder().T(0).Dtis("SS").Build(),
419 Builder().T(0).Dtis("SS").Fdiffs({1}).Build(),
420 Builder().T(1).Dtis("-S").Fdiffs({1}).Build(),
421 };
422 return template_structure;
423 }
424 default:
425 RTC_NOTREACHED();
426 // To make the compiler happy!
427 return template_structure;
428 }
429}
430
Erik Språng2c4c9142015-06-24 11:24:44 +0200431bool ScreenshareLayers::TimeToSync(int64_t timestamp) const {
sprang2ddb8bd2016-02-04 03:59:52 -0800432 RTC_DCHECK_EQ(1, active_layer_);
henrikg91d6ede2015-09-17 00:24:34 -0700433 RTC_DCHECK_NE(-1, layers_[0].last_qp);
Erik Språng2c4c9142015-06-24 11:24:44 +0200434 if (layers_[1].last_qp == -1) {
435 // First frame in TL1 should only depend on TL0 since there are no
436 // previous frames in TL1.
437 return true;
438 }
439
henrikg91d6ede2015-09-17 00:24:34 -0700440 RTC_DCHECK_NE(-1, last_sync_timestamp_);
Erik Språng2c4c9142015-06-24 11:24:44 +0200441 int64_t timestamp_diff = timestamp - last_sync_timestamp_;
442 if (timestamp_diff > kMaxTimeBetweenSyncs) {
443 // After a certain time, force a sync frame.
444 return true;
445 } else if (timestamp_diff < kMinTimeBetweenSyncs) {
446 // If too soon from previous sync frame, don't issue a new one.
447 return false;
448 }
449 // Issue a sync frame if difference in quality between TL0 and TL1 isn't too
450 // large.
451 if (layers_[0].last_qp - layers_[1].last_qp < kQpDeltaThresholdForSync)
452 return true;
453 return false;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000454}
455
sprangc7805db2016-11-25 08:09:43 -0800456uint32_t ScreenshareLayers::GetCodecTargetBitrateKbps() const {
457 uint32_t target_bitrate_kbps = layers_[0].target_rate_kbps_;
458
459 if (number_of_temporal_layers_ > 1) {
460 // Calculate a codec target bitrate. This may be higher than TL0, gaining
461 // quality at the expense of frame rate at TL0. Constraints:
462 // - TL0 frame rate no less than framerate / kMaxTL0FpsReduction.
463 // - Target rate * kAcceptableTargetOvershoot should not exceed TL1 rate.
464 target_bitrate_kbps =
465 std::min(layers_[0].target_rate_kbps_ * kMaxTL0FpsReduction,
466 layers_[1].target_rate_kbps_ / kAcceptableTargetOvershoot);
467 }
468
469 return std::max(layers_[0].target_rate_kbps_, target_bitrate_kbps);
470}
471
Elad Aloncde8ab22019-03-20 11:56:20 +0100472bool ScreenshareLayers::UpdateConfiguration(size_t stream_index,
473 Vp8EncoderConfig* cfg) {
474 RTC_DCHECK_LT(stream_index, StreamCount());
475
Erik Språngf1414702018-09-12 15:04:08 +0200476 if (min_qp_ == -1 || max_qp_ == -1) {
477 // Store the valid qp range. This must not change during the lifetime of
478 // this class.
479 min_qp_ = cfg->rc_min_quantizer;
480 max_qp_ = cfg->rc_max_quantizer;
481 }
482
Erik Språng08127a92016-11-16 16:41:30 +0100483 bool cfg_updated = false;
sprangc7805db2016-11-25 08:09:43 -0800484 uint32_t target_bitrate_kbps = GetCodecTargetBitrateKbps();
Erik Språng27a457d2018-01-12 11:00:21 +0100485
486 // TODO(sprang): We _really_ need to make an overhaul of this class. :(
487 // If we're dropping frames in order to meet a target framerate, adjust the
488 // bitrate assigned to the encoder so the total average bitrate is correct.
489 float encoder_config_bitrate_kbps = target_bitrate_kbps;
490 if (target_framerate_ && capture_framerate_ &&
491 *target_framerate_ < *capture_framerate_) {
492 encoder_config_bitrate_kbps *=
493 static_cast<float>(*capture_framerate_) / *target_framerate_;
494 }
495
496 if (bitrate_updated_ ||
497 cfg->rc_target_bitrate != encoder_config_bitrate_kbps) {
498 cfg->rc_target_bitrate = encoder_config_bitrate_kbps;
Erik Språng08127a92016-11-16 16:41:30 +0100499
500 // Don't reconfigure qp limits during quality boost frames.
501 if (active_layer_ == -1 ||
502 layers_[active_layer_].state != TemporalLayer::State::kQualityBoost) {
Erik Språng08127a92016-11-16 16:41:30 +0100503 // After a dropped frame, a frame with max qp will be encoded and the
504 // quality will then ramp up from there. To boost the speed of recovery,
sprang916170a2017-05-23 07:47:55 -0700505 // encode the next frame with lower max qp, if there is sufficient
506 // bandwidth to do so without causing excessive delay.
507 // TL0 is the most important to improve since the errors in this layer
508 // will propagate to TL1.
Erik Språng08127a92016-11-16 16:41:30 +0100509 // Currently, reduce max qp by 20% for TL0 and 15% for TL1.
sprang916170a2017-05-23 07:47:55 -0700510 if (layers_[1].target_rate_kbps_ >= kMinBitrateKbpsForQpBoost) {
511 layers_[0].enhanced_max_qp =
512 min_qp_ + (((max_qp_ - min_qp_) * 80) / 100);
513 layers_[1].enhanced_max_qp =
514 min_qp_ + (((max_qp_ - min_qp_) * 85) / 100);
515 } else {
516 layers_[0].enhanced_max_qp = -1;
517 layers_[1].enhanced_max_qp = -1;
518 }
Erik Språng08127a92016-11-16 16:41:30 +0100519 }
520
sprang0ad0de62017-01-11 05:01:32 -0800521 if (capture_framerate_) {
sprangac4a90d2016-12-28 05:58:07 -0800522 int avg_frame_size =
sprang0ad0de62017-01-11 05:01:32 -0800523 (target_bitrate_kbps * 1000) / (8 * *capture_framerate_);
sprang916170a2017-05-23 07:47:55 -0700524 // Allow max debt to be the size of a single optimal frame.
525 // TODO(sprang): Determine if this needs to be adjusted by some factor.
526 // (Lower values may cause more frame drops, higher may lead to queuing
527 // delays.)
528 max_debt_bytes_ = avg_frame_size;
Erik Språng08127a92016-11-16 16:41:30 +0100529 }
530
531 bitrate_updated_ = false;
532 cfg_updated = true;
533 }
534
535 // Don't try to update boosts state if not active yet.
536 if (active_layer_ == -1)
537 return cfg_updated;
538
sprangef7228c2015-08-05 02:01:29 -0700539 if (max_qp_ == -1 || number_of_temporal_layers_ <= 1)
Erik Språng08127a92016-11-16 16:41:30 +0100540 return cfg_updated;
Erik Språng2c4c9142015-06-24 11:24:44 +0200541
542 // If layer is in the quality boost state (following a dropped frame), update
543 // the configuration with the adjusted (lower) qp and set the state back to
544 // normal.
Erik Språngf1414702018-09-12 15:04:08 +0200545 unsigned int adjusted_max_qp = max_qp_; // Set the normal max qp.
546 if (layers_[active_layer_].state == TemporalLayer::State::kQualityBoost) {
547 if (layers_[active_layer_].enhanced_max_qp != -1) {
548 // Bitrate is high enough for quality boost, update max qp.
549 adjusted_max_qp = layers_[active_layer_].enhanced_max_qp;
550 }
551 // Regardless of qp, reset the boost state for the next frame.
Erik Språng2c4c9142015-06-24 11:24:44 +0200552 layers_[active_layer_].state = TemporalLayer::State::kNormal;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000553 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200554
555 if (adjusted_max_qp == cfg->rc_max_quantizer)
Erik Språng08127a92016-11-16 16:41:30 +0100556 return cfg_updated;
Erik Språng2c4c9142015-06-24 11:24:44 +0200557
558 cfg->rc_max_quantizer = adjusted_max_qp;
Erik Språng08127a92016-11-16 16:41:30 +0100559 cfg_updated = true;
sprangc7805db2016-11-25 08:09:43 -0800560
Erik Språng08127a92016-11-16 16:41:30 +0100561 return cfg_updated;
Erik Språng2c4c9142015-06-24 11:24:44 +0200562}
563
564void ScreenshareLayers::TemporalLayer::UpdateDebt(int64_t delta_ms) {
565 uint32_t debt_reduction_bytes = target_rate_kbps_ * delta_ms / 8;
566 if (debt_reduction_bytes >= debt_bytes_) {
567 debt_bytes_ = 0;
568 } else {
569 debt_bytes_ -= debt_reduction_bytes;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000570 }
571}
sprang@webrtc.org70f74f32014-12-17 10:57:10 +0000572
sprangb0fdfea2016-03-01 05:51:16 -0800573void ScreenshareLayers::UpdateHistograms() {
574 if (stats_.first_frame_time_ms_ == -1)
575 return;
576 int64_t duration_sec =
Sebastian Janssone64a6882019-03-01 18:04:07 +0100577 (rtc::TimeMillis() - stats_.first_frame_time_ms_ + 500) / 1000;
sprangb0fdfea2016-03-01 05:51:16 -0800578 if (duration_sec >= metrics::kMinRunTimeInSeconds) {
579 RTC_HISTOGRAM_COUNTS_10000(
580 "WebRTC.Video.Screenshare.Layer0.FrameRate",
581 (stats_.num_tl0_frames_ + (duration_sec / 2)) / duration_sec);
582 RTC_HISTOGRAM_COUNTS_10000(
583 "WebRTC.Video.Screenshare.Layer1.FrameRate",
584 (stats_.num_tl1_frames_ + (duration_sec / 2)) / duration_sec);
585 int total_frames = stats_.num_tl0_frames_ + stats_.num_tl1_frames_;
asapersson58d992e2016-03-29 02:15:06 -0700586 RTC_HISTOGRAM_COUNTS_10000(
587 "WebRTC.Video.Screenshare.FramesPerDrop",
Ilya Nikolaevskiybf352982017-10-02 10:08:25 +0200588 (stats_.num_dropped_frames_ == 0
589 ? 0
590 : total_frames / stats_.num_dropped_frames_));
asapersson58d992e2016-03-29 02:15:06 -0700591 RTC_HISTOGRAM_COUNTS_10000(
592 "WebRTC.Video.Screenshare.FramesPerOvershoot",
593 (stats_.num_overshoots_ == 0 ? 0
594 : total_frames / stats_.num_overshoots_));
sprangb0fdfea2016-03-01 05:51:16 -0800595 if (stats_.num_tl0_frames_ > 0) {
596 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.Screenshare.Layer0.Qp",
597 stats_.tl0_qp_sum_ / stats_.num_tl0_frames_);
598 RTC_HISTOGRAM_COUNTS_10000(
599 "WebRTC.Video.Screenshare.Layer0.TargetBitrate",
600 stats_.tl0_target_bitrate_sum_ / stats_.num_tl0_frames_);
601 }
602 if (stats_.num_tl1_frames_ > 0) {
603 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.Screenshare.Layer1.Qp",
604 stats_.tl1_qp_sum_ / stats_.num_tl1_frames_);
605 RTC_HISTOGRAM_COUNTS_10000(
606 "WebRTC.Video.Screenshare.Layer1.TargetBitrate",
607 stats_.tl1_target_bitrate_sum_ / stats_.num_tl1_frames_);
608 }
609 }
610}
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000611} // namespace webrtc