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