blob: 5fa7434acdff4e9f5594ae62c0897546ebe80c6f [file] [log] [blame]
Erik Språng7ca375c2019-02-06 16:20:17 +01001/*
2 * Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "video/encoder_bitrate_adjuster.h"
12
13#include <algorithm>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020014#include <memory>
Erik Språng3d11e2f2019-04-15 14:48:30 +020015#include <vector>
Erik Språng7ca375c2019-02-06 16:20:17 +010016
Erik Språng3d11e2f2019-04-15 14:48:30 +020017#include "rtc_base/experiments/rate_control_settings.h"
Erik Språng7ca375c2019-02-06 16:20:17 +010018#include "rtc_base/logging.h"
19#include "rtc_base/time_utils.h"
Erik Språng3d11e2f2019-04-15 14:48:30 +020020#include "system_wrappers/include/field_trial.h"
Erik Språng7ca375c2019-02-06 16:20:17 +010021
22namespace webrtc {
Erik Språng3d11e2f2019-04-15 14:48:30 +020023namespace {
24// Helper struct with metadata for a single spatial layer.
25struct LayerRateInfo {
26 double link_utilization_factor = 0.0;
27 double media_utilization_factor = 0.0;
28 DataRate target_rate = DataRate::Zero();
Erik Språng7ca375c2019-02-06 16:20:17 +010029
Erik Språng3d11e2f2019-04-15 14:48:30 +020030 DataRate WantedOvershoot() const {
31 // If there is headroom, allow bitrate to go up to media rate limit.
32 // Still limit media utilization to 1.0, so we don't overshoot over long
33 // runs even if we have headroom.
34 const double max_media_utilization =
35 std::max(1.0, media_utilization_factor);
36 if (link_utilization_factor > max_media_utilization) {
37 return (link_utilization_factor - max_media_utilization) * target_rate;
38 }
39 return DataRate::Zero();
40 }
41};
42} // namespace
Erik Språng7ca375c2019-02-06 16:20:17 +010043constexpr int64_t EncoderBitrateAdjuster::kWindowSizeMs;
44constexpr size_t EncoderBitrateAdjuster::kMinFramesSinceLayoutChange;
45constexpr double EncoderBitrateAdjuster::kDefaultUtilizationFactor;
46
47EncoderBitrateAdjuster::EncoderBitrateAdjuster(const VideoCodec& codec_settings)
Erik Språng3d11e2f2019-04-15 14:48:30 +020048 : utilize_bandwidth_headroom_(RateControlSettings::ParseFromFieldTrials()
49 .BitrateAdjusterCanUseNetworkHeadroom()),
Erik Språng7ca375c2019-02-06 16:20:17 +010050 frames_since_layout_change_(0),
51 min_bitrates_bps_{} {
52 if (codec_settings.codecType == VideoCodecType::kVideoCodecVP9) {
53 for (size_t si = 0; si < codec_settings.VP9().numberOfSpatialLayers; ++si) {
54 if (codec_settings.spatialLayers[si].active) {
55 min_bitrates_bps_[si] =
56 std::max(codec_settings.minBitrate * 1000,
57 codec_settings.spatialLayers[si].minBitrate * 1000);
58 }
59 }
60 } else {
61 for (size_t si = 0; si < codec_settings.numberOfSimulcastStreams; ++si) {
62 if (codec_settings.simulcastStream[si].active) {
63 min_bitrates_bps_[si] =
64 std::max(codec_settings.minBitrate * 1000,
65 codec_settings.simulcastStream[si].minBitrate * 1000);
66 }
67 }
68 }
69}
70
71EncoderBitrateAdjuster::~EncoderBitrateAdjuster() = default;
72
73VideoBitrateAllocation EncoderBitrateAdjuster::AdjustRateAllocation(
Erik Språng3d11e2f2019-04-15 14:48:30 +020074 const VideoEncoder::RateControlParameters& rates) {
75 current_rate_control_parameters_ = rates;
Erik Språng7ca375c2019-02-06 16:20:17 +010076
77 // First check that overshoot detectors exist, and store per spatial layer
78 // how many active temporal layers we have.
79 size_t active_tls_[kMaxSpatialLayers] = {};
80 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
81 active_tls_[si] = 0;
82 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
83 // Layer is enabled iff it has both positive bitrate and framerate target.
Erik Språng3d11e2f2019-04-15 14:48:30 +020084 if (rates.bitrate.GetBitrate(si, ti) > 0 &&
Erik Språng7ca375c2019-02-06 16:20:17 +010085 current_fps_allocation_[si].size() > ti &&
86 current_fps_allocation_[si][ti] > 0) {
87 ++active_tls_[si];
88 if (!overshoot_detectors_[si][ti]) {
89 overshoot_detectors_[si][ti] =
Mirko Bonadei317a1f02019-09-17 17:06:18 +020090 std::make_unique<EncoderOvershootDetector>(kWindowSizeMs);
Erik Språng7ca375c2019-02-06 16:20:17 +010091 frames_since_layout_change_ = 0;
92 }
93 } else if (overshoot_detectors_[si][ti]) {
94 // Layer removed, destroy overshoot detector.
95 overshoot_detectors_[si][ti].reset();
96 frames_since_layout_change_ = 0;
97 }
98 }
99 }
100
101 // Next poll the overshoot detectors and populate the adjusted allocation.
102 const int64_t now_ms = rtc::TimeMillis();
103 VideoBitrateAllocation adjusted_allocation;
Erik Språng3d11e2f2019-04-15 14:48:30 +0200104 std::vector<LayerRateInfo> layer_infos;
105 DataRate wanted_overshoot_sum = DataRate::Zero();
106
Erik Språng7ca375c2019-02-06 16:20:17 +0100107 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
Erik Språng3d11e2f2019-04-15 14:48:30 +0200108 layer_infos.emplace_back();
109 LayerRateInfo& layer_info = layer_infos.back();
110
111 layer_info.target_rate =
112 DataRate::bps(rates.bitrate.GetSpatialLayerSum(si));
Erik Språng7ca375c2019-02-06 16:20:17 +0100113
114 // Adjustment is done per spatial layer only (not per temporal layer).
Erik Språng7ca375c2019-02-06 16:20:17 +0100115 if (frames_since_layout_change_ < kMinFramesSinceLayoutChange) {
Erik Språng3d11e2f2019-04-15 14:48:30 +0200116 layer_info.link_utilization_factor = kDefaultUtilizationFactor;
117 layer_info.media_utilization_factor = kDefaultUtilizationFactor;
118 } else if (active_tls_[si] == 0 ||
119 layer_info.target_rate == DataRate::Zero()) {
Erik Språng7ca375c2019-02-06 16:20:17 +0100120 // No signaled temporal layers, or no bitrate set. Could either be unused
121 // spatial layer or bitrate dynamic mode; pass bitrate through without any
122 // change.
Erik Språng3d11e2f2019-04-15 14:48:30 +0200123 layer_info.link_utilization_factor = 1.0;
124 layer_info.media_utilization_factor = 1.0;
Erik Språng7ca375c2019-02-06 16:20:17 +0100125 } else if (active_tls_[si] == 1) {
126 // A single active temporal layer, this might mean single layer or that
127 // encoder does not support temporal layers. Merge target bitrates for
128 // this spatial layer.
129 RTC_DCHECK(overshoot_detectors_[si][0]);
Erik Språng3d11e2f2019-04-15 14:48:30 +0200130 layer_info.link_utilization_factor =
131 overshoot_detectors_[si][0]
132 ->GetNetworkRateUtilizationFactor(now_ms)
133 .value_or(kDefaultUtilizationFactor);
134 layer_info.media_utilization_factor =
135 overshoot_detectors_[si][0]
136 ->GetMediaRateUtilizationFactor(now_ms)
137 .value_or(kDefaultUtilizationFactor);
138 } else if (layer_info.target_rate > DataRate::Zero()) {
Erik Språng7ca375c2019-02-06 16:20:17 +0100139 // Multiple temporal layers enabled for this spatial layer. Update rate
140 // for each of them and make a weighted average of utilization factors,
141 // with bitrate fraction used as weight.
142 // If any layer is missing a utilization factor, fall back to default.
Erik Språng3d11e2f2019-04-15 14:48:30 +0200143 layer_info.link_utilization_factor = 0.0;
144 layer_info.media_utilization_factor = 0.0;
Erik Språng7ca375c2019-02-06 16:20:17 +0100145 for (size_t ti = 0; ti < active_tls_[si]; ++ti) {
146 RTC_DCHECK(overshoot_detectors_[si][ti]);
Erik Språng3d11e2f2019-04-15 14:48:30 +0200147 const absl::optional<double> ti_link_utilization_factor =
Erik Språng6c072ef2019-04-01 12:57:28 +0200148 overshoot_detectors_[si][ti]->GetNetworkRateUtilizationFactor(
149 now_ms);
Erik Språng3d11e2f2019-04-15 14:48:30 +0200150 const absl::optional<double> ti_media_utilization_factor =
151 overshoot_detectors_[si][ti]->GetMediaRateUtilizationFactor(now_ms);
152 if (!ti_link_utilization_factor || !ti_media_utilization_factor) {
153 layer_info.link_utilization_factor = kDefaultUtilizationFactor;
154 layer_info.media_utilization_factor = kDefaultUtilizationFactor;
Erik Språng7ca375c2019-02-06 16:20:17 +0100155 break;
156 }
157 const double weight =
Erik Språng3d11e2f2019-04-15 14:48:30 +0200158 static_cast<double>(rates.bitrate.GetBitrate(si, ti)) /
159 layer_info.target_rate.bps();
160 layer_info.link_utilization_factor +=
161 weight * ti_link_utilization_factor.value();
162 layer_info.media_utilization_factor +=
163 weight * ti_media_utilization_factor.value();
Erik Språng7ca375c2019-02-06 16:20:17 +0100164 }
165 } else {
166 RTC_NOTREACHED();
167 }
168
Erik Språng3d11e2f2019-04-15 14:48:30 +0200169 if (layer_info.link_utilization_factor < 1.0) {
170 // TODO(sprang): Consider checking underuse and allowing it to cancel some
171 // potential overuse by other streams.
Erik Språng7ca375c2019-02-06 16:20:17 +0100172
Erik Språng3d11e2f2019-04-15 14:48:30 +0200173 // Don't boost target bitrate if encoder is under-using.
174 layer_info.link_utilization_factor = 1.0;
175 } else {
176 // Don't reduce encoder target below 50%, in which case the frame dropper
177 // should kick in instead.
178 layer_info.link_utilization_factor =
179 std::min(layer_info.link_utilization_factor, 2.0);
Erik Språng7ca375c2019-02-06 16:20:17 +0100180
Erik Språng3d11e2f2019-04-15 14:48:30 +0200181 // Keep track of sum of desired overshoot bitrate.
182 wanted_overshoot_sum += layer_info.WantedOvershoot();
183 }
184 }
185
186 // Available link headroom that can be used to fill wanted overshoot.
187 DataRate available_headroom = DataRate::Zero();
188 if (utilize_bandwidth_headroom_) {
189 available_headroom =
190 rates.bandwidth_allocation - DataRate::bps(rates.bitrate.get_sum_bps());
191 }
192
193 // All wanted overshoots are satisfied in the same proportion based on
194 // available headroom.
195 const double granted_overshoot_ratio =
196 wanted_overshoot_sum == DataRate::Zero()
197 ? 0.0
198 : std::min(1.0, available_headroom.bps<double>() /
199 wanted_overshoot_sum.bps());
200
201 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
202 LayerRateInfo& layer_info = layer_infos[si];
203 double utilization_factor = layer_info.link_utilization_factor;
204 DataRate allowed_overshoot =
205 granted_overshoot_ratio * layer_info.WantedOvershoot();
206 if (allowed_overshoot > DataRate::Zero()) {
207 // Pretend the target bitrate is higher by the allowed overshoot.
208 // Since utilization_factor = actual_bitrate / target_bitrate, it can be
209 // done by multiplying by old_target_bitrate / new_target_bitrate.
210 utilization_factor *= layer_info.target_rate.bps<double>() /
211 (allowed_overshoot.bps<double>() +
212 layer_info.target_rate.bps<double>());
Erik Språng7ca375c2019-02-06 16:20:17 +0100213 }
214
Erik Språng3d11e2f2019-04-15 14:48:30 +0200215 if (min_bitrates_bps_[si] > 0 &&
216 layer_info.target_rate > DataRate::Zero() &&
217 DataRate::bps(min_bitrates_bps_[si]) < layer_info.target_rate) {
218 // Make sure rate adjuster doesn't push target bitrate below minimum.
219 utilization_factor =
220 std::min(utilization_factor, layer_info.target_rate.bps<double>() /
221 min_bitrates_bps_[si]);
222 }
223
224 if (layer_info.target_rate > DataRate::Zero()) {
225 RTC_LOG(LS_VERBOSE) << "Utilization factors for spatial index " << si
226 << ": link = " << layer_info.link_utilization_factor
227 << ", media = " << layer_info.media_utilization_factor
228 << ", wanted overshoot = "
229 << layer_info.WantedOvershoot().bps()
230 << " bps, available headroom = "
231 << available_headroom.bps()
232 << " bps, total utilization factor = "
233 << utilization_factor;
Erik Språng0e1a1f92019-02-18 18:45:13 +0100234 }
235
Erik Språng7ca375c2019-02-06 16:20:17 +0100236 // Populate the adjusted allocation with determined utilization factor.
237 if (active_tls_[si] == 1 &&
Erik Språng3d11e2f2019-04-15 14:48:30 +0200238 layer_info.target_rate >
239 DataRate::bps(rates.bitrate.GetBitrate(si, 0))) {
Erik Språng7ca375c2019-02-06 16:20:17 +0100240 // Bitrate allocation indicates temporal layer usage, but encoder
241 // does not seem to support it. Pipe all bitrate into a single
242 // overshoot detector.
Erik Språng3d11e2f2019-04-15 14:48:30 +0200243 uint32_t adjusted_layer_bitrate_bps =
244 std::min(static_cast<uint32_t>(
245 layer_info.target_rate.bps() / utilization_factor + 0.5),
246 layer_info.target_rate.bps<uint32_t>());
Erik Språng7ca375c2019-02-06 16:20:17 +0100247 adjusted_allocation.SetBitrate(si, 0, adjusted_layer_bitrate_bps);
248 } else {
249 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
Erik Språng3d11e2f2019-04-15 14:48:30 +0200250 if (rates.bitrate.HasBitrate(si, ti)) {
251 uint32_t adjusted_layer_bitrate_bps = std::min(
252 static_cast<uint32_t>(
253 rates.bitrate.GetBitrate(si, ti) / utilization_factor + 0.5),
254 rates.bitrate.GetBitrate(si, ti));
Erik Språng7ca375c2019-02-06 16:20:17 +0100255 adjusted_allocation.SetBitrate(si, ti, adjusted_layer_bitrate_bps);
256 }
257 }
258 }
259
260 // In case of rounding errors, add bitrate to TL0 until min bitrate
261 // constraint has been met.
262 const uint32_t adjusted_spatial_layer_sum =
263 adjusted_allocation.GetSpatialLayerSum(si);
Erik Språng3d11e2f2019-04-15 14:48:30 +0200264 if (layer_info.target_rate > DataRate::Zero() &&
Erik Språng7ca375c2019-02-06 16:20:17 +0100265 adjusted_spatial_layer_sum < min_bitrates_bps_[si]) {
266 adjusted_allocation.SetBitrate(si, 0,
267 adjusted_allocation.GetBitrate(si, 0) +
268 min_bitrates_bps_[si] -
269 adjusted_spatial_layer_sum);
270 }
271
272 // Update all detectors with the new adjusted bitrate targets.
273 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
274 const uint32_t layer_bitrate_bps = adjusted_allocation.GetBitrate(si, ti);
275 // Overshoot detector may not exist, eg for ScreenshareLayers case.
276 if (layer_bitrate_bps > 0 && overshoot_detectors_[si][ti]) {
277 // Number of frames in this layer alone is not cumulative, so
278 // subtract fps from any low temporal layer.
279 const double fps_fraction =
280 static_cast<double>(
281 current_fps_allocation_[si][ti] -
282 (ti == 0 ? 0 : current_fps_allocation_[si][ti - 1])) /
283 VideoEncoder::EncoderInfo::kMaxFramerateFraction;
284
285 overshoot_detectors_[si][ti]->SetTargetRate(
286 DataRate::bps(layer_bitrate_bps),
Erik Språng3d11e2f2019-04-15 14:48:30 +0200287 fps_fraction * rates.framerate_fps, now_ms);
Erik Språng7ca375c2019-02-06 16:20:17 +0100288 }
289 }
290 }
291
292 return adjusted_allocation;
293}
294
295void EncoderBitrateAdjuster::OnEncoderInfo(
296 const VideoEncoder::EncoderInfo& encoder_info) {
297 // Copy allocation into current state and re-allocate.
298 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
299 current_fps_allocation_[si] = encoder_info.fps_allocation[si];
300 }
301
302 // Trigger re-allocation so that overshoot detectors have correct targets.
Erik Språng3d11e2f2019-04-15 14:48:30 +0200303 AdjustRateAllocation(current_rate_control_parameters_);
Erik Språng7ca375c2019-02-06 16:20:17 +0100304}
305
306void EncoderBitrateAdjuster::OnEncodedFrame(const EncodedImage& encoded_image,
307 int temporal_index) {
308 ++frames_since_layout_change_;
309 // Detectors may not exist, for instance if ScreenshareLayers is used.
310 auto& detector =
311 overshoot_detectors_[encoded_image.SpatialIndex().value_or(0)]
312 [temporal_index];
313 if (detector) {
314 detector->OnEncodedFrame(encoded_image.size(), rtc::TimeMillis());
315 }
316}
317
318void EncoderBitrateAdjuster::Reset() {
319 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
320 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
321 overshoot_detectors_[si][ti].reset();
322 }
323 }
324 // Call AdjustRateAllocation() with the last know bitrate allocation, so that
325 // the appropriate overuse detectors are immediately re-created.
Erik Språng3d11e2f2019-04-15 14:48:30 +0200326 AdjustRateAllocation(current_rate_control_parameters_);
Erik Språng7ca375c2019-02-06 16:20:17 +0100327}
328
329} // namespace webrtc