1 /*
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>
14 #include <memory>
15 #include <vector>
16
17 #include "rtc_base/experiments/rate_control_settings.h"
18 #include "rtc_base/logging.h"
19 #include "rtc_base/time_utils.h"
20 #include "system_wrappers/include/field_trial.h"
21
22 namespace webrtc {
23 namespace {
24 // Helper struct with metadata for a single spatial layer.
25 struct LayerRateInfo {
26 double link_utilization_factor = 0.0;
27 double media_utilization_factor = 0.0;
28 DataRate target_rate = DataRate::Zero();
29
WantedOvershootwebrtc::__anon852b3b730111::LayerRateInfo30 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
43 constexpr int64_t EncoderBitrateAdjuster::kWindowSizeMs;
44 constexpr size_t EncoderBitrateAdjuster::kMinFramesSinceLayoutChange;
45 constexpr double EncoderBitrateAdjuster::kDefaultUtilizationFactor;
46
EncoderBitrateAdjuster(const VideoCodec & codec_settings)47 EncoderBitrateAdjuster::EncoderBitrateAdjuster(const VideoCodec& codec_settings)
48 : utilize_bandwidth_headroom_(RateControlSettings::ParseFromFieldTrials()
49 .BitrateAdjusterCanUseNetworkHeadroom()),
50 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
71 EncoderBitrateAdjuster::~EncoderBitrateAdjuster() = default;
72
AdjustRateAllocation(const VideoEncoder::RateControlParameters & rates)73 VideoBitrateAllocation EncoderBitrateAdjuster::AdjustRateAllocation(
74 const VideoEncoder::RateControlParameters& rates) {
75 current_rate_control_parameters_ = rates;
76
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.
84 if (rates.bitrate.GetBitrate(si, ti) > 0 &&
85 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] =
90 std::make_unique<EncoderOvershootDetector>(kWindowSizeMs);
91 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;
104 std::vector<LayerRateInfo> layer_infos;
105 DataRate wanted_overshoot_sum = DataRate::Zero();
106
107 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
108 layer_infos.emplace_back();
109 LayerRateInfo& layer_info = layer_infos.back();
110
111 layer_info.target_rate =
112 DataRate::BitsPerSec(rates.bitrate.GetSpatialLayerSum(si));
113
114 // Adjustment is done per spatial layer only (not per temporal layer).
115 if (frames_since_layout_change_ < kMinFramesSinceLayoutChange) {
116 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()) {
120 // 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.
123 layer_info.link_utilization_factor = 1.0;
124 layer_info.media_utilization_factor = 1.0;
125 } 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]);
130 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()) {
139 // 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.
143 layer_info.link_utilization_factor = 0.0;
144 layer_info.media_utilization_factor = 0.0;
145 for (size_t ti = 0; ti < active_tls_[si]; ++ti) {
146 RTC_DCHECK(overshoot_detectors_[si][ti]);
147 const absl::optional<double> ti_link_utilization_factor =
148 overshoot_detectors_[si][ti]->GetNetworkRateUtilizationFactor(
149 now_ms);
150 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;
155 break;
156 }
157 const double weight =
158 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();
164 }
165 } else {
166 RTC_NOTREACHED();
167 }
168
169 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.
172
173 // 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);
180
181 // 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 = rates.bandwidth_allocation -
190 DataRate::BitsPerSec(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>());
213 }
214
215 if (min_bitrates_bps_[si] > 0 &&
216 layer_info.target_rate > DataRate::Zero() &&
217 DataRate::BitsPerSec(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;
234 }
235
236 // Populate the adjusted allocation with determined utilization factor.
237 if (active_tls_[si] == 1 &&
238 layer_info.target_rate >
239 DataRate::BitsPerSec(rates.bitrate.GetBitrate(si, 0))) {
240 // Bitrate allocation indicates temporal layer usage, but encoder
241 // does not seem to support it. Pipe all bitrate into a single
242 // overshoot detector.
243 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>());
247 adjusted_allocation.SetBitrate(si, 0, adjusted_layer_bitrate_bps);
248 } else {
249 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
250 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));
255 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);
264 if (layer_info.target_rate > DataRate::Zero() &&
265 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 if (fps_fraction <= 0.0) {
286 RTC_LOG(LS_WARNING)
287 << "Encoder config has temporal layer with non-zero bitrate "
288 "allocation but zero framerate allocation.";
289 continue;
290 }
291
292 overshoot_detectors_[si][ti]->SetTargetRate(
293 DataRate::BitsPerSec(layer_bitrate_bps),
294 fps_fraction * rates.framerate_fps, now_ms);
295 }
296 }
297 }
298
299 // Since no spatial layers or streams are toggled by the adjustment
300 // bw-limited flag stays the same.
301 adjusted_allocation.set_bw_limited(rates.bitrate.is_bw_limited());
302
303 return adjusted_allocation;
304 }
305
OnEncoderInfo(const VideoEncoder::EncoderInfo & encoder_info)306 void EncoderBitrateAdjuster::OnEncoderInfo(
307 const VideoEncoder::EncoderInfo& encoder_info) {
308 // Copy allocation into current state and re-allocate.
309 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
310 current_fps_allocation_[si] = encoder_info.fps_allocation[si];
311 }
312
313 // Trigger re-allocation so that overshoot detectors have correct targets.
314 AdjustRateAllocation(current_rate_control_parameters_);
315 }
316
OnEncodedFrame(const EncodedImage & encoded_image,int temporal_index)317 void EncoderBitrateAdjuster::OnEncodedFrame(const EncodedImage& encoded_image,
318 int temporal_index) {
319 ++frames_since_layout_change_;
320 // Detectors may not exist, for instance if ScreenshareLayers is used.
321 auto& detector =
322 overshoot_detectors_[encoded_image.SpatialIndex().value_or(0)]
323 [temporal_index];
324 if (detector) {
325 detector->OnEncodedFrame(encoded_image.size(), rtc::TimeMillis());
326 }
327 }
328
Reset()329 void EncoderBitrateAdjuster::Reset() {
330 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
331 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
332 overshoot_detectors_[si][ti].reset();
333 }
334 }
335 // Call AdjustRateAllocation() with the last know bitrate allocation, so that
336 // the appropriate overuse detectors are immediately re-created.
337 AdjustRateAllocation(current_rate_control_parameters_);
338 }
339
340 } // namespace webrtc
341