blob: 97fe363c08dacf939a08e27b1044d22190f78fa5 [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]);
Erik Språng6c072ef2019-04-01 12:57:28 +0200101 utilization_factor = overshoot_detectors_[si][0]
102 ->GetNetworkRateUtilizationFactor(now_ms)
103 .value_or(kDefaultUtilizationFactor);
Erik Språng7ca375c2019-02-06 16:20:17 +0100104 } 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 =
Erik Språng6c072ef2019-04-01 12:57:28 +0200113 overshoot_detectors_[si][ti]->GetNetworkRateUtilizationFactor(
114 now_ms);
Erik Språng7ca375c2019-02-06 16:20:17 +0100115 if (!ti_utilization_factor) {
116 utilization_factor = kDefaultUtilizationFactor;
117 break;
118 }
119 const double weight =
120 static_cast<double>(bitrate_allocation.GetBitrate(si, ti)) /
121 spatial_layer_bitrate_bps;
122 utilization_factor += weight * ti_utilization_factor.value();
123 }
124 } else {
125 RTC_NOTREACHED();
126 }
127
128 // Don't boost target bitrate if encoder is under-using.
129 utilization_factor = std::max(utilization_factor, 1.0);
130
131 // Don't reduce encoder target below 50%, in which case the frame dropper
132 // should kick in instead.
133 utilization_factor = std::min(utilization_factor, 2.0);
134
135 if (min_bitrates_bps_[si] > 0 && spatial_layer_bitrate_bps > 0 &&
136 min_bitrates_bps_[si] < spatial_layer_bitrate_bps) {
137 // Make sure rate adjuster doesn't push target bitrate below minimum.
138 utilization_factor = std::min(
139 utilization_factor, static_cast<double>(spatial_layer_bitrate_bps) /
140 min_bitrates_bps_[si]);
141 }
142
Erik Språng0e1a1f92019-02-18 18:45:13 +0100143 if (spatial_layer_bitrate_bps > 0) {
144 RTC_LOG(LS_VERBOSE) << "Utilization factor for spatial index " << si
145 << ": " << utilization_factor;
146 }
147
Erik Språng7ca375c2019-02-06 16:20:17 +0100148 // Populate the adjusted allocation with determined utilization factor.
149 if (active_tls_[si] == 1 &&
150 spatial_layer_bitrate_bps > bitrate_allocation.GetBitrate(si, 0)) {
151 // Bitrate allocation indicates temporal layer usage, but encoder
152 // does not seem to support it. Pipe all bitrate into a single
153 // overshoot detector.
154 uint32_t adjusted_layer_bitrate_bps = static_cast<uint32_t>(
155 spatial_layer_bitrate_bps / utilization_factor + 0.5);
156 adjusted_allocation.SetBitrate(si, 0, adjusted_layer_bitrate_bps);
157 } else {
158 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
159 if (bitrate_allocation.HasBitrate(si, ti)) {
160 uint32_t adjusted_layer_bitrate_bps = static_cast<uint32_t>(
161 bitrate_allocation.GetBitrate(si, ti) / utilization_factor + 0.5);
162 adjusted_allocation.SetBitrate(si, ti, adjusted_layer_bitrate_bps);
163 }
164 }
165 }
166
167 // In case of rounding errors, add bitrate to TL0 until min bitrate
168 // constraint has been met.
169 const uint32_t adjusted_spatial_layer_sum =
170 adjusted_allocation.GetSpatialLayerSum(si);
171 if (spatial_layer_bitrate_bps > 0 &&
172 adjusted_spatial_layer_sum < min_bitrates_bps_[si]) {
173 adjusted_allocation.SetBitrate(si, 0,
174 adjusted_allocation.GetBitrate(si, 0) +
175 min_bitrates_bps_[si] -
176 adjusted_spatial_layer_sum);
177 }
178
179 // Update all detectors with the new adjusted bitrate targets.
180 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
181 const uint32_t layer_bitrate_bps = adjusted_allocation.GetBitrate(si, ti);
182 // Overshoot detector may not exist, eg for ScreenshareLayers case.
183 if (layer_bitrate_bps > 0 && overshoot_detectors_[si][ti]) {
184 // Number of frames in this layer alone is not cumulative, so
185 // subtract fps from any low temporal layer.
186 const double fps_fraction =
187 static_cast<double>(
188 current_fps_allocation_[si][ti] -
189 (ti == 0 ? 0 : current_fps_allocation_[si][ti - 1])) /
190 VideoEncoder::EncoderInfo::kMaxFramerateFraction;
191
192 overshoot_detectors_[si][ti]->SetTargetRate(
193 DataRate::bps(layer_bitrate_bps),
194 fps_fraction * current_total_framerate_fps_, now_ms);
195 }
196 }
197 }
198
199 return adjusted_allocation;
200}
201
202void EncoderBitrateAdjuster::OnEncoderInfo(
203 const VideoEncoder::EncoderInfo& encoder_info) {
204 // Copy allocation into current state and re-allocate.
205 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
206 current_fps_allocation_[si] = encoder_info.fps_allocation[si];
207 }
208
209 // Trigger re-allocation so that overshoot detectors have correct targets.
210 AdjustRateAllocation(current_bitrate_allocation_,
211 current_total_framerate_fps_);
212}
213
214void EncoderBitrateAdjuster::OnEncodedFrame(const EncodedImage& encoded_image,
215 int temporal_index) {
216 ++frames_since_layout_change_;
217 // Detectors may not exist, for instance if ScreenshareLayers is used.
218 auto& detector =
219 overshoot_detectors_[encoded_image.SpatialIndex().value_or(0)]
220 [temporal_index];
221 if (detector) {
222 detector->OnEncodedFrame(encoded_image.size(), rtc::TimeMillis());
223 }
224}
225
226void EncoderBitrateAdjuster::Reset() {
227 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
228 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
229 overshoot_detectors_[si][ti].reset();
230 }
231 }
232 // Call AdjustRateAllocation() with the last know bitrate allocation, so that
233 // the appropriate overuse detectors are immediately re-created.
234 AdjustRateAllocation(current_bitrate_allocation_,
235 current_total_framerate_fps_);
236}
237
238} // namespace webrtc