blob: eb6017c787c8b7613242814cc0fb865fab4fa65d [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>
14
15#include "absl/memory/memory.h"
16#include "rtc_base/logging.h"
17#include "rtc_base/time_utils.h"
18
19namespace webrtc {
20
21constexpr int64_t EncoderBitrateAdjuster::kWindowSizeMs;
22constexpr size_t EncoderBitrateAdjuster::kMinFramesSinceLayoutChange;
23constexpr double EncoderBitrateAdjuster::kDefaultUtilizationFactor;
24
25EncoderBitrateAdjuster::EncoderBitrateAdjuster(const VideoCodec& codec_settings)
26 : current_total_framerate_fps_(0),
27 frames_since_layout_change_(0),
28 min_bitrates_bps_{} {
29 if (codec_settings.codecType == VideoCodecType::kVideoCodecVP9) {
30 for (size_t si = 0; si < codec_settings.VP9().numberOfSpatialLayers; ++si) {
31 if (codec_settings.spatialLayers[si].active) {
32 min_bitrates_bps_[si] =
33 std::max(codec_settings.minBitrate * 1000,
34 codec_settings.spatialLayers[si].minBitrate * 1000);
35 }
36 }
37 } else {
38 for (size_t si = 0; si < codec_settings.numberOfSimulcastStreams; ++si) {
39 if (codec_settings.simulcastStream[si].active) {
40 min_bitrates_bps_[si] =
41 std::max(codec_settings.minBitrate * 1000,
42 codec_settings.simulcastStream[si].minBitrate * 1000);
43 }
44 }
45 }
46}
47
48EncoderBitrateAdjuster::~EncoderBitrateAdjuster() = default;
49
50VideoBitrateAllocation EncoderBitrateAdjuster::AdjustRateAllocation(
51 const VideoBitrateAllocation& bitrate_allocation,
52 int framerate_fps) {
53 current_bitrate_allocation_ = bitrate_allocation;
54 current_total_framerate_fps_ = framerate_fps;
55
56 // First check that overshoot detectors exist, and store per spatial layer
57 // how many active temporal layers we have.
58 size_t active_tls_[kMaxSpatialLayers] = {};
59 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
60 active_tls_[si] = 0;
61 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
62 // Layer is enabled iff it has both positive bitrate and framerate target.
63 if (bitrate_allocation.GetBitrate(si, ti) > 0 &&
64 current_fps_allocation_[si].size() > ti &&
65 current_fps_allocation_[si][ti] > 0) {
66 ++active_tls_[si];
67 if (!overshoot_detectors_[si][ti]) {
68 overshoot_detectors_[si][ti] =
69 absl::make_unique<EncoderOvershootDetector>(kWindowSizeMs);
70 frames_since_layout_change_ = 0;
71 }
72 } else if (overshoot_detectors_[si][ti]) {
73 // Layer removed, destroy overshoot detector.
74 overshoot_detectors_[si][ti].reset();
75 frames_since_layout_change_ = 0;
76 }
77 }
78 }
79
80 // Next poll the overshoot detectors and populate the adjusted allocation.
81 const int64_t now_ms = rtc::TimeMillis();
82 VideoBitrateAllocation adjusted_allocation;
83 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
84 const uint32_t spatial_layer_bitrate_bps =
85 bitrate_allocation.GetSpatialLayerSum(si);
86
87 // Adjustment is done per spatial layer only (not per temporal layer).
88 double utilization_factor;
89 if (frames_since_layout_change_ < kMinFramesSinceLayoutChange) {
90 utilization_factor = kDefaultUtilizationFactor;
91 } else if (active_tls_[si] == 0 || spatial_layer_bitrate_bps == 0) {
92 // No signaled temporal layers, or no bitrate set. Could either be unused
93 // spatial layer or bitrate dynamic mode; pass bitrate through without any
94 // change.
95 utilization_factor = 1.0;
96 } else if (active_tls_[si] == 1) {
97 // A single active temporal layer, this might mean single layer or that
98 // encoder does not support temporal layers. Merge target bitrates for
99 // this spatial layer.
100 RTC_DCHECK(overshoot_detectors_[si][0]);
101 utilization_factor =
102 overshoot_detectors_[si][0]->GetUtilizationFactor(now_ms).value_or(
103 kDefaultUtilizationFactor);
104 } else if (spatial_layer_bitrate_bps > 0) {
105 // Multiple temporal layers enabled for this spatial layer. Update rate
106 // for each of them and make a weighted average of utilization factors,
107 // with bitrate fraction used as weight.
108 // If any layer is missing a utilization factor, fall back to default.
109 utilization_factor = 0.0;
110 for (size_t ti = 0; ti < active_tls_[si]; ++ti) {
111 RTC_DCHECK(overshoot_detectors_[si][ti]);
112 const absl::optional<double> ti_utilization_factor =
113 overshoot_detectors_[si][ti]->GetUtilizationFactor(now_ms);
114 if (!ti_utilization_factor) {
115 utilization_factor = kDefaultUtilizationFactor;
116 break;
117 }
118 const double weight =
119 static_cast<double>(bitrate_allocation.GetBitrate(si, ti)) /
120 spatial_layer_bitrate_bps;
121 utilization_factor += weight * ti_utilization_factor.value();
122 }
123 } else {
124 RTC_NOTREACHED();
125 }
126
127 // Don't boost target bitrate if encoder is under-using.
128 utilization_factor = std::max(utilization_factor, 1.0);
129
130 // Don't reduce encoder target below 50%, in which case the frame dropper
131 // should kick in instead.
132 utilization_factor = std::min(utilization_factor, 2.0);
133
134 if (min_bitrates_bps_[si] > 0 && spatial_layer_bitrate_bps > 0 &&
135 min_bitrates_bps_[si] < spatial_layer_bitrate_bps) {
136 // Make sure rate adjuster doesn't push target bitrate below minimum.
137 utilization_factor = std::min(
138 utilization_factor, static_cast<double>(spatial_layer_bitrate_bps) /
139 min_bitrates_bps_[si]);
140 }
141
142 // Populate the adjusted allocation with determined utilization factor.
143 if (active_tls_[si] == 1 &&
144 spatial_layer_bitrate_bps > bitrate_allocation.GetBitrate(si, 0)) {
145 // Bitrate allocation indicates temporal layer usage, but encoder
146 // does not seem to support it. Pipe all bitrate into a single
147 // overshoot detector.
148 uint32_t adjusted_layer_bitrate_bps = static_cast<uint32_t>(
149 spatial_layer_bitrate_bps / utilization_factor + 0.5);
150 adjusted_allocation.SetBitrate(si, 0, adjusted_layer_bitrate_bps);
151 } else {
152 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
153 if (bitrate_allocation.HasBitrate(si, ti)) {
154 uint32_t adjusted_layer_bitrate_bps = static_cast<uint32_t>(
155 bitrate_allocation.GetBitrate(si, ti) / utilization_factor + 0.5);
156 adjusted_allocation.SetBitrate(si, ti, adjusted_layer_bitrate_bps);
157 }
158 }
159 }
160
161 // In case of rounding errors, add bitrate to TL0 until min bitrate
162 // constraint has been met.
163 const uint32_t adjusted_spatial_layer_sum =
164 adjusted_allocation.GetSpatialLayerSum(si);
165 if (spatial_layer_bitrate_bps > 0 &&
166 adjusted_spatial_layer_sum < min_bitrates_bps_[si]) {
167 adjusted_allocation.SetBitrate(si, 0,
168 adjusted_allocation.GetBitrate(si, 0) +
169 min_bitrates_bps_[si] -
170 adjusted_spatial_layer_sum);
171 }
172
173 // Update all detectors with the new adjusted bitrate targets.
174 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
175 const uint32_t layer_bitrate_bps = adjusted_allocation.GetBitrate(si, ti);
176 // Overshoot detector may not exist, eg for ScreenshareLayers case.
177 if (layer_bitrate_bps > 0 && overshoot_detectors_[si][ti]) {
178 // Number of frames in this layer alone is not cumulative, so
179 // subtract fps from any low temporal layer.
180 const double fps_fraction =
181 static_cast<double>(
182 current_fps_allocation_[si][ti] -
183 (ti == 0 ? 0 : current_fps_allocation_[si][ti - 1])) /
184 VideoEncoder::EncoderInfo::kMaxFramerateFraction;
185
186 overshoot_detectors_[si][ti]->SetTargetRate(
187 DataRate::bps(layer_bitrate_bps),
188 fps_fraction * current_total_framerate_fps_, now_ms);
189 }
190 }
191 }
192
193 return adjusted_allocation;
194}
195
196void EncoderBitrateAdjuster::OnEncoderInfo(
197 const VideoEncoder::EncoderInfo& encoder_info) {
198 // Copy allocation into current state and re-allocate.
199 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
200 current_fps_allocation_[si] = encoder_info.fps_allocation[si];
201 }
202
203 // Trigger re-allocation so that overshoot detectors have correct targets.
204 AdjustRateAllocation(current_bitrate_allocation_,
205 current_total_framerate_fps_);
206}
207
208void EncoderBitrateAdjuster::OnEncodedFrame(const EncodedImage& encoded_image,
209 int temporal_index) {
210 ++frames_since_layout_change_;
211 // Detectors may not exist, for instance if ScreenshareLayers is used.
212 auto& detector =
213 overshoot_detectors_[encoded_image.SpatialIndex().value_or(0)]
214 [temporal_index];
215 if (detector) {
216 detector->OnEncodedFrame(encoded_image.size(), rtc::TimeMillis());
217 }
218}
219
220void EncoderBitrateAdjuster::Reset() {
221 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
222 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
223 overshoot_detectors_[si][ti].reset();
224 }
225 }
226 // Call AdjustRateAllocation() with the last know bitrate allocation, so that
227 // the appropriate overuse detectors are immediately re-created.
228 AdjustRateAllocation(current_bitrate_allocation_,
229 current_total_framerate_fps_);
230}
231
232} // namespace webrtc