blob: 2f4b482033985da551b4d9014f7387d6830e8557 [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 Alon979c4422019-04-17 12:53:08 +020085Vp8FrameConfig ScreenshareLayers::NextFrameConfig(size_t stream_index,
86 uint32_t timestamp) {
Elad Aloncde8ab22019-03-20 11:56:20 +010087 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");
philipelda5aa4d2019-04-26 13:37:37 +0200308 generic_frame_info.encoder_buffers.emplace_back(
309 0, /*referenced=*/!is_keyframe, /*updated=*/true);
Erik Språng59021ba2018-10-03 11:05:16 +0200310 } else {
311 int64_t unwrapped_timestamp = time_wrap_handler_.Unwrap(rtp_timestamp);
philipelb19f27a2019-03-28 16:09:52 +0100312 if (dependency_info) {
313 vp8_info.temporalIdx =
314 dependency_info->frame_config.packetizer_temporal_idx;
315 vp8_info.layerSync = dependency_info->frame_config.layer_sync;
316 generic_frame_info.decode_target_indications =
317 dependency_info->decode_target_indications;
Erik Språng59021ba2018-10-03 11:05:16 +0200318 } else {
Elad Alon819661a2019-01-29 17:17:09 +0100319 RTC_DCHECK(is_keyframe);
philipelb19f27a2019-03-28 16:09:52 +0100320 generic_frame_info.decode_target_indications =
321 GenericFrameInfo::DecodeTargetInfo("SS");
Erik Språng59021ba2018-10-03 11:05:16 +0200322 }
Elad Alon819661a2019-01-29 17:17:09 +0100323
Erik Språng59021ba2018-10-03 11:05:16 +0200324 if (is_keyframe) {
philipel9df33532019-03-04 16:37:50 +0100325 vp8_info.temporalIdx = 0;
Erik Språng59021ba2018-10-03 11:05:16 +0200326 last_sync_timestamp_ = unwrapped_timestamp;
philipel9df33532019-03-04 16:37:50 +0100327 vp8_info.layerSync = true;
Erik Språng59021ba2018-10-03 11:05:16 +0200328 layers_[0].state = TemporalLayer::State::kKeyFrame;
329 layers_[1].state = TemporalLayer::State::kKeyFrame;
330 active_layer_ = 1;
philipel9df33532019-03-04 16:37:50 +0100331 info->template_structure =
332 GetTemplateStructure(number_of_temporal_layers_);
Erik Språngdb6335e2019-04-01 16:22:57 +0200333 } else if (active_layer_ >= 0 && layers_[active_layer_].state ==
334 TemporalLayer::State::kKeyFrame) {
335 layers_[active_layer_].state = TemporalLayer::State::kNormal;
Erik Språng59021ba2018-10-03 11:05:16 +0200336 }
Elad Alon819661a2019-01-29 17:17:09 +0100337
philipel9df33532019-03-04 16:37:50 +0100338 vp8_info.useExplicitDependencies = true;
339 RTC_DCHECK_EQ(vp8_info.referencedBuffersCount, 0u);
340 RTC_DCHECK_EQ(vp8_info.updatedBuffersCount, 0u);
Elad Alon819661a2019-01-29 17:17:09 +0100341
342 // Note that |frame_config| is not derefernced if |is_keyframe|,
343 // meaning it's never dereferenced if the optional may be unset.
Niels Möller1f44bc12019-04-09 10:27:34 +0200344 for (int i = 0; i < static_cast<int>(Vp8FrameConfig::Buffer::kCount); ++i) {
philipelda5aa4d2019-04-26 13:37:37 +0200345 bool references = false;
346 bool updates = is_keyframe;
Niels Möller1f44bc12019-04-09 10:27:34 +0200347 if (!is_keyframe && dependency_info->frame_config.References(
348 static_cast<Vp8FrameConfig::Buffer>(i))) {
philipel9df33532019-03-04 16:37:50 +0100349 RTC_DCHECK_LT(vp8_info.referencedBuffersCount,
Elad Alon819661a2019-01-29 17:17:09 +0100350 arraysize(CodecSpecificInfoVP8::referencedBuffers));
philipelda5aa4d2019-04-26 13:37:37 +0200351 references = true;
philipel9df33532019-03-04 16:37:50 +0100352 vp8_info.referencedBuffers[vp8_info.referencedBuffersCount++] = i;
Elad Alon819661a2019-01-29 17:17:09 +0100353 }
354
Niels Möller1f44bc12019-04-09 10:27:34 +0200355 if (is_keyframe || dependency_info->frame_config.Updates(
356 static_cast<Vp8FrameConfig::Buffer>(i))) {
philipel9df33532019-03-04 16:37:50 +0100357 RTC_DCHECK_LT(vp8_info.updatedBuffersCount,
Elad Alon819661a2019-01-29 17:17:09 +0100358 arraysize(CodecSpecificInfoVP8::updatedBuffers));
philipelda5aa4d2019-04-26 13:37:37 +0200359 updates = true;
philipel9df33532019-03-04 16:37:50 +0100360 vp8_info.updatedBuffers[vp8_info.updatedBuffersCount++] = i;
Elad Alon819661a2019-01-29 17:17:09 +0100361 }
philipelda5aa4d2019-04-26 13:37:37 +0200362
363 if (references || updates)
364 generic_frame_info.encoder_buffers.emplace_back(i, references, updates);
Elad Alon819661a2019-01-29 17:17:09 +0100365 }
Erik Språng59021ba2018-10-03 11:05:16 +0200366 }
367
Sebastian Janssone64a6882019-03-01 18:04:07 +0100368 encode_framerate_.Update(1, rtc::TimeMillis());
Erik Språng59021ba2018-10-03 11:05:16 +0200369
370 if (number_of_temporal_layers_ == 1)
371 return;
372
373 RTC_DCHECK_NE(-1, active_layer_);
Erik Språng2c4c9142015-06-24 11:24:44 +0200374 if (layers_[active_layer_].state == TemporalLayer::State::kDropped) {
375 layers_[active_layer_].state = TemporalLayer::State::kQualityBoost;
376 }
377
378 if (qp != -1)
379 layers_[active_layer_].last_qp = qp;
380
381 if (active_layer_ == 0) {
Erik Språng59021ba2018-10-03 11:05:16 +0200382 layers_[0].debt_bytes_ += size_bytes;
383 layers_[1].debt_bytes_ += size_bytes;
sprangb0fdfea2016-03-01 05:51:16 -0800384 ++stats_.num_tl0_frames_;
385 stats_.tl0_target_bitrate_sum_ += layers_[0].target_rate_kbps_;
386 stats_.tl0_qp_sum_ += qp;
Erik Språng2c4c9142015-06-24 11:24:44 +0200387 } else if (active_layer_ == 1) {
Erik Språng59021ba2018-10-03 11:05:16 +0200388 layers_[1].debt_bytes_ += size_bytes;
sprangb0fdfea2016-03-01 05:51:16 -0800389 ++stats_.num_tl1_frames_;
390 stats_.tl1_target_bitrate_sum_ += layers_[1].target_rate_kbps_;
391 stats_.tl1_qp_sum_ += qp;
Erik Språng2c4c9142015-06-24 11:24:44 +0200392 }
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000393}
394
Elad Alon6796ec22019-04-15 10:07:50 +0200395void ScreenshareLayers::OnFrameDropped(size_t stream_index,
396 uint32_t rtp_timestamp) {
397 layers_[active_layer_].state = TemporalLayer::State::kDropped;
398 ++stats_.num_overshoots_;
399}
400
Elad Aloncde8ab22019-03-20 11:56:20 +0100401void ScreenshareLayers::OnPacketLossRateUpdate(float packet_loss_rate) {}
402
403void ScreenshareLayers::OnRttUpdate(int64_t rtt_ms) {}
404
Elad Alon6c371ca2019-04-04 12:28:51 +0200405void ScreenshareLayers::OnLossNotification(
Elad Alon123ee9b2019-04-17 12:48:06 +0200406 const VideoEncoder::LossNotification& loss_notification) {}
Elad Alon6c371ca2019-04-04 12:28:51 +0200407
philipel9df33532019-03-04 16:37:50 +0100408TemplateStructure ScreenshareLayers::GetTemplateStructure(
409 int num_layers) const {
410 RTC_CHECK_LT(num_layers, 3);
411 RTC_CHECK_GT(num_layers, 0);
412
413 TemplateStructure template_structure;
philipel361855b2019-03-28 14:12:10 +0100414 template_structure.num_decode_targets = num_layers;
philipel9df33532019-03-04 16:37:50 +0100415
416 using Builder = GenericFrameInfo::Builder;
417 switch (num_layers) {
418 case 1: {
419 template_structure.templates = {
420 Builder().T(0).Dtis("S").Build(),
421 Builder().T(0).Dtis("S").Fdiffs({1}).Build(),
422 };
423 return template_structure;
424 }
425 case 2: {
426 template_structure.templates = {
427 Builder().T(0).Dtis("SS").Build(),
428 Builder().T(0).Dtis("SS").Fdiffs({1}).Build(),
429 Builder().T(1).Dtis("-S").Fdiffs({1}).Build(),
430 };
431 return template_structure;
432 }
433 default:
434 RTC_NOTREACHED();
435 // To make the compiler happy!
436 return template_structure;
437 }
438}
439
Erik Språng2c4c9142015-06-24 11:24:44 +0200440bool ScreenshareLayers::TimeToSync(int64_t timestamp) const {
sprang2ddb8bd2016-02-04 03:59:52 -0800441 RTC_DCHECK_EQ(1, active_layer_);
henrikg91d6ede2015-09-17 00:24:34 -0700442 RTC_DCHECK_NE(-1, layers_[0].last_qp);
Erik Språng2c4c9142015-06-24 11:24:44 +0200443 if (layers_[1].last_qp == -1) {
444 // First frame in TL1 should only depend on TL0 since there are no
445 // previous frames in TL1.
446 return true;
447 }
448
henrikg91d6ede2015-09-17 00:24:34 -0700449 RTC_DCHECK_NE(-1, last_sync_timestamp_);
Erik Språng2c4c9142015-06-24 11:24:44 +0200450 int64_t timestamp_diff = timestamp - last_sync_timestamp_;
451 if (timestamp_diff > kMaxTimeBetweenSyncs) {
452 // After a certain time, force a sync frame.
453 return true;
454 } else if (timestamp_diff < kMinTimeBetweenSyncs) {
455 // If too soon from previous sync frame, don't issue a new one.
456 return false;
457 }
458 // Issue a sync frame if difference in quality between TL0 and TL1 isn't too
459 // large.
460 if (layers_[0].last_qp - layers_[1].last_qp < kQpDeltaThresholdForSync)
461 return true;
462 return false;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000463}
464
sprangc7805db2016-11-25 08:09:43 -0800465uint32_t ScreenshareLayers::GetCodecTargetBitrateKbps() const {
466 uint32_t target_bitrate_kbps = layers_[0].target_rate_kbps_;
467
468 if (number_of_temporal_layers_ > 1) {
469 // Calculate a codec target bitrate. This may be higher than TL0, gaining
470 // quality at the expense of frame rate at TL0. Constraints:
471 // - TL0 frame rate no less than framerate / kMaxTL0FpsReduction.
472 // - Target rate * kAcceptableTargetOvershoot should not exceed TL1 rate.
473 target_bitrate_kbps =
474 std::min(layers_[0].target_rate_kbps_ * kMaxTL0FpsReduction,
475 layers_[1].target_rate_kbps_ / kAcceptableTargetOvershoot);
476 }
477
478 return std::max(layers_[0].target_rate_kbps_, target_bitrate_kbps);
479}
480
Elad Aloncde8ab22019-03-20 11:56:20 +0100481bool ScreenshareLayers::UpdateConfiguration(size_t stream_index,
482 Vp8EncoderConfig* cfg) {
483 RTC_DCHECK_LT(stream_index, StreamCount());
484
Erik Språngf1414702018-09-12 15:04:08 +0200485 if (min_qp_ == -1 || max_qp_ == -1) {
486 // Store the valid qp range. This must not change during the lifetime of
487 // this class.
488 min_qp_ = cfg->rc_min_quantizer;
489 max_qp_ = cfg->rc_max_quantizer;
490 }
491
Erik Språng08127a92016-11-16 16:41:30 +0100492 bool cfg_updated = false;
sprangc7805db2016-11-25 08:09:43 -0800493 uint32_t target_bitrate_kbps = GetCodecTargetBitrateKbps();
Erik Språng27a457d2018-01-12 11:00:21 +0100494
495 // TODO(sprang): We _really_ need to make an overhaul of this class. :(
496 // If we're dropping frames in order to meet a target framerate, adjust the
497 // bitrate assigned to the encoder so the total average bitrate is correct.
498 float encoder_config_bitrate_kbps = target_bitrate_kbps;
499 if (target_framerate_ && capture_framerate_ &&
500 *target_framerate_ < *capture_framerate_) {
501 encoder_config_bitrate_kbps *=
502 static_cast<float>(*capture_framerate_) / *target_framerate_;
503 }
504
505 if (bitrate_updated_ ||
506 cfg->rc_target_bitrate != encoder_config_bitrate_kbps) {
507 cfg->rc_target_bitrate = encoder_config_bitrate_kbps;
Erik Språng08127a92016-11-16 16:41:30 +0100508
509 // Don't reconfigure qp limits during quality boost frames.
510 if (active_layer_ == -1 ||
511 layers_[active_layer_].state != TemporalLayer::State::kQualityBoost) {
Erik Språng08127a92016-11-16 16:41:30 +0100512 // After a dropped frame, a frame with max qp will be encoded and the
513 // quality will then ramp up from there. To boost the speed of recovery,
sprang916170a2017-05-23 07:47:55 -0700514 // encode the next frame with lower max qp, if there is sufficient
515 // bandwidth to do so without causing excessive delay.
516 // TL0 is the most important to improve since the errors in this layer
517 // will propagate to TL1.
Erik Språng08127a92016-11-16 16:41:30 +0100518 // Currently, reduce max qp by 20% for TL0 and 15% for TL1.
sprang916170a2017-05-23 07:47:55 -0700519 if (layers_[1].target_rate_kbps_ >= kMinBitrateKbpsForQpBoost) {
520 layers_[0].enhanced_max_qp =
521 min_qp_ + (((max_qp_ - min_qp_) * 80) / 100);
522 layers_[1].enhanced_max_qp =
523 min_qp_ + (((max_qp_ - min_qp_) * 85) / 100);
524 } else {
525 layers_[0].enhanced_max_qp = -1;
526 layers_[1].enhanced_max_qp = -1;
527 }
Erik Språng08127a92016-11-16 16:41:30 +0100528 }
529
sprang0ad0de62017-01-11 05:01:32 -0800530 if (capture_framerate_) {
sprangac4a90d2016-12-28 05:58:07 -0800531 int avg_frame_size =
sprang0ad0de62017-01-11 05:01:32 -0800532 (target_bitrate_kbps * 1000) / (8 * *capture_framerate_);
sprang916170a2017-05-23 07:47:55 -0700533 // Allow max debt to be the size of a single optimal frame.
534 // TODO(sprang): Determine if this needs to be adjusted by some factor.
535 // (Lower values may cause more frame drops, higher may lead to queuing
536 // delays.)
537 max_debt_bytes_ = avg_frame_size;
Erik Språng08127a92016-11-16 16:41:30 +0100538 }
539
540 bitrate_updated_ = false;
541 cfg_updated = true;
542 }
543
544 // Don't try to update boosts state if not active yet.
545 if (active_layer_ == -1)
546 return cfg_updated;
547
sprangef7228c2015-08-05 02:01:29 -0700548 if (max_qp_ == -1 || number_of_temporal_layers_ <= 1)
Erik Språng08127a92016-11-16 16:41:30 +0100549 return cfg_updated;
Erik Språng2c4c9142015-06-24 11:24:44 +0200550
551 // If layer is in the quality boost state (following a dropped frame), update
552 // the configuration with the adjusted (lower) qp and set the state back to
553 // normal.
Erik Språngf1414702018-09-12 15:04:08 +0200554 unsigned int adjusted_max_qp = max_qp_; // Set the normal max qp.
555 if (layers_[active_layer_].state == TemporalLayer::State::kQualityBoost) {
556 if (layers_[active_layer_].enhanced_max_qp != -1) {
557 // Bitrate is high enough for quality boost, update max qp.
558 adjusted_max_qp = layers_[active_layer_].enhanced_max_qp;
559 }
560 // Regardless of qp, reset the boost state for the next frame.
Erik Språng2c4c9142015-06-24 11:24:44 +0200561 layers_[active_layer_].state = TemporalLayer::State::kNormal;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000562 }
Erik Språng2c4c9142015-06-24 11:24:44 +0200563
564 if (adjusted_max_qp == cfg->rc_max_quantizer)
Erik Språng08127a92016-11-16 16:41:30 +0100565 return cfg_updated;
Erik Språng2c4c9142015-06-24 11:24:44 +0200566
567 cfg->rc_max_quantizer = adjusted_max_qp;
Erik Språng08127a92016-11-16 16:41:30 +0100568 cfg_updated = true;
sprangc7805db2016-11-25 08:09:43 -0800569
Erik Språng08127a92016-11-16 16:41:30 +0100570 return cfg_updated;
Erik Språng2c4c9142015-06-24 11:24:44 +0200571}
572
573void ScreenshareLayers::TemporalLayer::UpdateDebt(int64_t delta_ms) {
574 uint32_t debt_reduction_bytes = target_rate_kbps_ * delta_ms / 8;
575 if (debt_reduction_bytes >= debt_bytes_) {
576 debt_bytes_ = 0;
577 } else {
578 debt_bytes_ -= debt_reduction_bytes;
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000579 }
580}
sprang@webrtc.org70f74f32014-12-17 10:57:10 +0000581
sprangb0fdfea2016-03-01 05:51:16 -0800582void ScreenshareLayers::UpdateHistograms() {
583 if (stats_.first_frame_time_ms_ == -1)
584 return;
585 int64_t duration_sec =
Sebastian Janssone64a6882019-03-01 18:04:07 +0100586 (rtc::TimeMillis() - stats_.first_frame_time_ms_ + 500) / 1000;
sprangb0fdfea2016-03-01 05:51:16 -0800587 if (duration_sec >= metrics::kMinRunTimeInSeconds) {
588 RTC_HISTOGRAM_COUNTS_10000(
589 "WebRTC.Video.Screenshare.Layer0.FrameRate",
590 (stats_.num_tl0_frames_ + (duration_sec / 2)) / duration_sec);
591 RTC_HISTOGRAM_COUNTS_10000(
592 "WebRTC.Video.Screenshare.Layer1.FrameRate",
593 (stats_.num_tl1_frames_ + (duration_sec / 2)) / duration_sec);
594 int total_frames = stats_.num_tl0_frames_ + stats_.num_tl1_frames_;
asapersson58d992e2016-03-29 02:15:06 -0700595 RTC_HISTOGRAM_COUNTS_10000(
596 "WebRTC.Video.Screenshare.FramesPerDrop",
Ilya Nikolaevskiybf352982017-10-02 10:08:25 +0200597 (stats_.num_dropped_frames_ == 0
598 ? 0
599 : total_frames / stats_.num_dropped_frames_));
asapersson58d992e2016-03-29 02:15:06 -0700600 RTC_HISTOGRAM_COUNTS_10000(
601 "WebRTC.Video.Screenshare.FramesPerOvershoot",
602 (stats_.num_overshoots_ == 0 ? 0
603 : total_frames / stats_.num_overshoots_));
sprangb0fdfea2016-03-01 05:51:16 -0800604 if (stats_.num_tl0_frames_ > 0) {
605 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.Screenshare.Layer0.Qp",
606 stats_.tl0_qp_sum_ / stats_.num_tl0_frames_);
607 RTC_HISTOGRAM_COUNTS_10000(
608 "WebRTC.Video.Screenshare.Layer0.TargetBitrate",
609 stats_.tl0_target_bitrate_sum_ / stats_.num_tl0_frames_);
610 }
611 if (stats_.num_tl1_frames_ > 0) {
612 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.Screenshare.Layer1.Qp",
613 stats_.tl1_qp_sum_ / stats_.num_tl1_frames_);
614 RTC_HISTOGRAM_COUNTS_10000(
615 "WebRTC.Video.Screenshare.Layer1.TargetBitrate",
616 stats_.tl1_target_bitrate_sum_ / stats_.num_tl1_frames_);
617 }
618 }
619}
pbos@webrtc.org9115cde2014-12-09 10:36:40 +0000620} // namespace webrtc