| /* | |
| * Copyright (c) 2026 The WebRTC project authors. All Rights Reserved. | |
| * | |
| * Use of this source code is governed by a BSD-style license | |
| * that can be found in the LICENSE file in the root of the source | |
| * tree. An additional intellectual property rights grant can be found | |
| * in the file PATENTS. All contributing project authors may | |
| * be found in the AUTHORS file in the root of the source tree. | |
| */ | |
| #include "modules/video_coding/rate_control/buffer_level_rate_controller.h" | |
| #include <algorithm> | |
| #include <cmath> | |
| #include <cstdint> | |
| #include <optional> | |
| #include <span> | |
| #include <utility> | |
| #include "absl/base/nullability.h" | |
| #include "api/media_stream_interface.h" | |
| #include "api/sequence_checker.h" | |
| #include "api/units/data_rate.h" | |
| #include "api/units/data_size.h" | |
| #include "api/units/frequency.h" | |
| #include "api/units/time_delta.h" | |
| #include "api/units/timestamp.h" | |
| #include "api/video/resolution.h" | |
| #include "api/video_codecs/buffer_level_rate_controller_config.h" | |
| #include "api/video_codecs/video_encoder_interface.h" | |
| #include "api/video_codecs/video_rate_controller.h" | |
| #include "modules/video_coding/rate_control/scene_analyzer.h" | |
| #include "rtc_base/checks.h" | |
| namespace webrtc { | |
| namespace { | |
| using ContentHint = VideoTrackInterface::ContentHint; | |
| using FrameType = VideoEncoderInterface::FrameType; | |
| // Many constants and heuristics below originate from libaom's one-pass CBR | |
| // rate controller (`av1/encoder/ratectrl.c`). | |
| // AV1 defines 256 quantizer indices [0, 255], where 0 is lossless. | |
| constexpr int kNumAv1QIndices = 256; | |
| // Minimum estimated frame size floor accounting for fixed bitstream headers | |
| // (libaom's `FRAME_OVERHEAD_BITS = 200 bits`). | |
| constexpr DataSize kFrameOverhead = DataSize::Bytes(25); | |
| // Bounds on the adaptive bits-per-macroblock correction multiplier so outlier | |
| // frames cannot corrupt the R-Q model (libaom's `MIN_BPB_FACTOR` / | |
| // `MAX_BPB_FACTOR`). | |
| constexpr double kMinRateCorrectionFactor = 0.005; | |
| constexpr double kMaxRateCorrectionFactor = 50.0; | |
| // Upper cap on a single frame's planned target size: 250 bits per 16x16 | |
| // macroblock, floored at the 1080p equivalent (`1920*1080/256 * 250 bits = | |
| // 253,125 bytes`, libaom's `MAX_MB_RATE` and `MAXRATE_1080P`) so lower | |
| // resolutions retain burst headroom for keyframes and scene changes. | |
| constexpr int64_t kMaxTargetBitsPerMb = 250; | |
| constexpr DataSize kMinMaxFrameTarget = DataSize::Bytes(253125); | |
| // Max percentage a P-frame target may shrink on buffer deficit or grow on | |
| // buffer surplus (`CalcPframeTarget` divides by 200, so 50 gives +/-25%; | |
| // matches `LibaomAv1Encoder`'s libaom configuration). | |
| constexpr int kUndershootPct = 50; | |
| constexpr int kOvershootPct = 50; | |
| // Smoothing factor for each layer's measured temporal decimation factor. Small | |
| // enough (0.5) that genuine cadence changes (e.g. L1T3 <-> L1T2) settle within | |
| // a few base-layer cycles. | |
| constexpr double kDecimationFactorAlpha = 0.5; | |
| // Relative bitrate change above which QP damping is bypassed for one frame. | |
| constexpr double kBitrateChangeResetFraction = 0.1; | |
| // Duration after a scene change, re-encode, or post-encode drop during which | |
| // `fast_recovery` doubles the downward QP step limit. | |
| constexpr TimeDelta kFastRecoveryWindow = TimeDelta::Seconds(1); | |
| // Minimum per-64x64-block SAD indicating active content change when relaxing | |
| // the upward QP jump cap after an overshoot with a low buffer. | |
| constexpr double kOvershootSadPer64x64Threshold = 1000.0; | |
| // Maximum per-64x64-block SAD allowed before suppressing the base-layer QP | |
| // push (above this, content is changing rapidly enough not to bias QP down). | |
| constexpr double kBaseLayerPushMaxSadPer64x64 = 100000.0; | |
| // Average SAD threshold (32 luma levels per pixel in a 64x64 block) below | |
| // which HD+ camera scene changes use a gentler QP jump. | |
| constexpr double kCameraSceneChangeSadPer64x64Threshold = 64 * 64 * 32.0; | |
| constexpr int kHdPixelCountThreshold = 1280 * 720; | |
| constexpr int kSceneBlockPixels = 64 * 64; | |
| // Closed-form approximation of the AV1 8-bit AC quantizer step curve | |
| // (`ac_qlookup_QTX / 4`): exact at q = 0 (1.0), exact linear `(q + 7) / 4` on | |
| // q = 1..95 (2.0..25.5), and a shifted exponential on q = 96..255 | |
| // (25.5..457.0) matching the spec table within ~1.8%. | |
| constexpr int kLinearQIndexMax = 95; | |
| constexpr double kLinearQStepMax = (kLinearQIndexMax + 7) / 4.0; | |
| constexpr double kExpQStepScale = 84.0 / 4.0; | |
| constexpr double kExpQStepOffset = 18.0 / 4.0; | |
| constexpr double kMaxQStep = 1828.0 / 4.0; | |
| // `log((kMaxQStep - kExpQStepOffset) / kExpQStepScale) / | |
| // (kNumAv1QIndices - 1 - kLinearQIndexMax)` so qindex 255 lands on | |
| // `kMaxQStep`. | |
| constexpr double kExpQStepRate = 0.019189158283853487; | |
| // Converts an AV1 qindex [0, 255] to its 8-bit AC quantizer step [1.0, 457.0]. | |
| double Av1QIndexToQStep(int qindex) { | |
| if (qindex <= 0) { | |
| return 1.0; | |
| } | |
| if (qindex >= kNumAv1QIndices - 1) { | |
| return kMaxQStep; | |
| } | |
| if (qindex <= kLinearQIndexMax) { | |
| return (qindex + 7) / 4.0; | |
| } | |
| return kExpQStepScale * | |
| std::exp(kExpQStepRate * (qindex - kLinearQIndexMax)) + | |
| kExpQStepOffset; | |
| } | |
| // Lowest qindex in `[best_qindex, worst_qindex]` whose quantizer step is at | |
| // least `desired_q_step`. | |
| int FindQIndexForQStep(double desired_q_step, | |
| int best_qindex, | |
| int worst_qindex) { | |
| if (!(desired_q_step < kMaxQStep)) { | |
| return worst_qindex; | |
| } | |
| int raw_q; | |
| if (desired_q_step <= 1.0) { | |
| raw_q = 0; | |
| } else if (desired_q_step <= kLinearQStepMax) { | |
| raw_q = | |
| std::max(1, static_cast<int>(std::ceil(4.0 * desired_q_step - 7.0))); | |
| } else { | |
| const double continuous_q = | |
| kLinearQIndexMax + | |
| std::log((desired_q_step - kExpQStepOffset) / kExpQStepScale) / | |
| kExpQStepRate; | |
| raw_q = std::max(kLinearQIndexMax + 1, | |
| static_cast<int>(std::ceil(continuous_q))); | |
| } | |
| int q = std::clamp(raw_q, best_qindex, worst_qindex); | |
| // Guard against 1-ULP rounding at exact integer qindex boundaries. | |
| if (q > best_qindex && Av1QIndexToQStep(q - 1) >= desired_q_step) { | |
| --q; | |
| } else if (q < worst_qindex && Av1QIndexToQStep(q) < desired_q_step) { | |
| ++q; | |
| } | |
| return q; | |
| } | |
| // Empirical 3rd-order polynomial from libaom (`init_minq_luts`, `rtc` table) | |
| // mapping `active_worst_qindex` to a floor `active_best_qindex` so QP does not | |
| // plunge far below the recent quality envelope. Steps <= 2.0 map to 0 (matching | |
| // libaom's `get_minq_index`). | |
| int RtcMinQIndex(int worst_qindex) { | |
| const double max_q_step = Av1QIndexToQStep(worst_qindex); | |
| const double min_q_step_target = std::min( | |
| ((0.00000271 * max_q_step - 0.00113) * max_q_step + 0.70) * max_q_step, | |
| max_q_step); | |
| if (min_q_step_target <= 2.0) { | |
| return 0; | |
| } | |
| return FindQIndexForQStep(min_q_step_target, 0, kNumAv1QIndices - 1); | |
| } | |
| // Indexes `avg_frame_qindex` and `last_qindex`. | |
| enum FrameKind { kKeyFrameKind = 0, kInterFrameKind = 1 }; | |
| // Indexes `rate_correction_factors`: separate R-Q multipliers for intra vs | |
| // inter frames. | |
| enum RateFactorLevel { kInterNormal = 0, kKfStd = 1 }; | |
| // Empirical baseline bits per 16x16 macroblock at `q_step = 1.0` and | |
| // `rate_correction_factor = 1.0` (libaom's `get_bpmb_enumerator` divided by | |
| // `2^9` from `BPER_MB_NORMBITS`). Screen content needs roughly half the bits | |
| // of camera video, and intra frames need ~1.33x inter frames. | |
| double BaseBitsPerMb(bool is_screen, bool intra) { | |
| constexpr double kLibaomNormScale = 512.0; // 2^BPER_MB_NORMBITS | |
| const double numerator = is_screen ? (intra ? 1000000.0 : 750000.0) | |
| : (intra ? 2000000.0 : 1500000.0); | |
| return numerator / kLibaomNormScale; | |
| } | |
| // Counts 16x16 macroblocks using libaom's `av1_get_MBs` rounding (dimensions | |
| // rounded up to 8-pixel multiples, then to 16x16 blocks; minimum 1). | |
| int64_t NumMacroblocks(Resolution resolution) { | |
| const int mi_cols = ((resolution.width + 7) & ~7) >> 2; | |
| const int mi_rows = ((resolution.height + 7) & ~7) >> 2; | |
| const int64_t mb_cols = (mi_cols + 2) >> 2; | |
| const int64_t mb_rows = (mi_rows + 2) >> 2; | |
| return std::max<int64_t>(1, mb_cols * mb_rows); | |
| } | |
| // Expected temporal decimation factor (stream frame slots per layer frame) of | |
| // `tid` in a dyadic hierarchy whose highest active layer is `top_tid` (e.g. | |
| // L1T3: TL0=4, TL1=4, TL2=2; L1T2: TL0=2, TL1=2; L1T1: TL0=1). | |
| double ExpectedDyadicDecimationFactor(int tid, int top_tid) { | |
| if (top_tid <= 0) { | |
| return 1.0; | |
| } | |
| return static_cast<double>(1 << (top_tid - std::max(0, tid - 1))); | |
| } | |
| } // namespace | |
| BufferLevelRateController::BufferLevelRateController( | |
| const BufferLevelRateControllerConfig& config) | |
| : config_(config), | |
| worst_quality_qindex_(std::clamp(config.max_qp, 0, kNumAv1QIndices - 1)), | |
| // qindex 0 is lossless coding in AV1 (orders of magnitude larger than | |
| // qindex 1), so clamp the lossy floor to at least 1 unless max_qp == 0. | |
| best_quality_qindex_(std::clamp(config.min_qp, | |
| std::min(1, worst_quality_qindex_), | |
| worst_quality_qindex_)) { | |
| RTC_DCHECK(config.max_buffer_size.IsFinite()); | |
| RTC_DCHECK_GT(config.max_buffer_size, TimeDelta::Zero()); | |
| RTC_DCHECK_GT(config.target_buffer_size, TimeDelta::Zero()); | |
| RTC_DCHECK_LE(config.target_buffer_size, config.max_buffer_size); | |
| RTC_DCHECK_GE(config.max_intra_bitrate_factor, 0.0); | |
| RTC_DCHECK_LE(config.min_qp, config.max_qp); | |
| RTC_DCHECK_GE(config.drop_frames_water_mark_pct, 0); | |
| RTC_DCHECK_LE(config.drop_frames_water_mark_pct, 100); | |
| RTC_DCHECK_GE(config.max_consecutive_drop, TimeDelta::Zero()); | |
| RTC_DCHECK_GE(config.reencode_target_factor, 0.0); | |
| RTC_DCHECK_GE(config.base_layer_qp_push, 0); | |
| if (config.max_buffer_credit_pct.has_value()) { | |
| RTC_DCHECK_GE(*config.max_buffer_credit_pct, 0); | |
| RTC_DCHECK_LE(*config.max_buffer_credit_pct, 100); | |
| } | |
| RTC_DCHECK_GE(config.max_static_source_sad_per_64x64, 0.0); | |
| } | |
| BufferLevelRateController::LayerState | |
| BufferLevelRateController::InitialLayerState() const { | |
| // Matches libaom's `av1_primary_rc_init` for one-pass CBR: start the inter | |
| // QP envelope conservatively at max QP; `last_keyframe_index_` guards | |
| // against using the initial keyframe `last_qindex` on delta-only streams. | |
| LayerState state; | |
| state.buffer_level = config_.target_buffer_size; | |
| state.avg_frame_qindex = {worst_quality_qindex_, worst_quality_qindex_}; | |
| state.last_qindex[kKeyFrameKind] = best_quality_qindex_; | |
| state.last_qindex[kInterFrameKind] = worst_quality_qindex_; | |
| return state; | |
| } | |
| BufferLevelRateController::PendingFrame* absl_nullable | |
| BufferLevelRateController::FindPending(PlanId id) { | |
| for (PendingFrame& pending : pending_frames_) { | |
| if (pending.id == id) { | |
| return &pending; | |
| } | |
| } | |
| return nullptr; | |
| } | |
| const BufferLevelRateController::PendingFrame* absl_nullable | |
| BufferLevelRateController::FindPending(PlanId id) const { | |
| for (const PendingFrame& pending : pending_frames_) { | |
| if (pending.id == id) { | |
| return &pending; | |
| } | |
| } | |
| return nullptr; | |
| } | |
| BufferLevelRateController::PendingFrame BufferLevelRateController::TakePending( | |
| PlanId id) { | |
| auto it = std::find_if( | |
| pending_frames_.begin(), pending_frames_.end(), | |
| [id](const PendingFrame& pending) { return pending.id == id; }); | |
| RTC_CHECK(it != pending_frames_.end()) | |
| << "Unknown or already retired PlanId: " << id; | |
| PendingFrame pending = std::move(*it); | |
| pending_frames_.erase(it); | |
| return pending; | |
| } | |
| bool BufferLevelRateController::HasPendingForLayer(int tid) const { | |
| return std::any_of(pending_frames_.begin(), pending_frames_.end(), | |
| [tid](const PendingFrame& pending) { | |
| return pending.ctx.temporal_id == tid; | |
| }); | |
| } | |
| TimeDelta BufferLevelRateController::InFlightDuration( | |
| int tid, | |
| std::optional<PlanId> exclude_id) const { | |
| DataSize in_flight_size = DataSize::Zero(); | |
| for (const PendingFrame& pending : pending_frames_) { | |
| if (!pending.drop && pending.ctx.temporal_id <= tid && | |
| (!exclude_id.has_value() || pending.id != *exclude_id)) { | |
| in_flight_size += pending.current_target_size; | |
| } | |
| } | |
| const DataRate bitrate = CumulativeBitrate(tid); | |
| if (in_flight_size.IsZero() || bitrate.IsZero()) { | |
| return TimeDelta::Zero(); | |
| } | |
| return in_flight_size / bitrate; | |
| } | |
| BufferLevelRateController::LayerState | |
| BufferLevelRateController::EffectiveLayerState( | |
| int tid, | |
| std::optional<PlanId> exclude_id) const { | |
| LayerState state = layers_[tid]; | |
| state.buffer_level -= InFlightDuration(tid, exclude_id); | |
| return state; | |
| } | |
| void BufferLevelRateController::CapBufferLevel( | |
| LayerState& layer, | |
| TimeDelta in_flight_duration) const { | |
| layer.buffer_level = std::min(layer.buffer_level, | |
| config_.max_buffer_size + in_flight_duration); | |
| if (config_.max_buffer_credit_pct) { | |
| const TimeDelta headroom = | |
| std::max(TimeDelta::Zero(), | |
| config_.max_buffer_size - config_.target_buffer_size); | |
| layer.buffer_level = | |
| std::min(layer.buffer_level, | |
| config_.target_buffer_size + | |
| headroom * (*config_.max_buffer_credit_pct) / 100 + | |
| in_flight_duration); | |
| } | |
| } | |
| void BufferLevelRateController::AdvanceClockAndDrainBuffers( | |
| Timestamp timestamp, | |
| TimeDelta duration) { | |
| if (!last_timestamp_.has_value()) { | |
| last_timestamp_ = timestamp; | |
| prev_frame_duration_ = duration; | |
| return; | |
| } | |
| const TimeDelta elapsed = | |
| std::max(TimeDelta::Zero(), timestamp - *last_timestamp_); | |
| last_timestamp_ = std::max(*last_timestamp_, timestamp); | |
| if (elapsed > TimeDelta::Zero()) { | |
| if (prev_frame_duration_ > TimeDelta::Zero()) { | |
| slot_position_ += elapsed / prev_frame_duration_; | |
| } | |
| for (int tid = 0; tid < kMaxTemporalLayers; ++tid) { | |
| if (layers_[tid].initialized) { | |
| layers_[tid].buffer_level += elapsed; | |
| CapBufferLevel(layers_[tid], InFlightDuration(tid)); | |
| } | |
| } | |
| } | |
| prev_frame_duration_ = duration; | |
| } | |
| double BufferLevelRateController::LayerDecimationFactor(int tid) const { | |
| if (layers_[tid].temporal_decimation_factor.has_value()) { | |
| return *layers_[tid].temporal_decimation_factor; | |
| } | |
| return ExpectedDyadicDecimationFactor(tid, HighestInitializedTemporalId()); | |
| } | |
| double BufferLevelRateController::CumulativeFrameFraction(int tid) const { | |
| double fraction = 0.0; | |
| for (int t = 0; t <= tid; ++t) { | |
| if (layers_[t].initialized) { | |
| const double factor = LayerDecimationFactor(t); | |
| if (factor > 0.0) { | |
| fraction += 1.0 / factor; | |
| } | |
| } | |
| } | |
| return fraction > 0.0 ? fraction : 1.0; | |
| } | |
| DataRate BufferLevelRateController::CumulativeBitrate(int tid) const { | |
| DataRate bitrate = DataRate::Zero(); | |
| for (int t = 0; t <= tid; ++t) { | |
| if (layers_[t].initialized) { | |
| bitrate += layers_[t].target_bitrate; | |
| } | |
| } | |
| return bitrate; | |
| } | |
| int BufferLevelRateController::HighestInitializedTemporalId() const { | |
| for (int t = kMaxTemporalLayers - 1; t >= 0; --t) { | |
| if (layers_[t].initialized) { | |
| return t; | |
| } | |
| } | |
| return 0; | |
| } | |
| int BufferLevelRateController::Tl0PeriodFrames() const { | |
| if (!layers_[0].initialized || HighestInitializedTemporalId() == 0) { | |
| return 1; | |
| } | |
| return std::max(1, static_cast<int>(std::round(LayerDecimationFactor(0)))); | |
| } | |
| std::optional<int64_t> BufferLevelRateController::FramesSinceKey() const { | |
| if (!last_keyframe_index_.has_value()) { | |
| return std::nullopt; | |
| } | |
| return frame_count_ - *last_keyframe_index_; | |
| } | |
| void BufferLevelRateController::RecordOvershoot(Timestamp timestamp) { | |
| last_overshoot_timestamp_ = | |
| last_overshoot_timestamp_.has_value() | |
| ? std::max(*last_overshoot_timestamp_, timestamp) | |
| : timestamp; | |
| } | |
| void BufferLevelRateController::UpdateLayerCadenceAndRate( | |
| int tid, | |
| DataRate target_bitrate) { | |
| LayerState& layer = layers_[tid]; | |
| const std::optional<double> prev_slot = layer.last_frame_slot; | |
| const double slots_since_last = | |
| prev_slot.has_value() ? slot_position_ - *prev_slot : 0.0; | |
| // Retire upper layers whose minimum dyadic period is incompatible with this | |
| // layer's newly observed cadence (e.g. L1T3 -> L1T2 where TL0/TL1 arrive 2 | |
| // slots apart without TL2, or L1T3 -> L1T1 where TL0 arrives 1 slot apart). | |
| // Repeat-frame dropping (`kQualityConvergence` / `kKeepAlive`) keeps TL0 at | |
| // >= its full multi-layer period (e.g. 4 slots or >= 500 ms), so upper layers | |
| // stay intact and resume immediately on user activity. | |
| if (layer.initialized && prev_slot.has_value() && slots_since_last >= 0.5) { | |
| for (int top = kMaxTemporalLayers - 1; top > tid; --top) { | |
| if (!layers_[top].initialized) { | |
| continue; | |
| } | |
| const bool top_unseen_in_cycle = | |
| !layers_[top].last_frame_slot.has_value() || | |
| *layers_[top].last_frame_slot < *prev_slot; | |
| const double required_period = ExpectedDyadicDecimationFactor(tid, top); | |
| if (top_unseen_in_cycle && slots_since_last < 0.75 * required_period && | |
| !HasPendingForLayer(top)) { | |
| layers_[top] = {}; | |
| } else { | |
| break; | |
| } | |
| } | |
| } | |
| if (!layer.initialized) { | |
| if (tid > 0 && layers_[0].initialized) { | |
| // Inherit the base layer's R-Q and buffer envelope when an enhancement | |
| // layer first appears (or reappears after being retired during L1T1). | |
| layer = layers_[0]; | |
| layer.temporal_decimation_factor.reset(); | |
| layer.last_frame_slot.reset(); | |
| } else { | |
| layer = InitialLayerState(); | |
| } | |
| layer.initialized = true; | |
| layer.target_bitrate = target_bitrate; | |
| layer.bitrate_estimated = false; | |
| layer.prev_bitrate = CumulativeBitrate(tid); | |
| // Keep `prev_bitrate` consistent for any higher layer that initialized | |
| // earlier (e.g. T2 before T1 on L1T3 startup) so lazy initialization does | |
| // not falsely trigger `ChangedTargetBitsPerMb`. | |
| for (int t = tid + 1; t < kMaxTemporalLayers; ++t) { | |
| if (layers_[t].initialized) { | |
| layers_[t].prev_bitrate += target_bitrate; | |
| } | |
| } | |
| } else { | |
| if (!layer.bitrate_estimated && layer.target_bitrate > DataRate::Zero() && | |
| layer.target_bitrate != target_bitrate) { | |
| // Scale other initialized layers proportionally so cumulative bitrates | |
| // reflect target bitrate changes before every layer arrives. Mark scaled | |
| // layers as estimated so a non-proportional split change does not rescale | |
| // already confirmed layers or oscillate during subsequent rate changes. | |
| const double change = target_bitrate / layer.target_bitrate; | |
| for (int t = 0; t < kMaxTemporalLayers; ++t) { | |
| if (t != tid && layers_[t].initialized && | |
| layers_[t].target_bitrate > DataRate::Zero()) { | |
| layers_[t].target_bitrate = std::max( | |
| DataRate::BitsPerSec(1), layers_[t].target_bitrate * change); | |
| layers_[t].bitrate_estimated = true; | |
| } | |
| } | |
| } | |
| layer.target_bitrate = target_bitrate; | |
| layer.bitrate_estimated = false; | |
| const int top_tid = HighestInitializedTemporalId(); | |
| if (top_tid == 0) { | |
| // Single-layer stream: TL0 is 100% of frames regardless of capture | |
| // pauses or variable capture framerate. | |
| layer.temporal_decimation_factor.reset(); | |
| } else if (prev_slot.has_value()) { | |
| const double expected = ExpectedDyadicDecimationFactor(tid, top_tid); | |
| if (slots_since_last >= 0.5 && slots_since_last <= 1.25 * expected) { | |
| if (!layer.temporal_decimation_factor.has_value()) { | |
| layer.temporal_decimation_factor = slots_since_last; | |
| } else { | |
| layer.temporal_decimation_factor = | |
| kDecimationFactorAlpha * (*layer.temporal_decimation_factor) + | |
| (1.0 - kDecimationFactorAlpha) * slots_since_last; | |
| } | |
| } | |
| } | |
| } | |
| layer.last_frame_slot = slot_position_; | |
| // Re-cap initialized layers after a bitrate update changes | |
| // `InFlightDuration`. | |
| for (int t = 0; t < kMaxTemporalLayers; ++t) { | |
| if (layers_[t].initialized) { | |
| CapBufferLevel(layers_[t], InFlightDuration(t)); | |
| } | |
| } | |
| } | |
| DataSize BufferLevelRateController::LayerFrameBandwidth( | |
| int tid, | |
| TimeDelta duration) const { | |
| return CumulativeBitrate(tid) * (duration / CumulativeFrameFraction(tid)); | |
| } | |
| DataSize BufferLevelRateController::LayerFrameSize(int tid, | |
| TimeDelta duration) const { | |
| // Budget of this layer's frames alone: `target_bitrate * layer_interval`. | |
| return layers_[tid].target_bitrate * (duration * LayerDecimationFactor(tid)); | |
| } | |
| BufferLevelRateController::FrameContext BufferLevelRateController::MakeContext( | |
| int tid, | |
| TimeDelta duration, | |
| const TemporalUnitSettings& tu_settings, | |
| const FrameEncodeSettings& frame_settings) const { | |
| FrameContext ctx; | |
| ctx.temporal_id = tid; | |
| ctx.multi_layer = HighestInitializedTemporalId() > 0; | |
| ctx.tl0_period_frames = Tl0PeriodFrames(); | |
| ctx.intra = frame_settings.frame_type() != FrameType::kDeltaFrame; | |
| ctx.is_screen = tu_settings.content_hint() == ContentHint::kText || | |
| tu_settings.content_hint() == ContentHint::kDetailed; | |
| ctx.timestamp = tu_settings.presentation_timestamp(); | |
| ctx.duration = duration; | |
| ctx.resolution = frame_settings.resolution(); | |
| ctx.num_macroblocks = NumMacroblocks(ctx.resolution); | |
| ctx.avg_frame_bandwidth = LayerFrameBandwidth(ctx.temporal_id, ctx.duration); | |
| ctx.avg_frame_size = LayerFrameSize(ctx.temporal_id, ctx.duration); | |
| ctx.max_frame_size = | |
| std::max(DataSize::Bytes(ctx.num_macroblocks * kMaxTargetBitsPerMb / 8), | |
| kMinMaxFrameTarget); | |
| return ctx; | |
| } | |
| // Keyframe target size (`av1_calc_iframe_target_size_one_pass_cbr`). | |
| DataSize BufferLevelRateController::CalcIframeTarget( | |
| const FrameContext& ctx) const { | |
| DataSize target; | |
| if (frame_count_ == 0) { | |
| // The very first frame gets half the initial target buffer. | |
| target = | |
| CumulativeBitrate(ctx.temporal_id) * config_.target_buffer_size / 2; | |
| } else { | |
| // Mid-stream keyframes get `(16 + kf_boost) / 16` times the nominal frame | |
| // budget (at least 3x, growing with framerate up to ~125 ms of stream | |
| // bitrate), ramped down linearly if another keyframe occurred within 0.5 s. | |
| const Frequency framerate = 1 / ctx.duration; | |
| int kf_boost = std::max( | |
| 32, static_cast<int>(std::round(2 * framerate.hertz<double>() - 16))); | |
| const double half_sec_frames = framerate * TimeDelta::Millis(500); | |
| if (std::optional<int64_t> frames_since_key = FramesSinceKey(); | |
| frames_since_key.has_value() && *frames_since_key < half_sec_frames) { | |
| kf_boost = | |
| static_cast<int>(kf_boost * (*frames_since_key) / half_sec_frames); | |
| } | |
| target = ctx.avg_frame_bandwidth * (16 + kf_boost) / 16; | |
| } | |
| if (config_.max_intra_bitrate_factor > 0) { | |
| // Note: because temporal layers are discovered lazily, on `frame_count_ == | |
| // 0` `CumulativeFrameFraction` is 1.0, so the initial keyframe is capped | |
| // using TL0's 1-slot duration until enhancement layers arrive. | |
| const DataSize max_intra_size = | |
| CumulativeBitrate(ctx.temporal_id) * | |
| (ctx.duration / CumulativeFrameFraction(ctx.temporal_id) * | |
| config_.max_intra_bitrate_factor); | |
| target = std::min(target, max_intra_size); | |
| } | |
| return std::min(target, ctx.max_frame_size); | |
| } | |
| // Delta-frame target size (`av1_calc_pframe_target_size_one_pass_cbr`). | |
| DataSize BufferLevelRateController::CalcPframeTarget( | |
| const FrameContext& ctx, | |
| const LayerState& layer) const { | |
| const TimeDelta deficit = config_.target_buffer_size - layer.buffer_level; | |
| const TimeDelta one_pct = | |
| TimeDelta::Micros(1) + config_.target_buffer_size / 100; | |
| DataSize target = ctx.avg_frame_size; | |
| const DataSize min_frame_target = | |
| std::max(ctx.avg_frame_size / 16, kFrameOverhead); | |
| if (deficit > TimeDelta::Zero()) { | |
| // Buffer below target: shrink budget by up to `kUndershootPct / 2`%. | |
| const int64_t pct_low = static_cast<int64_t>( | |
| std::min(deficit / one_pct, double{kUndershootPct})); | |
| target -= (target * pct_low) / 200; | |
| } else if (deficit < TimeDelta::Zero()) { | |
| // Buffer above target: grow budget by up to `kOvershootPct / 2`%. | |
| const int64_t pct_high = static_cast<int64_t>( | |
| std::min(-deficit / one_pct, double{kOvershootPct})); | |
| target += (target * pct_high) / 200; | |
| } | |
| return std::min(std::max(min_frame_target, target), ctx.max_frame_size); | |
| } | |
| double BufferLevelRateController::GetRateCorrectionFactor( | |
| const FrameContext& ctx, | |
| const LayerState& layer) const { | |
| const double rcf = | |
| layer.rate_correction_factors[ctx.intra ? kKfStd : kInterNormal]; | |
| return std::clamp(rcf, kMinRateCorrectionFactor, kMaxRateCorrectionFactor); | |
| } | |
| void BufferLevelRateController::SetRateCorrectionFactor(const FrameContext& ctx, | |
| LayerState& layer, | |
| double factor) const { | |
| layer.rate_correction_factors[ctx.intra ? kKfStd : kInterNormal] = | |
| std::clamp(factor, kMinRateCorrectionFactor, kMaxRateCorrectionFactor); | |
| } | |
| double BufferLevelRateController::BitsPerMacroblock( | |
| const FrameContext& ctx, | |
| int qindex, | |
| double correction_factor) const { | |
| return BaseBitsPerMb(ctx.is_screen, ctx.intra) * correction_factor / | |
| Av1QIndexToQStep(qindex); | |
| } | |
| DataSize BufferLevelRateController::EstimateSizeAtQIndex( | |
| const FrameContext& ctx, | |
| int qindex, | |
| double correction_factor) const { | |
| const double estimated_bits = | |
| BitsPerMacroblock(ctx, qindex, correction_factor) * ctx.num_macroblocks; | |
| return std::max(kFrameOverhead, | |
| DataSize::Bytes(static_cast<int64_t>(estimated_bits / 8.0))); | |
| } | |
| int BufferLevelRateController::FindClosestQIndexByRate( | |
| const FrameContext& ctx, | |
| double desired_bits_per_mb, | |
| double correction_factor, | |
| int best_qindex, | |
| int worst_qindex) const { | |
| RTC_DCHECK_LE(best_qindex, worst_qindex); | |
| if (desired_bits_per_mb <= 0.0) { | |
| return worst_qindex; | |
| } | |
| const double desired_q_step = BaseBitsPerMb(ctx.is_screen, ctx.intra) * | |
| correction_factor / desired_bits_per_mb; | |
| const int curr_qindex = | |
| FindQIndexForQStep(desired_q_step, best_qindex, worst_qindex); | |
| const double curr_bits_per_mb = | |
| BitsPerMacroblock(ctx, curr_qindex, correction_factor); | |
| if (curr_bits_per_mb > desired_bits_per_mb || curr_qindex == best_qindex) { | |
| return curr_qindex; | |
| } | |
| // Pick the lower qindex if its predicted rate is closer to the target. | |
| const double prev_bits_per_mb = | |
| BitsPerMacroblock(ctx, curr_qindex - 1, correction_factor); | |
| return desired_bits_per_mb - curr_bits_per_mb <= | |
| prev_bits_per_mb - desired_bits_per_mb | |
| ? curr_qindex | |
| : curr_qindex - 1; | |
| } | |
| // Upper QP bound for the current frame | |
| // (`calc_active_worst_quality_no_stats_cbr`). | |
| int BufferLevelRateController::CalcActiveWorstQIndex( | |
| const FrameContext& ctx, | |
| const LayerState& layer) const { | |
| if (ctx.intra) { | |
| // Spatial-variance relaxation for keyframes is not used here. | |
| return worst_quality_qindex_; | |
| } | |
| const int num_frames_weight_key = 5 * ctx.tl0_period_frames; | |
| // For the first few cycles after a keyframe, weigh in the keyframe QP | |
| // (stored on the base layer for layered streams) so inter quality does not | |
| // abruptly drop after a clean keyframe. | |
| int ambient_qindex = layer.avg_frame_qindex[kInterFrameKind]; | |
| if (std::optional<int64_t> frames_since_key = FramesSinceKey()) { | |
| int avg_qindex_key = layer.avg_frame_qindex[kKeyFrameKind]; | |
| if ((ctx.multi_layer || config_.keyframe_recovery) && | |
| layers_[0].initialized) { | |
| const LayerState& base = layers_[0]; | |
| avg_qindex_key = std::min(base.avg_frame_qindex[kKeyFrameKind], | |
| base.last_qindex[kKeyFrameKind]); | |
| } | |
| if (ctx.temporal_id > 0 && *frames_since_key < 2 * ctx.tl0_period_frames) { | |
| ambient_qindex = avg_qindex_key; | |
| } else if (*frames_since_key < num_frames_weight_key) { | |
| ambient_qindex = std::min(ambient_qindex, avg_qindex_key); | |
| } | |
| } | |
| ambient_qindex = std::min(worst_quality_qindex_, ambient_qindex); | |
| // Above target fullness, start at 1.25x ambient and pull down by up to 1/3 | |
| // as the buffer fills toward `max_buffer_size`. Between 12.5% (`critical`) | |
| // and target, interpolate from `ambient` up to `worst_quality_qindex_`. | |
| const TimeDelta critical_level = config_.target_buffer_size / 8; | |
| int active_worst_qindex; | |
| if (layer.buffer_level > config_.target_buffer_size) { | |
| active_worst_qindex = | |
| std::min(worst_quality_qindex_, ambient_qindex * 5 / 4); | |
| const int max_adjustment_down_qindex = active_worst_qindex / 3; | |
| if (max_adjustment_down_qindex > 0) { | |
| const TimeDelta buffer_step = | |
| (config_.max_buffer_size - config_.target_buffer_size) / | |
| max_adjustment_down_qindex; | |
| if (buffer_step > TimeDelta::Zero()) { | |
| active_worst_qindex -= static_cast<int>( | |
| (layer.buffer_level - config_.target_buffer_size) / buffer_step); | |
| } | |
| } | |
| } else if (layer.buffer_level > critical_level) { | |
| active_worst_qindex = std::min(worst_quality_qindex_, ambient_qindex); | |
| if (critical_level > TimeDelta::Zero()) { | |
| const TimeDelta buffer_span = config_.target_buffer_size - critical_level; | |
| if (buffer_span > TimeDelta::Zero()) { | |
| active_worst_qindex += static_cast<int>( | |
| (worst_quality_qindex_ - ambient_qindex) * | |
| ((config_.target_buffer_size - layer.buffer_level) / buffer_span)); | |
| } | |
| } | |
| } else { | |
| active_worst_qindex = worst_quality_qindex_; | |
| } | |
| return active_worst_qindex; | |
| } | |
| // Lower QP bound for the current frame | |
| // (`calc_active_best_quality_no_stats_cbr`). | |
| int BufferLevelRateController::CalcActiveBestQIndex( | |
| const FrameContext& ctx, | |
| const LayerState& layer, | |
| int active_worst_qindex) const { | |
| if (ctx.intra) { | |
| return best_quality_qindex_; | |
| } | |
| const std::optional<int64_t> frames_since_key = FramesSinceKey(); | |
| const FrameKind kind = frames_since_key.has_value() && *frames_since_key <= 1 | |
| ? kKeyFrameKind | |
| : kInterFrameKind; | |
| return RtcMinQIndex( | |
| std::min(layer.avg_frame_qindex[kind], active_worst_qindex)); | |
| } | |
| bool BufferLevelRateController::ChangedTargetBitsPerMb( | |
| const FrameContext& ctx, | |
| const LayerState& layer) const { | |
| // Compare resolution and cumulative bitrate (rather than per-frame bits, as | |
| // libaom does) so framerate changes keep QP damping intact. | |
| if (!prev_coded_resolution_) { | |
| return false; | |
| } | |
| if (ctx.resolution != *prev_coded_resolution_) { | |
| return true; | |
| } | |
| if (layer.prev_bitrate.IsZero()) { | |
| return false; | |
| } | |
| const DataRate bitrate = CumulativeBitrate(ctx.temporal_id); | |
| const DataRate diff = bitrate > layer.prev_bitrate | |
| ? bitrate - layer.prev_bitrate | |
| : layer.prev_bitrate - bitrate; | |
| return diff > bitrate * kBitrateChangeResetFraction; | |
| } | |
| // Applies QP step limits, oscillation damping, and temporal-layer biases | |
| // (`adjust_q_cbr` without cyclic refresh). | |
| int BufferLevelRateController::AdjustQIndexCbr(const FrameContext& ctx, | |
| const LayerState& layer, | |
| int qindex, | |
| int active_worst_qindex) const { | |
| const std::optional<int64_t> frames_since_key = FramesSinceKey(); | |
| // If the previous frame overshot, content is changing, and the buffer is | |
| // below half target, allow a large upward QP jump (120 vs 20) to recover. | |
| const bool overshoot_buffer_low = | |
| layer.prev_rate_outcome == RateOutcome::kOvershoot && | |
| ctx.source_sad_per_64x64.value_or(0.0) > kOvershootSadPer64x64Threshold && | |
| layer.buffer_level < config_.target_buffer_size / 2 && | |
| (!frames_since_key.has_value() || *frames_since_key > 4); | |
| int max_delta_up_qindex = overshoot_buffer_low ? 120 : 20; | |
| const bool recovering = | |
| config_.fast_recovery && last_overshoot_timestamp_.has_value() && | |
| ctx.timestamp - *last_overshoot_timestamp_ < kFastRecoveryWindow; | |
| const int recovery_factor = recovering ? 2 : 1; | |
| // Screen text is more sensitive to sudden bitrate spikes, so normally halve | |
| // its downward QP step limit relative to camera video. | |
| int max_delta_down_qindex = | |
| recovery_factor * (ctx.is_screen | |
| ? std::clamp(layer.prev_frame_qindex / 16, 1, 8) | |
| : std::clamp(layer.prev_frame_qindex / 8, 1, 16)); | |
| // For static screen content after a scene change with a healthy buffer, let | |
| // QP converge down much faster (`rc_faster_convergence_static`). | |
| if (config_.faster_convergence_static && ctx.is_screen && | |
| ctx.source_sad_per_64x64.has_value() && | |
| *ctx.source_sad_per_64x64 <= config_.max_static_source_sad_per_64x64 && | |
| static_scene_change_index_.has_value() && | |
| frame_count_ - *static_scene_change_index_ > 4 && | |
| layer.buffer_level > config_.target_buffer_size / 2) { | |
| const bool buffer_above_target = | |
| layer.buffer_level > config_.target_buffer_size; | |
| if (layer.prev_rate_outcome == RateOutcome::kUndershoot) { | |
| qindex -= buffer_above_target ? 32 : 16; | |
| } | |
| max_delta_down_qindex = | |
| std::max(max_delta_down_qindex, buffer_above_target ? 60 : 32); | |
| max_delta_up_qindex = std::min(max_delta_up_qindex, 4); | |
| } | |
| const bool change_target_bits_mb = ChangedTargetBitsPerMb(ctx, layer); | |
| if (!ctx.intra && (!frames_since_key.has_value() || *frames_since_key > 1) && | |
| layer.prev_frame_qindex > 0 && layer.prev2_frame_qindex > 0 && | |
| (!ctx.multi_layer || frame_count_ > ctx.tl0_period_frames) && | |
| !change_target_bits_mb) { | |
| // After an overshoot followed by an undershoot (or vice versa), clamp | |
| // qindex between the previous two frames to damp oscillation. | |
| const bool oscillated = | |
| (layer.prev_rate_outcome == RateOutcome::kOvershoot && | |
| layer.prev2_rate_outcome == RateOutcome::kUndershoot) || | |
| (layer.prev_rate_outcome == RateOutcome::kUndershoot && | |
| layer.prev2_rate_outcome == RateOutcome::kOvershoot); | |
| if (oscillated && layer.prev_frame_qindex != layer.prev2_frame_qindex && | |
| !overshoot_buffer_low) { | |
| const int qindex_clamp = std::clamp( | |
| qindex, std::min(layer.prev_frame_qindex, layer.prev2_frame_qindex), | |
| std::max(layer.prev_frame_qindex, layer.prev2_frame_qindex)); | |
| // React faster if the immediate previous frame overshot. | |
| if (layer.prev_rate_outcome == RateOutcome::kOvershoot && | |
| qindex > qindex_clamp && | |
| (!frames_since_key.has_value() || *frames_since_key > 10)) { | |
| qindex = (qindex + qindex_clamp) >> 1; | |
| } else { | |
| qindex = qindex_clamp; | |
| } | |
| } | |
| if (layer.prev_frame_qindex - qindex > max_delta_down_qindex) { | |
| qindex = layer.prev_frame_qindex - max_delta_down_qindex; | |
| } else if (qindex - layer.prev_frame_qindex > max_delta_up_qindex) { | |
| qindex = layer.prev_frame_qindex + max_delta_up_qindex; | |
| } | |
| } | |
| if (!change_target_bits_mb) { | |
| if (ctx.temporal_id > 0 && layers_[0].initialized) { | |
| // Keep enhancement-layer QP close to or above the base layer when | |
| // enhancement frames have a smaller per-frame budget, since enhancement | |
| // layers predict from the base layer. Use the keyframe QP until a TL0 | |
| // delta frame has actually been coded. | |
| const LayerState& base = layers_[0]; | |
| const int last_qindex_tl0 = | |
| (!coded_inter_on_tl0_since_key_ && frames_since_key.has_value()) | |
| ? base.last_qindex[kKeyFrameKind] | |
| : base.last_qindex[kInterFrameKind]; | |
| const bool smaller_frames = | |
| ctx.avg_frame_size < LayerFrameSize(0, ctx.duration); | |
| if (smaller_frames && qindex < last_qindex_tl0 - 4) { | |
| qindex = last_qindex_tl0 - 4; | |
| } | |
| } else if (ctx.temporal_id == 0 && !ctx.intra && | |
| layer.buffer_level > config_.target_buffer_size / 4 && | |
| ctx.source_sad_per_64x64.value_or(0.0) < | |
| kBaseLayerPushMaxSadPer64x64) { | |
| // Bias base-layer QP downward while the buffer is healthy because all | |
| // enhancement layers reference it. | |
| if (ctx.multi_layer) { | |
| qindex -= ctx.tl0_period_frames >= 4 ? 10 : 4; | |
| } else if (config_.base_layer_qp_push > 0) { | |
| qindex -= config_.base_layer_qp_push; | |
| } | |
| } | |
| } | |
| // On a single-layer upscale (>1.5x pixels), pull QP halfway toward active | |
| // worst so the larger frame does not start at the smaller resolution's QP. | |
| if (!ctx.multi_layer && prev_coded_resolution_ && | |
| ctx.resolution.PixelCount() > | |
| 1.5 * prev_coded_resolution_->PixelCount()) { | |
| qindex = (qindex + active_worst_qindex) >> 1; | |
| } | |
| return std::clamp(qindex, best_quality_qindex_, worst_quality_qindex_); | |
| } | |
| int BufferLevelRateController::PickQIndex(const FrameContext& ctx, | |
| const LayerState& layer, | |
| DataSize target_size) const { | |
| int active_worst_qindex = CalcActiveWorstQIndex(ctx, layer); | |
| int active_best_qindex = | |
| CalcActiveBestQIndex(ctx, layer, active_worst_qindex); | |
| active_best_qindex = std::clamp(active_best_qindex, best_quality_qindex_, | |
| worst_quality_qindex_); | |
| active_worst_qindex = std::clamp(active_worst_qindex, active_best_qindex, | |
| worst_quality_qindex_); | |
| const double target_bits_per_mb = | |
| target_size.bytes<double>() * 8.0 / ctx.num_macroblocks; | |
| int qindex = FindClosestQIndexByRate(ctx, target_bits_per_mb, | |
| GetRateCorrectionFactor(ctx, layer), | |
| active_best_qindex, active_worst_qindex); | |
| qindex = AdjustQIndexCbr(ctx, layer, qindex, active_worst_qindex); | |
| // Only exceed `active_worst_qindex` when already targeting the max size cap. | |
| if (qindex > active_worst_qindex && target_size < ctx.max_frame_size) { | |
| qindex = active_worst_qindex; | |
| } | |
| return qindex; | |
| } | |
| int BufferLevelRateController::ResolveReportedQIndex( | |
| std::optional<int> reported_qp, | |
| int planned_qindex) const { | |
| if (!reported_qp.has_value() || *reported_qp < 0 || | |
| *reported_qp >= kNumAv1QIndices) { | |
| return planned_qindex; | |
| } | |
| return *reported_qp; | |
| } | |
| // Picks a strictly higher qindex for a re-encode by fitting the R-Q correction | |
| // factor directly to the rejected attempt's observed size without mutating | |
| // controller state. | |
| int BufferLevelRateController::PickReencodeQIndex( | |
| const FrameContext& ctx, | |
| std::span<const EncodeAttempt> attempts, | |
| int planned_qindex, | |
| DataSize target_size) const { | |
| // Always strictly advance beyond `planned_qindex` and all prior resolved | |
| // attempts so re-encode retries converge monotonically toward max QP. | |
| int min_qindex = std::max( | |
| best_quality_qindex_, | |
| std::min(worst_quality_qindex_, | |
| std::clamp(planned_qindex, 0, worst_quality_qindex_) + 1)); | |
| for (const EncodeAttempt& attempt : attempts) { | |
| const int attempt_qindex = | |
| std::clamp(attempt.qindex, 0, worst_quality_qindex_); | |
| min_qindex = std::max(min_qindex, | |
| std::min(worst_quality_qindex_, attempt_qindex + 1)); | |
| } | |
| if (min_qindex >= worst_quality_qindex_) { | |
| return worst_quality_qindex_; | |
| } | |
| const EncodeAttempt& last = attempts.back(); | |
| const int last_qindex = | |
| std::clamp(last.qindex, best_quality_qindex_, worst_quality_qindex_); | |
| // Invert `BitsPerMacroblock` directly rather than dividing by | |
| // `EstimateSizeAtQIndex`, which floors small sizes at `kFrameOverhead`. | |
| const double actual_bits_per_mb = | |
| last.encoded_size.bytes<double>() * 8.0 / ctx.num_macroblocks; | |
| const double observed_factor = | |
| std::clamp(actual_bits_per_mb * Av1QIndexToQStep(last_qindex) / | |
| BaseBitsPerMb(ctx.is_screen, ctx.intra), | |
| kMinRateCorrectionFactor, kMaxRateCorrectionFactor); | |
| const double target_bits_per_mb = | |
| target_size.bytes<double>() * 8.0 / ctx.num_macroblocks; | |
| return FindClosestQIndexByRate(ctx, target_bits_per_mb, observed_factor, | |
| min_qindex, worst_quality_qindex_); | |
| } | |
| // Evaluates pre-encode frame drop (`av1_rc_drop_frame`) without mutating state. | |
| BufferLevelRateController::DropDecision | |
| BufferLevelRateController::PreEncodeDrop(const FrameContext& ctx, | |
| const LayerState& layer) const { | |
| DropDecision decision = { | |
| .decimation_factor_frames = decimation_factor_frames_, | |
| .decimation_count_frames = decimation_count_frames_}; | |
| if (ctx.intra || config_.drop_frames_water_mark_pct <= 0) { | |
| return decision; | |
| } | |
| if (config_.max_consecutive_drop.IsFinite() && | |
| config_.max_consecutive_drop > TimeDelta::Zero()) { | |
| const double max_consecutive_drop_frames = | |
| std::ceil(config_.max_consecutive_drop / ctx.duration); | |
| if (consecutive_drop_count_ >= max_consecutive_drop_frames) { | |
| return decision; | |
| } | |
| } | |
| if (layer.buffer_level < TimeDelta::Zero()) { | |
| decision.drop = true; | |
| return decision; | |
| } | |
| // Below the drop watermark, drop every other frame until the buffer recovers. | |
| const TimeDelta drop_mark = | |
| config_.target_buffer_size * config_.drop_frames_water_mark_pct / 100; | |
| const bool below = layer.buffer_level <= drop_mark; | |
| if (!below && decision.decimation_factor_frames > 0) { | |
| --decision.decimation_factor_frames; | |
| } else if (below && decision.decimation_factor_frames == 0) { | |
| decision.decimation_factor_frames = 1; | |
| } | |
| if (decision.decimation_factor_frames > 0) { | |
| if (decision.decimation_count_frames > 0) { | |
| --decision.decimation_count_frames; | |
| decision.drop = true; | |
| } else { | |
| decision.decimation_count_frames = decision.decimation_factor_frames; | |
| } | |
| } else { | |
| decision.decimation_count_frames = 0; | |
| } | |
| return decision; | |
| } | |
| bool BufferLevelRateController::IsHighQpSceneChange( | |
| const FrameContext& ctx) const { | |
| return config_.scene_change_high_qp && !ctx.intra && ctx.scene_change; | |
| } | |
| // High-QP choice on detected scene changes (`av1_encodedframe_overshoot_cbr`, | |
| // without spatial-variance relaxation). | |
| int BufferLevelRateController::SceneChangeQIndex(const FrameContext& ctx, | |
| const LayerState& layer, | |
| int qindex) const { | |
| if (ctx.is_screen) { | |
| // `soft_screen_scene_change` leaves headroom up to `worst_quality_qindex_` | |
| // so `CheckEncodedFrame` can still request a re-encode on a huge slide. | |
| return config_.soft_screen_scene_change | |
| ? (qindex + worst_quality_qindex_) >> 1 | |
| : worst_quality_qindex_; | |
| } | |
| if (ctx.resolution.PixelCount() >= kHdPixelCountThreshold && | |
| layer.buffer_level > config_.target_buffer_size / 2 && | |
| avg_source_sad_per_64x64_ < kCameraSceneChangeSadPer64x64Threshold) { | |
| return (qindex + worst_quality_qindex_) >> 1; | |
| } | |
| return (3 * worst_quality_qindex_ + qindex) >> 2; | |
| } | |
| VideoRateController::FramePlan BufferLevelRateController::PlanFrame( | |
| const FrameParams& params) { | |
| RTC_DCHECK_RUN_ON(&sequence_checker_); | |
| RTC_DCHECK(params.target_bitrate.IsFinite()); | |
| RTC_DCHECK_GT(params.target_bitrate, DataRate::Zero()); | |
| RTC_DCHECK(params.duration.IsFinite()); | |
| RTC_DCHECK_GT(params.duration, TimeDelta::Zero()); | |
| RTC_DCHECK(params.tu_settings.presentation_timestamp().IsFinite()); | |
| RTC_DCHECK_GT(params.frame_settings.resolution().width, 0); | |
| RTC_DCHECK_GT(params.frame_settings.resolution().height, 0); | |
| const int tid = std::clamp(params.frame_settings.temporal_id(), 0, | |
| kMaxTemporalLayers - 1); | |
| AdvanceClockAndDrainBuffers(params.tu_settings.presentation_timestamp(), | |
| params.duration); | |
| UpdateLayerCadenceAndRate(tid, params.target_bitrate); | |
| FrameContext ctx = MakeContext(tid, params.duration, params.tu_settings, | |
| params.frame_settings); | |
| const LayerState effective_layer = EffectiveLayerState(ctx.temporal_id); | |
| const DataSize target_size = ctx.intra | |
| ? CalcIframeTarget(ctx) | |
| : CalcPframeTarget(ctx, effective_layer); | |
| const PlanId id = next_plan_id_++; | |
| // Advance pre-encode drop/decimation state at planning time against | |
| // `effective_layer` so pipelined frames see consistent drop counts and | |
| // decimation phase. | |
| if (params.allow_drop) { | |
| const DropDecision drop_decision = PreEncodeDrop(ctx, effective_layer); | |
| decimation_factor_frames_ = drop_decision.decimation_factor_frames; | |
| decimation_count_frames_ = drop_decision.decimation_count_frames; | |
| if (drop_decision.drop || | |
| (base_layer_dropped_ && ctx.temporal_id > 0 && !ctx.intra)) { | |
| if (drop_decision.drop) { | |
| ++consecutive_drop_count_; | |
| } | |
| pending_frames_.push_back(PendingFrame{.id = id, | |
| .ctx = ctx, | |
| .base_target_size = target_size, | |
| .current_target_size = target_size, | |
| .drop = true}); | |
| return {.id = id, .decision = DropFrame{}}; | |
| } | |
| } | |
| consecutive_drop_count_ = 0; | |
| bool analyzed_source = false; | |
| if (params.frame_buffer != nullptr) { | |
| analyzed_source = true; | |
| if (std::optional<SceneAnalyzer::Stats> stats = | |
| scene_analyzer_.Analyze(*params.frame_buffer, ctx.is_screen)) { | |
| ctx.source_sad_per_64x64 = stats->mean_abs_diff * kSceneBlockPixels; | |
| ctx.scene_change = stats->scene_change; | |
| } | |
| } | |
| bool forced_max_qp = false; | |
| int qindex = PickQIndex(ctx, effective_layer, target_size); | |
| if (effective_layer.force_max_qp && !ctx.intra) { | |
| qindex = worst_quality_qindex_; | |
| forced_max_qp = true; | |
| } else if (IsHighQpSceneChange(ctx)) { | |
| qindex = SceneChangeQIndex(ctx, effective_layer, qindex); | |
| } | |
| pending_frames_.push_back(PendingFrame{.id = id, | |
| .ctx = ctx, | |
| .base_target_size = target_size, | |
| .current_target_size = target_size, | |
| .planned_qindex = qindex, | |
| .forced_max_qp = forced_max_qp, | |
| .analyzed_source = analyzed_source}); | |
| return {.id = id, | |
| .decision = EncodeFrame{.qp = qindex, .target_size = target_size}}; | |
| } | |
| // Post-encode overshoot check (`av1_postencode_drop_cbr`, or a re-encode). | |
| VideoRateController::Verdict BufferLevelRateController::CheckEncodedFrame( | |
| PlanId id, | |
| const EncodedFrameStats& stats) const { | |
| RTC_DCHECK_RUN_ON(&sequence_checker_); | |
| RTC_DCHECK(stats.encoded_size.IsFinite()); | |
| const PendingFrame* pending = FindPending(id); | |
| RTC_CHECK(pending != nullptr) << "Unknown or already retired PlanId: " << id; | |
| RTC_DCHECK(!pending->drop); | |
| const FrameContext& ctx = pending->ctx; | |
| RTC_DCHECK(layers_[ctx.temporal_id].initialized); | |
| if (!config_.postencode_drop && !config_.reencode_overshoot) { | |
| return Verdict::kAccept; | |
| } | |
| const LayerState effective_layer = | |
| EffectiveLayerState(ctx.temporal_id, /*exclude_id=*/id); | |
| const bool high_qp_scene_change = IsHighQpSceneChange(ctx); | |
| const bool soft_screen_reencode = high_qp_scene_change && ctx.is_screen && | |
| config_.soft_screen_scene_change && | |
| config_.reencode_overshoot; | |
| // Frames coded at a high QP for a scene change are accepted as-is, unless | |
| // `soft_screen_scene_change` left headroom to retry up to max QP. | |
| if (high_qp_scene_change && !soft_screen_reencode) { | |
| return Verdict::kAccept; | |
| } | |
| const DataRate bitrate = CumulativeBitrate(ctx.temporal_id); | |
| RTC_DCHECK_GT(bitrate, DataRate::Zero()); | |
| // Mirror libaom's `av1_postencode_drop_cbr` check: accept unless the frame | |
| // exceeds both its planned target and 8x its nominal budget, would pull the | |
| // buffer below 25% of target, and was not already coded near max QP. | |
| const TimeDelta projected_buffer_level = effective_layer.buffer_level + | |
| ctx.avg_frame_bandwidth / bitrate - | |
| stats.encoded_size / bitrate; | |
| const int qp_threshold_qindex = | |
| soft_screen_reencode && pending->previous_attempts.empty() | |
| ? worst_quality_qindex_ | |
| : 3 * (worst_quality_qindex_ >> 2); | |
| const DataSize accept_size_ceiling = | |
| std::max(8 * ctx.avg_frame_bandwidth, pending->current_target_size); | |
| if (projected_buffer_level >= config_.target_buffer_size / 4 || | |
| stats.encoded_size <= accept_size_ceiling || | |
| pending->planned_qindex >= qp_threshold_qindex) { | |
| return Verdict::kAccept; | |
| } | |
| if (config_.reencode_overshoot) { | |
| return Verdict::kReencode; | |
| } | |
| return ctx.intra ? Verdict::kAccept : Verdict::kDrop; | |
| } | |
| VideoRateController::FramePlan BufferLevelRateController::ReplanFrame( | |
| PlanId id, | |
| const EncodedFrameStats& rejected_attempt) { | |
| RTC_DCHECK_RUN_ON(&sequence_checker_); | |
| RTC_DCHECK(rejected_attempt.encoded_size.IsFinite()); | |
| PendingFrame* pending = FindPending(id); | |
| RTC_CHECK(pending != nullptr) << "Unknown or already retired PlanId: " << id; | |
| RTC_DCHECK(!pending->drop); | |
| const FrameContext& ctx = pending->ctx; | |
| RTC_DCHECK(layers_[ctx.temporal_id].initialized); | |
| const int resolved_qindex = | |
| ResolveReportedQIndex(rejected_attempt.qp, pending->planned_qindex); | |
| pending->previous_attempts.push_back( | |
| {.encoded_size = rejected_attempt.encoded_size, | |
| .qindex = resolved_qindex}); | |
| const LayerState effective_layer = | |
| EffectiveLayerState(ctx.temporal_id, /*exclude_id=*/id); | |
| DataSize retry_target = pending->base_target_size; | |
| if (config_.reencode_target_factor > 0 && !ctx.intra) { | |
| // Allow spending up to `reencode_target_factor` times the nominal budget, | |
| // capped to what keeps the projected buffer above the 25% drop mark. | |
| const DataRate bitrate = CumulativeBitrate(ctx.temporal_id); | |
| RTC_DCHECK_GT(bitrate, DataRate::Zero()); | |
| const DataSize boosted = | |
| ctx.avg_frame_bandwidth * config_.reencode_target_factor; | |
| const TimeDelta room_duration = | |
| std::max(TimeDelta::Zero(), effective_layer.buffer_level + | |
| ctx.avg_frame_bandwidth / bitrate - | |
| config_.target_buffer_size / 4); | |
| const DataSize room = bitrate * room_duration; | |
| retry_target = std::max(pending->base_target_size, std::min(boosted, room)); | |
| } | |
| pending->current_target_size = retry_target; | |
| pending->planned_qindex = PickReencodeQIndex( | |
| ctx, pending->previous_attempts, pending->planned_qindex, retry_target); | |
| return {.id = id, | |
| .decision = EncodeFrame{.qp = pending->planned_qindex, | |
| .target_size = retry_target}}; | |
| } | |
| // Updates the adaptive R-Q correction factor | |
| // (`av1_rc_update_rate_correction_factors`). | |
| void BufferLevelRateController::UpdateRateCorrectionFactors( | |
| const FrameContext& ctx, | |
| LayerState& layer, | |
| int qindex, | |
| DataSize encoded_size) { | |
| double rate_correction_factor = GetRateCorrectionFactor(ctx, layer); | |
| const DataSize projected_size = | |
| EstimateSizeAtQIndex(ctx, qindex, rate_correction_factor); | |
| double ratio = 1.0; | |
| if (projected_size > kFrameOverhead || encoded_size > kFrameOverhead) { | |
| ratio = encoded_size / projected_size; | |
| } | |
| // Cap single-frame downward steps to 4x so one blank/skip frame cannot crash | |
| // the R-Q model. | |
| ratio = std::max(ratio, 0.25); | |
| layer.prev2_frame_qindex = layer.prev_frame_qindex; | |
| layer.prev_frame_qindex = qindex; | |
| layer.prev2_rate_outcome = layer.prev_rate_outcome; | |
| if (ratio > 1.1) { | |
| layer.prev_rate_outcome = RateOutcome::kOvershoot; | |
| } else if (ratio < 0.9) { | |
| layer.prev_rate_outcome = RateOutcome::kUndershoot; | |
| } else { | |
| layer.prev_rate_outcome = RateOutcome::kOnTarget; | |
| } | |
| // Dampen the update: larger errors adapt faster (25%..62.5% for camera, | |
| // 25%..50% for screen), with a +/-1% deadband. | |
| const double adjustment_limit = | |
| 0.25 + (ctx.is_screen ? 0.5 : 0.75) * | |
| std::min(0.5, std::fabs(std::log10(ratio))); | |
| if (ratio > 1.01) { | |
| const double damped = 1.0 + (ratio - 1.0) * adjustment_limit; | |
| rate_correction_factor = | |
| std::min(rate_correction_factor * damped, kMaxRateCorrectionFactor); | |
| } else if (ratio < 0.99) { | |
| const double inv_ratio = 1.0 / ratio; | |
| const double damped_inv = 1.0 + (inv_ratio - 1.0) * adjustment_limit; | |
| rate_correction_factor = | |
| std::max(rate_correction_factor / damped_inv, kMinRateCorrectionFactor); | |
| } | |
| SetRateCorrectionFactor(ctx, layer, rate_correction_factor); | |
| } | |
| // Debits the coded frame against its own layer substream and all initialized | |
| // higher temporal layers. Queue drain happens continuously in | |
| // `AdvanceClockAndDrainBuffers`. | |
| void BufferLevelRateController::UpdateBufferLevel(const FrameContext& ctx, | |
| DataSize encoded_size) { | |
| for (int tid = ctx.temporal_id; tid < kMaxTemporalLayers; ++tid) { | |
| LayerState& layer = layers_[tid]; | |
| if (!layer.initialized) { | |
| continue; | |
| } | |
| const DataRate bitrate = CumulativeBitrate(tid); | |
| if (!encoded_size.IsZero() && bitrate > DataRate::Zero()) { | |
| layer.buffer_level -= encoded_size / bitrate; | |
| } | |
| CapBufferLevel(layer, InFlightDuration(tid)); | |
| // For screen content, floor debt at one buffer duration so recovery after | |
| // a large slide-change overshoot stays bounded. | |
| if (ctx.is_screen) { | |
| layer.buffer_level = | |
| std::max(layer.buffer_level, -config_.max_buffer_size); | |
| } | |
| } | |
| } | |
| void BufferLevelRateController::FinishFrame(const FrameContext& ctx, | |
| bool coded) { | |
| if (coded) { | |
| layers_[ctx.temporal_id].prev_bitrate = CumulativeBitrate(ctx.temporal_id); | |
| prev_coded_resolution_ = ctx.resolution; | |
| if (ctx.intra) { | |
| last_keyframe_index_ = frame_count_; | |
| coded_inter_on_tl0_since_key_ = false; | |
| } else if (ctx.temporal_id == 0) { | |
| coded_inter_on_tl0_since_key_ = true; | |
| } | |
| } | |
| ++frame_count_; | |
| } | |
| // Applies the scene-change state resets of `av1_encodedframe_overshoot_cbr`. | |
| void BufferLevelRateController::OnSceneChangeEncoded(const FrameContext& ctx, | |
| int qindex) { | |
| // Raise the correction factor halfway toward what the nominal budget at this | |
| // qindex implies (inverse of `BitsPerMacroblock`). | |
| const double target_bits_per_mb = | |
| ctx.avg_frame_bandwidth.bytes<double>() * 8.0 / ctx.num_macroblocks; | |
| const double new_factor = target_bits_per_mb * Av1QIndexToQStep(qindex) / | |
| BaseBitsPerMb(ctx.is_screen, /*intra=*/false); | |
| double factor = GetRateCorrectionFactor(ctx, layers_[ctx.temporal_id]); | |
| if (new_factor > factor) { | |
| factor = std::min((new_factor + factor) / 2, kMaxRateCorrectionFactor); | |
| } | |
| for (int tid = 0; tid < kMaxTemporalLayers; ++tid) { | |
| LayerState& layer = layers_[tid]; | |
| if (!layer.initialized) { | |
| continue; | |
| } | |
| layer.avg_frame_qindex[kInterFrameKind] = qindex; | |
| if (config_.reset_buffer_on_overshoot) { | |
| layer.buffer_level = config_.target_buffer_size; | |
| } | |
| layer.prev_frame_qindex = qindex; | |
| layer.prev2_frame_qindex = qindex; | |
| layer.prev_rate_outcome = RateOutcome::kOnTarget; | |
| layer.prev2_rate_outcome = RateOutcome::kOnTarget; | |
| SetRateCorrectionFactor(ctx, layer, factor); | |
| } | |
| } | |
| void BufferLevelRateController::UpdateAvgSourceSad(const FrameContext& ctx) { | |
| if (ctx.source_sad_per_64x64) { | |
| avg_source_sad_per_64x64_ = | |
| (3 * avg_source_sad_per_64x64_ + *ctx.source_sad_per_64x64) / 4; | |
| } | |
| if (ctx.scene_change) { | |
| static_scene_change_index_ = frame_count_; | |
| } else if (!ctx.source_sad_per_64x64 || | |
| *ctx.source_sad_per_64x64 > | |
| config_.max_static_source_sad_per_64x64) { | |
| static_scene_change_index_.reset(); | |
| } | |
| } | |
| void BufferLevelRateController::OnFrameEncoded(PlanId id, | |
| const EncodedFrameStats& stats) { | |
| RTC_DCHECK_RUN_ON(&sequence_checker_); | |
| RTC_DCHECK(stats.encoded_size.IsFinite()); | |
| const PendingFrame pending = TakePending(id); | |
| RTC_DCHECK(!pending.drop); | |
| const FrameContext& ctx = pending.ctx; | |
| LayerState& layer = layers_[ctx.temporal_id]; | |
| RTC_DCHECK(layer.initialized); | |
| const int qindex = ResolveReportedQIndex(stats.qp, pending.planned_qindex); | |
| const bool scene_change = pending.previous_attempts.empty() && | |
| !pending.forced_max_qp && IsHighQpSceneChange(ctx); | |
| if (pending.forced_max_qp) { | |
| layer.force_max_qp = false; | |
| } | |
| if (ctx.temporal_id == 0) { | |
| base_layer_dropped_ = false; | |
| } | |
| if (scene_change) { | |
| OnSceneChangeEncoded(ctx, qindex); | |
| RecordOvershoot(ctx.timestamp); | |
| } else { | |
| UpdateRateCorrectionFactors(ctx, layer, qindex, stats.encoded_size); | |
| } | |
| if (!pending.previous_attempts.empty() && !ctx.intra) { | |
| RecordOvershoot(ctx.timestamp); | |
| if (config_.seed_after_reencode) { | |
| // Seed the QP envelope from the retry's qindex so the pre-overshoot | |
| // average QP does not cap the next frame too low and overshoot again. | |
| for (int tid = 0; tid < kMaxTemporalLayers; ++tid) { | |
| LayerState& l = layers_[tid]; | |
| if (!l.initialized) { | |
| continue; | |
| } | |
| l.avg_frame_qindex[kInterFrameKind] = qindex; | |
| l.prev_frame_qindex = qindex; | |
| l.prev2_frame_qindex = qindex; | |
| l.prev_rate_outcome = RateOutcome::kOnTarget; | |
| l.prev2_rate_outcome = RateOutcome::kOnTarget; | |
| } | |
| } | |
| } | |
| // 3:1 integer-rounded EMA of coded qindex. | |
| const FrameKind kind = ctx.intra ? kKeyFrameKind : kInterFrameKind; | |
| layer.last_qindex[kind] = qindex; | |
| layer.avg_frame_qindex[kind] = | |
| (3 * layer.avg_frame_qindex[kind] + qindex + 2) >> 2; | |
| UpdateBufferLevel(ctx, stats.encoded_size); | |
| UpdateAvgSourceSad(ctx); | |
| FinishFrame(ctx, /*coded=*/true); | |
| } | |
| void BufferLevelRateController::OnFrameDropped( | |
| PlanId id, | |
| std::optional<EncodedFrameStats> discarded_attempt) { | |
| RTC_DCHECK_RUN_ON(&sequence_checker_); | |
| PendingFrame pending = TakePending(id); | |
| if (discarded_attempt.has_value()) { | |
| RTC_DCHECK(discarded_attempt->encoded_size.IsFinite()); | |
| pending.previous_attempts.push_back( | |
| {.encoded_size = discarded_attempt->encoded_size, | |
| .qindex = ResolveReportedQIndex(discarded_attempt->qp, | |
| pending.planned_qindex)}); | |
| } | |
| const FrameContext& ctx = pending.ctx; | |
| LayerState& layer = layers_[ctx.temporal_id]; | |
| RTC_DCHECK(layer.initialized); | |
| UpdateBufferLevel(ctx, DataSize::Zero()); | |
| layer.prev_rate_outcome = RateOutcome::kOnTarget; | |
| layer.prev2_rate_outcome = RateOutcome::kOnTarget; | |
| if (!pending.previous_attempts.empty()) { | |
| // Post-encode drop: force the next delta frame of every active layer to | |
| // max QP. | |
| RecordOvershoot(ctx.timestamp); | |
| if (ctx.temporal_id == 0 && config_.drop_upper_layers_after_base_drop) { | |
| base_layer_dropped_ = true; | |
| } | |
| for (int tid = 0; tid < kMaxTemporalLayers; ++tid) { | |
| LayerState& l = layers_[tid]; | |
| if (!l.initialized) { | |
| continue; | |
| } | |
| l.force_max_qp = true; | |
| l.avg_frame_qindex[kInterFrameKind] = worst_quality_qindex_; | |
| if (config_.reset_buffer_on_overshoot) { | |
| l.buffer_level = config_.target_buffer_size; | |
| } | |
| l.prev_rate_outcome = RateOutcome::kOnTarget; | |
| l.prev2_rate_outcome = RateOutcome::kOnTarget; | |
| } | |
| } | |
| if (pending.analyzed_source) { | |
| UpdateAvgSourceSad(ctx); | |
| } | |
| FinishFrame(ctx, /*coded=*/false); | |
| } | |
| } // namespace webrtc |