Skip to main content

Vp8TwoPassEncoder

Struct Vp8TwoPassEncoder 

Source
pub struct Vp8TwoPassEncoder { /* private fields */ }
Expand description

Two-pass encoder driver.

§Algorithm (clean-room, RFC 6386 §9.6 + in-tree primitives only)

RFC 6386 is intentionally silent on rate-control — the algorithm is the encoder’s choice. This implementation runs in one of two modes, selected by Vp8TwoPassConfig::bitrate_targeted:

  • Constant-quality (no bitrate target): a complexity-aware scheduler centred on config.base.qindex (steps 1–3 below).
  • Bitrate-targeted (target_bitrate_bps > 0 and a frame rate set): Self::first_pass_analyze solves the GOP base qindex that fits the budget (solve_base_qindex_for_budget) and caches a per-frame byte allotment. Each Self::encode_frame then re-centres the complexity delta on the solved base and adds a closed-loop feedback term proportional to the accumulated rate debt (bytes emitted so far minus bytes allotted), so the stream self-corrects toward the target. The feedback gain /clamp are RATE_FEEDBACK_QSTEP_PER_FRAME / RATE_FEEDBACK_MAX_QSTEP.

The complexity-aware scheduler (both modes share it) is built from a single linear pass over the luma plane:

  1. First pass (first_pass_analyze / the free fn of the same name): for each input frame, compute a lightweight cost surrogate from per-pixel luma arithmetic:

    • mad — mean absolute deviation vs the previous frame’s luma (motion proxy; first frame uses mad = 0).
    • var — luma variance vs the per-frame mean (spatial activity proxy).
    • bits_per_mb (the surrogate) ≈ α·log2(1+mad) + β·log2(1+var), multiplied by 100 and clamped non-negative. A pure-flat frame lands near 0; a noise-saturated moving frame lands near 1000.
    • Scene cut: declared when mad * 1024 / (prev_var + 1) exceeds DEFAULT_SCENE_CUT_THRESHOLD and mad >= SCENE_CUT_ABS_FLOOR / 1024.
  2. Second pass (two_pass_qindices / the free fn of the same name): distribute per-frame qindex around config.base.qindex so heavier frames get lower qindex (better quality, more bytes) and lighter frames get higher qindex (lower quality, fewer bytes):

    • mean = mean(bits_per_mb) across the GOP.
    • delta = clamp((cost - mean) / max(mean, 1.0) * range, -range, range) where range = DEFAULT_AQ_QINDEX_RANGE.
    • qindex = clamp(base + round(delta), 0, 127) per RFC 6386 §9.6.
    • Scene cuts subtract an additional DEFAULT_SCENE_CUT_QUANT_BOOST to give those frames extra quality.
  3. Encode pass (Self::encode_frame): for each input frame, look up its per-frame qindex, build a KeyframeParams with that y_ac_qi, and drive the in-tree key/P encoders against the reference [KeyframePlanes] stashed inside the driver. The first call always emits a key frame; subsequent calls emit P frames against the previous reconstruction.

The per-frame qindex is sourced purely from the supplied complexity and the global_mean_cost cached during the most recent Self::first_pass_analyze call. A caller that bypasses first_pass_analyze falls back to a no-delta schedule (every frame gets config.base.qindex).

Implementations§

Source§

impl Vp8TwoPassEncoder

Source

pub fn new(config: Vp8TwoPassConfig) -> Self

Build a fresh two-pass encoder.

The encoder starts with no first-pass state and no reference reconstruction — call Self::first_pass_analyze before Self::encode_frame to populate the rate-control mean.

Source

pub fn config(&self) -> &Vp8TwoPassConfig

Two-pass config (immutable handle).

Source

pub fn first_pass_analyze( &mut self, frames: &[I420Frame<'_>], ) -> Result<Vec<FrameComplexity>>

First-pass analysis entry — returns the per-frame FrameComplexity vector and caches the GOP-mean cost on self so the subsequent Self::encode_frame calls can pick per-frame qindex deltas relative to it.

Delegates to the free function first_pass_analyze for the core arithmetic; this method exists so a streaming consumer can keep the analysis state on the encoder handle rather than threading the mean by hand.

Source

pub fn encode_frame( &mut self, frame: &I420Frame<'_>, complexity: FrameComplexity, ) -> Result<Vec<u8>>

Second-pass encode of one frame, picking the qindex from the first-pass complexity report.

The first call always emits a key frame; subsequent calls emit a P-frame against the previous reconstruction. The complexity report’s scene_cut flag forces a key frame even mid-stream. Returns the raw VP8 bitstream bytes for the frame.

Source

pub fn rate_debt_bytes(&self) -> i64

Current accumulated rate debt in bytes (positive ⇒ over budget). Exposed so a streaming caller can observe how the closed-loop bitrate controller is tracking the target. Always 0 on the constant-quality (no bitrate target) path.

Trait Implementations§

Source§

impl Clone for Vp8TwoPassEncoder

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Vp8TwoPassEncoder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.