blob: c00f75410bddbb8d1336bacf6af940cb7a9e9523 [file]
/*
* 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.
*/
#ifndef MODULES_VIDEO_CODING_RATE_CONTROL_BUFFER_LEVEL_RATE_CONTROLLER_H_
#define MODULES_VIDEO_CODING_RATE_CONTROL_BUFFER_LEVEL_RATE_CONTROLLER_H_
#include <array>
#include <cstdint>
#include <optional>
#include <span>
#include "absl/base/nullability.h"
#include "absl/container/inlined_vector.h"
#include "api/sequence_checker.h"
#include "api/units/data_rate.h"
#include "api/units/data_size.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_rate_controller.h"
#include "modules/video_coding/rate_control/scene_analyzer.h"
#include "rtc_base/system/no_unique_address.h"
#include "rtc_base/thread_annotations.h"
namespace webrtc {
// One-pass real-time CBR rate controller derived from libaom: a leaky bucket
// per temporal layer substream and a bits-per-macroblock model with an adaptive
// correction factor that maps each frame's target size to a QP in the AV1
// qindex scale [0, 255].
//
// Unlike libaom, queues drain continuously by elapsed presentation timestamp
// while `duration` determines per-frame budgets, each temporal layer's bitrate
// and cadence are tracked lazily as frames arrive without upfront layer
// declarations (retiring upper layers when the observed cadence shrinks),
// configuration changes never reset the state, multiple frames may be in flight
// concurrently, and re-encodes pick a QP strictly above the rejected attempts.
class BufferLevelRateController final : public VideoRateController {
public:
static constexpr int kMaxTemporalLayers = 4;
explicit BufferLevelRateController(
const BufferLevelRateControllerConfig& config = {});
~BufferLevelRateController() override = default;
BufferLevelRateController(const BufferLevelRateController&) = delete;
BufferLevelRateController& operator=(const BufferLevelRateController&) =
delete;
[[nodiscard]] FramePlan PlanFrame(const FrameParams& params) override;
[[nodiscard]] Verdict CheckEncodedFrame(
PlanId id,
const EncodedFrameStats& stats) const override;
[[nodiscard]] FramePlan ReplanFrame(
PlanId id,
const EncodedFrameStats& rejected_attempt) override;
void OnFrameEncoded(PlanId id, const EncodedFrameStats& stats) override;
void OnFrameDropped(
PlanId id,
std::optional<EncodedFrameStats> discarded_attempt) override;
private:
// Whether a coded frame's size deviated significantly from the R-Q model's
// prediction, used to damp QP oscillations in `AdjustQIndexCbr`.
enum class RateOutcome { kOnTarget, kOvershoot, kUndershoot };
// Outcome of `PreEncodeDrop` and the frame-decimation state following it.
struct DropDecision {
bool drop = false;
// Frames skipped per coded frame while below the drop watermark (0 = off,
// 1 = drop every other frame).
int decimation_factor_frames = 0;
// Remaining frames to drop in the current decimation cycle.
int decimation_count_frames = 0;
};
// Rate-control state for the cumulative substream formed by a temporal layer
// and all layers below it (a single-layer stream uses `layers_[0]`).
struct LayerState {
// True while this temporal layer is active.
bool initialized = false;
// Current non-cumulative target bitrate for this layer (provisionally
// scaled when another layer's target bitrate changes, until this layer's
// next frame arrives).
DataRate target_bitrate = DataRate::Zero();
// True when `target_bitrate` was provisionally scaled from another layer's
// bitrate change and has not yet been confirmed by this layer's own frame.
bool bitrate_estimated = false;
// Measured temporal decimation factor for this layer (stream frame slots
// per layer frame, e.g. 4.0 for TL0/TL1 and 2.0 for TL2 in L1T3). Unset
// until two in-cadence frames of this layer are observed (and on
// single-layer streams), falling back to the expected dyadic factor.
std::optional<double> temporal_decimation_factor;
// Stream frame-slot position (`slot_position_`) when this layer was last
// planned; used to measure `temporal_decimation_factor` and detect when
// higher temporal layers stop arriving.
std::optional<double> last_frame_slot;
// Code the next delta frame of this layer at max QP after a post-encode
// drop so every active layer recovers from max QP.
bool force_max_qp = false;
// Leaky-bucket fullness in time-of-bitrate (higher = more headroom,
// negative = over-budget debt). Stored as `TimeDelta` so negative debt is
// represented directly and fullness stays invariant across bitrate changes.
TimeDelta buffer_level = TimeDelta::Zero();
// Adaptive R-Q multipliers indexed by `RateFactorLevel`. Inter starts at
// 0.7 (libaom's `av1_primary_rc_init` default) to start conservatively
// before the model adapts; intra starts at 1.0.
std::array<double, 2> rate_correction_factors = {0.7, 1.0};
// Exponentially smoothed and last coded qindex, indexed by `FrameKind`.
std::array<int, 2> avg_frame_qindex = {0, 0};
std::array<int, 2> last_qindex = {0, 0};
// Qindex and model-fit outcome of the previous two coded frames on this
// layer, used to damp QP oscillation and step sizes.
int prev_frame_qindex = 0;
int prev2_frame_qindex = 0;
RateOutcome prev_rate_outcome = RateOutcome::kOnTarget;
RateOutcome prev2_rate_outcome = RateOutcome::kOnTarget;
// Cumulative bitrate of this layer substream when its last frame was coded.
DataRate prev_bitrate = DataRate::Zero();
};
// Per-frame parameters derived from stream state and `FrameParams`.
struct FrameContext {
int temporal_id = 0;
// True when at least one enhancement layer (`tid > 0`) is currently active.
bool multi_layer = false;
// Estimated base-layer (TL0) cycle length in stream frame slots (e.g. 1
// for L1T1, 2 for L1T2, 4 for L1T3).
int tl0_period_frames = 1;
bool intra = false;
bool is_screen = false;
Timestamp timestamp = Timestamp::MinusInfinity();
TimeDelta duration = TimeDelta::Zero();
Resolution resolution;
int64_t num_macroblocks = 1;
// Nominal per-frame budget of the cumulative substream (`0..tid`).
DataSize avg_frame_bandwidth = DataSize::Zero();
// Nominal per-frame budget of this layer alone (excluding lower layers).
DataSize avg_frame_size = DataSize::Zero();
// Hard ceiling on a single frame's planned target size.
DataSize max_frame_size = DataSize::Zero();
// Pre-encode luma SAD per 64x64 block relative to the previous frame.
std::optional<double> source_sad_per_64x64;
bool scene_change = false;
};
// Recorded encode attempt with a resolved AV1 qindex.
struct EncodeAttempt {
DataSize encoded_size = DataSize::Zero();
int qindex = 0;
};
// In-flight frame state between `PlanFrame` and `OnFrameEncoded` /
// `OnFrameDropped`.
struct PendingFrame {
PlanId id = 0;
FrameContext ctx;
// Initial planned target size, preserved as the floor across retries.
DataSize base_target_size = DataSize::Zero();
// Active target size of the latest plan (`PlanFrame` or `ReplanFrame`).
DataSize current_target_size = DataSize::Zero();
int planned_qindex = 0;
bool drop = false;
bool forced_max_qp = false;
bool analyzed_source = false;
absl::InlinedVector<EncodeAttempt, 2> previous_attempts;
};
PendingFrame* absl_nullable FindPending(PlanId id)
RTC_RUN_ON(sequence_checker_);
const PendingFrame* absl_nullable FindPending(PlanId id) const
RTC_RUN_ON(sequence_checker_);
PendingFrame TakePending(PlanId id) RTC_RUN_ON(sequence_checker_);
bool HasPendingForLayer(int tid) const RTC_RUN_ON(sequence_checker_);
// Planned bit-time of in-flight non-dropped frames in layers `<= tid`,
// optionally excluding `exclude_id`.
TimeDelta InFlightDuration(int tid,
std::optional<PlanId> exclude_id = std::nullopt)
const RTC_RUN_ON(sequence_checker_);
LayerState EffectiveLayerState(
int tid,
std::optional<PlanId> exclude_id = std::nullopt) const
RTC_RUN_ON(sequence_checker_);
void AdvanceClockAndDrainBuffers(Timestamp timestamp, TimeDelta duration)
RTC_RUN_ON(sequence_checker_);
void CapBufferLevel(LayerState& layer, TimeDelta in_flight_duration) const;
void UpdateLayerCadenceAndRate(int tid, DataRate target_bitrate)
RTC_RUN_ON(sequence_checker_);
double LayerDecimationFactor(int tid) const RTC_RUN_ON(sequence_checker_);
double CumulativeFrameFraction(int tid) const RTC_RUN_ON(sequence_checker_);
DataRate CumulativeBitrate(int tid) const RTC_RUN_ON(sequence_checker_);
int HighestInitializedTemporalId() const RTC_RUN_ON(sequence_checker_);
int Tl0PeriodFrames() const RTC_RUN_ON(sequence_checker_);
std::optional<int64_t> FramesSinceKey() const RTC_RUN_ON(sequence_checker_);
void RecordOvershoot(Timestamp timestamp) RTC_RUN_ON(sequence_checker_);
FrameContext MakeContext(int tid,
TimeDelta duration,
const TemporalUnitSettings& tu_settings,
const FrameEncodeSettings& frame_settings) const
RTC_RUN_ON(sequence_checker_);
DropDecision PreEncodeDrop(const FrameContext& ctx,
const LayerState& layer) const
RTC_RUN_ON(sequence_checker_);
bool IsHighQpSceneChange(const FrameContext& ctx) const;
int SceneChangeQIndex(const FrameContext& ctx,
const LayerState& layer,
int qindex) const RTC_RUN_ON(sequence_checker_);
void OnSceneChangeEncoded(const FrameContext& ctx, int qindex)
RTC_RUN_ON(sequence_checker_);
void UpdateAvgSourceSad(const FrameContext& ctx)
RTC_RUN_ON(sequence_checker_);
DataSize LayerFrameBandwidth(int tid, TimeDelta duration) const
RTC_RUN_ON(sequence_checker_);
DataSize LayerFrameSize(int tid, TimeDelta duration) const
RTC_RUN_ON(sequence_checker_);
DataSize CalcIframeTarget(const FrameContext& ctx) const
RTC_RUN_ON(sequence_checker_);
DataSize CalcPframeTarget(const FrameContext& ctx,
const LayerState& layer) const;
int PickQIndex(const FrameContext& ctx,
const LayerState& layer,
DataSize target_size) const RTC_RUN_ON(sequence_checker_);
int CalcActiveWorstQIndex(const FrameContext& ctx,
const LayerState& layer) const
RTC_RUN_ON(sequence_checker_);
int CalcActiveBestQIndex(const FrameContext& ctx,
const LayerState& layer,
int active_worst_qindex) const
RTC_RUN_ON(sequence_checker_);
int AdjustQIndexCbr(const FrameContext& ctx,
const LayerState& layer,
int qindex,
int active_worst_qindex) const
RTC_RUN_ON(sequence_checker_);
int PickReencodeQIndex(const FrameContext& ctx,
std::span<const EncodeAttempt> attempts,
int planned_qindex,
DataSize target_size) const;
int ResolveReportedQIndex(std::optional<int> reported_qp,
int planned_qindex) const;
double GetRateCorrectionFactor(const FrameContext& ctx,
const LayerState& layer) const;
void SetRateCorrectionFactor(const FrameContext& ctx,
LayerState& layer,
double factor) const;
double BitsPerMacroblock(const FrameContext& ctx,
int qindex,
double correction_factor) const;
DataSize EstimateSizeAtQIndex(const FrameContext& ctx,
int qindex,
double correction_factor) const;
int FindClosestQIndexByRate(const FrameContext& ctx,
double desired_bits_per_mb,
double correction_factor,
int best_qindex,
int worst_qindex) const;
bool ChangedTargetBitsPerMb(const FrameContext& ctx,
const LayerState& layer) const
RTC_RUN_ON(sequence_checker_);
void UpdateRateCorrectionFactors(const FrameContext& ctx,
LayerState& layer,
int qindex,
DataSize encoded_size);
void UpdateBufferLevel(const FrameContext& ctx, DataSize encoded_size)
RTC_RUN_ON(sequence_checker_);
void FinishFrame(const FrameContext& ctx, bool coded)
RTC_RUN_ON(sequence_checker_);
LayerState InitialLayerState() const;
RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_{
SequenceChecker::kDetached};
const BufferLevelRateControllerConfig config_;
const int worst_quality_qindex_;
const int best_quality_qindex_;
std::optional<Timestamp> last_timestamp_ RTC_GUARDED_BY(sequence_checker_);
TimeDelta prev_frame_duration_ RTC_GUARDED_BY(sequence_checker_) =
TimeDelta::Zero();
// Cumulative stream-slot clock (`+= elapsed / prev_frame_duration_`). Lets
// each layer measure its own frame cadence independently of dropped
// enhancement frames, framerate changes, or idle pauses.
double slot_position_ RTC_GUARDED_BY(sequence_checker_) = 0.0;
// Indexed by temporal id; lazily initialized on first arrival of each layer.
std::array<LayerState, kMaxTemporalLayers> layers_
RTC_GUARDED_BY(sequence_checker_);
PlanId next_plan_id_ RTC_GUARDED_BY(sequence_checker_) = 1;
absl::InlinedVector<PendingFrame, 4> pending_frames_
RTC_GUARDED_BY(sequence_checker_);
SceneAnalyzer scene_analyzer_ RTC_GUARDED_BY(sequence_checker_);
// Total frames (coded or dropped) since stream start.
int64_t frame_count_ RTC_GUARDED_BY(sequence_checker_) = 0;
// `frame_count_` of the most recently coded intra frame, if any.
std::optional<int64_t> last_keyframe_index_ RTC_GUARDED_BY(sequence_checker_);
// Whether a non-intra TL0 frame has been coded since the last intra frame;
// until one has, enhancement layers compare against the keyframe's qindex.
bool coded_inter_on_tl0_since_key_ RTC_GUARDED_BY(sequence_checker_) = false;
// Set after a post-encode drop of a base-layer frame until the next base
// frame is coded; see `drop_upper_layers_after_base_drop`.
bool base_layer_dropped_ RTC_GUARDED_BY(sequence_checker_) = false;
std::optional<Resolution> prev_coded_resolution_
RTC_GUARDED_BY(sequence_checker_);
// Pre-encode drop and decimation state.
int consecutive_drop_count_ RTC_GUARDED_BY(sequence_checker_) = 0;
int decimation_factor_frames_ RTC_GUARDED_BY(sequence_checker_) = 0;
int decimation_count_frames_ RTC_GUARDED_BY(sequence_checker_) = 0;
// Exponentially smoothed luma SAD per 64x64 block (3:1 decay).
double avg_source_sad_per_64x64_ RTC_GUARDED_BY(sequence_checker_) = 0.0;
// Presentation timestamp of the most recent scene change, accepted
// re-encode, or post-encode drop, for `fast_recovery`.
std::optional<Timestamp> last_overshoot_timestamp_
RTC_GUARDED_BY(sequence_checker_);
// `frame_count_` of the most recent scene change while all subsequent frames
// have remained static (unset once motion resumes), for
// `faster_convergence_static`.
std::optional<int64_t> static_scene_change_index_
RTC_GUARDED_BY(sequence_checker_);
};
} // namespace webrtc
#endif // MODULES_VIDEO_CODING_RATE_CONTROL_BUFFER_LEVEL_RATE_CONTROLLER_H_