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
21 namespace webrtc {
22 namespace {
23 // Helper struct with metadata for a single spatial layer.
24 struct LayerRateInfo {
25 double link_utilization_factor = 0.0;
26 double media_utilization_factor = 0.0;
27 DataRate target_rate = DataRate::Zero();
28
WantedOvershootwebrtc::__anonf3d500d10111::LayerRateInfo29 DataRate WantedOvershoot() const {
30 // If there is headroom, allow bitrate to go up to media rate limit.
31 // Still limit media utilization to 1.0, so we don't overshoot over long
32 // runs even if we have headroom.
33 const double max_media_utilization =
34 std::max(1.0, media_utilization_factor);
35 if (link_utilization_factor > max_media_utilization) {
36 return (link_utilization_factor - max_media_utilization) * target_rate;
37 }
38 return DataRate::Zero();
39 }
40 };
41 } // namespace
42 constexpr int64_t EncoderBitrateAdjuster::kWindowSizeMs;
43 constexpr size_t EncoderBitrateAdjuster::kMinFramesSinceLayoutChange;
44 constexpr double EncoderBitrateAdjuster::kDefaultUtilizationFactor;
45
EncoderBitrateAdjuster(const VideoCodec & codec_settings)46 EncoderBitrateAdjuster::EncoderBitrateAdjuster(const VideoCodec& codec_settings)
47 : utilize_bandwidth_headroom_(RateControlSettings::ParseFromFieldTrials()
48 .BitrateAdjusterCanUseNetworkHeadroom()),
49 frames_since_layout_change_(0),
50 min_bitrates_bps_{} {
51 if (codec_settings.codecType == VideoCodecType::kVideoCodecVP9) {
52 for (size_t si = 0; si < codec_settings.VP9().numberOfSpatialLayers; ++si) {
53 if (codec_settings.spatialLayers[si].active) {
54 min_bitrates_bps_[si] =
55 std::max(codec_settings.minBitrate * 1000,
56 codec_settings.spatialLayers[si].minBitrate * 1000);
57 }
58 }
59 } else {
60 for (size_t si = 0; si < codec_settings.numberOfSimulcastStreams; ++si) {
61 if (codec_settings.simulcastStream[si].active) {
62 min_bitrates_bps_[si] =
63 std::max(codec_settings.minBitrate * 1000,
64 codec_settings.simulcastStream[si].minBitrate * 1000);
65 }
66 }
67 }
68 }
69
70 EncoderBitrateAdjuster::~EncoderBitrateAdjuster() = default;
71
AdjustRateAllocation(const VideoEncoder::RateControlParameters & rates)72 VideoBitrateAllocation EncoderBitrateAdjuster::AdjustRateAllocation(
73 const VideoEncoder::RateControlParameters& rates) {
74 current_rate_control_parameters_ = rates;
75
76 // First check that overshoot detectors exist, and store per spatial layer
77 // how many active temporal layers we have.
78 size_t active_tls_[kMaxSpatialLayers] = {};
79 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
80 active_tls_[si] = 0;
81 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
82 // Layer is enabled iff it has both positive bitrate and framerate target.
83 if (rates.bitrate.GetBitrate(si, ti) > 0 &&
84 current_fps_allocation_[si].size() > ti &&
85 current_fps_allocation_[si][ti] > 0) {
86 ++active_tls_[si];
87 if (!overshoot_detectors_[si][ti]) {
88 overshoot_detectors_[si][ti] =
89 std::make_unique<EncoderOvershootDetector>(kWindowSizeMs);
90 frames_since_layout_change_ = 0;
91 }
92 } else if (overshoot_detectors_[si][ti]) {
93 // Layer removed, destroy overshoot detector.
94 overshoot_detectors_[si][ti].reset();
95 frames_since_layout_change_ = 0;
96 }
97 }
98 }
99
100 // Next poll the overshoot detectors and populate the adjusted allocation.
101 const int64_t now_ms = rtc::TimeMillis();
102 VideoBitrateAllocation adjusted_allocation;
103 std::vector<LayerRateInfo> layer_infos;
104 DataRate wanted_overshoot_sum = DataRate::Zero();
105
106 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
107 layer_infos.emplace_back();
108 LayerRateInfo& layer_info = layer_infos.back();
109
110 layer_info.target_rate =
111 DataRate::BitsPerSec(rates.bitrate.GetSpatialLayerSum(si));
112
113 // Adjustment is done per spatial layer only (not per temporal layer).
114 if (frames_since_layout_change_ < kMinFramesSinceLayoutChange) {
115 layer_info.link_utilization_factor = kDefaultUtilizationFactor;
116 layer_info.media_utilization_factor = kDefaultUtilizationFactor;
117 } else if (active_tls_[si] == 0 ||
118 layer_info.target_rate == DataRate::Zero()) {
119 // No signaled temporal layers, or no bitrate set. Could either be unused
120 // spatial layer or bitrate dynamic mode; pass bitrate through without any
121 // change.
122 layer_info.link_utilization_factor = 1.0;
123 layer_info.media_utilization_factor = 1.0;
124 } else if (active_tls_[si] == 1) {
125 // A single active temporal layer, this might mean single layer or that
126 // encoder does not support temporal layers. Merge target bitrates for
127 // this spatial layer.
128 RTC_DCHECK(overshoot_detectors_[si][0]);
129 layer_info.link_utilization_factor =
130 overshoot_detectors_[si][0]
131 ->GetNetworkRateUtilizationFactor(now_ms)
132 .value_or(kDefaultUtilizationFactor);
133 layer_info.media_utilization_factor =
134 overshoot_detectors_[si][0]
135 ->GetMediaRateUtilizationFactor(now_ms)
136 .value_or(kDefaultUtilizationFactor);
137 } else if (layer_info.target_rate > DataRate::Zero()) {
138 // Multiple temporal layers enabled for this spatial layer. Update rate
139 // for each of them and make a weighted average of utilization factors,
140 // with bitrate fraction used as weight.
141 // If any layer is missing a utilization factor, fall back to default.
142 layer_info.link_utilization_factor = 0.0;
143 layer_info.media_utilization_factor = 0.0;
144 for (size_t ti = 0; ti < active_tls_[si]; ++ti) {
145 RTC_DCHECK(overshoot_detectors_[si][ti]);
146 const absl::optional<double> ti_link_utilization_factor =
147 overshoot_detectors_[si][ti]->GetNetworkRateUtilizationFactor(
148 now_ms);
149 const absl::optional<double> ti_media_utilization_factor =
150 overshoot_detectors_[si][ti]->GetMediaRateUtilizationFactor(now_ms);
151 if (!ti_link_utilization_factor || !ti_media_utilization_factor) {
152 layer_info.link_utilization_factor = kDefaultUtilizationFactor;
153 layer_info.media_utilization_factor = kDefaultUtilizationFactor;
154 break;
155 }
156 const double weight =
157 static_cast<double>(rates.bitrate.GetBitrate(si, ti)) /
158 layer_info.target_rate.bps();
159 layer_info.link_utilization_factor +=
160 weight * ti_link_utilization_factor.value();
161 layer_info.media_utilization_factor +=
162 weight * ti_media_utilization_factor.value();
163 }
164 } else {
165 RTC_DCHECK_NOTREACHED();
166 }
167
168 if (layer_info.link_utilization_factor < 1.0) {
169 // TODO(sprang): Consider checking underuse and allowing it to cancel some
170 // potential overuse by other streams.
171
172 // Don't boost target bitrate if encoder is under-using.
173 layer_info.link_utilization_factor = 1.0;
174 } else {
175 // Don't reduce encoder target below 50%, in which case the frame dropper
176 // should kick in instead.
177 layer_info.link_utilization_factor =
178 std::min(layer_info.link_utilization_factor, 2.0);
179
180 // Keep track of sum of desired overshoot bitrate.
181 wanted_overshoot_sum += layer_info.WantedOvershoot();
182 }
183 }
184
185 // Available link headroom that can be used to fill wanted overshoot.
186 DataRate available_headroom = DataRate::Zero();
187 if (utilize_bandwidth_headroom_) {
188 available_headroom = rates.bandwidth_allocation -
189 DataRate::BitsPerSec(rates.bitrate.get_sum_bps());
190 }
191
192 // All wanted overshoots are satisfied in the same proportion based on
193 // available headroom.
194 const double granted_overshoot_ratio =
195 wanted_overshoot_sum == DataRate::Zero()
196 ? 0.0
197 : std::min(1.0, available_headroom.bps<double>() /
198 wanted_overshoot_sum.bps());
199
200 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
201 LayerRateInfo& layer_info = layer_infos[si];
202 double utilization_factor = layer_info.link_utilization_factor;
203 DataRate allowed_overshoot =
204 granted_overshoot_ratio * layer_info.WantedOvershoot();
205 if (allowed_overshoot > DataRate::Zero()) {
206 // Pretend the target bitrate is higher by the allowed overshoot.
207 // Since utilization_factor = actual_bitrate / target_bitrate, it can be
208 // done by multiplying by old_target_bitrate / new_target_bitrate.
209 utilization_factor *= layer_info.target_rate.bps<double>() /
210 (allowed_overshoot.bps<double>() +
211 layer_info.target_rate.bps<double>());
212 }
213
214 if (min_bitrates_bps_[si] > 0 &&
215 layer_info.target_rate > DataRate::Zero() &&
216 DataRate::BitsPerSec(min_bitrates_bps_[si]) < layer_info.target_rate) {
217 // Make sure rate adjuster doesn't push target bitrate below minimum.
218 utilization_factor =
219 std::min(utilization_factor, layer_info.target_rate.bps<double>() /
220 min_bitrates_bps_[si]);
221 }
222
223 if (layer_info.target_rate > DataRate::Zero()) {
224 RTC_LOG(LS_VERBOSE) << "Utilization factors for spatial index " << si
225 << ": link = " << layer_info.link_utilization_factor
226 << ", media = " << layer_info.media_utilization_factor
227 << ", wanted overshoot = "
228 << layer_info.WantedOvershoot().bps()
229 << " bps, available headroom = "
230 << available_headroom.bps()
231 << " bps, total utilization factor = "
232 << utilization_factor;
233 }
234
235 // Populate the adjusted allocation with determined utilization factor.
236 if (active_tls_[si] == 1 &&
237 layer_info.target_rate >
238 DataRate::BitsPerSec(rates.bitrate.GetBitrate(si, 0))) {
239 // Bitrate allocation indicates temporal layer usage, but encoder
240 // does not seem to support it. Pipe all bitrate into a single
241 // overshoot detector.
242 uint32_t adjusted_layer_bitrate_bps =
243 std::min(static_cast<uint32_t>(
244 layer_info.target_rate.bps() / utilization_factor + 0.5),
245 layer_info.target_rate.bps<uint32_t>());
246 adjusted_allocation.SetBitrate(si, 0, adjusted_layer_bitrate_bps);
247 } else {
248 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
249 if (rates.bitrate.HasBitrate(si, ti)) {
250 uint32_t adjusted_layer_bitrate_bps = std::min(
251 static_cast<uint32_t>(
252 rates.bitrate.GetBitrate(si, ti) / utilization_factor + 0.5),
253 rates.bitrate.GetBitrate(si, ti));
254 adjusted_allocation.SetBitrate(si, ti, adjusted_layer_bitrate_bps);
255 }
256 }
257 }
258
259 // In case of rounding errors, add bitrate to TL0 until min bitrate
260 // constraint has been met.
261 const uint32_t adjusted_spatial_layer_sum =
262 adjusted_allocation.GetSpatialLayerSum(si);
263 if (layer_info.target_rate > DataRate::Zero() &&
264 adjusted_spatial_layer_sum < min_bitrates_bps_[si]) {
265 adjusted_allocation.SetBitrate(si, 0,
266 adjusted_allocation.GetBitrate(si, 0) +
267 min_bitrates_bps_[si] -
268 adjusted_spatial_layer_sum);
269 }
270
271 // Update all detectors with the new adjusted bitrate targets.
272 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
273 const uint32_t layer_bitrate_bps = adjusted_allocation.GetBitrate(si, ti);
274 // Overshoot detector may not exist, eg for ScreenshareLayers case.
275 if (layer_bitrate_bps > 0 && overshoot_detectors_[si][ti]) {
276 // Number of frames in this layer alone is not cumulative, so
277 // subtract fps from any low temporal layer.
278 const double fps_fraction =
279 static_cast<double>(
280 current_fps_allocation_[si][ti] -
281 (ti == 0 ? 0 : current_fps_allocation_[si][ti - 1])) /
282 VideoEncoder::EncoderInfo::kMaxFramerateFraction;
283
284 if (fps_fraction <= 0.0) {
285 RTC_LOG(LS_WARNING)
286 << "Encoder config has temporal layer with non-zero bitrate "
287 "allocation but zero framerate allocation.";
288 continue;
289 }
290
291 overshoot_detectors_[si][ti]->SetTargetRate(
292 DataRate::BitsPerSec(layer_bitrate_bps),
293 fps_fraction * rates.framerate_fps, now_ms);
294 }
295 }
296 }
297
298 // Since no spatial layers or streams are toggled by the adjustment
299 // bw-limited flag stays the same.
300 adjusted_allocation.set_bw_limited(rates.bitrate.is_bw_limited());
301
302 return adjusted_allocation;
303 }
304
OnEncoderInfo(const VideoEncoder::EncoderInfo & encoder_info)305 void EncoderBitrateAdjuster::OnEncoderInfo(
306 const VideoEncoder::EncoderInfo& encoder_info) {
307 // Copy allocation into current state and re-allocate.
308 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
309 current_fps_allocation_[si] = encoder_info.fps_allocation[si];
310 }
311
312 // Trigger re-allocation so that overshoot detectors have correct targets.
313 AdjustRateAllocation(current_rate_control_parameters_);
314 }
315
OnEncodedFrame(DataSize size,int spatial_index,int temporal_index)316 void EncoderBitrateAdjuster::OnEncodedFrame(DataSize size,
317 int spatial_index,
318 int temporal_index) {
319 ++frames_since_layout_change_;
320 // Detectors may not exist, for instance if ScreenshareLayers is used.
321 auto& detector = overshoot_detectors_[spatial_index][temporal_index];
322 if (detector) {
323 detector->OnEncodedFrame(size.bytes(), rtc::TimeMillis());
324 }
325 }
326
Reset()327 void EncoderBitrateAdjuster::Reset() {
328 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
329 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
330 overshoot_detectors_[si][ti].reset();
331 }
332 }
333 // Call AdjustRateAllocation() with the last know bitrate allocation, so that
334 // the appropriate overuse detectors are immediately re-created.
335 AdjustRateAllocation(current_rate_control_parameters_);
336 }
337
338 } // namespace webrtc
339