blob: d3f4d426ca0f7e64e7a1522bec491538ebfe99f5 [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 Buffer = Vp8FrameConfig::Buffer;
27using BufferFlags = Vp8FrameConfig::BufferFlags;
28
29constexpr BufferFlags kNone = Vp8FrameConfig::BufferFlags::kNone;
30constexpr BufferFlags kReference = Vp8FrameConfig::BufferFlags::kReference;
31constexpr BufferFlags kUpdate = Vp8FrameConfig::BufferFlags::kUpdate;
32constexpr BufferFlags kReferenceAndUpdate =
33 Vp8FrameConfig::BufferFlags::kReferenceAndUpdate;
34
35constexpr int kOneSecond90Khz = 90000;
36constexpr int kMinTimeBetweenSyncs = kOneSecond90Khz * 2;
37constexpr int kMaxTimeBetweenSyncs = kOneSecond90Khz * 4;
38constexpr int kQpDeltaThresholdForSync = 8;
39constexpr int kMinBitrateKbpsForQpBoost = 500;
Erik Språng59021ba2018-10-03 11:05:16 +020040} // namespace
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000041
sprang@webrtc.org70f74f32014-12-17 10:57:10 +000042const double ScreenshareLayers::kMaxTL0FpsReduction = 2.5;
43const double ScreenshareLayers::kAcceptableTargetOvershoot = 2.0;
44
sprang429600d2017-01-26 06:12:26 -080045constexpr int ScreenshareLayers::kMaxNumTemporalLayers;
46
sprangafe1f742016-04-12 02:45:13 -070047// Always emit a frame with certain interval, even if bitrate targets have
sprang916170a2017-05-23 07:47:55 -070048// been exceeded. This prevents needless keyframe requests.
sprang6c4bbfa2017-05-30 10:08:23 -070049const int ScreenshareLayers::kMaxFrameIntervalMs = 2750;
sprangafe1f742016-04-12 02:45:13 -070050
Sebastian Janssone64a6882019-03-01 18:04:07 +010051ScreenshareLayers::ScreenshareLayers(int num_temporal_layers)
52 : number_of_temporal_layers_(
sprang429600d2017-01-26 06:12:26 -080053 std::min(kMaxNumTemporalLayers, num_temporal_layers)),
Erik Språng2c4c9142015-06-24 11:24:44 +020054 active_layer_(-1),
55 last_timestamp_(-1),
56 last_sync_timestamp_(-1),
sprangafe1f742016-04-12 02:45:13 -070057 last_emitted_tl0_timestamp_(-1),
Erik Språng27a457d2018-01-12 11:00:21 +010058 last_frame_time_ms_(-1),
Erik Språng2c4c9142015-06-24 11:24:44 +020059 min_qp_(-1),
60 max_qp_(-1),
61 max_debt_bytes_(0),
sprangac4a90d2016-12-28 05:58:07 -080062 encode_framerate_(1000.0f, 1000.0f), // 1 second window, second scale.
Erik Språng59021ba2018-10-03 11:05:16 +020063 bitrate_updated_(false),
64 checker_(TemporalLayersChecker::CreateTemporalLayersChecker(
Erik Språng4529fbc2018-10-12 10:30:31 +020065 Vp8TemporalLayersType::kBitrateDynamic,
Erik Språng59021ba2018-10-03 11:05:16 +020066 num_temporal_layers)) {
sprang429600d2017-01-26 06:12:26 -080067 RTC_CHECK_GT(number_of_temporal_layers_, 0);
68 RTC_CHECK_LE(number_of_temporal_layers_, kMaxNumTemporalLayers);
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000069}
70
sprangb0fdfea2016-03-01 05:51:16 -080071ScreenshareLayers::~ScreenshareLayers() {
72 UpdateHistograms();
73}
74
Erik Språngfb2a66a2018-09-10 10:48:01 +020075bool ScreenshareLayers::SupportsEncoderFrameDropping() const {
76 // Frame dropping is handled internally by this class.
77 return false;
78}
79
Elad Alon411b49b2019-01-29 14:05:55 +010080Vp8FrameConfig ScreenshareLayers::UpdateLayerConfig(uint32_t timestamp) {
Erik Språng59021ba2018-10-03 11:05:16 +020081 auto it = pending_frame_configs_.find(timestamp);
82 if (it != pending_frame_configs_.end()) {
83 // Drop and re-encode, reuse the previous config.
84 return it->second;
85 }
86
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000087 if (number_of_temporal_layers_ <= 1) {
88 // No flags needed for 1 layer screenshare.
Peter Boström1436c832017-03-27 15:01:49 -040089 // TODO(pbos): Consider updating only last, and not all buffers.
Elad Alon411b49b2019-01-29 14:05:55 +010090 Vp8FrameConfig tl_config(kReferenceAndUpdate, kReferenceAndUpdate,
91 kReferenceAndUpdate);
Erik Språng59021ba2018-10-03 11:05:16 +020092 pending_frame_configs_[timestamp] = tl_config;
pbos51f083c2017-05-04 06:39:04 -070093 return tl_config;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +000094 }
Erik Språng2c4c9142015-06-24 11:24:44 +020095
Sebastian Janssone64a6882019-03-01 18:04:07 +010096 const int64_t now_ms = rtc::TimeMillis();
sprangb0fdfea2016-03-01 05:51:16 -080097
Erik Språng2c4c9142015-06-24 11:24:44 +020098 int64_t unwrapped_timestamp = time_wrap_handler_.Unwrap(timestamp);
sprang916170a2017-05-23 07:47:55 -070099 int64_t ts_diff;
100 if (last_timestamp_ == -1) {
101 ts_diff = kOneSecond90Khz / capture_framerate_.value_or(*target_framerate_);
102 } else {
103 ts_diff = unwrapped_timestamp - last_timestamp_;
104 }
Erik Språng27a457d2018-01-12 11:00:21 +0100105
106 if (target_framerate_) {
107 // If input frame rate exceeds target frame rate, either over a one second
108 // averaging window, or if frame interval is below 90% of desired value,
109 // drop frame.
Erik Språng27a457d2018-01-12 11:00:21 +0100110 if (encode_framerate_.Rate(now_ms).value_or(0) > *target_framerate_)
Elad Alon411b49b2019-01-29 14:05:55 +0100111 return Vp8FrameConfig(kNone, kNone, kNone);
Erik Språng27a457d2018-01-12 11:00:21 +0100112
Erik Språngdb9e9d52018-01-22 09:23:11 -0800113 // Primarily check if frame interval is too short using frame timestamps,
114 // as if they are correct they won't be affected by queuing in webrtc.
115 const int64_t expected_frame_interval_90khz =
116 kOneSecond90Khz / *target_framerate_;
117 if (last_timestamp_ != -1 && ts_diff > 0) {
118 if (ts_diff < 85 * expected_frame_interval_90khz / 100) {
Elad Alon411b49b2019-01-29 14:05:55 +0100119 return Vp8FrameConfig(kNone, kNone, kNone);
Erik Språngdb9e9d52018-01-22 09:23:11 -0800120 }
121 } else {
122 // Timestamps looks off, use realtime clock here instead.
123 const int64_t expected_frame_interval_ms = 1000 / *target_framerate_;
124 if (last_frame_time_ms_ != -1 &&
125 now_ms - last_frame_time_ms_ <
126 (85 * expected_frame_interval_ms) / 100) {
Elad Alon411b49b2019-01-29 14:05:55 +0100127 return Vp8FrameConfig(kNone, kNone, kNone);
Erik Språngdb9e9d52018-01-22 09:23:11 -0800128 }
Erik Språng27a457d2018-01-12 11:00:21 +0100129 }
130 }
131
132 if (stats_.first_frame_time_ms_ == -1)
133 stats_.first_frame_time_ms_ = now_ms;
134
sprang916170a2017-05-23 07:47:55 -0700135 // Make sure both frame droppers leak out bits.
136 layers_[0].UpdateDebt(ts_diff / 90);
137 layers_[1].UpdateDebt(ts_diff / 90);
138 last_timestamp_ = timestamp;
Erik Språng27a457d2018-01-12 11:00:21 +0100139 last_frame_time_ms_ = now_ms;
sprang916170a2017-05-23 07:47:55 -0700140
141 TemporalLayerState layer_state = TemporalLayerState::kDrop;
142
Erik Språng2c4c9142015-06-24 11:24:44 +0200143 if (active_layer_ == -1 ||
144 layers_[active_layer_].state != TemporalLayer::State::kDropped) {
sprangafe1f742016-04-12 02:45:13 -0700145 if (last_emitted_tl0_timestamp_ != -1 &&
146 (unwrapped_timestamp - last_emitted_tl0_timestamp_) / 90 >
147 kMaxFrameIntervalMs) {
148 // Too long time has passed since the last frame was emitted, cancel
149 // enough debt to allow a single frame.
150 layers_[0].debt_bytes_ = max_debt_bytes_ - 1;
151 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200152 if (layers_[0].debt_bytes_ > max_debt_bytes_) {
153 // Must drop TL0, encode TL1 instead.
154 if (layers_[1].debt_bytes_ > max_debt_bytes_) {
155 // Must drop both TL0 and TL1.
156 active_layer_ = -1;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000157 } else {
Erik Språng2c4c9142015-06-24 11:24:44 +0200158 active_layer_ = 1;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000159 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200160 } else {
161 active_layer_ = 0;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000162 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000163 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200164
165 switch (active_layer_) {
166 case 0:
sprang916170a2017-05-23 07:47:55 -0700167 layer_state = TemporalLayerState::kTl0;
sprangafe1f742016-04-12 02:45:13 -0700168 last_emitted_tl0_timestamp_ = unwrapped_timestamp;
Erik Språng2c4c9142015-06-24 11:24:44 +0200169 break;
170 case 1:
sprangf03ea042017-07-13 03:53:51 -0700171 if (layers_[1].state != TemporalLayer::State::kDropped) {
Erik Språngb75d6b82018-08-13 16:05:33 +0200172 if (TimeToSync(unwrapped_timestamp) ||
173 layers_[1].state == TemporalLayer::State::kKeyFrame) {
sprangf03ea042017-07-13 03:53:51 -0700174 last_sync_timestamp_ = unwrapped_timestamp;
175 layer_state = TemporalLayerState::kTl1Sync;
176 } else {
177 layer_state = TemporalLayerState::kTl1;
178 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200179 } else {
sprangf03ea042017-07-13 03:53:51 -0700180 layer_state = last_sync_timestamp_ == unwrapped_timestamp
181 ? TemporalLayerState::kTl1Sync
182 : TemporalLayerState::kTl1;
Erik Språng2c4c9142015-06-24 11:24:44 +0200183 }
184 break;
185 case -1:
sprang916170a2017-05-23 07:47:55 -0700186 layer_state = TemporalLayerState::kDrop;
sprangb0fdfea2016-03-01 05:51:16 -0800187 ++stats_.num_dropped_frames_;
Erik Språng2c4c9142015-06-24 11:24:44 +0200188 break;
189 default:
Erik Språng2c4c9142015-06-24 11:24:44 +0200190 RTC_NOTREACHED();
191 }
192
Elad Alon411b49b2019-01-29 14:05:55 +0100193 Vp8FrameConfig tl_config;
Peter Boström1436c832017-03-27 15:01:49 -0400194 // TODO(pbos): Consider referencing but not updating the 'alt' buffer for all
195 // layers.
196 switch (layer_state) {
sprang916170a2017-05-23 07:47:55 -0700197 case TemporalLayerState::kDrop:
Elad Alon411b49b2019-01-29 14:05:55 +0100198 tl_config = Vp8FrameConfig(kNone, kNone, kNone);
pbos51f083c2017-05-04 06:39:04 -0700199 break;
sprang916170a2017-05-23 07:47:55 -0700200 case TemporalLayerState::kTl0:
Peter Boström1436c832017-03-27 15:01:49 -0400201 // TL0 only references and updates 'last'.
Elad Alon411b49b2019-01-29 14:05:55 +0100202 tl_config = Vp8FrameConfig(kReferenceAndUpdate, kNone, kNone);
pbos1777c5f2017-07-19 17:04:02 -0700203 tl_config.packetizer_temporal_idx = 0;
pbos51f083c2017-05-04 06:39:04 -0700204 break;
sprang916170a2017-05-23 07:47:55 -0700205 case TemporalLayerState::kTl1:
Peter Boström1436c832017-03-27 15:01:49 -0400206 // TL1 references both 'last' and 'golden' but only updates 'golden'.
Elad Alon411b49b2019-01-29 14:05:55 +0100207 tl_config = Vp8FrameConfig(kReference, kReferenceAndUpdate, kNone);
pbos1777c5f2017-07-19 17:04:02 -0700208 tl_config.packetizer_temporal_idx = 1;
pbos51f083c2017-05-04 06:39:04 -0700209 break;
sprang916170a2017-05-23 07:47:55 -0700210 case TemporalLayerState::kTl1Sync:
Peter Boström1436c832017-03-27 15:01:49 -0400211 // Predict from only TL0 to allow participants to switch to the high
212 // bitrate stream. Updates 'golden' so that TL1 can continue to refer to
213 // and update 'golden' from this point on.
Elad Alon411b49b2019-01-29 14:05:55 +0100214 tl_config = Vp8FrameConfig(kReference, kUpdate, kNone);
pbos1777c5f2017-07-19 17:04:02 -0700215 tl_config.packetizer_temporal_idx = 1;
pbos51f083c2017-05-04 06:39:04 -0700216 break;
Peter Boström1436c832017-03-27 15:01:49 -0400217 }
pbos51f083c2017-05-04 06:39:04 -0700218
pbos1777c5f2017-07-19 17:04:02 -0700219 tl_config.layer_sync = layer_state == TemporalLayerState::kTl1Sync;
Erik Språng59021ba2018-10-03 11:05:16 +0200220 pending_frame_configs_[timestamp] = tl_config;
pbos51f083c2017-05-04 06:39:04 -0700221 return tl_config;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000222}
223
Erik Språngbb60a3a2018-03-19 18:25:10 +0100224void ScreenshareLayers::OnRatesUpdated(
225 const std::vector<uint32_t>& bitrates_bps,
226 int framerate_fps) {
227 RTC_DCHECK_GT(framerate_fps, 0);
228 RTC_DCHECK_GE(bitrates_bps.size(), 1);
229 RTC_DCHECK_LE(bitrates_bps.size(), 2);
230
231 // |bitrates_bps| uses individual rates per layer, but we want to use the
232 // accumulated rate here.
233 uint32_t tl0_kbps = bitrates_bps[0] / 1000;
234 uint32_t tl1_kbps = tl0_kbps;
235 if (bitrates_bps.size() > 1) {
236 tl1_kbps += bitrates_bps[1] / 1000;
237 }
238
sprangac4a90d2016-12-28 05:58:07 -0800239 if (!target_framerate_) {
Erik Språngbb60a3a2018-03-19 18:25:10 +0100240 // First OnRatesUpdated() is called during construction, with the
241 // configured targets as parameters.
242 target_framerate_ = framerate_fps;
sprang0ad0de62017-01-11 05:01:32 -0800243 capture_framerate_ = target_framerate_;
sprangac4a90d2016-12-28 05:58:07 -0800244 bitrate_updated_ = true;
245 } else {
Erik Språnge624d072018-04-11 16:47:27 +0200246 if ((capture_framerate_ &&
247 framerate_fps != static_cast<int>(*capture_framerate_)) ||
248 (tl0_kbps != layers_[0].target_rate_kbps_) ||
249 (tl1_kbps != layers_[1].target_rate_kbps_)) {
250 bitrate_updated_ = true;
251 }
Erik Språngbb60a3a2018-03-19 18:25:10 +0100252
253 if (framerate_fps < 0) {
sprang0ad0de62017-01-11 05:01:32 -0800254 capture_framerate_.reset();
sprangac4a90d2016-12-28 05:58:07 -0800255 } else {
Erik Språngbb60a3a2018-03-19 18:25:10 +0100256 capture_framerate_ = framerate_fps;
sprangac4a90d2016-12-28 05:58:07 -0800257 }
258 }
259
Erik Språngbb60a3a2018-03-19 18:25:10 +0100260 layers_[0].target_rate_kbps_ = tl0_kbps;
261 layers_[1].target_rate_kbps_ = tl1_kbps;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000262}
263
Erik Språng59021ba2018-10-03 11:05:16 +0200264void ScreenshareLayers::OnEncodeDone(uint32_t rtp_timestamp,
265 size_t size_bytes,
266 bool is_keyframe,
267 int qp,
268 CodecSpecificInfoVP8* vp8_info) {
269 if (size_bytes == 0) {
Erik Språng2c4c9142015-06-24 11:24:44 +0200270 layers_[active_layer_].state = TemporalLayer::State::kDropped;
sprangb0fdfea2016-03-01 05:51:16 -0800271 ++stats_.num_overshoots_;
Erik Språng2c4c9142015-06-24 11:24:44 +0200272 return;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000273 }
sprangef7228c2015-08-05 02:01:29 -0700274
Elad Alon411b49b2019-01-29 14:05:55 +0100275 absl::optional<Vp8FrameConfig> frame_config;
Erik Språng59021ba2018-10-03 11:05:16 +0200276 auto it = pending_frame_configs_.find(rtp_timestamp);
277 if (it != pending_frame_configs_.end()) {
278 frame_config = it->second;
279 pending_frame_configs_.erase(it);
280
281 if (checker_) {
282 RTC_DCHECK(checker_->CheckTemporalConfig(is_keyframe, *frame_config));
283 }
284 }
285
286 if (number_of_temporal_layers_ == 1) {
287 vp8_info->temporalIdx = kNoTemporalIdx;
288 vp8_info->layerSync = false;
289 } else {
290 int64_t unwrapped_timestamp = time_wrap_handler_.Unwrap(rtp_timestamp);
291 if (frame_config) {
292 vp8_info->temporalIdx = frame_config->packetizer_temporal_idx;
293 vp8_info->layerSync = frame_config->layer_sync;
294 } else {
Elad Alon819661a2019-01-29 17:17:09 +0100295 RTC_DCHECK(is_keyframe);
Erik Språng59021ba2018-10-03 11:05:16 +0200296 }
Elad Alon819661a2019-01-29 17:17:09 +0100297
Erik Språng59021ba2018-10-03 11:05:16 +0200298 if (is_keyframe) {
299 vp8_info->temporalIdx = 0;
300 last_sync_timestamp_ = unwrapped_timestamp;
301 vp8_info->layerSync = true;
302 layers_[0].state = TemporalLayer::State::kKeyFrame;
303 layers_[1].state = TemporalLayer::State::kKeyFrame;
304 active_layer_ = 1;
305 }
Elad Alon819661a2019-01-29 17:17:09 +0100306
307 vp8_info->useExplicitDependencies = true;
308 RTC_DCHECK_EQ(vp8_info->referencedBuffersCount, 0u);
309 RTC_DCHECK_EQ(vp8_info->updatedBuffersCount, 0u);
310
311 // Note that |frame_config| is not derefernced if |is_keyframe|,
312 // meaning it's never dereferenced if the optional may be unset.
313 for (int i = 0; i < static_cast<int>(Buffer::kCount); ++i) {
314 if (!is_keyframe && frame_config->References(static_cast<Buffer>(i))) {
315 RTC_DCHECK_LT(vp8_info->referencedBuffersCount,
316 arraysize(CodecSpecificInfoVP8::referencedBuffers));
317 vp8_info->referencedBuffers[vp8_info->referencedBuffersCount++] = i;
318 }
319
320 if (is_keyframe || frame_config->Updates(static_cast<Buffer>(i))) {
321 RTC_DCHECK_LT(vp8_info->updatedBuffersCount,
322 arraysize(CodecSpecificInfoVP8::updatedBuffers));
323 vp8_info->updatedBuffers[vp8_info->updatedBuffersCount++] = i;
324 }
325 }
Erik Språng59021ba2018-10-03 11:05:16 +0200326 }
327
Sebastian Janssone64a6882019-03-01 18:04:07 +0100328 encode_framerate_.Update(1, rtc::TimeMillis());
Erik Språng59021ba2018-10-03 11:05:16 +0200329
330 if (number_of_temporal_layers_ == 1)
331 return;
332
333 RTC_DCHECK_NE(-1, active_layer_);
Erik Språng2c4c9142015-06-24 11:24:44 +0200334 if (layers_[active_layer_].state == TemporalLayer::State::kDropped) {
335 layers_[active_layer_].state = TemporalLayer::State::kQualityBoost;
336 }
337
338 if (qp != -1)
339 layers_[active_layer_].last_qp = qp;
340
341 if (active_layer_ == 0) {
Erik Språng59021ba2018-10-03 11:05:16 +0200342 layers_[0].debt_bytes_ += size_bytes;
343 layers_[1].debt_bytes_ += size_bytes;
sprangb0fdfea2016-03-01 05:51:16 -0800344 ++stats_.num_tl0_frames_;
345 stats_.tl0_target_bitrate_sum_ += layers_[0].target_rate_kbps_;
346 stats_.tl0_qp_sum_ += qp;
Erik Språng2c4c9142015-06-24 11:24:44 +0200347 } else if (active_layer_ == 1) {
Erik Språng59021ba2018-10-03 11:05:16 +0200348 layers_[1].debt_bytes_ += size_bytes;
sprangb0fdfea2016-03-01 05:51:16 -0800349 ++stats_.num_tl1_frames_;
350 stats_.tl1_target_bitrate_sum_ += layers_[1].target_rate_kbps_;
351 stats_.tl1_qp_sum_ += qp;
Erik Språng2c4c9142015-06-24 11:24:44 +0200352 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000353}
354
Erik Språng2c4c9142015-06-24 11:24:44 +0200355bool ScreenshareLayers::TimeToSync(int64_t timestamp) const {
sprang2ddb8bd2016-02-04 03:59:52 -0800356 RTC_DCHECK_EQ(1, active_layer_);
henrikg91d6ede2015-09-17 00:24:34 -0700357 RTC_DCHECK_NE(-1, layers_[0].last_qp);
Erik Språng2c4c9142015-06-24 11:24:44 +0200358 if (layers_[1].last_qp == -1) {
359 // First frame in TL1 should only depend on TL0 since there are no
360 // previous frames in TL1.
361 return true;
362 }
363
henrikg91d6ede2015-09-17 00:24:34 -0700364 RTC_DCHECK_NE(-1, last_sync_timestamp_);
Erik Språng2c4c9142015-06-24 11:24:44 +0200365 int64_t timestamp_diff = timestamp - last_sync_timestamp_;
366 if (timestamp_diff > kMaxTimeBetweenSyncs) {
367 // After a certain time, force a sync frame.
368 return true;
369 } else if (timestamp_diff < kMinTimeBetweenSyncs) {
370 // If too soon from previous sync frame, don't issue a new one.
371 return false;
372 }
373 // Issue a sync frame if difference in quality between TL0 and TL1 isn't too
374 // large.
375 if (layers_[0].last_qp - layers_[1].last_qp < kQpDeltaThresholdForSync)
376 return true;
377 return false;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000378}
379
sprangc7805db2016-11-25 08:09:43 -0800380uint32_t ScreenshareLayers::GetCodecTargetBitrateKbps() const {
381 uint32_t target_bitrate_kbps = layers_[0].target_rate_kbps_;
382
383 if (number_of_temporal_layers_ > 1) {
384 // Calculate a codec target bitrate. This may be higher than TL0, gaining
385 // quality at the expense of frame rate at TL0. Constraints:
386 // - TL0 frame rate no less than framerate / kMaxTL0FpsReduction.
387 // - Target rate * kAcceptableTargetOvershoot should not exceed TL1 rate.
388 target_bitrate_kbps =
389 std::min(layers_[0].target_rate_kbps_ * kMaxTL0FpsReduction,
390 layers_[1].target_rate_kbps_ / kAcceptableTargetOvershoot);
391 }
392
393 return std::max(layers_[0].target_rate_kbps_, target_bitrate_kbps);
394}
395
Anders Carlssonbeabdcb2018-01-24 10:25:15 +0100396bool ScreenshareLayers::UpdateConfiguration(Vp8EncoderConfig* cfg) {
Erik Språngf1414702018-09-12 15:04:08 +0200397 if (min_qp_ == -1 || max_qp_ == -1) {
398 // Store the valid qp range. This must not change during the lifetime of
399 // this class.
400 min_qp_ = cfg->rc_min_quantizer;
401 max_qp_ = cfg->rc_max_quantizer;
402 }
403
Erik Språng08127a92016-11-16 16:41:30 +0100404 bool cfg_updated = false;
sprangc7805db2016-11-25 08:09:43 -0800405 uint32_t target_bitrate_kbps = GetCodecTargetBitrateKbps();
Erik Språng27a457d2018-01-12 11:00:21 +0100406
407 // TODO(sprang): We _really_ need to make an overhaul of this class. :(
408 // If we're dropping frames in order to meet a target framerate, adjust the
409 // bitrate assigned to the encoder so the total average bitrate is correct.
410 float encoder_config_bitrate_kbps = target_bitrate_kbps;
411 if (target_framerate_ && capture_framerate_ &&
412 *target_framerate_ < *capture_framerate_) {
413 encoder_config_bitrate_kbps *=
414 static_cast<float>(*capture_framerate_) / *target_framerate_;
415 }
416
417 if (bitrate_updated_ ||
418 cfg->rc_target_bitrate != encoder_config_bitrate_kbps) {
419 cfg->rc_target_bitrate = encoder_config_bitrate_kbps;
Erik Språng08127a92016-11-16 16:41:30 +0100420
421 // Don't reconfigure qp limits during quality boost frames.
422 if (active_layer_ == -1 ||
423 layers_[active_layer_].state != TemporalLayer::State::kQualityBoost) {
Erik Språng08127a92016-11-16 16:41:30 +0100424 // After a dropped frame, a frame with max qp will be encoded and the
425 // quality will then ramp up from there. To boost the speed of recovery,
sprang916170a2017-05-23 07:47:55 -0700426 // encode the next frame with lower max qp, if there is sufficient
427 // bandwidth to do so without causing excessive delay.
428 // TL0 is the most important to improve since the errors in this layer
429 // will propagate to TL1.
Erik Språng08127a92016-11-16 16:41:30 +0100430 // Currently, reduce max qp by 20% for TL0 and 15% for TL1.
sprang916170a2017-05-23 07:47:55 -0700431 if (layers_[1].target_rate_kbps_ >= kMinBitrateKbpsForQpBoost) {
432 layers_[0].enhanced_max_qp =
433 min_qp_ + (((max_qp_ - min_qp_) * 80) / 100);
434 layers_[1].enhanced_max_qp =
435 min_qp_ + (((max_qp_ - min_qp_) * 85) / 100);
436 } else {
437 layers_[0].enhanced_max_qp = -1;
438 layers_[1].enhanced_max_qp = -1;
439 }
Erik Språng08127a92016-11-16 16:41:30 +0100440 }
441
sprang0ad0de62017-01-11 05:01:32 -0800442 if (capture_framerate_) {
sprangac4a90d2016-12-28 05:58:07 -0800443 int avg_frame_size =
sprang0ad0de62017-01-11 05:01:32 -0800444 (target_bitrate_kbps * 1000) / (8 * *capture_framerate_);
sprang916170a2017-05-23 07:47:55 -0700445 // Allow max debt to be the size of a single optimal frame.
446 // TODO(sprang): Determine if this needs to be adjusted by some factor.
447 // (Lower values may cause more frame drops, higher may lead to queuing
448 // delays.)
449 max_debt_bytes_ = avg_frame_size;
Erik Språng08127a92016-11-16 16:41:30 +0100450 }
451
452 bitrate_updated_ = false;
453 cfg_updated = true;
454 }
455
456 // Don't try to update boosts state if not active yet.
457 if (active_layer_ == -1)
458 return cfg_updated;
459
sprangef7228c2015-08-05 02:01:29 -0700460 if (max_qp_ == -1 || number_of_temporal_layers_ <= 1)
Erik Språng08127a92016-11-16 16:41:30 +0100461 return cfg_updated;
Erik Språng2c4c9142015-06-24 11:24:44 +0200462
463 // If layer is in the quality boost state (following a dropped frame), update
464 // the configuration with the adjusted (lower) qp and set the state back to
465 // normal.
Erik Språngf1414702018-09-12 15:04:08 +0200466 unsigned int adjusted_max_qp = max_qp_; // Set the normal max qp.
467 if (layers_[active_layer_].state == TemporalLayer::State::kQualityBoost) {
468 if (layers_[active_layer_].enhanced_max_qp != -1) {
469 // Bitrate is high enough for quality boost, update max qp.
470 adjusted_max_qp = layers_[active_layer_].enhanced_max_qp;
471 }
472 // Regardless of qp, reset the boost state for the next frame.
Erik Språng2c4c9142015-06-24 11:24:44 +0200473 layers_[active_layer_].state = TemporalLayer::State::kNormal;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000474 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200475
476 if (adjusted_max_qp == cfg->rc_max_quantizer)
Erik Språng08127a92016-11-16 16:41:30 +0100477 return cfg_updated;
Erik Språng2c4c9142015-06-24 11:24:44 +0200478
479 cfg->rc_max_quantizer = adjusted_max_qp;
Erik Språng08127a92016-11-16 16:41:30 +0100480 cfg_updated = true;
sprangc7805db2016-11-25 08:09:43 -0800481
Erik Språng08127a92016-11-16 16:41:30 +0100482 return cfg_updated;
Erik Språng2c4c9142015-06-24 11:24:44 +0200483}
484
485void ScreenshareLayers::TemporalLayer::UpdateDebt(int64_t delta_ms) {
486 uint32_t debt_reduction_bytes = target_rate_kbps_ * delta_ms / 8;
487 if (debt_reduction_bytes >= debt_bytes_) {
488 debt_bytes_ = 0;
489 } else {
490 debt_bytes_ -= debt_reduction_bytes;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000491 }
492}
sprang@webrtc.org70f74f32014-12-17 10:57:10 +0000493
sprangb0fdfea2016-03-01 05:51:16 -0800494void ScreenshareLayers::UpdateHistograms() {
495 if (stats_.first_frame_time_ms_ == -1)
496 return;
497 int64_t duration_sec =
Sebastian Janssone64a6882019-03-01 18:04:07 +0100498 (rtc::TimeMillis() - stats_.first_frame_time_ms_ + 500) / 1000;
sprangb0fdfea2016-03-01 05:51:16 -0800499 if (duration_sec >= metrics::kMinRunTimeInSeconds) {
500 RTC_HISTOGRAM_COUNTS_10000(
501 "WebRTC.Video.Screenshare.Layer0.FrameRate",
502 (stats_.num_tl0_frames_ + (duration_sec / 2)) / duration_sec);
503 RTC_HISTOGRAM_COUNTS_10000(
504 "WebRTC.Video.Screenshare.Layer1.FrameRate",
505 (stats_.num_tl1_frames_ + (duration_sec / 2)) / duration_sec);
506 int total_frames = stats_.num_tl0_frames_ + stats_.num_tl1_frames_;
asapersson58d992e2016-03-29 02:15:06 -0700507 RTC_HISTOGRAM_COUNTS_10000(
508 "WebRTC.Video.Screenshare.FramesPerDrop",
Ilya Nikolaevskiybf352982017-10-02 10:08:25 +0200509 (stats_.num_dropped_frames_ == 0
510 ? 0
511 : total_frames / stats_.num_dropped_frames_));
asapersson58d992e2016-03-29 02:15:06 -0700512 RTC_HISTOGRAM_COUNTS_10000(
513 "WebRTC.Video.Screenshare.FramesPerOvershoot",
514 (stats_.num_overshoots_ == 0 ? 0
515 : total_frames / stats_.num_overshoots_));
sprangb0fdfea2016-03-01 05:51:16 -0800516 if (stats_.num_tl0_frames_ > 0) {
517 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.Screenshare.Layer0.Qp",
518 stats_.tl0_qp_sum_ / stats_.num_tl0_frames_);
519 RTC_HISTOGRAM_COUNTS_10000(
520 "WebRTC.Video.Screenshare.Layer0.TargetBitrate",
521 stats_.tl0_target_bitrate_sum_ / stats_.num_tl0_frames_);
522 }
523 if (stats_.num_tl1_frames_ > 0) {
524 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.Screenshare.Layer1.Qp",
525 stats_.tl1_qp_sum_ / stats_.num_tl1_frames_);
526 RTC_HISTOGRAM_COUNTS_10000(
527 "WebRTC.Video.Screenshare.Layer1.TargetBitrate",
528 stats_.tl1_target_bitrate_sum_ / stats_.num_tl1_frames_);
529 }
530 }
531}
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000532} // namespace webrtc