oxideav_vp8/stream.rs
1//! Multi-frame VP8 keyframe encoder driver
2//! ([`Vp8KeyframeStreamEncoder`]).
3//!
4//! This module is the encoder-side counterpart of
5//! [`crate::state::Vp8DecoderState`]: it owns the per-stream state a
6//! sequence of VP8 frames needs (frame count, locked dimensions, the
7//! §9 three-slot reference-frame buffer) and exposes a single
8//! [`Vp8KeyframeStreamEncoder::encode_frame`] entry that turns one
9//! input I420 picture into one VP8 keyframe's bytes while updating
10//! that state.
11//!
12//! ## Scope
13//!
14//! Every emitted frame is a **key frame** — independently decodable, no
15//! cross-frame prediction. The reference-frame slot machinery is wired
16//! up because every key frame implicitly refreshes all three slots per
17//! RFC 6386 §9.7 / §9.8 (the `if (key_frame) … hdr->refresh_last = 1`
18//! body referenced in §19.2's header listing): a downstream decoder
19//! observing the emitted stream sees its `LAST`, `GOLDEN`, and `ALTREF`
20//! slots overwritten with the same picture after every frame.
21//! Maintaining the slots in the encoder mirrors that, so the eventual
22//! inter-encoder round drops in without further plumbing — it will
23//! just need to (a) flip the `key_frame` bit, (b) consult the slots
24//! for motion-compensation source pixels, and (c) honour the §9.7
25//! `refresh_*` / `copy_buffer_to_*` rules to decide which slot(s) the
26//! frame refreshes.
27//!
28//! Inter prediction itself, reference-frame selection (§16.2), per-MB
29//! motion vectors (§17), and motion compensation (§18) are
30//! intentionally out of scope for this round.
31//!
32//! ## Per-frame self-decode invariant
33//!
34//! Each emitted frame's bytes decode through the crate's own
35//! [`crate::state::Vp8DecoderState`] driver to within the §14 quantiser
36//! distortion of the input picture. The
37//! `encoder_keyframe_stream.rs` integration test pins this on a
38//! synthetic 5-frame sequence (different pattern per frame, mid
39//! quantiser, whole-frame PSNR ≥ 30 dB).
40//!
41//! ## Reference-slot lifecycle
42//!
43//! Internally the driver reuses [`crate::encoder::encode_keyframe_with_reconstruction`]
44//! so the *exact* post-§15 macroblock-aligned reconstruction the
45//! decoder will rebuild from the emitted bytes is available without a
46//! re-decode. After every successful `encode_frame` call the three
47//! [`crate::state::RefFrameSlot`]s are atomically replaced with a clone
48//! of that reconstruction, matching the
49//! [`crate::state::Vp8DecoderState::decode_key_frame`] update logic
50//! one-for-one.
51//!
52//! ## Reference
53//!
54//! * RFC 6386 §4 page 8 — "The first frame of a VP8 stream is always a
55//! key frame".
56//! * RFC 6386 §9.1 / §19.2 — the `key_frame` bit + the keyframe-only
57//! `start_code` `0x9d 0x01 0x2a` in the frame tag.
58//! * RFC 6386 §9.7 / §9.8 — `refresh_golden_frame`,
59//! `refresh_alternate_frame`, `refresh_last`. For a key frame all
60//! three are forced to 1 implicitly (the on-wire bits are
61//! key-frame-suppressed; the listing in §19.2 only emits them on
62//! `if (!key_frame)`).
63
64use crate::coded_header::TokenProbUpdates;
65use crate::encoder::{
66 EncodeError, I420Frame, KeyframeParams, LoopFilterDeltas, RefreshControls,
67 encode_keyframe_with_reconstruction,
68 encode_keyframe_with_reconstruction_and_fitted_token_prob_updates, encode_p_frame_multi_ref,
69 encode_p_frame_multi_ref_with_fitted_token_prob_updates,
70 encode_p_frame_multi_ref_with_intra_pick, encode_p_frame_multi_ref_with_refresh,
71 encode_p_frame_multi_ref_with_refresh_and_intra_pick,
72 encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates,
73 encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick_and_fitted_token_prob_updates,
74};
75use crate::frame::KeyframePlanes;
76use crate::state::RefFrameSlot;
77
78/// Errors surfaced by [`Vp8KeyframeStreamEncoder::encode_frame`].
79///
80/// Wraps the per-frame [`EncodeError`] surface and adds the
81/// cross-frame-only failures (a dimensions change between frames,
82/// which the §9.1 keyframe-only-resize rule would technically allow
83/// for *another* key frame but which most container clients treat as
84/// a stream split — we reject it here to keep the contract explicit).
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86#[non_exhaustive]
87pub enum StreamEncodeError {
88 /// A frame after the first was supplied with different dimensions
89 /// than the first. The driver treats the dimensions as locked at
90 /// the first `encode_frame` call.
91 DimensionsChanged {
92 /// `(width, height)` of the first frame fed in.
93 first: (u32, u32),
94 /// `(width, height)` of the offending later frame.
95 got: (u32, u32),
96 },
97 /// The underlying per-frame encoder rejected the inputs (validator
98 /// failure or §13 token failure). Carries the underlying
99 /// [`EncodeError`].
100 Frame(EncodeError),
101 /// [`Vp8InterStreamEncoder::encode_p_frame_with_refresh`] was called
102 /// before the stream had emitted its first frame, so no `LAST`
103 /// reference is available. The caller should drive at least one
104 /// frame through the scheduler first.
105 NoLastReference,
106}
107
108impl core::fmt::Display for StreamEncodeError {
109 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
110 match self {
111 StreamEncodeError::DimensionsChanged { first, got } => write!(
112 f,
113 "vp8 stream encode: frame dimensions {}x{} differ from \
114 stream's first frame {}x{} (dimensions are locked at \
115 the first encode_frame call)",
116 got.0, got.1, first.0, first.1
117 ),
118 StreamEncodeError::Frame(e) => write!(f, "vp8 stream encode: {e}"),
119 StreamEncodeError::NoLastReference => write!(
120 f,
121 "vp8 stream encode: encode_p_frame_with_refresh called before \
122 the stream emitted its first frame (LAST reference slot is empty)"
123 ),
124 }
125 }
126}
127
128impl std::error::Error for StreamEncodeError {
129 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
130 match self {
131 StreamEncodeError::DimensionsChanged { .. } => None,
132 StreamEncodeError::Frame(e) => Some(e),
133 StreamEncodeError::NoLastReference => None,
134 }
135 }
136}
137
138impl From<EncodeError> for StreamEncodeError {
139 fn from(e: EncodeError) -> Self {
140 StreamEncodeError::Frame(e)
141 }
142}
143
144/// Multi-frame VP8 keyframe encoder driver.
145///
146/// One instance owns the cross-frame state of a single VP8 elementary
147/// stream: the frame counter, the locked-after-first-frame dimensions,
148/// and the §9 three-slot reference-frame buffer
149/// (`LAST` / `GOLDEN` / `ALTREF`).
150///
151/// All emitted frames are key frames this round. Each successful
152/// [`Self::encode_frame`] call:
153///
154/// 1. Validates that this frame's dimensions match the first frame's
155/// (or, on the first call, locks them in).
156/// 2. Calls [`encode_keyframe_with_reconstruction`] with the driver's
157/// [`KeyframeParams`].
158/// 3. Replaces all three reference slots with a clone of the
159/// macroblock-aligned post-§15 reconstruction (§9.7 / §9.8 keyframe
160/// refresh).
161/// 4. Increments the frame counter.
162/// 5. Returns the emitted bytes.
163///
164/// Construct with [`Self::new`] and drive with [`Self::encode_frame`].
165/// [`Self::frame_count`], [`Self::dimensions`], and the per-slot
166/// accessors [`Self::last`], [`Self::golden`], [`Self::altref`]
167/// expose the running state.
168#[derive(Debug, Clone)]
169pub struct Vp8KeyframeStreamEncoder {
170 params: KeyframeParams,
171 /// Visible dimensions of the first frame fed in. Locked after the
172 /// first successful `encode_frame` call; `None` before then.
173 dimensions: Option<(u32, u32)>,
174 /// Number of frames successfully encoded so far.
175 frame_count: u64,
176 /// `LAST` reference slot. `None` before the first frame; populated
177 /// (and replaced) on every successful `encode_frame` call.
178 last: Option<RefFrameSlot>,
179 /// `GOLDEN` reference slot. Same lifecycle as
180 /// [`Self::last`] this round (every key frame refreshes all three).
181 golden: Option<RefFrameSlot>,
182 /// `ALTREF` reference slot. Same lifecycle as [`Self::last`].
183 altref: Option<RefFrameSlot>,
184}
185
186impl Vp8KeyframeStreamEncoder {
187 /// Build a fresh stream encoder configured with the supplied
188 /// per-frame [`KeyframeParams`]. Same parameters are applied to
189 /// every encoded frame in this stream.
190 ///
191 /// The frame counter starts at 0 and all three reference slots
192 /// start as `None`. The dimensions are not locked until the first
193 /// `encode_frame` call.
194 pub fn new(params: KeyframeParams) -> Self {
195 Vp8KeyframeStreamEncoder {
196 params,
197 dimensions: None,
198 frame_count: 0,
199 last: None,
200 golden: None,
201 altref: None,
202 }
203 }
204
205 /// Encode one frame of the stream as a VP8 key frame.
206 ///
207 /// On the first call this also locks the stream's dimensions to
208 /// `frame`'s visible width/height. Every subsequent call must
209 /// supply a frame with the same dimensions; a mismatch is
210 /// surfaced as [`StreamEncodeError::DimensionsChanged`] and leaves
211 /// the encoder state unchanged.
212 ///
213 /// Returns the raw bytes of one VP8 elementary-stream frame
214 /// (`one packet = one frame`) ready to be fed to a container muxer
215 /// (e.g. IVF) or decoded directly through
216 /// [`crate::decode_vp8`] / [`crate::state::Vp8DecoderState::decode_frame`].
217 pub fn encode_frame(&mut self, frame: &I420Frame<'_>) -> Result<Vec<u8>, StreamEncodeError> {
218 let dims = (frame.width, frame.height);
219 match self.dimensions {
220 Some(locked) if locked != dims => {
221 return Err(StreamEncodeError::DimensionsChanged {
222 first: locked,
223 got: dims,
224 });
225 }
226 _ => {}
227 }
228
229 let (bytes, planes) = encode_keyframe_with_reconstruction(frame, &self.params)?;
230
231 // §9.7 / §9.8 keyframe slot refresh — all three slots take a
232 // clone of the post-§15 macroblock-aligned reconstruction.
233 // Mirrors `Vp8DecoderState::decode_key_frame`'s slot installation.
234 let slot = RefFrameSlot::from_keyframe_planes(&planes);
235 self.last = Some(slot.clone());
236 self.golden = Some(slot.clone());
237 self.altref = Some(slot);
238
239 self.dimensions = Some(dims);
240 self.frame_count += 1;
241 Ok(bytes)
242 }
243
244 /// Encode one frame of the stream as a VP8 key frame, with an
245 /// automatically-fitted §13.4 `token_prob_update()` payload per
246 /// [`crate::encoder::encode_keyframe_with_reconstruction_and_fitted_token_prob_updates`].
247 ///
248 /// Drop-in fitted companion to [`Self::encode_frame`]: same K/P
249 /// scheduling rules (every emitted frame is a key frame on this
250 /// driver), same dimension-lock semantics, same §9.7 / §9.8
251 /// three-slot refresh — only the bitstream differs (the fitter is
252 /// allowed to *shrink* the wire by overlaying observed-counts
253 /// probabilities on the §13.5 defaults, with the round-157 fitter's
254 /// safety guard that never *grows* the wire relative to the
255 /// caller-driven `None` baseline).
256 ///
257 /// The returned bytes always decode through
258 /// [`crate::state::Vp8DecoderState::decode_frame`] and every
259 /// compliant VP8 decoder; the §9 reference-frame slots are refreshed
260 /// with the matching reconstruction (the round-157 safety-guard
261 /// fall-back returns the **default-pass** planes alongside the
262 /// default-pass bytes, so the slot state stays consistent with the
263 /// wire on both fitter outcomes).
264 ///
265 /// Closes the round-157 / round-158 follow-up identified in
266 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates`]
267 /// ("Out of round-158 scope: threading the fitter into
268 /// `Vp8KeyframeStreamEncoder` / `Vp8InterStreamEncoder`").
269 pub fn encode_frame_with_fitted_token_prob_updates(
270 &mut self,
271 frame: &I420Frame<'_>,
272 ) -> Result<Vec<u8>, StreamEncodeError> {
273 let dims = (frame.width, frame.height);
274 match self.dimensions {
275 Some(locked) if locked != dims => {
276 return Err(StreamEncodeError::DimensionsChanged {
277 first: locked,
278 got: dims,
279 });
280 }
281 _ => {}
282 }
283
284 let (bytes, planes) =
285 encode_keyframe_with_reconstruction_and_fitted_token_prob_updates(frame, &self.params)?;
286
287 // §9.7 / §9.8 keyframe slot refresh — identical to
288 // `Self::encode_frame`: a key frame refreshes all three slots
289 // with the post-§15 reconstruction. The fitter's matching-planes
290 // guarantee means `planes` is the reconstruction that matches
291 // the emitted `bytes` regardless of which pass (default or
292 // fitted) won the safety-guard comparison.
293 let slot = RefFrameSlot::from_keyframe_planes(&planes);
294 self.last = Some(slot.clone());
295 self.golden = Some(slot.clone());
296 self.altref = Some(slot);
297
298 self.dimensions = Some(dims);
299 self.frame_count += 1;
300 Ok(bytes)
301 }
302
303 /// Number of frames successfully encoded so far.
304 pub fn frame_count(&self) -> u64 {
305 self.frame_count
306 }
307
308 /// Stream dimensions, locked at the first successful
309 /// `encode_frame` call. `None` before then.
310 pub fn dimensions(&self) -> Option<(u32, u32)> {
311 self.dimensions
312 }
313
314 /// Borrow the current `LAST` reference slot. `None` before the
315 /// first frame.
316 pub fn last(&self) -> Option<&RefFrameSlot> {
317 self.last.as_ref()
318 }
319
320 /// Borrow the current `GOLDEN` reference slot. `None` before the
321 /// first frame.
322 pub fn golden(&self) -> Option<&RefFrameSlot> {
323 self.golden.as_ref()
324 }
325
326 /// Borrow the current `ALTREF` reference slot. `None` before the
327 /// first frame.
328 pub fn altref(&self) -> Option<&RefFrameSlot> {
329 self.altref.as_ref()
330 }
331
332 /// Borrow the [`KeyframeParams`] applied to every frame this
333 /// stream emits.
334 pub fn params(&self) -> &KeyframeParams {
335 &self.params
336 }
337}
338
339// ───────────────── Multi-frame I + P stream driver (Phase 10) ────────────────
340//
341// `Vp8InterStreamEncoder` extends the keyframe driver by interleaving
342// ZERO_MV P-frames between key frames per a caller-specified keyframe
343// interval (or a per-frame force-keyframe flag). It uses
344// `encode_keyframe_with_reconstruction` for the K-frame path and
345// `encode_p_frame_zero_mv` for the P-frame path, and maintains the §9
346// three-slot reference-frame ladder one-for-one with
347// `Vp8DecoderState::decode_frame`:
348//
349// * A keyframe replaces all three slots with the post-§15
350// reconstruction (§9.7 / §9.8 — every refresh / copy bit is forced
351// to 1 for a key frame).
352// * A ZERO_MV P-frame replaces LAST only (§9.7 — the P-frame encoder
353// emits `refresh_last = 1`, all other refresh / copy bits 0).
354//
355// Reference: RFC 6386 §9 (frame-header layout for K vs P), §9.7
356// (refresh ladder), §9.8 (`refresh_last` interpretation), §16
357// (interframe header), §17 (motion-vector layer), §18 (motion
358// compensation — ZERO_MV path is the §18 identity copy).
359
360/// Per-frame keyframe scheduling decision for
361/// [`Vp8InterStreamEncoder`].
362///
363/// Returned by [`Vp8InterStreamEncoder::next_frame_is_keyframe`] and by
364/// the [`EncodedStreamFrame::is_keyframe`] field of every encoded
365/// output; the caller can use it to confirm the K/P interleave the
366/// encoder picked agreed with its expectations.
367#[derive(Debug, Clone, Copy, PartialEq, Eq)]
368pub enum FrameKind {
369 /// VP8 key frame — independently decodable, refreshes all three
370 /// reference slots (§9.7 / §9.8).
371 Key,
372 /// VP8 inter frame coded as ZERO_MV against LAST — predicts from
373 /// the LAST reference at MV (0, 0) per §16.2 / §18, refreshes LAST
374 /// only (§9.7 inter refresh ladder).
375 InterZeroMv,
376}
377
378/// One frame emitted by [`Vp8InterStreamEncoder::encode_frame`].
379///
380/// Bundles the raw VP8 elementary-stream bytes with the K-vs-P
381/// classification and the running frame index, so the caller can sink
382/// the bytes into a container while logging or asserting the
383/// scheduling pattern.
384#[derive(Debug, Clone)]
385#[non_exhaustive]
386pub struct EncodedStreamFrame {
387 /// Raw VP8 elementary-stream bytes for this frame (one packet =
388 /// one frame). Suitable for IVF muxing or for
389 /// [`crate::state::Vp8DecoderState::decode_frame`].
390 pub bytes: Vec<u8>,
391 /// Whether the encoder coded this frame as a key frame or as a
392 /// ZERO_MV P-frame.
393 pub kind: FrameKind,
394 /// 0-based frame index inside this stream — equal to the encoder's
395 /// `frame_count()` at the moment this frame was emitted minus one.
396 pub frame_index: u64,
397}
398
399impl EncodedStreamFrame {
400 /// Build a `EncodedStreamFrame` from every field.
401 pub fn new(bytes: Vec<u8>, kind: FrameKind, frame_index: u64) -> Self {
402 Self {
403 bytes,
404 kind,
405 frame_index,
406 }
407 }
408
409 /// Set `bytes`.
410 #[must_use]
411 pub fn with_bytes(mut self, v: Vec<u8>) -> Self {
412 self.bytes = v;
413 self
414 }
415
416 /// Set `kind`.
417 #[must_use]
418 pub fn with_kind(mut self, v: FrameKind) -> Self {
419 self.kind = v;
420 self
421 }
422
423 /// Set `frame_index`.
424 #[must_use]
425 pub fn with_frame_index(mut self, v: u64) -> Self {
426 self.frame_index = v;
427 self
428 }
429}
430
431impl EncodedStreamFrame {
432 /// Convenience: `true` iff this frame was coded as a key frame.
433 pub fn is_keyframe(&self) -> bool {
434 matches!(self.kind, FrameKind::Key)
435 }
436}
437
438/// Multi-frame VP8 I + P stream encoder.
439///
440/// One instance drives a sequence of source I420 pictures into a VP8
441/// elementary stream of alternating key frames and ZERO_MV P-frames,
442/// owning every piece of cross-frame state the §9 / §16 layers need:
443///
444/// * the frame counter,
445/// * the locked-after-first-frame visible dimensions,
446/// * the §9 three-slot reference-frame buffer
447/// (`LAST` / `GOLDEN` / `ALTREF`),
448/// * the keyframe scheduling parameters (interval + per-call override).
449///
450/// ## Scheduling
451///
452/// The encoder picks K or P per frame using two inputs:
453///
454/// 1. A non-zero `keyframe_interval` configured at construction —
455/// every `keyframe_interval`th frame (0, K, 2K, 3K, …) is a key
456/// frame, the rest are ZERO_MV P-frames.
457/// 2. A per-call `force_keyframe` flag on
458/// [`Self::encode_frame_with_force`] — set to `true`, the next
459/// emitted frame is a key frame regardless of the interval, and
460/// the interval re-anchors to the forced index.
461///
462/// The first frame fed into a fresh encoder is **always** a key
463/// frame — there is no prior reference to predict from, matching
464/// [`crate::state::Vp8DecoderState`]'s rejection of an interframe with
465/// no prior key frame.
466///
467/// ## Reference-slot lifecycle
468///
469/// After every successful `encode_frame` call the three reference
470/// slots are updated to match what
471/// [`crate::state::Vp8DecoderState::decode_frame`] would do for the
472/// just-emitted frame:
473///
474/// * **Key frame** (§9.7 / §9.8) — all three slots are replaced with
475/// a clone of the post-§15 reconstruction.
476/// * **ZERO_MV P-frame** (§9.7) — `refresh_last = 1` only, so the LAST
477/// slot is replaced with the post-§15 reconstruction; GOLDEN and
478/// ALTREF are left untouched.
479///
480/// This mirrors the underlying [`encode_p_frame_zero_mv`] refresh
481/// ladder one-for-one.
482///
483/// ## Per-frame self-decode invariant
484///
485/// Every emitted frame's bytes are decodable through
486/// [`crate::state::Vp8DecoderState::decode_frame`], and a sequence of
487/// frames replays into the same per-frame pictures the encoder was
488/// fed (to within the §14 quantiser distortion). The
489/// `encoder_inter_stream.rs` integration test pins this on a synthetic
490/// 10-frame I420 sequence at keyframe interval 4, requiring per-frame
491/// PSNR ≥ 30 dB at a mid quantiser.
492///
493/// ## Scope (this round)
494///
495/// * Every P-frame is ZERO_MV from LAST — no motion search, no
496/// NEARESTMV / NEARMV / NEWMV / SPLITMV, no GOLDEN / ALTREF
497/// selection. Quality on natural content beyond slow translation is
498/// bounded by the §14 quantiser absorbing the residual.
499/// * The §9.5 partition count is whatever the caller put in
500/// [`KeyframeParams::nbr_of_dct_partitions`] for K-frames; P-frames
501/// stay single-partition this round (the underlying
502/// [`encode_p_frame_zero_mv`] hardwires 1).
503/// * Mid-stream resize is rejected with
504/// [`StreamEncodeError::DimensionsChanged`].
505#[derive(Debug, Clone)]
506pub struct Vp8InterStreamEncoder {
507 params: KeyframeParams,
508 keyframe_interval: u64,
509 dimensions: Option<(u32, u32)>,
510 frame_count: u64,
511 /// Frame index that received the most recent key frame. Used to
512 /// re-anchor the interval after a forced keyframe so the next
513 /// K-frame is `keyframe_interval` frames later, not always at a
514 /// multiple of `keyframe_interval` from the absolute start.
515 last_keyframe_index: Option<u64>,
516 last: Option<RefFrameSlot>,
517 golden: Option<RefFrameSlot>,
518 altref: Option<RefFrameSlot>,
519 /// Across-frame §9.4 `ref_frame_delta[]` state in the §20.6
520 /// `{CURRENT, LAST, GOLDEN, ALTREF}` order. Threaded into every
521 /// P-frame's [`oxideav_vp8::LoopFilterDeltas::effective`] call so
522 /// the encoder's §15 post-walk filter matches what the decoder
523 /// derives from the wire. Reset to `[0; 4]` on every key frame
524 /// (RFC 6386 §9.4 — key frames begin a fresh delta sequence).
525 carried_ref_deltas: [i16; 4],
526 /// Across-frame §9.4 `mode_delta[]` state in the §20.6 `{B_PRED,
527 /// ZERO_MV, OTHER_MV, SPLIT_MV}` order. Same lifecycle as
528 /// `carried_ref_deltas`.
529 carried_mode_deltas: [i16; 4],
530 /// Automatic §9.7 `refresh_golden_frame` cadence for the
531 /// scheduler-driven [`Self::encode_frame`] path. `0` disables the
532 /// automatic golden refresh (the historical behaviour — GOLDEN
533 /// stays frozen at the most-recent keyframe's reconstruction until
534 /// the next key frame). `N > 0` makes every `N`-th P-frame **after a
535 /// key frame** also set `refresh_golden_frame = 1`, so GOLDEN tracks
536 /// recent content for the inter MBs that match it better than LAST.
537 /// Counted in P-frames since the last key frame (a key frame already
538 /// refreshes every slot per §9.7, so it resets the count).
539 golden_interval: u64,
540 /// Number of P-frames emitted since the last key frame, used to
541 /// drive [`Self::golden_interval`]. Reset to `0` on every key frame.
542 p_frames_since_keyframe: u64,
543}
544
545impl Vp8InterStreamEncoder {
546 /// Build a fresh I + P stream encoder.
547 ///
548 /// `keyframe_interval` controls automatic keyframe scheduling:
549 ///
550 /// * `1` — every frame is a key frame (degenerates to the
551 /// keyframe-only driver).
552 /// * `N > 1` — frames 0, N, 2N, 3N, … are key frames; frames in
553 /// between are ZERO_MV P-frames.
554 /// * `0` — rejected; the keyframe interval must be at least 1 or
555 /// the encoder would never emit a key frame.
556 ///
557 /// Returns `None` for `keyframe_interval == 0` to make the bad
558 /// configuration impossible-by-construction at the call site.
559 pub fn new(params: KeyframeParams, keyframe_interval: u64) -> Option<Self> {
560 if keyframe_interval == 0 {
561 return None;
562 }
563 Some(Vp8InterStreamEncoder {
564 params,
565 keyframe_interval,
566 dimensions: None,
567 frame_count: 0,
568 last_keyframe_index: None,
569 last: None,
570 golden: None,
571 altref: None,
572 carried_ref_deltas: [0; 4],
573 carried_mode_deltas: [0; 4],
574 golden_interval: 0,
575 p_frames_since_keyframe: 0,
576 })
577 }
578
579 /// Set the automatic §9.7 `refresh_golden_frame` cadence (builder
580 /// style) and return the modified encoder.
581 ///
582 /// With `golden_interval = N > 0`, the scheduler-driven
583 /// [`Self::encode_frame`] / [`Self::encode_frame_with_force`] path
584 /// sets `refresh_golden_frame = 1` on every `N`-th P-frame measured
585 /// from the most-recent key frame (i.e. the `N`-th, `2N`-th, …
586 /// P-frame after each key frame). On those frames the current
587 /// reconstruction is written into the encoder's GOLDEN slot exactly
588 /// as the decoder will write its own — the §16.2 inter MBs of later
589 /// P-frames can then predict off a recent GOLDEN instead of one
590 /// frozen at the last key frame.
591 ///
592 /// `golden_interval = 0` (the default after [`Self::new`]) disables
593 /// the automatic refresh and reproduces the historical
594 /// `refresh_last`-only auto path byte-for-byte. Callers that want
595 /// full manual control over the §9.7 / §9.8 ladder keep using the
596 /// `encode_p_frame_with_refresh*` family, which is unaffected.
597 #[must_use]
598 pub fn with_golden_interval(mut self, golden_interval: u64) -> Self {
599 self.golden_interval = golden_interval;
600 self
601 }
602
603 /// The configured automatic §9.7 golden-refresh cadence (`0` =
604 /// disabled). See [`Self::with_golden_interval`].
605 pub fn golden_interval(&self) -> u64 {
606 self.golden_interval
607 }
608
609 /// Whether the next scheduler-driven P-frame would set
610 /// `refresh_golden_frame = 1` under the configured
611 /// [`Self::golden_interval`], **without** encoding anything.
612 ///
613 /// Always `false` when the automatic cadence is disabled
614 /// (`golden_interval == 0`) or when the next frame is a key frame
615 /// (key frames refresh every slot regardless). Otherwise `true`
616 /// exactly when this would be the `N`-th, `2N`-th, … P-frame after
617 /// the last key frame.
618 pub fn next_p_frame_refreshes_golden(&self) -> bool {
619 if self.golden_interval == 0 {
620 return false;
621 }
622 if self.next_frame_is_keyframe() == FrameKind::Key {
623 return false;
624 }
625 // This call would emit P-frame number `p_frames_since_keyframe
626 // + 1` since the last key frame.
627 (self.p_frames_since_keyframe + 1).is_multiple_of(self.golden_interval)
628 }
629
630 /// Decide whether the next [`Self::encode_frame`] call would emit
631 /// a key frame, given the current frame index and the last forced
632 /// keyframe anchor — without actually encoding anything.
633 ///
634 /// Useful for a caller that wants to pre-roll metadata (IVF
635 /// keyframe markers, container random-access entries) before
636 /// handing the frame in. The decision is:
637 ///
638 /// * `FrameKind::Key` if no frame has been encoded yet (first
639 /// frame must be a key frame), or if `frame_count -
640 /// last_keyframe_index >= keyframe_interval`.
641 /// * `FrameKind::InterZeroMv` otherwise.
642 pub fn next_frame_is_keyframe(&self) -> FrameKind {
643 match self.last_keyframe_index {
644 None => FrameKind::Key,
645 Some(anchor) => {
646 if self
647 .frame_count
648 .saturating_sub(anchor)
649 .ge(&self.keyframe_interval)
650 {
651 FrameKind::Key
652 } else {
653 FrameKind::InterZeroMv
654 }
655 }
656 }
657 }
658
659 /// Encode one frame of the stream using the configured keyframe
660 /// interval to pick K vs P.
661 ///
662 /// On the first call this also locks the stream's dimensions to
663 /// `frame`'s visible width/height. Every subsequent call must
664 /// supply a frame with the same dimensions; a mismatch is
665 /// surfaced as [`StreamEncodeError::DimensionsChanged`] and leaves
666 /// the encoder state unchanged.
667 ///
668 /// Returns the emitted bytes wrapped in an
669 /// [`EncodedStreamFrame`] so the caller knows which kind of frame
670 /// it received without re-parsing the §9.1 tag bit.
671 pub fn encode_frame(
672 &mut self,
673 frame: &I420Frame<'_>,
674 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
675 self.encode_frame_with_force(frame, false)
676 }
677
678 /// Encode one frame of the stream, with an optional override that
679 /// forces it to be coded as a key frame regardless of the
680 /// configured interval.
681 ///
682 /// A `force_keyframe = true` call **also re-anchors the interval**:
683 /// after the forced K-frame at frame index `i`, the next automatic
684 /// keyframe lands at `i + keyframe_interval`, not at the original
685 /// multiple of `keyframe_interval` from the absolute start. This
686 /// keeps the inter-keyframe spacing predictable in the presence of
687 /// scene-cut overrides.
688 pub fn encode_frame_with_force(
689 &mut self,
690 frame: &I420Frame<'_>,
691 force_keyframe: bool,
692 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
693 let dims = (frame.width, frame.height);
694 match self.dimensions {
695 Some(locked) if locked != dims => {
696 return Err(StreamEncodeError::DimensionsChanged {
697 first: locked,
698 got: dims,
699 });
700 }
701 _ => {}
702 }
703
704 let scheduled = self.next_frame_is_keyframe();
705 let must_be_key = scheduled == FrameKind::Key || force_keyframe;
706
707 // We can only emit a P-frame if we actually hold a LAST
708 // reference; otherwise we must promote to a key frame even
709 // though the scheduler said "P". (Belt-and-suspenders: the
710 // scheduler already returns Key for the first frame, so this
711 // arm is only ever taken if a future variant of the API lets
712 // the caller drop the slots externally.)
713 let emit_key = must_be_key || self.last.is_none();
714
715 // §9.7 automatic golden-refresh schedule: when a non-zero
716 // `golden_interval` is configured, the `N`-th P-frame after the
717 // last key frame also sets `refresh_golden_frame = 1` so GOLDEN
718 // tracks recent content rather than staying frozen at the most-
719 // recent key frame. The first scheduled refresh therefore lands
720 // when `p_frames_since_keyframe + 1` (this P-frame's index since
721 // the key frame) is a multiple of the interval.
722 let refresh_golden = !emit_key
723 && self.golden_interval != 0
724 && (self.p_frames_since_keyframe + 1).is_multiple_of(self.golden_interval);
725
726 let (bytes, planes, kind) = if emit_key {
727 let (b, p) = encode_keyframe_with_reconstruction(frame, &self.params)?;
728 (b, p, FrameKind::Key)
729 } else {
730 // Safe: `emit_key` is false ⇒ `self.last` is Some by the
731 // expression above. We pass all three §9 reference slots
732 // (`LAST` required, `GOLDEN` / `ALTREF` optional) to the
733 // multi-ref encoder so it can score each MB against every
734 // available reference and emit the §16.2 `ref_frame_tree`
735 // selector bits per MB.
736 //
737 // When `refresh_golden` is set the §9.7 wire ladder is
738 // `refresh_golden_frame = 1, refresh_last = 1` (everything
739 // else 0); otherwise it is the default `refresh_last = 1`
740 // only — byte-identical to the historical auto path. The
741 // matching `RefreshControls` is reproduced on the slot side
742 // below so the encoder's GOLDEN slot stays in lockstep with
743 // what the decoder writes from the wire.
744 let last_planes = ref_slot_to_keyframe_planes(
745 self.last.as_ref().expect("LAST slot present for P-frame"),
746 );
747 let golden_planes = self.golden.as_ref().map(ref_slot_to_keyframe_planes);
748 let altref_planes = self.altref.as_ref().map(ref_slot_to_keyframe_planes);
749 let (b, p) = if refresh_golden {
750 let refresh = RefreshControls {
751 refresh_golden_frame: true,
752 refresh_last: true,
753 ..RefreshControls::default()
754 };
755 encode_p_frame_multi_ref_with_refresh(
756 frame,
757 &last_planes,
758 golden_planes.as_ref(),
759 altref_planes.as_ref(),
760 &self.params,
761 &refresh,
762 )?
763 } else {
764 encode_p_frame_multi_ref(
765 frame,
766 &last_planes,
767 golden_planes.as_ref(),
768 altref_planes.as_ref(),
769 &self.params,
770 )?
771 };
772 (b, p, FrameKind::InterZeroMv)
773 };
774
775 let frame_index = self.frame_count;
776
777 // ---- Reference-slot update (§9.7) -----------------------------
778 let new_slot = RefFrameSlot::from_keyframe_planes(&planes);
779 match kind {
780 FrameKind::Key => {
781 // §9.7 / §9.8 keyframe — every slot is refreshed with
782 // the same reconstruction.
783 self.last = Some(new_slot.clone());
784 self.golden = Some(new_slot.clone());
785 self.altref = Some(new_slot);
786 self.last_keyframe_index = Some(frame_index);
787 // §9.4 key frames begin a fresh delta sequence — clear
788 // the carried state so the next P-frame's effective
789 // deltas start from 0 (matching the decoder's behaviour
790 // after a key frame).
791 self.carried_ref_deltas = [0; 4];
792 self.carried_mode_deltas = [0; 4];
793 // §9.7 key frames reset the automatic golden-refresh
794 // cadence: every slot was just refreshed, so the count
795 // of P-frames since the last key frame restarts at 0.
796 self.p_frames_since_keyframe = 0;
797 }
798 FrameKind::InterZeroMv => {
799 // §9.7 inter refresh ladder. By default only LAST
800 // changes (refresh_last = 1, everything else 0). When
801 // the automatic golden-refresh schedule fired for this
802 // frame the wire carried `refresh_golden_frame = 1` as
803 // well, so GOLDEN takes the same current reconstruction
804 // — keeping the encoder slot in lockstep with the
805 // decoder's §9.7 write. ALTREF and the §20 copy_buffer_*
806 // paths stay untouched on this auto schedule. The §9.4
807 // carried-delta state stays unchanged (this path emits
808 // `loop_filter_adj_enable = 0`, so the effective deltas
809 // are all 0 and there is nothing fresh to carry).
810 if refresh_golden {
811 self.golden = Some(new_slot.clone());
812 }
813 self.last = Some(new_slot);
814 self.p_frames_since_keyframe += 1;
815 }
816 }
817
818 self.dimensions = Some(dims);
819 self.frame_count += 1;
820 Ok(EncodedStreamFrame {
821 bytes,
822 kind,
823 frame_index,
824 })
825 }
826
827 /// Encode one frame using the configured keyframe interval to pick
828 /// K vs P, with the round-160 / round-161 §11 intra-within-inter
829 /// MB picker engaged on every P-frame.
830 ///
831 /// Drop-in `intra-pick` companion to [`Self::encode_frame`]: the
832 /// scheduling decision (K vs P) and the §9.7 reference-slot ladder
833 /// are identical to the non-intra-pick path; only the per-MB picker
834 /// changes. On every emitted P-frame the per-MB picker scores the
835 /// full §11.2 × §11.4 whole-block intra grid (4 luma × 4 chroma =
836 /// 16 candidates, `B_PRED` excluded) against the running in-frame
837 /// neighbours in addition to the §16 inter ladder, and picks
838 /// whichever of (best inter pick, J-best intra) wins on
839 /// `J + lambda * is_inter_mb-bit`. When the intra candidate wins
840 /// on at least one MB the §9.10 `prob_intra` byte drops below 255
841 /// and the §16.1 intra-mode-tree path emits on those MBs.
842 ///
843 /// K-frames go through the same
844 /// [`encode_keyframe_with_reconstruction`] path as
845 /// [`Self::encode_frame`] — the intra-pick flag only affects the
846 /// inter (P-frame) arm. The §9.4 carried-delta state, the §9.7
847 /// reference-slot rotation, and the dimensions-lock semantics are
848 /// unchanged.
849 ///
850 /// Wire compatibility: on any source where the round-161 picker
851 /// never selects an intra MB (e.g. a slow-translation flat
852 /// gradient where ZERO_MV already absorbs the residual), the
853 /// emitted bytes match [`Self::encode_frame`] modulo the
854 /// `prob_intra` byte's drop from 255 to 1 (≈ 6 extra bits ≈ 1
855 /// extra byte per P-frame). This is the same bound the bare
856 /// `encode_p_frame_multi_ref_with_intra_pick` entry-point already
857 /// pins under `tests/encoder_pframe_intra_pick.rs`.
858 pub fn encode_frame_with_intra_pick(
859 &mut self,
860 frame: &I420Frame<'_>,
861 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
862 self.encode_frame_with_force_and_intra_pick(frame, false)
863 }
864
865 /// Encode one frame with the round-160 / round-161 intra-pick
866 /// engaged **and** an optional `force_keyframe` override that
867 /// re-anchors the keyframe interval, exactly mirroring
868 /// [`Self::encode_frame_with_force`].
869 ///
870 /// Companion to [`Self::encode_frame_with_intra_pick`]: the
871 /// `force_keyframe` semantics (re-anchoring the interval after a
872 /// forced K-frame at frame index `i` so the next automatic K-frame
873 /// lands at `i + keyframe_interval`) match
874 /// [`Self::encode_frame_with_force`] exactly. On the K-frame arm
875 /// the intra-pick flag is a no-op — every MB in a key frame is
876 /// intra by construction.
877 pub fn encode_frame_with_force_and_intra_pick(
878 &mut self,
879 frame: &I420Frame<'_>,
880 force_keyframe: bool,
881 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
882 let dims = (frame.width, frame.height);
883 match self.dimensions {
884 Some(locked) if locked != dims => {
885 return Err(StreamEncodeError::DimensionsChanged {
886 first: locked,
887 got: dims,
888 });
889 }
890 _ => {}
891 }
892
893 let scheduled = self.next_frame_is_keyframe();
894 let must_be_key = scheduled == FrameKind::Key || force_keyframe;
895 let emit_key = must_be_key || self.last.is_none();
896
897 let (bytes, planes, kind) = if emit_key {
898 let (b, p) = encode_keyframe_with_reconstruction(frame, &self.params)?;
899 (b, p, FrameKind::Key)
900 } else {
901 // Inter arm — same LAST/GOLDEN/ALTREF plane harvesting as
902 // `encode_frame_with_force`, but the per-MB picker is the
903 // round-160 / round-161 intra-within-inter widened
904 // candidate set.
905 let last_planes = ref_slot_to_keyframe_planes(
906 self.last.as_ref().expect("LAST slot present for P-frame"),
907 );
908 let golden_planes = self.golden.as_ref().map(ref_slot_to_keyframe_planes);
909 let altref_planes = self.altref.as_ref().map(ref_slot_to_keyframe_planes);
910 let (b, p) = encode_p_frame_multi_ref_with_intra_pick(
911 frame,
912 &last_planes,
913 golden_planes.as_ref(),
914 altref_planes.as_ref(),
915 &self.params,
916 )?;
917 (b, p, FrameKind::InterZeroMv)
918 };
919
920 let frame_index = self.frame_count;
921
922 // ---- Reference-slot update (§9.7) — identical to
923 // `encode_frame_with_force`. The intra-pick flag does NOT
924 // affect the §9.7 ladder; `planes` is the reconstruction that
925 // matches `bytes` regardless of which per-MB pick won.
926 let new_slot = RefFrameSlot::from_keyframe_planes(&planes);
927 match kind {
928 FrameKind::Key => {
929 self.last = Some(new_slot.clone());
930 self.golden = Some(new_slot.clone());
931 self.altref = Some(new_slot);
932 self.last_keyframe_index = Some(frame_index);
933 // §9.4 — key frames start a fresh delta sequence.
934 self.carried_ref_deltas = [0; 4];
935 self.carried_mode_deltas = [0; 4];
936 }
937 FrameKind::InterZeroMv => {
938 // §9.7 inter refresh ladder used by the multi-ref
939 // P-frame encoder's default `RefreshControls`:
940 // refresh_last = 1 only.
941 self.last = Some(new_slot);
942 }
943 }
944
945 self.dimensions = Some(dims);
946 self.frame_count += 1;
947 Ok(EncodedStreamFrame {
948 bytes,
949 kind,
950 frame_index,
951 })
952 }
953
954 /// Encode one frame using the configured keyframe interval to pick
955 /// K vs P, with an automatically-fitted §13.4 `token_prob_update()`
956 /// payload on every emitted frame.
957 ///
958 /// Drop-in fitted companion to [`Self::encode_frame`] / the K-frame
959 /// arm of [`Self::encode_frame_with_force`]: scheduling, dimension-
960 /// lock semantics, and the §9.7 reference-slot ladder are identical;
961 /// only the bitstream differs. Each emitted frame independently
962 /// runs the round-157 (keyframe) or round-158 (inter) two-pass
963 /// fitter — the §13.4 payload is decided per frame from that frame's
964 /// observed counts, never carried over to the next.
965 ///
966 /// Wire compatibility: on a frame where no §13.4 slot crosses the
967 /// fitter's saving threshold, the safety-guard fall-back returns
968 /// the bytes [`Self::encode_frame_with_force`] would have emitted
969 /// for the same kind of frame.
970 ///
971 /// **Carried-base assumption.** The inter fitter assumes the prior
972 /// key frame was emitted with the §13.5 defaults (i.e. an
973 /// `encode_keyframe`-equivalent base table). This entry-point is
974 /// the closure of that loop: K-frames go through
975 /// [`encode_keyframe_with_reconstruction_and_fitted_token_prob_updates`]
976 /// which itself emits a fitted-on-defaults wire — the decoder
977 /// rebuilds `coeff_probs[4][8][3][11]` from defaults overlaid with
978 /// the K-frame's payload, then the next P-frame's fitter again
979 /// overlays its own payload on top of the §13.5 defaults. This
980 /// matches what [`crate::state::Vp8DecoderState::decode_inter_frame`]
981 /// does (`overlay_token_probs(self.coeff_probs, &coded.token_prob_updates)`
982 /// where `self.coeff_probs` was reset to §13.5 defaults by the prior
983 /// key frame).
984 pub fn encode_frame_with_fitted_token_prob_updates(
985 &mut self,
986 frame: &I420Frame<'_>,
987 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
988 self.encode_frame_with_force_and_fitted_token_prob_updates(frame, false)
989 }
990
991 /// Encode one frame, with an optional `force_keyframe` override and
992 /// the round-157 / round-158 fitter applied to every emitted frame.
993 ///
994 /// Companion to [`Self::encode_frame_with_force`] /
995 /// [`Self::encode_frame_with_fitted_token_prob_updates`]. The
996 /// `force_keyframe` semantics (re-anchoring the interval) match
997 /// [`Self::encode_frame_with_force`] exactly.
998 pub fn encode_frame_with_force_and_fitted_token_prob_updates(
999 &mut self,
1000 frame: &I420Frame<'_>,
1001 force_keyframe: bool,
1002 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
1003 let dims = (frame.width, frame.height);
1004 match self.dimensions {
1005 Some(locked) if locked != dims => {
1006 return Err(StreamEncodeError::DimensionsChanged {
1007 first: locked,
1008 got: dims,
1009 });
1010 }
1011 _ => {}
1012 }
1013
1014 let scheduled = self.next_frame_is_keyframe();
1015 let must_be_key = scheduled == FrameKind::Key || force_keyframe;
1016 let emit_key = must_be_key || self.last.is_none();
1017
1018 let (bytes, planes, kind) = if emit_key {
1019 let (b, p) = encode_keyframe_with_reconstruction_and_fitted_token_prob_updates(
1020 frame,
1021 &self.params,
1022 )?;
1023 (b, p, FrameKind::Key)
1024 } else {
1025 // Mirrors the non-fitted arm exactly — same LAST/GOLDEN/ALTREF
1026 // plane harvesting, same multi-ref picker, only the fitted
1027 // inter entry-point swapped in.
1028 let last_planes = ref_slot_to_keyframe_planes(
1029 self.last.as_ref().expect("LAST slot present for P-frame"),
1030 );
1031 let golden_planes = self.golden.as_ref().map(ref_slot_to_keyframe_planes);
1032 let altref_planes = self.altref.as_ref().map(ref_slot_to_keyframe_planes);
1033 let (b, p) = encode_p_frame_multi_ref_with_fitted_token_prob_updates(
1034 frame,
1035 &last_planes,
1036 golden_planes.as_ref(),
1037 altref_planes.as_ref(),
1038 &self.params,
1039 )?;
1040 (b, p, FrameKind::InterZeroMv)
1041 };
1042
1043 let frame_index = self.frame_count;
1044
1045 // ---- Reference-slot update (§9.7) — identical to
1046 // `encode_frame_with_force`. The fitter does NOT affect the
1047 // §9.7 ladder; the fitter's matching-planes guarantee means
1048 // `planes` is the reconstruction that matches `bytes` regardless
1049 // of which pass won.
1050 let new_slot = RefFrameSlot::from_keyframe_planes(&planes);
1051 match kind {
1052 FrameKind::Key => {
1053 self.last = Some(new_slot.clone());
1054 self.golden = Some(new_slot.clone());
1055 self.altref = Some(new_slot);
1056 self.last_keyframe_index = Some(frame_index);
1057 // §9.4 — key frames start a fresh delta sequence.
1058 self.carried_ref_deltas = [0; 4];
1059 self.carried_mode_deltas = [0; 4];
1060 }
1061 FrameKind::InterZeroMv => {
1062 // §9.7 inter refresh ladder used by the multi-ref
1063 // P-frame encoder's default `RefreshControls`:
1064 // refresh_last = 1 only.
1065 self.last = Some(new_slot);
1066 }
1067 }
1068
1069 self.dimensions = Some(dims);
1070 self.frame_count += 1;
1071 Ok(EncodedStreamFrame {
1072 bytes,
1073 kind,
1074 frame_index,
1075 })
1076 }
1077
1078 /// Encode one P-frame with a caller-supplied §9.7 / §9.8
1079 /// reference-slot refresh pattern.
1080 ///
1081 /// This is the slot-rotation companion to
1082 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh`]: it
1083 /// emits a P-frame whose header carries the requested `refresh`
1084 /// bits and then evolves the driver's `LAST` / `GOLDEN` / `ALTREF`
1085 /// slots per the §20 page-147 walk (`copy_arf → copy_gf →
1086 /// refresh_gf → refresh_arf → refresh_last`), so the next
1087 /// `encode_frame*` call sees the same slot trio the in-tree
1088 /// decoder would after consuming the same wire.
1089 ///
1090 /// Pre-conditions:
1091 ///
1092 /// * A `LAST` slot must be present (the stream must have emitted at
1093 /// least one prior frame). If not, the call returns
1094 /// [`StreamEncodeError::NoLastReference`] — the caller should
1095 /// drive at least one frame through the scheduler
1096 /// ([`Self::encode_frame`] or [`Self::encode_frame_with_force`])
1097 /// first.
1098 /// * Dimensions must match the stream's locked dimensions; a
1099 /// mismatch is surfaced as
1100 /// [`StreamEncodeError::DimensionsChanged`].
1101 /// * `refresh` is forwarded to
1102 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh`],
1103 /// which runs [`RefreshControls::validate`]; invalid
1104 /// `copy_buffer_to_*` selectors surface as
1105 /// [`EncodeError::InvalidCopyBufferSelector`] wrapped in
1106 /// [`StreamEncodeError::Frame`].
1107 ///
1108 /// The keyframe scheduler is **bypassed** by this entry-point: the
1109 /// caller has asked for a specific refresh pattern, and forcing a
1110 /// key frame here would lose it.
1111 ///
1112 /// The slot rotation runs after the bitstream is emitted, mirroring
1113 /// the §20 page-147 ordering verbatim:
1114 ///
1115 /// 1. `copy_buffer_to_alternate` (1 = LAST → ALTREF, 2 = GOLDEN → ALTREF).
1116 /// 2. `copy_buffer_to_golden` (1 = LAST → GOLDEN, 2 = ALTREF → GOLDEN).
1117 /// 3. `refresh_golden_frame` (replace GOLDEN with current reconstruction).
1118 /// 4. `refresh_alternate_frame` (replace ALTREF with current reconstruction).
1119 /// 5. `refresh_last` (replace LAST with current reconstruction).
1120 ///
1121 /// `last_keyframe_index` is **not** touched (this is a P-frame).
1122 pub fn encode_p_frame_with_refresh(
1123 &mut self,
1124 frame: &I420Frame<'_>,
1125 refresh: &RefreshControls,
1126 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
1127 self.encode_p_frame_with_refresh_and_lf_deltas(frame, refresh, &LoopFilterDeltas::default())
1128 }
1129
1130 /// Encode one P-frame with a caller-supplied §9.7 / §9.8
1131 /// reference-slot refresh pattern, with the round-160 / round-161
1132 /// §11 intra-within-inter MB picker engaged.
1133 ///
1134 /// Combines [`Self::encode_p_frame_with_refresh`] (caller-driven
1135 /// refresh ladder + stream-side slot rotation per §20 page-147)
1136 /// with the round-161 picker. On every MB the picker scores the
1137 /// full §11.2 × §11.4 whole-block intra grid (4 luma × 4 chroma)
1138 /// against the running in-frame neighbours in addition to the §16
1139 /// inter ladder, and picks whichever of (best inter, J-best intra)
1140 /// wins on `J + lambda * is_inter_mb-bit`.
1141 ///
1142 /// Pre-conditions and slot-rotation mirror
1143 /// [`Self::encode_p_frame_with_refresh`] exactly:
1144 ///
1145 /// * A `LAST` slot must be present —
1146 /// [`StreamEncodeError::NoLastReference`] otherwise.
1147 /// * Dimensions must match the stream's locked dimensions —
1148 /// [`StreamEncodeError::DimensionsChanged`] otherwise.
1149 /// * `refresh` is forwarded to
1150 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh_and_intra_pick`],
1151 /// which runs [`RefreshControls::validate`]; invalid selectors
1152 /// surface as [`EncodeError::InvalidCopyBufferSelector`] wrapped
1153 /// in [`StreamEncodeError::Frame`].
1154 /// * The keyframe scheduler is **bypassed** (the caller is asking
1155 /// for a P-frame with a specific refresh).
1156 ///
1157 /// Slot-rotation runs after the bitstream is emitted, mirroring
1158 /// the §20 page-147 walk (`copy_arf → copy_gf → refresh_gf →
1159 /// refresh_arf → refresh_last`). `last_keyframe_index` is **not**
1160 /// touched. The §9.4 carried-delta state is **not** updated this
1161 /// round — the picker engages the round-160 inter path with
1162 /// [`LoopFilterDeltas::default`] (matching the bare-encoder
1163 /// `encode_p_frame_multi_ref_with_refresh_and_intra_pick`
1164 /// signature), so the effective deltas resolve to `0` and there
1165 /// is no fresh value to carry. Callers that need both intra-pick
1166 /// AND §9.4 deltas should sit one round above this — the
1167 /// composition fits naturally into the
1168 /// `…_intra_pick_and_lf_deltas` companion that a follow-up round
1169 /// will expose; this round's scope is exactly the intra-pick
1170 /// thread, not the full Cartesian product.
1171 pub fn encode_p_frame_with_refresh_and_intra_pick(
1172 &mut self,
1173 frame: &I420Frame<'_>,
1174 refresh: &RefreshControls,
1175 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
1176 let dims = (frame.width, frame.height);
1177 match self.dimensions {
1178 Some(locked) if locked != dims => {
1179 return Err(StreamEncodeError::DimensionsChanged {
1180 first: locked,
1181 got: dims,
1182 });
1183 }
1184 _ => {}
1185 }
1186 let last_slot = self
1187 .last
1188 .as_ref()
1189 .ok_or(StreamEncodeError::NoLastReference)?;
1190
1191 let last_planes = ref_slot_to_keyframe_planes(last_slot);
1192 let golden_planes = self.golden.as_ref().map(ref_slot_to_keyframe_planes);
1193 let altref_planes = self.altref.as_ref().map(ref_slot_to_keyframe_planes);
1194 let (bytes, planes) = encode_p_frame_multi_ref_with_refresh_and_intra_pick(
1195 frame,
1196 &last_planes,
1197 golden_planes.as_ref(),
1198 altref_planes.as_ref(),
1199 &self.params,
1200 refresh,
1201 )?;
1202
1203 let frame_index = self.frame_count;
1204
1205 // ---- §9.7 / §9.8 reference-slot rotation -----------------------
1206 // Identical to `encode_p_frame_with_refresh_and_lf_deltas`: the
1207 // intra-pick flag governs per-MB candidate scoring only and
1208 // does NOT alter the §9.7 slot ladder. The §20 page-147 walk
1209 // is `copy_arf → copy_gf → refresh_gf → refresh_arf →
1210 // refresh_last`; the "copy" cases consult pre-refresh state,
1211 // so capture the pre-rotation slots into temporaries first.
1212 let current_slot = RefFrameSlot::from_keyframe_planes(&planes);
1213 let pre_last = self.last.clone();
1214 let pre_golden = self.golden.clone();
1215 let pre_altref = self.altref.clone();
1216
1217 let mut new_altref = pre_altref.clone();
1218 match refresh.copy_buffer_to_alternate {
1219 1 => new_altref = pre_last.clone(),
1220 2 => new_altref = pre_golden.clone(),
1221 _ => {}
1222 }
1223 let mut new_golden = pre_golden.clone();
1224 match refresh.copy_buffer_to_golden {
1225 1 => new_golden = pre_last.clone(),
1226 2 => new_golden = pre_altref.clone(),
1227 _ => {}
1228 }
1229 if refresh.refresh_golden_frame {
1230 new_golden = Some(current_slot.clone());
1231 }
1232 if refresh.refresh_alternate_frame {
1233 new_altref = Some(current_slot.clone());
1234 }
1235 let new_last = if refresh.refresh_last {
1236 Some(current_slot.clone())
1237 } else {
1238 pre_last
1239 };
1240
1241 self.last = new_last;
1242 self.golden = new_golden;
1243 self.altref = new_altref;
1244 self.dimensions = Some(dims);
1245 self.frame_count += 1;
1246 Ok(EncodedStreamFrame {
1247 bytes,
1248 kind: FrameKind::InterZeroMv,
1249 frame_index,
1250 })
1251 }
1252
1253 /// Encode one P-frame with a caller-supplied §9.7 / §9.8
1254 /// reference-slot refresh pattern **and** a caller-supplied §9.4
1255 /// `mb_lf_adjustments()` per-reference / per-mode loop-filter
1256 /// delta layer.
1257 ///
1258 /// Companion to [`Self::encode_p_frame_with_refresh`] that exposes
1259 /// the §9.4 `loop_filter_adj_enable` /
1260 /// `mode_ref_lf_delta_update` + per-slot delta fields through
1261 /// [`crate::encoder::LoopFilterDeltas`]. The stream encoder threads
1262 /// the across-frame carried delta state per RFC 6386 §9.4 ("the
1263 /// values from the previous frame are used, unless they are updated
1264 /// in the current header") — the caller does not need to track it.
1265 ///
1266 /// Wire compatibility: passing
1267 /// [`crate::encoder::LoopFilterDeltas::default`] (with
1268 /// `enabled = false`) reproduces
1269 /// [`Self::encode_p_frame_with_refresh`] byte-for-byte, including
1270 /// when called repeatedly through the carried-state mechanism
1271 /// (`enabled = false` resolves effective deltas to 0 regardless
1272 /// of carried state).
1273 ///
1274 /// Slot-rotation and pre-conditions match
1275 /// [`Self::encode_p_frame_with_refresh`].
1276 pub fn encode_p_frame_with_refresh_and_lf_deltas(
1277 &mut self,
1278 frame: &I420Frame<'_>,
1279 refresh: &RefreshControls,
1280 lf_deltas: &LoopFilterDeltas,
1281 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
1282 let dims = (frame.width, frame.height);
1283 match self.dimensions {
1284 Some(locked) if locked != dims => {
1285 return Err(StreamEncodeError::DimensionsChanged {
1286 first: locked,
1287 got: dims,
1288 });
1289 }
1290 _ => {}
1291 }
1292 let last_slot = self
1293 .last
1294 .as_ref()
1295 .ok_or(StreamEncodeError::NoLastReference)?;
1296
1297 let last_planes = ref_slot_to_keyframe_planes(last_slot);
1298 let golden_planes = self.golden.as_ref().map(ref_slot_to_keyframe_planes);
1299 let altref_planes = self.altref.as_ref().map(ref_slot_to_keyframe_planes);
1300 let (bytes, planes) = crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas(
1301 frame,
1302 &last_planes,
1303 golden_planes.as_ref(),
1304 altref_planes.as_ref(),
1305 &self.params,
1306 refresh,
1307 lf_deltas,
1308 self.carried_ref_deltas,
1309 self.carried_mode_deltas,
1310 )?;
1311
1312 let frame_index = self.frame_count;
1313
1314 // ---- §9.4 across-frame delta carry ----------------------------
1315 // The decoder updates its carried state with the effective
1316 // values it just resolved (carried + present updates). Mirror
1317 // that exactly so the next frame's effective deltas line up.
1318 let (eff_ref, eff_mode) =
1319 lf_deltas.effective(self.carried_ref_deltas, self.carried_mode_deltas);
1320 if lf_deltas.enabled {
1321 // RFC 6386 §9.4: when adj is enabled, the carried state for
1322 // the NEXT frame is what this frame's effective deltas
1323 // resolved to (whether they came from updates or carry).
1324 // When adj is DISABLED this frame, the spec keeps the
1325 // carried state untouched — the disabled-this-frame case is
1326 // not a "reset" event, it just means no delta is applied
1327 // this frame; the deltas persist for whenever the next
1328 // frame re-enables the feature.
1329 self.carried_ref_deltas = eff_ref;
1330 self.carried_mode_deltas = eff_mode;
1331 }
1332
1333 // ---- §9.7 / §9.8 reference-slot rotation -----------------------
1334 // Mirror the §20 page-147 ordering exactly (the same walk the
1335 // decoder runs in `Vp8DecoderState`):
1336 // copy_buffer_to_alternate → copy_buffer_to_golden →
1337 // refresh_golden_frame → refresh_alternate_frame →
1338 // refresh_last. The "copy" cases consult the slot state from
1339 // BEFORE the refresh writes, so we capture pre-state in
1340 // temporaries first.
1341 let current_slot = RefFrameSlot::from_keyframe_planes(&planes);
1342 let pre_last = self.last.clone();
1343 let pre_golden = self.golden.clone();
1344 let pre_altref = self.altref.clone();
1345
1346 let mut new_altref = pre_altref.clone();
1347 match refresh.copy_buffer_to_alternate {
1348 1 => new_altref = pre_last.clone(),
1349 2 => new_altref = pre_golden.clone(),
1350 _ => {}
1351 }
1352 let mut new_golden = pre_golden.clone();
1353 match refresh.copy_buffer_to_golden {
1354 1 => new_golden = pre_last.clone(),
1355 2 => new_golden = pre_altref.clone(),
1356 _ => {}
1357 }
1358 if refresh.refresh_golden_frame {
1359 new_golden = Some(current_slot.clone());
1360 }
1361 if refresh.refresh_alternate_frame {
1362 new_altref = Some(current_slot.clone());
1363 }
1364 let new_last = if refresh.refresh_last {
1365 Some(current_slot.clone())
1366 } else {
1367 pre_last
1368 };
1369
1370 self.last = new_last;
1371 self.golden = new_golden;
1372 self.altref = new_altref;
1373 self.dimensions = Some(dims);
1374 self.frame_count += 1;
1375 Ok(EncodedStreamFrame {
1376 bytes,
1377 kind: FrameKind::InterZeroMv,
1378 frame_index,
1379 })
1380 }
1381
1382 /// Encode one P-frame with a caller-supplied §9.7 / §9.8 refresh
1383 /// pattern, §9.4 `mb_lf_adjustments()` delta layer, **and** §13.4
1384 /// `token_prob_update()` payload.
1385 ///
1386 /// Companion to [`Self::encode_p_frame_with_refresh_and_lf_deltas`]
1387 /// that exposes the §13.4 per-position
1388 /// `coeff_prob_update_flag` / `coeff_prob` sub-block through
1389 /// [`crate::coded_header::TokenProbUpdates`]. The encoder writes the
1390 /// replacement layer into the first-partition header and codes the
1391 /// §13.3 residual tokens against the merged
1392 /// `coeff_probs[4][8][3][11]` table (§13.5 defaults overlaid with
1393 /// the caller's per-position values), exactly mirroring what the
1394 /// decoder's `decode_inter_frame` rebuilds from the same wire.
1395 ///
1396 /// Wire compatibility: passing `token_updates = None` (or an
1397 /// all-`None` array) reproduces
1398 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas`] byte-for-byte
1399 /// — every §13.4 flag is 0 and the §13.5 defaults stay in force.
1400 ///
1401 /// Slot-rotation and pre-conditions match
1402 /// [`Self::encode_p_frame_with_refresh`].
1403 ///
1404 /// **Assumption on carried entropy state.** This entry-point assumes
1405 /// the prior key frame was emitted with the §13.5 defaults (i.e.
1406 /// either [`crate::encoder::encode_keyframe`] /
1407 /// [`crate::encoder::encode_keyframe_with_reconstruction`], or
1408 /// [`crate::encoder::encode_keyframe_with_token_prob_updates`]
1409 /// called with an all-`None` array). The standard stream entry-points
1410 /// [`Self::encode_frame`] / [`Self::encode_frame_with_force`] both
1411 /// satisfy this since they go through
1412 /// [`crate::encoder::encode_keyframe_with_reconstruction`]. Mixing a
1413 /// non-default-base keyframe with this entry-point is out of round-
1414 /// 156 scope.
1415 pub fn encode_p_frame_with_refresh_and_lf_deltas_and_token_updates(
1416 &mut self,
1417 frame: &I420Frame<'_>,
1418 refresh: &RefreshControls,
1419 lf_deltas: &LoopFilterDeltas,
1420 token_updates: Option<&TokenProbUpdates>,
1421 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
1422 let dims = (frame.width, frame.height);
1423 match self.dimensions {
1424 Some(locked) if locked != dims => {
1425 return Err(StreamEncodeError::DimensionsChanged {
1426 first: locked,
1427 got: dims,
1428 });
1429 }
1430 _ => {}
1431 }
1432 let last_slot = self
1433 .last
1434 .as_ref()
1435 .ok_or(StreamEncodeError::NoLastReference)?;
1436
1437 let last_planes = ref_slot_to_keyframe_planes(last_slot);
1438 let golden_planes = self.golden.as_ref().map(ref_slot_to_keyframe_planes);
1439 let altref_planes = self.altref.as_ref().map(ref_slot_to_keyframe_planes);
1440 let (bytes, planes) =
1441 crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_token_updates(
1442 frame,
1443 &last_planes,
1444 golden_planes.as_ref(),
1445 altref_planes.as_ref(),
1446 &self.params,
1447 refresh,
1448 lf_deltas,
1449 self.carried_ref_deltas,
1450 self.carried_mode_deltas,
1451 token_updates,
1452 )?;
1453
1454 let frame_index = self.frame_count;
1455
1456 // ---- §9.4 across-frame delta carry ----------------------------
1457 // Same lifecycle rule as `encode_p_frame_with_refresh_and_lf_deltas`:
1458 // adj-enabled frames update the carried state with this frame's
1459 // effective deltas; adj-disabled frames leave it unchanged. The
1460 // §13.4 token-prob layer does NOT affect the §9.4 delta carry.
1461 let (eff_ref, eff_mode) =
1462 lf_deltas.effective(self.carried_ref_deltas, self.carried_mode_deltas);
1463 if lf_deltas.enabled {
1464 self.carried_ref_deltas = eff_ref;
1465 self.carried_mode_deltas = eff_mode;
1466 }
1467
1468 // ---- §9.7 / §9.8 reference-slot rotation -----------------------
1469 // Identical to `encode_p_frame_with_refresh_and_lf_deltas`: token-
1470 // prob updates do NOT alter the §9.7 slot ladder (they govern
1471 // residual coding only).
1472 let current_slot = RefFrameSlot::from_keyframe_planes(&planes);
1473 let pre_last = self.last.clone();
1474 let pre_golden = self.golden.clone();
1475 let pre_altref = self.altref.clone();
1476
1477 let mut new_altref = pre_altref.clone();
1478 match refresh.copy_buffer_to_alternate {
1479 1 => new_altref = pre_last.clone(),
1480 2 => new_altref = pre_golden.clone(),
1481 _ => {}
1482 }
1483 let mut new_golden = pre_golden.clone();
1484 match refresh.copy_buffer_to_golden {
1485 1 => new_golden = pre_last.clone(),
1486 2 => new_golden = pre_altref.clone(),
1487 _ => {}
1488 }
1489 if refresh.refresh_golden_frame {
1490 new_golden = Some(current_slot.clone());
1491 }
1492 if refresh.refresh_alternate_frame {
1493 new_altref = Some(current_slot.clone());
1494 }
1495 let new_last = if refresh.refresh_last {
1496 Some(current_slot.clone())
1497 } else {
1498 pre_last
1499 };
1500
1501 self.last = new_last;
1502 self.golden = new_golden;
1503 self.altref = new_altref;
1504 self.dimensions = Some(dims);
1505 self.frame_count += 1;
1506 Ok(EncodedStreamFrame {
1507 bytes,
1508 kind: FrameKind::InterZeroMv,
1509 frame_index,
1510 })
1511 }
1512
1513 /// Encode one P-frame with a caller-supplied §9.7 / §9.8
1514 /// reference-slot refresh pattern, a caller-supplied §9.4
1515 /// `mb_lf_adjustments()` per-reference / per-mode loop-filter delta
1516 /// layer, **and** the round-160 / round-161 §11 intra-within-inter
1517 /// MB picker engaged.
1518 ///
1519 /// Composition of [`Self::encode_p_frame_with_refresh_and_lf_deltas`]
1520 /// (round 151 §9.4 layer + across-frame carried-delta state) and
1521 /// [`Self::encode_p_frame_with_refresh_and_intra_pick`] (round 162
1522 /// stream thread of the round-160 / 161 picker). The round 162 next-
1523 /// step ladder named exactly this composition — "compose the §9.4
1524 /// `mb_lf_adjustments()` deltas with the intra-pick on the refresh
1525 /// path (`encode_p_frame_with_refresh_and_lf_deltas_and_intra_pick`)"
1526 /// — as the follow-up that would expose both knobs together. Round
1527 /// 163 lands it.
1528 ///
1529 /// Internally calls
1530 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick`]
1531 /// (the matching bare-encoder wrapper). The stream encoder threads
1532 /// the across-frame carried delta state per RFC 6386 §9.4 ("the
1533 /// values from the previous frame are used, unless they are updated
1534 /// in the current header") — the caller does not need to track it;
1535 /// the carry-update rule is identical to
1536 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas`] (adj-enabled
1537 /// frames write back the effective deltas; adj-disabled frames leave
1538 /// the carry untouched). The intra-pick toggle does NOT affect the
1539 /// §9.4 delta carry — it governs per-MB candidate scoring only.
1540 ///
1541 /// Wire compatibility:
1542 ///
1543 /// * Passing [`crate::encoder::LoopFilterDeltas::default`] (with
1544 /// `enabled = false`) reproduces
1545 /// [`Self::encode_p_frame_with_refresh_and_intra_pick`]
1546 /// byte-for-byte. The §9.4 layer is gated on `lf_deltas.enabled`
1547 /// exactly as on the non-intra-pick path.
1548 /// * On a source where intra never beats inter the wire matches
1549 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas`] modulo a
1550 /// ~6 bits ≈ 1 byte frame-constant difference at the §9.10
1551 /// `prob_intra` byte (sentinel `255` → fitted `1`), matching the
1552 /// bound documented on the bare-encoder intra-pick path.
1553 ///
1554 /// Pre-conditions, slot-rotation (§20 page-147 walk
1555 /// `copy_arf → copy_gf → refresh_gf → refresh_arf → refresh_last`),
1556 /// and error surface (`NoLastReference`, `DimensionsChanged`) match
1557 /// [`Self::encode_p_frame_with_refresh`] exactly. `last_keyframe_index`
1558 /// is **not** touched.
1559 pub fn encode_p_frame_with_refresh_and_lf_deltas_and_intra_pick(
1560 &mut self,
1561 frame: &I420Frame<'_>,
1562 refresh: &RefreshControls,
1563 lf_deltas: &LoopFilterDeltas,
1564 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
1565 let dims = (frame.width, frame.height);
1566 match self.dimensions {
1567 Some(locked) if locked != dims => {
1568 return Err(StreamEncodeError::DimensionsChanged {
1569 first: locked,
1570 got: dims,
1571 });
1572 }
1573 _ => {}
1574 }
1575 let last_slot = self
1576 .last
1577 .as_ref()
1578 .ok_or(StreamEncodeError::NoLastReference)?;
1579
1580 let last_planes = ref_slot_to_keyframe_planes(last_slot);
1581 let golden_planes = self.golden.as_ref().map(ref_slot_to_keyframe_planes);
1582 let altref_planes = self.altref.as_ref().map(ref_slot_to_keyframe_planes);
1583 let (bytes, planes) =
1584 crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick(
1585 frame,
1586 &last_planes,
1587 golden_planes.as_ref(),
1588 altref_planes.as_ref(),
1589 &self.params,
1590 refresh,
1591 lf_deltas,
1592 self.carried_ref_deltas,
1593 self.carried_mode_deltas,
1594 )?;
1595
1596 let frame_index = self.frame_count;
1597
1598 // ---- §9.4 across-frame delta carry ----------------------------
1599 // Identical to `encode_p_frame_with_refresh_and_lf_deltas` /
1600 // `encode_p_frame_with_refresh_and_lf_deltas_and_token_updates`:
1601 // adj-enabled frames update the carried state with this frame's
1602 // effective deltas; adj-disabled frames leave it unchanged. The
1603 // §11 intra-pick toggle does NOT affect the §9.4 delta carry —
1604 // it governs per-MB candidate scoring only.
1605 let (eff_ref, eff_mode) =
1606 lf_deltas.effective(self.carried_ref_deltas, self.carried_mode_deltas);
1607 if lf_deltas.enabled {
1608 self.carried_ref_deltas = eff_ref;
1609 self.carried_mode_deltas = eff_mode;
1610 }
1611
1612 // ---- §9.7 / §9.8 reference-slot rotation -----------------------
1613 // Mirror the §20 page-147 ordering exactly (the same walk the
1614 // decoder runs in `Vp8DecoderState` and the same walk every other
1615 // refresh-aware entry-point on this struct runs):
1616 // copy_buffer_to_alternate → copy_buffer_to_golden →
1617 // refresh_golden_frame → refresh_alternate_frame →
1618 // refresh_last. The "copy" cases consult the slot state from
1619 // BEFORE the refresh writes, so we capture pre-state in
1620 // temporaries first.
1621 let current_slot = RefFrameSlot::from_keyframe_planes(&planes);
1622 let pre_last = self.last.clone();
1623 let pre_golden = self.golden.clone();
1624 let pre_altref = self.altref.clone();
1625
1626 let mut new_altref = pre_altref.clone();
1627 match refresh.copy_buffer_to_alternate {
1628 1 => new_altref = pre_last.clone(),
1629 2 => new_altref = pre_golden.clone(),
1630 _ => {}
1631 }
1632 let mut new_golden = pre_golden.clone();
1633 match refresh.copy_buffer_to_golden {
1634 1 => new_golden = pre_last.clone(),
1635 2 => new_golden = pre_altref.clone(),
1636 _ => {}
1637 }
1638 if refresh.refresh_golden_frame {
1639 new_golden = Some(current_slot.clone());
1640 }
1641 if refresh.refresh_alternate_frame {
1642 new_altref = Some(current_slot.clone());
1643 }
1644 let new_last = if refresh.refresh_last {
1645 Some(current_slot.clone())
1646 } else {
1647 pre_last
1648 };
1649
1650 self.last = new_last;
1651 self.golden = new_golden;
1652 self.altref = new_altref;
1653 self.dimensions = Some(dims);
1654 self.frame_count += 1;
1655 Ok(EncodedStreamFrame {
1656 bytes,
1657 kind: FrameKind::InterZeroMv,
1658 frame_index,
1659 })
1660 }
1661
1662 /// Encode one P-frame with a caller-supplied §9.7 / §9.8
1663 /// reference-slot refresh pattern, a caller-supplied §9.4
1664 /// `mb_lf_adjustments()` per-reference / per-mode loop-filter delta
1665 /// layer, **and** the round-157 / round-158 §13.4 token-prob
1666 /// observed-counts fitter engaged.
1667 ///
1668 /// Round 158 landed the bare-encoder
1669 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates`]
1670 /// (two-pass: encode with §13.5 defaults to collect observed branch
1671 /// counts, run [`crate::encoder::fit_token_prob_updates`] to derive
1672 /// a [`TokenProbUpdates`] payload that nets a positive bit saving,
1673 /// then re-encode with that payload through
1674 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_token_updates`]
1675 /// — with the `bytes_fitted <= bytes_default` safety guard). Round
1676 /// 159 threaded the *scheduler-driven* fitter through
1677 /// [`Self::encode_frame_with_fitted_token_prob_updates`] /
1678 /// [`Self::encode_frame_with_force_and_fitted_token_prob_updates`].
1679 /// The round-158 entry-point itself flagged the gap that this
1680 /// method closes:
1681 ///
1682 /// > *Out of round-158 scope: threading the fitter into
1683 /// > `Vp8InterStreamEncoder`'s `encode_frame` ladder — the
1684 /// > stream-driver method
1685 /// > `encode_p_frame_with_refresh_and_lf_deltas_and_token_updates`
1686 /// > stays on the caller-driven entry-point for now; a subsequent
1687 /// > round adds the analogous `_with_fitted_token_prob_updates`
1688 /// > stream method.*
1689 ///
1690 /// Round 164 lands that subsequent-round method on the **refresh +
1691 /// lf-deltas** axis — i.e. composed with the caller-supplied §9.4
1692 /// delta layer. The companion scheduler-driven fitter path
1693 /// ([`Self::encode_frame_with_fitted_token_prob_updates`]) already
1694 /// exists; this is the missing refresh-axis sibling.
1695 ///
1696 /// Internally calls
1697 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates`].
1698 /// The stream encoder threads the across-frame carried delta state
1699 /// per RFC 6386 §9.4 — the caller does not need to track it; the
1700 /// carry-update rule is identical to
1701 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas`] (adj-enabled
1702 /// frames write back the effective deltas; adj-disabled frames
1703 /// leave the carry untouched). The §13.4 fitter does NOT affect
1704 /// the §9.4 delta carry — it governs residual-token coding only,
1705 /// exactly as on the caller-driven token-updates sibling
1706 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas_and_token_updates`].
1707 ///
1708 /// Wire compatibility:
1709 ///
1710 /// * Whenever the fitter's safety guard falls back (no slot crossed
1711 /// the saving threshold, **or** the fitted re-encode is larger
1712 /// than the default-encode wire), the returned bytes are the
1713 /// default-encode bytes, byte-equal to
1714 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas`] on the
1715 /// same inputs.
1716 /// * Whenever the fitter wins, the bytes are byte-equal to the
1717 /// bare-encoder composition
1718 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates`]
1719 /// on the same inputs. The bare-encoder's safety guard also
1720 /// ensures the wire is `<=` the default-encode wire on every
1721 /// frame — this property carries through unchanged to the
1722 /// stream driver.
1723 ///
1724 /// Pre-conditions, slot-rotation (§20 page-147 walk
1725 /// `copy_arf → copy_gf → refresh_gf → refresh_arf → refresh_last`),
1726 /// and error surface (`NoLastReference`, `DimensionsChanged`) match
1727 /// [`Self::encode_p_frame_with_refresh`] exactly. `last_keyframe_index`
1728 /// is **not** touched.
1729 ///
1730 /// **Carried-base assumption.** Same as the round-158 bare-encoder
1731 /// fitter: this method assumes the prior key frame was emitted
1732 /// with the §13.5 defaults — i.e. either
1733 /// [`crate::encoder::encode_keyframe`] /
1734 /// [`crate::encoder::encode_keyframe_with_reconstruction`], or
1735 /// [`crate::encoder::encode_keyframe_with_token_prob_updates`]
1736 /// called with an all-`None` array. The standard stream entry-points
1737 /// [`Self::encode_frame`] / [`Self::encode_frame_with_force`] both
1738 /// satisfy this since they go through
1739 /// [`crate::encoder::encode_keyframe_with_reconstruction`]. Mixing
1740 /// a fitted keyframe (e.g.
1741 /// [`Self::encode_frame_with_fitted_token_prob_updates`]) with this
1742 /// entry-point is out of round-164 scope — same rule as the
1743 /// round-156 caller-driven token-updates sibling.
1744 pub fn encode_p_frame_with_refresh_and_lf_deltas_and_fitted_token_prob_updates(
1745 &mut self,
1746 frame: &I420Frame<'_>,
1747 refresh: &RefreshControls,
1748 lf_deltas: &LoopFilterDeltas,
1749 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
1750 let dims = (frame.width, frame.height);
1751 match self.dimensions {
1752 Some(locked) if locked != dims => {
1753 return Err(StreamEncodeError::DimensionsChanged {
1754 first: locked,
1755 got: dims,
1756 });
1757 }
1758 _ => {}
1759 }
1760 let last_slot = self
1761 .last
1762 .as_ref()
1763 .ok_or(StreamEncodeError::NoLastReference)?;
1764
1765 let last_planes = ref_slot_to_keyframe_planes(last_slot);
1766 let golden_planes = self.golden.as_ref().map(ref_slot_to_keyframe_planes);
1767 let altref_planes = self.altref.as_ref().map(ref_slot_to_keyframe_planes);
1768 let (bytes, planes) =
1769 encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates(
1770 frame,
1771 &last_planes,
1772 golden_planes.as_ref(),
1773 altref_planes.as_ref(),
1774 &self.params,
1775 refresh,
1776 lf_deltas,
1777 self.carried_ref_deltas,
1778 self.carried_mode_deltas,
1779 )?;
1780
1781 let frame_index = self.frame_count;
1782
1783 // ---- §9.4 across-frame delta carry ----------------------------
1784 // Identical to `encode_p_frame_with_refresh_and_lf_deltas` /
1785 // `encode_p_frame_with_refresh_and_lf_deltas_and_token_updates` /
1786 // `encode_p_frame_with_refresh_and_lf_deltas_and_intra_pick`:
1787 // adj-enabled frames update the carried state with this frame's
1788 // effective deltas; adj-disabled frames leave it unchanged. The
1789 // §13.4 token-prob fitter does NOT affect the §9.4 delta carry —
1790 // the fitter's bytes-vs-default safety guard does not interact
1791 // with the loop-filter delta layer either way.
1792 let (eff_ref, eff_mode) =
1793 lf_deltas.effective(self.carried_ref_deltas, self.carried_mode_deltas);
1794 if lf_deltas.enabled {
1795 self.carried_ref_deltas = eff_ref;
1796 self.carried_mode_deltas = eff_mode;
1797 }
1798
1799 // ---- §9.7 / §9.8 reference-slot rotation -----------------------
1800 // §20 page-147 ordering — identical to every other refresh-aware
1801 // entry-point. The fitter's pass-2 vs. pass-1 reconstruction
1802 // choice is already resolved inside
1803 // `encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates`
1804 // (it returns matched `(bytes, planes)`), so the slot we hand
1805 // forward matches what the decoder will reconstruct from
1806 // `bytes`.
1807 let current_slot = RefFrameSlot::from_keyframe_planes(&planes);
1808 let pre_last = self.last.clone();
1809 let pre_golden = self.golden.clone();
1810 let pre_altref = self.altref.clone();
1811
1812 let mut new_altref = pre_altref.clone();
1813 match refresh.copy_buffer_to_alternate {
1814 1 => new_altref = pre_last.clone(),
1815 2 => new_altref = pre_golden.clone(),
1816 _ => {}
1817 }
1818 let mut new_golden = pre_golden.clone();
1819 match refresh.copy_buffer_to_golden {
1820 1 => new_golden = pre_last.clone(),
1821 2 => new_golden = pre_altref.clone(),
1822 _ => {}
1823 }
1824 if refresh.refresh_golden_frame {
1825 new_golden = Some(current_slot.clone());
1826 }
1827 if refresh.refresh_alternate_frame {
1828 new_altref = Some(current_slot.clone());
1829 }
1830 let new_last = if refresh.refresh_last {
1831 Some(current_slot.clone())
1832 } else {
1833 pre_last
1834 };
1835
1836 self.last = new_last;
1837 self.golden = new_golden;
1838 self.altref = new_altref;
1839 self.dimensions = Some(dims);
1840 self.frame_count += 1;
1841 Ok(EncodedStreamFrame {
1842 bytes,
1843 kind: FrameKind::InterZeroMv,
1844 frame_index,
1845 })
1846 }
1847
1848 /// Encode one P-frame with a caller-supplied §9.7 / §9.8
1849 /// reference-slot refresh pattern, a caller-supplied §9.4
1850 /// `mb_lf_adjustments()` per-reference / per-mode loop-filter delta
1851 /// layer, the round-160 / round-161 §11 intra-within-inter MB
1852 /// picker, **and** the round-157 / round-158 §13.4 token-prob
1853 /// observed-counts fitter — all on the stream-driver path.
1854 ///
1855 /// Round 163 landed
1856 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas_and_intra_pick`]
1857 /// (§11 picker on the refresh + §9.4 deltas axis) and round 164
1858 /// landed
1859 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas_and_fitted_token_prob_updates`]
1860 /// (§13.4 fitter on the refresh + §9.4 deltas axis). Each composed
1861 /// individually with the lf-deltas axis but neither composed with
1862 /// the other.
1863 ///
1864 /// Round 164's next-step ladder names this as item (5):
1865 ///
1866 /// > *(5) parallel fitter composition on the intra-pick + refresh +
1867 /// > lf-deltas axis (combining r163 + r164 — the picker on the
1868 /// > fitted refresh path).*
1869 ///
1870 /// Internally calls
1871 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick_and_fitted_token_prob_updates`]
1872 /// — a two-pass encode that mirrors the round-158 fitter (pass 1
1873 /// with the §13.5 defaults to collect observed branch counts; pass
1874 /// 2 with the fitted [`crate::coded_header::TokenProbUpdates`]
1875 /// payload), with the §11 intra picker engaged on **both** passes
1876 /// so the recorded counts already reflect the intra/inter mix that
1877 /// will reappear on pass 2. The pass-2 RD picker re-scores against
1878 /// the merged probability table.
1879 ///
1880 /// The stream encoder threads the across-frame carried §9.4 delta
1881 /// state per RFC 6386 §9.4 exactly as
1882 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas`] /
1883 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas_and_intra_pick`] /
1884 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas_and_fitted_token_prob_updates`]:
1885 /// adj-enabled frames write back the effective deltas; adj-disabled
1886 /// frames leave the carry untouched. Neither the §11 picker nor the
1887 /// §13.4 fitter perturbs the §9.4 carry — both govern residual /
1888 /// per-MB decisions only.
1889 ///
1890 /// Wire compatibility:
1891 ///
1892 /// * Whenever the fitter's safety guard falls back (no slot crossed
1893 /// the saving threshold, **or** the fitted re-encode is larger
1894 /// than the default-encode wire), the returned bytes are the
1895 /// default-encode bytes, byte-equal to
1896 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas_and_intra_pick`]
1897 /// on the same inputs. The pass-1 planes are also returned in the
1898 /// fallback so a streaming caller's next-frame LAST matches the
1899 /// decoder's reconstruction.
1900 /// * Whenever the fitter wins, the bytes are byte-equal to the
1901 /// bare-encoder composition
1902 /// [`crate::encoder::encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick_and_fitted_token_prob_updates`]
1903 /// on the same inputs.
1904 /// * In every case the wire is `<=` the
1905 /// [`Self::encode_p_frame_with_refresh_and_lf_deltas_and_intra_pick`]
1906 /// default — the round-158 bare-encoder safety guard lifted into
1907 /// the stream driver.
1908 ///
1909 /// Pre-conditions, slot-rotation (§20 page-147 walk
1910 /// `copy_arf → copy_gf → refresh_gf → refresh_arf → refresh_last`),
1911 /// and error surface (`NoLastReference`, `DimensionsChanged`) match
1912 /// [`Self::encode_p_frame_with_refresh`] exactly. `last_keyframe_index`
1913 /// is **not** touched.
1914 ///
1915 /// **Carried-base assumption.** Same as the round-158 bare-encoder
1916 /// fitter: this method assumes the prior key frame was emitted with
1917 /// the §13.5 defaults — i.e. either
1918 /// [`crate::encoder::encode_keyframe`] /
1919 /// [`crate::encoder::encode_keyframe_with_reconstruction`], or
1920 /// [`crate::encoder::encode_keyframe_with_token_prob_updates`]
1921 /// called with an all-`None` array. The standard stream entry-points
1922 /// [`Self::encode_frame`] / [`Self::encode_frame_with_force`] both
1923 /// satisfy this. Mixing a fitted keyframe (e.g.
1924 /// [`Self::encode_frame_with_fitted_token_prob_updates`]) with this
1925 /// entry-point is out of round-165 scope — same rule as the
1926 /// round-156 / round-164 caller-driven / fitted-token-updates
1927 /// siblings.
1928 pub fn encode_p_frame_with_refresh_and_lf_deltas_and_intra_pick_and_fitted_token_prob_updates(
1929 &mut self,
1930 frame: &I420Frame<'_>,
1931 refresh: &RefreshControls,
1932 lf_deltas: &LoopFilterDeltas,
1933 ) -> Result<EncodedStreamFrame, StreamEncodeError> {
1934 let dims = (frame.width, frame.height);
1935 match self.dimensions {
1936 Some(locked) if locked != dims => {
1937 return Err(StreamEncodeError::DimensionsChanged {
1938 first: locked,
1939 got: dims,
1940 });
1941 }
1942 _ => {}
1943 }
1944 let last_slot = self
1945 .last
1946 .as_ref()
1947 .ok_or(StreamEncodeError::NoLastReference)?;
1948
1949 let last_planes = ref_slot_to_keyframe_planes(last_slot);
1950 let golden_planes = self.golden.as_ref().map(ref_slot_to_keyframe_planes);
1951 let altref_planes = self.altref.as_ref().map(ref_slot_to_keyframe_planes);
1952 let (bytes, planes) =
1953 encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick_and_fitted_token_prob_updates(
1954 frame,
1955 &last_planes,
1956 golden_planes.as_ref(),
1957 altref_planes.as_ref(),
1958 &self.params,
1959 refresh,
1960 lf_deltas,
1961 self.carried_ref_deltas,
1962 self.carried_mode_deltas,
1963 )?;
1964
1965 let frame_index = self.frame_count;
1966
1967 // ---- §9.4 across-frame delta carry ----------------------------
1968 // Identical to every other refresh+lf-deltas sibling. Neither
1969 // the §11 intra picker nor the §13.4 fitter perturbs the §9.4
1970 // carry; both govern per-MB / residual decisions only.
1971 let (eff_ref, eff_mode) =
1972 lf_deltas.effective(self.carried_ref_deltas, self.carried_mode_deltas);
1973 if lf_deltas.enabled {
1974 self.carried_ref_deltas = eff_ref;
1975 self.carried_mode_deltas = eff_mode;
1976 }
1977
1978 // ---- §9.7 / §9.8 reference-slot rotation -----------------------
1979 // §20 page-147 ordering — identical to every other refresh-aware
1980 // entry-point. The bare-encoder returns matched `(bytes, planes)`
1981 // (pass-2 win or pass-1 fall-back), so the slot we hand forward
1982 // matches what the decoder reconstructs from `bytes`.
1983 let current_slot = RefFrameSlot::from_keyframe_planes(&planes);
1984 let pre_last = self.last.clone();
1985 let pre_golden = self.golden.clone();
1986 let pre_altref = self.altref.clone();
1987
1988 let mut new_altref = pre_altref.clone();
1989 match refresh.copy_buffer_to_alternate {
1990 1 => new_altref = pre_last.clone(),
1991 2 => new_altref = pre_golden.clone(),
1992 _ => {}
1993 }
1994 let mut new_golden = pre_golden.clone();
1995 match refresh.copy_buffer_to_golden {
1996 1 => new_golden = pre_last.clone(),
1997 2 => new_golden = pre_altref.clone(),
1998 _ => {}
1999 }
2000 if refresh.refresh_golden_frame {
2001 new_golden = Some(current_slot.clone());
2002 }
2003 if refresh.refresh_alternate_frame {
2004 new_altref = Some(current_slot.clone());
2005 }
2006 let new_last = if refresh.refresh_last {
2007 Some(current_slot.clone())
2008 } else {
2009 pre_last
2010 };
2011
2012 self.last = new_last;
2013 self.golden = new_golden;
2014 self.altref = new_altref;
2015 self.dimensions = Some(dims);
2016 self.frame_count += 1;
2017 Ok(EncodedStreamFrame {
2018 bytes,
2019 kind: FrameKind::InterZeroMv,
2020 frame_index,
2021 })
2022 }
2023
2024 /// Borrow the across-frame §9.4 `ref_frame_delta[]` carried state
2025 /// (in `{CURRENT, LAST, GOLDEN, ALTREF}` order). Cleared to
2026 /// `[0; 4]` on every key frame per RFC 6386 §9.4.
2027 pub fn carried_ref_deltas(&self) -> [i16; 4] {
2028 self.carried_ref_deltas
2029 }
2030
2031 /// Borrow the across-frame §9.4 `mode_delta[]` carried state
2032 /// (in `{B_PRED, ZERO_MV, OTHER_MV, SPLIT_MV}` order). Cleared
2033 /// to `[0; 4]` on every key frame per RFC 6386 §9.4.
2034 pub fn carried_mode_deltas(&self) -> [i16; 4] {
2035 self.carried_mode_deltas
2036 }
2037
2038 /// Number of frames successfully encoded so far.
2039 pub fn frame_count(&self) -> u64 {
2040 self.frame_count
2041 }
2042
2043 /// Stream dimensions, locked at the first successful
2044 /// `encode_frame` call. `None` before then.
2045 pub fn dimensions(&self) -> Option<(u32, u32)> {
2046 self.dimensions
2047 }
2048
2049 /// Configured keyframe interval.
2050 pub fn keyframe_interval(&self) -> u64 {
2051 self.keyframe_interval
2052 }
2053
2054 /// 0-based frame index of the most recent key frame, or `None` if
2055 /// no frame has been encoded yet.
2056 pub fn last_keyframe_index(&self) -> Option<u64> {
2057 self.last_keyframe_index
2058 }
2059
2060 /// Borrow the current `LAST` reference slot. `None` before the
2061 /// first frame.
2062 pub fn last(&self) -> Option<&RefFrameSlot> {
2063 self.last.as_ref()
2064 }
2065
2066 /// Borrow the current `GOLDEN` reference slot. `None` before the
2067 /// first frame.
2068 pub fn golden(&self) -> Option<&RefFrameSlot> {
2069 self.golden.as_ref()
2070 }
2071
2072 /// Borrow the current `ALTREF` reference slot. `None` before the
2073 /// first frame.
2074 pub fn altref(&self) -> Option<&RefFrameSlot> {
2075 self.altref.as_ref()
2076 }
2077
2078 /// Borrow the [`KeyframeParams`] applied to every frame this
2079 /// stream emits.
2080 pub fn params(&self) -> &KeyframeParams {
2081 &self.params
2082 }
2083}
2084
2085/// Borrow a [`RefFrameSlot`] back into the [`KeyframePlanes`] shape
2086/// the P-frame encoder consumes as its `reference` argument.
2087///
2088/// The two structs hold the same fields (the §9 reference-frame buffer
2089/// is the same shape as a freshly-reconstructed key frame's planes);
2090/// this helper is just the field-by-field translation. We clone the
2091/// plane buffers because `encode_p_frame_zero_mv` takes
2092/// `&KeyframePlanes` and we don't want to leak the slot lifetime into
2093/// the encoder's call.
2094fn ref_slot_to_keyframe_planes(slot: &RefFrameSlot) -> KeyframePlanes {
2095 KeyframePlanes {
2096 y: slot.y.clone(),
2097 u: slot.u.clone(),
2098 v: slot.v.clone(),
2099 y_stride: slot.y_stride,
2100 uv_stride: slot.uv_stride,
2101 mb_cols: slot.mb_cols,
2102 mb_rows: slot.mb_rows,
2103 }
2104}
2105
2106// ───────────────────────── auto-altref (lagged) stream driver ─────────────────
2107
2108/// Configuration for [`Vp8AltrefStreamEncoder`].
2109#[derive(Debug, Clone, Copy)]
2110#[non_exhaustive]
2111pub struct AltrefStreamConfig {
2112 /// Per-frame encode parameters (§9.6 quantiser, §9.4 loop filter,
2113 /// §13 trellis strength, …) applied to every emitted frame.
2114 pub params: KeyframeParams,
2115 /// Key-frame cadence in *source* frames: frame 0 and every
2116 /// `keyframe_interval`-th source frame is coded as a key frame.
2117 /// `0` keys only the first frame.
2118 pub keyframe_interval: u64,
2119 /// Lookahead group size in source frames (≥ 1). Each full group is
2120 /// encoded together: one invisible ARNR altref anchor (built from
2121 /// the whole group, aligned to its last frame) followed by the
2122 /// group's visible frames. `1` degenerates to plain streaming (no
2123 /// anchors — a single-frame group has nothing to look ahead at).
2124 pub altref_window: usize,
2125 /// Temporal-filter dial for the anchor synthesis (see
2126 /// [`crate::arnr::ArnrConfig`]). `strength = 0` anchors on the raw
2127 /// last frame of each group.
2128 pub arnr: crate::arnr::ArnrConfig,
2129 /// §9.7 copy-ladder GOLDEN promotion. When `true` (the default),
2130 /// the **last** P-frame of every anchored group carries
2131 /// `copy_buffer_to_golden = 2` (ALTREF → GOLDEN — two header bits,
2132 /// no pixel data travels), so the next group's P-frames see a
2133 /// *bracketing* reference pair: GOLDEN holds the previous group's
2134 /// anchor while the fresh invisible update re-points ALTREF at the
2135 /// next one. `false` leaves GOLDEN pinned at the most recent key
2136 /// frame.
2137 pub golden_promotion: bool,
2138 /// Scene-cut detector threshold, in mean-absolute-luma-difference
2139 /// per pixel against the previously pushed frame (`0.0..=255.0`).
2140 /// When a pushed frame's MAD against its predecessor exceeds the
2141 /// threshold, the in-progress group is closed **before** the frame
2142 /// enters the buffer and the frame is coded as a key frame: an
2143 /// anchor must not blend across a cut (per-block SAD rejection
2144 /// already keeps foreign content out of the blend, but a
2145 /// cross-scene group would still waste an anchor and chain
2146 /// P-frames off dead references). `0.0` disables detection (the
2147 /// pure count-based grouping). Default `40.0` — far above photo
2148 /// noise / motion MAD, comfortably below a full scene change.
2149 pub scene_cut_mad_threshold: f64,
2150 /// §9.4 RD loop-filter auto-selection for **every** emitted frame
2151 /// (key frames, invisible anchors, and P-frames): when `true`,
2152 /// `params.loop_filter_level` / `sharpness_level` are ignored and
2153 /// each frame's level / sharpness pair is chosen to minimise the
2154 /// post-§15 visible-window SSD of the frame's own reconstruction
2155 /// against its source (see
2156 /// [`crate::encoder::KeyframeCodingOptions::auto_loop_filter`]).
2157 /// Default `false` (the fixed-level round-384 behaviour).
2158 pub auto_loop_filter: bool,
2159 /// §13.4 in-header `token_prob_update()` emission, fitted per frame
2160 /// to the observed §13.3 branch counts by the two-pass
2161 /// [`crate::encoder::fit_token_prob_updates`] fitter, on **every**
2162 /// emitted frame. The fitted pass only ships when it shrinks the
2163 /// wire (never-grow guard), at the cost of a second encode pass per
2164 /// frame. Default `false`.
2165 pub fitted_token_prob_updates: bool,
2166 /// §11 intra-within-inter picker on the visible P-frames: every MB
2167 /// additionally scores the 16 whole-block `(y_mode, uv_mode)` intra
2168 /// candidates against the best inter pick — insurance for occluded
2169 /// / uncovered content the reference set cannot predict. The
2170 /// invisible anchor always encodes with the picker on (it is the
2171 /// round-383 `encode_invisible_altref_update` behaviour); this knob
2172 /// extends it to the P-frames. Default `false`.
2173 pub intra_pick: bool,
2174 /// §9.3 / §10 segment-based adaptive quantisation on every **inter**
2175 /// frame the driver emits (invisible anchors and visible P-frames):
2176 /// per-MB variance classification, per-segment quantisers driving
2177 /// the RD walk, and the full `update_segmentation()` header block
2178 /// (see [`crate::encoder::InterSegmentationConfig`]). Key frames
2179 /// keep the frame-wide quantiser (the keyframe AQ path is a
2180 /// separate front door). Default `None`.
2181 pub segmentation: Option<crate::encoder::InterSegmentationConfig>,
2182 /// Mode-search effort of the stream's **key frames** (see
2183 /// [`EncodeEffort`](crate::encoder::EncodeEffort)). The inter frames
2184 /// follow [`inter_effort`](Self::inter_effort). Default `Thorough`
2185 /// (the historical key-frame bytes).
2186 pub effort: crate::encoder::EncodeEffort,
2187 /// Thread budget for each frame's macroblock-row wavefront, key and
2188 /// inter frames alike (`0` / `1` = serial, the default). Does not
2189 /// change the bytes.
2190 pub threads: usize,
2191 /// Mode-search effort of the stream's **inter frames** (the
2192 /// invisible anchors and the visible P-frames). Defaults to
2193 /// [`EncodeEffort::Balanced`](crate::encoder::EncodeEffort::Balanced).
2194 pub inter_effort: crate::encoder::EncodeEffort,
2195 /// One-pass rate control target in bits per second; `0` (the
2196 /// default) codes every frame at `params.y_ac_qi`. With a target the
2197 /// stream starts at `params.y_ac_qi` and then moves the quantiser
2198 /// frame by frame so that the stream's average rate approaches the
2199 /// target (see [`RateControl`]); no frame is ever dropped, so a
2200 /// target below what the coarsest quantiser produces is overshot.
2201 pub target_bitrate_bps: u32,
2202 /// Frames per second the rate target is spread over (default 30).
2203 pub frame_rate: f64,
2204}
2205
2206/// One-pass rate control for the lagged stream: a per-frame quantiser
2207/// from a bit budget, without lookahead statistics.
2208///
2209/// Every visible frame adds `bitrate / frame_rate` bits to a budget and
2210/// every packet (visible or not) spends from it. The next inter frame
2211/// aims at the per-frame share, less what the invisible alt-ref frames
2212/// have been costing per visible frame, less a fraction of the running
2213/// overspend — so a key frame is paid back over the following frames
2214/// instead of at once.
2215/// The quantiser step for that aim comes from the measured cost of the
2216/// previous inter frames: with `bits ∝ step^(−1.3)` across the range,
2217/// `X = bits · step^1.3` is tracked as a running average and the step
2218/// that meets a target `t` is `(X / t)^(1 / 1.3)`. Alt-ref frames are
2219/// coded at the current inter quantiser. A key frame gets a budget of
2220/// its own (a quarter of the payback window) and a quantiser from what
2221/// the previous key frame cost; before the first key frame a
2222/// lowest-effort trial encode stands in for that measurement.
2223///
2224/// The quantiser never moves more than a few indices per frame once the
2225/// stream is under way, so quality does not pump.
2226#[derive(Debug, Clone, Copy)]
2227struct RateControl {
2228 bits_per_frame: f64,
2229 /// Frames an overspend is paid back over.
2230 window: f64,
2231 /// Bits spent minus bits budgeted so far.
2232 overspend: f64,
2233 /// Running average of `bits · step^1.3` over inter frames.
2234 complexity: Option<f64>,
2235 /// `bits · step^1.1` of the last key frame (or of a trial encode
2236 /// before the first).
2237 key_complexity: Option<f64>,
2238 /// Running average of what an invisible alt-ref frame costs, spread
2239 /// over the visible frames of its group (bits per visible frame).
2240 hidden_share: f64,
2241 /// Visible frames per alt-ref frame.
2242 group: f64,
2243 /// Quantiser index of the next frame.
2244 qindex: u8,
2245 /// Visible inter frames coded so far.
2246 inter_frames: u32,
2247}
2248
2249impl RateControl {
2250 const RATE_EXPONENT: f64 = 1.3;
2251
2252 fn new(config: &AltrefStreamConfig) -> Option<Self> {
2253 // A missing, zero, negative or NaN frame rate leaves the stream
2254 // at a constant quantiser.
2255 if config.target_bitrate_bps == 0 || config.frame_rate.is_nan() || config.frame_rate <= 0.0
2256 {
2257 return None;
2258 }
2259 let window = match config.keyframe_interval {
2260 0 => 30.0,
2261 n => (2 * n).clamp(12, 60) as f64,
2262 };
2263 Some(RateControl {
2264 bits_per_frame: config.target_bitrate_bps as f64 / config.frame_rate,
2265 window,
2266 overspend: 0.0,
2267 complexity: None,
2268 key_complexity: None,
2269 hidden_share: 0.0,
2270 group: config.altref_window.max(1) as f64,
2271 qindex: config.params.y_ac_qi.min(127),
2272 inter_frames: 0,
2273 })
2274 }
2275
2276 fn step(qindex: u8) -> f64 {
2277 crate::inverse_transform::AC_QLOOKUP[qindex as usize] as f64
2278 }
2279
2280 /// The first quantiser index whose step is at least `step`.
2281 fn qindex_for_step(step: f64) -> u8 {
2282 crate::inverse_transform::AC_QLOOKUP
2283 .iter()
2284 .position(|&s| s as f64 >= step)
2285 .unwrap_or(127) as u8
2286 }
2287
2288 /// Key frames cost `∝ step^(−1.1)` across the range.
2289 const KEY_RATE_EXPONENT: f64 = 1.1;
2290
2291 /// Note what a key frame cost at `qindex`.
2292 fn measure_key(&mut self, qindex: u8, bytes: usize) {
2293 self.key_complexity =
2294 Some(bytes as f64 * 8.0 * Self::step(qindex).powf(Self::KEY_RATE_EXPONENT));
2295 }
2296
2297 /// The quantiser for a key frame: a quarter of the payback window's
2298 /// budget (between two and ten frames' worth), less what is already
2299 /// overspent — but never finer than the inter frames are running.
2300 fn key_qindex(&self) -> u8 {
2301 let Some(complexity) = self.key_complexity else {
2302 return self.qindex;
2303 };
2304 let frames = (self.window / 4.0).clamp(2.0, 10.0);
2305 let budget =
2306 (frames * self.bits_per_frame - self.overspend.max(0.0) / 2.0).max(self.bits_per_frame);
2307 let wanted =
2308 Self::qindex_for_step((complexity / budget).powf(1.0 / Self::KEY_RATE_EXPONENT));
2309 if self.complexity.is_some() {
2310 wanted.max(self.qindex.saturating_sub(8))
2311 } else {
2312 wanted
2313 }
2314 }
2315
2316 /// Account for one coded packet and choose the next quantiser.
2317 fn record(&mut self, kind: AltrefPacketKind, bytes: usize) {
2318 let bits = bytes as f64 * 8.0;
2319 let visible = kind != AltrefPacketKind::AltrefUpdate;
2320 self.overspend += bits - if visible { self.bits_per_frame } else { 0.0 };
2321 if kind == AltrefPacketKind::Key {
2322 self.measure_key(self.qindex, bytes);
2323 }
2324 if kind == AltrefPacketKind::Inter {
2325 let x = bits * Self::step(self.qindex).powf(Self::RATE_EXPONENT);
2326 self.complexity = Some(match self.complexity {
2327 Some(average) => 0.75 * average + 0.25 * x,
2328 None => x,
2329 });
2330 self.inter_frames += 1;
2331 }
2332 if !visible {
2333 let share = bits / self.group;
2334 self.hidden_share = if self.hidden_share == 0.0 {
2335 share
2336 } else {
2337 0.5 * self.hidden_share + 0.5 * share
2338 };
2339 }
2340 let Some(complexity) = self.complexity else {
2341 return;
2342 };
2343 let target = (self.bits_per_frame - self.hidden_share - self.overspend / self.window)
2344 .clamp(0.15 * self.bits_per_frame, 4.0 * self.bits_per_frame);
2345 let wanted_step = (complexity / target).powf(1.0 / Self::RATE_EXPONENT);
2346 let wanted = Self::qindex_for_step(wanted_step) as i32;
2347 // Free movement while the model settles, then a few indices per
2348 // frame.
2349 let reach = if self.inter_frames <= 2 { 127 } else { 6 };
2350 let current = self.qindex as i32;
2351 self.qindex = wanted.clamp(current - reach, current + reach).clamp(0, 127) as u8;
2352 }
2353}
2354
2355impl AltrefStreamConfig {
2356 /// Set `target_bitrate_bps`.
2357 #[must_use]
2358 pub fn with_target_bitrate_bps(mut self, v: u32) -> Self {
2359 self.target_bitrate_bps = v;
2360 self
2361 }
2362
2363 /// Set `frame_rate`.
2364 #[must_use]
2365 pub fn with_frame_rate(mut self, v: f64) -> Self {
2366 self.frame_rate = v;
2367 self
2368 }
2369
2370 /// Set `inter_effort`.
2371 #[must_use]
2372 pub fn with_inter_effort(mut self, v: crate::encoder::EncodeEffort) -> Self {
2373 self.inter_effort = v;
2374 self
2375 }
2376
2377 /// Set `effort`.
2378 #[must_use]
2379 pub fn with_effort(mut self, v: crate::encoder::EncodeEffort) -> Self {
2380 self.effort = v;
2381 self
2382 }
2383
2384 /// Set `threads`.
2385 #[must_use]
2386 pub fn with_threads(mut self, v: usize) -> Self {
2387 self.threads = v;
2388 self
2389 }
2390
2391 /// Set `params`.
2392 #[must_use]
2393 pub fn with_params(mut self, v: KeyframeParams) -> Self {
2394 self.params = v;
2395 self
2396 }
2397
2398 /// Set `keyframe_interval`.
2399 #[must_use]
2400 pub fn with_keyframe_interval(mut self, v: u64) -> Self {
2401 self.keyframe_interval = v;
2402 self
2403 }
2404
2405 /// Set `altref_window`.
2406 #[must_use]
2407 pub fn with_altref_window(mut self, v: usize) -> Self {
2408 self.altref_window = v;
2409 self
2410 }
2411
2412 /// Set `arnr`.
2413 #[must_use]
2414 pub fn with_arnr(mut self, v: crate::arnr::ArnrConfig) -> Self {
2415 self.arnr = v;
2416 self
2417 }
2418
2419 /// Set `golden_promotion`.
2420 #[must_use]
2421 pub fn with_golden_promotion(mut self, v: bool) -> Self {
2422 self.golden_promotion = v;
2423 self
2424 }
2425
2426 /// Set `scene_cut_mad_threshold`.
2427 #[must_use]
2428 pub fn with_scene_cut_mad_threshold(mut self, v: f64) -> Self {
2429 self.scene_cut_mad_threshold = v;
2430 self
2431 }
2432
2433 /// Set `auto_loop_filter`.
2434 #[must_use]
2435 pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
2436 self.auto_loop_filter = v;
2437 self
2438 }
2439
2440 /// Set `fitted_token_prob_updates`.
2441 #[must_use]
2442 pub fn with_fitted_token_prob_updates(mut self, v: bool) -> Self {
2443 self.fitted_token_prob_updates = v;
2444 self
2445 }
2446
2447 /// Set `intra_pick`.
2448 #[must_use]
2449 pub fn with_intra_pick(mut self, v: bool) -> Self {
2450 self.intra_pick = v;
2451 self
2452 }
2453
2454 /// Set `segmentation`.
2455 #[must_use]
2456 pub fn with_segmentation(mut self, v: Option<crate::encoder::InterSegmentationConfig>) -> Self {
2457 self.segmentation = v;
2458 self
2459 }
2460}
2461
2462impl Default for AltrefStreamConfig {
2463 /// Key the first frame only, 8-frame lookahead groups, default
2464 /// ARNR strength, GOLDEN promotion on, scene-cut keying at MAD 40.
2465 fn default() -> Self {
2466 AltrefStreamConfig {
2467 params: KeyframeParams::default(),
2468 keyframe_interval: 0,
2469 altref_window: 8,
2470 arnr: crate::arnr::ArnrConfig::default(),
2471 golden_promotion: true,
2472 scene_cut_mad_threshold: 40.0,
2473 auto_loop_filter: false,
2474 fitted_token_prob_updates: false,
2475 intra_pick: false,
2476 segmentation: None,
2477 effort: crate::encoder::EncodeEffort::Thorough,
2478 threads: 1,
2479 inter_effort: crate::encoder::EncodeEffort::Balanced,
2480 target_bitrate_bps: 0,
2481 frame_rate: 30.0,
2482 }
2483 }
2484}
2485
2486/// Classification of one packet emitted by [`Vp8AltrefStreamEncoder`].
2487#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2488#[non_exhaustive]
2489pub enum AltrefPacketKind {
2490 /// §9.1 key frame (visible; refreshes all three slots).
2491 Key,
2492 /// Invisible §9.7 altref-update frame (`show_frame = 0`,
2493 /// `refresh_alternate_frame = 1`, `refresh_last = 0`). Not part of
2494 /// the display sequence — a muxer stores it, a player never shows
2495 /// it.
2496 AltrefUpdate,
2497 /// Visible §16 multi-reference P-frame (`refresh_last = 1`).
2498 Inter,
2499}
2500
2501/// One packet emitted by [`Vp8AltrefStreamEncoder`]. The stream emits
2502/// **more packets than source frames** (one extra invisible anchor per
2503/// lookahead group); `source_index` ties visible packets back to their
2504/// source frame.
2505#[derive(Debug, Clone)]
2506#[non_exhaustive]
2507pub struct AltrefStreamPacket {
2508 /// Raw VP8 elementary-stream bytes (one packet = one frame; feed to
2509 /// [`crate::state::Vp8DecoderState::decode_frame`] in emission
2510 /// order).
2511 pub bytes: Vec<u8>,
2512 /// What the packet carries.
2513 pub kind: AltrefPacketKind,
2514 /// 0-based index of the source frame this packet displays, or
2515 /// `None` for an invisible anchor (which displays nothing).
2516 pub source_index: Option<u64>,
2517}
2518
2519impl AltrefStreamPacket {
2520 /// Build a `AltrefStreamPacket` from every field.
2521 pub fn new(bytes: Vec<u8>, kind: AltrefPacketKind, source_index: Option<u64>) -> Self {
2522 Self {
2523 bytes,
2524 kind,
2525 source_index,
2526 }
2527 }
2528
2529 /// Set `bytes`.
2530 #[must_use]
2531 pub fn with_bytes(mut self, v: Vec<u8>) -> Self {
2532 self.bytes = v;
2533 self
2534 }
2535
2536 /// Set `kind`.
2537 #[must_use]
2538 pub fn with_kind(mut self, v: AltrefPacketKind) -> Self {
2539 self.kind = v;
2540 self
2541 }
2542
2543 /// Set `source_index`.
2544 #[must_use]
2545 pub fn with_source_index(mut self, v: Option<u64>) -> Self {
2546 self.source_index = v;
2547 self
2548 }
2549}
2550
2551impl AltrefStreamPacket {
2552 /// Convenience: `true` iff a player should display this packet's
2553 /// decoded picture (mirrors the §9.1 `show_frame` bit on the wire).
2554 pub fn is_visible(&self) -> bool {
2555 self.source_index.is_some()
2556 }
2557}
2558
2559/// Owned tightly-packed copy of a source picture (the lookahead buffer
2560/// element).
2561#[derive(Debug, Clone)]
2562struct OwnedI420 {
2563 width: u32,
2564 height: u32,
2565 y: Vec<u8>,
2566 u: Vec<u8>,
2567 v: Vec<u8>,
2568}
2569
2570impl OwnedI420 {
2571 fn from_frame(frame: &I420Frame<'_>) -> Self {
2572 let w = frame.width as usize;
2573 let h = frame.height as usize;
2574 let cw = w.div_ceil(2);
2575 let ch = h.div_ceil(2);
2576 let mut y = Vec::with_capacity(w * h);
2577 for r in 0..h {
2578 y.extend_from_slice(&frame.y[r * frame.y_stride..r * frame.y_stride + w]);
2579 }
2580 let mut u = Vec::with_capacity(cw * ch);
2581 let mut v = Vec::with_capacity(cw * ch);
2582 for r in 0..ch {
2583 u.extend_from_slice(&frame.u[r * frame.uv_stride..r * frame.uv_stride + cw]);
2584 v.extend_from_slice(&frame.v[r * frame.uv_stride..r * frame.uv_stride + cw]);
2585 }
2586 OwnedI420 {
2587 width: frame.width,
2588 height: frame.height,
2589 y,
2590 u,
2591 v,
2592 }
2593 }
2594
2595 fn as_i420(&self) -> I420Frame<'_> {
2596 I420Frame::packed(self.width, self.height, &self.y, &self.u, &self.v)
2597 }
2598}
2599
2600/// Lagged multi-frame VP8 encoder with **automatic invisible-altref
2601/// management** — the B-frame-less GOLDEN / ALTREF pattern assembled
2602/// from this round's building blocks:
2603///
2604/// 1. Source frames buffer into lookahead groups of
2605/// [`AltrefStreamConfig::altref_window`] frames.
2606/// 2. When a group completes, [`crate::arnr::build_arnr_altref`]
2607/// synthesizes a noise-reduced anchor aligned to the group's **last**
2608/// frame, and [`crate::encoder::encode_invisible_altref_update`]
2609/// ships it as an invisible frame (§9.1 `show_frame = 0`, §9.7
2610/// `refresh_alternate_frame = 1` / `refresh_last = 0`).
2611/// 3. The group's frames then encode as visible multi-reference
2612/// P-frames whose per-MB §16.2 `ref_frame` selector can predict from
2613/// the anchor — forward prediction from a picture that is never
2614/// displayed.
2615///
2616/// Because the pipeline is lagged, [`Self::push_frame`] returns zero or
2617/// more packets per call and [`Self::finish`] drains the tail group.
2618/// Packets must reach the decoder in emission order; visible packets
2619/// map 1:1 onto source frames (`source_index`), invisible anchors carry
2620/// `source_index = None`.
2621///
2622/// The encoder mirrors the §9.7 / §9.8 slot ladder exactly as
2623/// [`crate::state::Vp8DecoderState`] applies it, so every packet
2624/// self-decodes in pixel lockstep (pinned by
2625/// `tests/encoder_altref_stream.rs`).
2626#[derive(Debug, Clone)]
2627pub struct Vp8AltrefStreamEncoder {
2628 config: AltrefStreamConfig,
2629 dimensions: Option<(u32, u32)>,
2630 /// Lookahead buffer — the group being accumulated.
2631 pending: Vec<OwnedI420>,
2632 /// Source index of `pending[0]`.
2633 pending_start: u64,
2634 /// `true` when `pending[0]` entered on a detected scene cut, so
2635 /// [`Self::flush_group`] must key it even off the scheduled
2636 /// cadence.
2637 pending_forced_key: bool,
2638 /// Copy of the most recently pushed source frame — the scene-cut
2639 /// detector's comparison baseline (spans group boundaries).
2640 last_pushed: Option<OwnedI420>,
2641 /// Total source frames pushed.
2642 input_count: u64,
2643 /// §9 reference slots (encoder-side mirror of the decoder's).
2644 last: Option<KeyframePlanes>,
2645 golden: Option<KeyframePlanes>,
2646 altref: Option<KeyframePlanes>,
2647 /// One-pass rate control state (`None` = constant quantiser).
2648 rate: Option<RateControl>,
2649}
2650
2651/// Mean absolute luma difference per pixel between the previous
2652/// (packed) frame and the incoming (possibly strided) one — the
2653/// scene-cut metric. Both frames are dimension-locked by the caller.
2654fn luma_mad(prev: &OwnedI420, frame: &I420Frame<'_>) -> f64 {
2655 let w = prev.width as usize;
2656 let h = prev.height as usize;
2657 let mut sad = 0u64;
2658 for r in 0..h {
2659 let a = &prev.y[r * w..r * w + w];
2660 let b = &frame.y[r * frame.y_stride..r * frame.y_stride + w];
2661 for (&x, &y) in a.iter().zip(b.iter()) {
2662 sad += u64::from(x.abs_diff(y));
2663 }
2664 }
2665 sad as f64 / (w * h) as f64
2666}
2667
2668impl Vp8AltrefStreamEncoder {
2669 /// Build a fresh lagged encoder. Returns `None` when
2670 /// `config.altref_window == 0` (a zero-frame lookahead group cannot
2671 /// make progress).
2672 pub fn new(config: AltrefStreamConfig) -> Option<Self> {
2673 if config.altref_window == 0 {
2674 return None;
2675 }
2676 Some(Vp8AltrefStreamEncoder {
2677 rate: RateControl::new(&config),
2678 config,
2679 dimensions: None,
2680 pending: Vec::new(),
2681 pending_start: 0,
2682 pending_forced_key: false,
2683 last_pushed: None,
2684 input_count: 0,
2685 last: None,
2686 golden: None,
2687 altref: None,
2688 })
2689 }
2690
2691 /// Change the thread budget of a running stream (the bytes do not
2692 /// depend on it).
2693 #[cfg_attr(not(feature = "registry"), allow(dead_code))]
2694 pub(crate) fn set_threads(&mut self, threads: usize) {
2695 self.config.threads = threads;
2696 }
2697
2698 /// The configuration this stream was built with.
2699 pub fn config(&self) -> &AltrefStreamConfig {
2700 &self.config
2701 }
2702
2703 /// The §9.6 quantiser index the next frame will be coded at: the
2704 /// configured `params.y_ac_qi`, or the rate control's current choice.
2705 pub fn next_qindex(&self) -> u8 {
2706 self.rate
2707 .map_or(self.config.params.y_ac_qi, |rate| rate.qindex)
2708 }
2709
2710 /// The frame parameters for the next packet (the configured ones at
2711 /// the rate control's quantiser).
2712 fn frame_params(&self) -> KeyframeParams {
2713 let mut params = self.config.params;
2714 params.y_ac_qi = self.next_qindex();
2715 params
2716 }
2717
2718 /// Tell the rate control what a packet cost.
2719 fn spent(&mut self, kind: AltrefPacketKind, bytes: usize) {
2720 if let Some(rate) = &mut self.rate {
2721 rate.record(kind, bytes);
2722 }
2723 }
2724
2725 /// Total source frames pushed so far (buffered + encoded).
2726 pub fn input_count(&self) -> u64 {
2727 self.input_count
2728 }
2729
2730 /// Source frames currently buffered awaiting their group to
2731 /// complete (the current lag, `0..altref_window`).
2732 pub fn buffered(&self) -> usize {
2733 self.pending.len()
2734 }
2735
2736 /// Whether source frame `index` is scheduled as a key frame.
2737 fn is_key_index(&self, index: u64) -> bool {
2738 index == 0
2739 || (self.config.keyframe_interval > 0
2740 && index.is_multiple_of(self.config.keyframe_interval))
2741 }
2742
2743 /// Feed one source frame; returns every packet the stream can emit
2744 /// so far (empty while the lookahead group is still filling).
2745 ///
2746 /// Dimensions are locked at the first frame
2747 /// ([`StreamEncodeError::DimensionsChanged`] otherwise). A frame
2748 /// scheduled as a key frame closes the in-progress group early so
2749 /// the key frame starts a fresh group.
2750 pub fn push_frame(
2751 &mut self,
2752 frame: &I420Frame<'_>,
2753 ) -> Result<Vec<AltrefStreamPacket>, StreamEncodeError> {
2754 let dims = (frame.width, frame.height);
2755 match self.dimensions {
2756 Some(locked) if locked != dims => {
2757 return Err(StreamEncodeError::DimensionsChanged {
2758 first: locked,
2759 got: dims,
2760 });
2761 }
2762 None => self.dimensions = Some(dims),
2763 _ => {}
2764 }
2765 let mut out = Vec::new();
2766 // Scene-cut detection: a frame whose luma MAD against its
2767 // predecessor exceeds the configured threshold starts new
2768 // content — close the running group *before* it (an anchor
2769 // must not blend across the cut) and key it.
2770 let scene_cut = self.config.scene_cut_mad_threshold > 0.0
2771 && self
2772 .last_pushed
2773 .as_ref()
2774 .is_some_and(|prev| luma_mad(prev, frame) > self.config.scene_cut_mad_threshold);
2775 // A scheduled key frame closes the previous group early too:
2776 // the anchor of a group must not look across a key frame (the
2777 // key frame resets all three slots anyway).
2778 if (scene_cut || self.is_key_index(self.input_count)) && !self.pending.is_empty() {
2779 self.flush_group(&mut out)?;
2780 }
2781 if self.pending.is_empty() {
2782 self.pending_start = self.input_count;
2783 self.pending_forced_key = scene_cut;
2784 }
2785 self.pending.push(OwnedI420::from_frame(frame));
2786 self.last_pushed = Some(self.pending.last().expect("just pushed").clone());
2787 self.input_count += 1;
2788 if self.pending.len() >= self.config.altref_window {
2789 self.flush_group(&mut out)?;
2790 }
2791 Ok(out)
2792 }
2793
2794 /// Drain the in-progress lookahead group (call once after the final
2795 /// `push_frame`). Idempotent — a drained stream returns no packets.
2796 pub fn finish(&mut self) -> Result<Vec<AltrefStreamPacket>, StreamEncodeError> {
2797 let mut out = Vec::new();
2798 if !self.pending.is_empty() {
2799 self.flush_group(&mut out)?;
2800 }
2801 Ok(out)
2802 }
2803
2804 /// Encode one completed lookahead group:
2805 /// `[K?] [invisible anchor] [P …]`.
2806 fn flush_group(&mut self, out: &mut Vec<AltrefStreamPacket>) -> Result<(), StreamEncodeError> {
2807 let group = core::mem::take(&mut self.pending);
2808 let start = self.pending_start;
2809 let forced_key = core::mem::take(&mut self.pending_forced_key);
2810 let mut first_p = 0usize;
2811
2812 // Per-frame feature toggles from the stream config. All-false
2813 // reproduces the round-384 wire byte-for-byte (the coding-
2814 // options front doors are pinned byte-identical to the
2815 // dedicated entries this driver previously called).
2816 let kf_options = crate::encoder::KeyframeCodingOptions {
2817 auto_loop_filter: self.config.auto_loop_filter,
2818 fitted_token_prob_updates: self.config.fitted_token_prob_updates,
2819 };
2820 // The invisible anchor keeps the §11 intra picker hardwired on
2821 // (the encode_invisible_altref_update behaviour).
2822 let anchor_options = crate::encoder::InterCodingOptions {
2823 intra_pick: true,
2824 auto_loop_filter: self.config.auto_loop_filter,
2825 fitted_token_prob_updates: self.config.fitted_token_prob_updates,
2826 effort: Some(self.config.inter_effort),
2827 threads: self.config.threads,
2828 search_token_probs: None,
2829 };
2830 let p_options = crate::encoder::InterCodingOptions {
2831 intra_pick: self.config.intra_pick,
2832 auto_loop_filter: self.config.auto_loop_filter,
2833 fitted_token_prob_updates: self.config.fitted_token_prob_updates,
2834 effort: Some(self.config.inter_effort),
2835 threads: self.config.threads,
2836 search_token_probs: None,
2837 };
2838
2839 // Key frame: scheduled, scene-cut-forced, or forced because
2840 // the stream has no reference yet.
2841 if self.is_key_index(start) || forced_key || self.last.is_none() {
2842 let mut key_params = self.frame_params();
2843 if let Some(rate) = &mut self.rate {
2844 // The key frame's quantiser comes from its own bit
2845 // budget. The first one has nothing to go by, so a quick
2846 // lowest-effort encode measures what the picture costs.
2847 if rate.key_complexity.is_none() {
2848 let trial = crate::encoder::encode_keyframe_with_options(
2849 &group[0].as_i420(),
2850 &key_params,
2851 &crate::encoder::KeyframeEncodeOptions::exhaustive()
2852 .with_effort(crate::encoder::EncodeEffort::Fastest)
2853 .with_threads(self.config.threads),
2854 )?;
2855 rate.measure_key(key_params.y_ac_qi, trial.len());
2856 }
2857 key_params.y_ac_qi = rate.key_qindex();
2858 rate.qindex = key_params.y_ac_qi;
2859 }
2860 let (bytes, recon) = crate::encoder::encode_keyframe_with_reconstruction_and_options(
2861 &group[0].as_i420(),
2862 &key_params,
2863 &crate::encoder::KeyframeEncodeOptions::exhaustive()
2864 .with_effort(self.config.effort)
2865 .with_threads(self.config.threads)
2866 .with_auto_loop_filter(kf_options.auto_loop_filter)
2867 .with_fitted_token_prob_updates(kf_options.fitted_token_prob_updates),
2868 )?;
2869 self.last = Some(recon.clone());
2870 self.golden = Some(recon.clone());
2871 self.altref = Some(recon);
2872 self.spent(AltrefPacketKind::Key, bytes.len());
2873 out.push(AltrefStreamPacket {
2874 bytes,
2875 kind: AltrefPacketKind::Key,
2876 source_index: Some(start),
2877 });
2878 first_p = 1;
2879 }
2880
2881 let p_count = group.len() - first_p;
2882
2883 // Invisible anchor: only worth shipping when the group has ≥ 2
2884 // frames of lookahead context and at least one P-frame to use
2885 // it (a single-frame group's anchor would just duplicate that
2886 // frame's own encode).
2887 let mut anchored = false;
2888 if p_count > 0 && group.len() >= 2 {
2889 let views: Vec<I420Frame<'_>> = group.iter().map(|f| f.as_i420()).collect();
2890 let anchor = crate::arnr::build_arnr_altref_threaded(
2891 &views,
2892 views.len() - 1,
2893 &self.config.arnr,
2894 self.config.threads,
2895 )
2896 .map_err(StreamEncodeError::Frame)?;
2897 let last_planes = self.last.as_ref().expect("keyframe path ran");
2898 let (bytes, alt_recon) = crate::encoder::encode_invisible_altref_update_full(
2899 &anchor.as_i420(),
2900 last_planes,
2901 self.golden.as_ref(),
2902 self.altref.as_ref(),
2903 &self.frame_params(),
2904 &anchor_options,
2905 self.config.segmentation.as_ref(),
2906 )?;
2907 self.altref = Some(alt_recon);
2908 anchored = true;
2909 self.spent(AltrefPacketKind::AltrefUpdate, bytes.len());
2910 out.push(AltrefStreamPacket {
2911 bytes,
2912 kind: AltrefPacketKind::AltrefUpdate,
2913 source_index: None,
2914 });
2915 }
2916
2917 // Visible P-frames — §9.7 `refresh_last = 1` ladder, per-MB
2918 // LAST / GOLDEN / ALTREF selection. With `golden_promotion` on,
2919 // the group's last P-frame additionally carries
2920 // `copy_buffer_to_golden = 2`: per the §20 page-147 walk the
2921 // copy is applied *before* `refresh_last` and reads the
2922 // pre-refresh ALTREF (this group's anchor), so GOLDEN enters
2923 // the next group holding the anchor at a cost of two header
2924 // bits.
2925 for (j, frame) in group.iter().enumerate().skip(first_p) {
2926 let promote = self.config.golden_promotion && anchored && j == group.len() - 1;
2927 let refresh = RefreshControls {
2928 copy_buffer_to_golden: if promote { 2 } else { 0 },
2929 ..RefreshControls::default()
2930 };
2931 let last_planes = self.last.as_ref().expect("keyframe path ran");
2932 let (bytes, recon) = crate::encoder::encode_p_frame_options_and_segmentation(
2933 &frame.as_i420(),
2934 last_planes,
2935 self.golden.as_ref(),
2936 self.altref.as_ref(),
2937 &self.frame_params(),
2938 &refresh,
2939 &p_options,
2940 self.config.segmentation.as_ref(),
2941 )?;
2942 self.spent(AltrefPacketKind::Inter, bytes.len());
2943 // Encoder-side slot mirror of the §20 page-147 walk:
2944 // copy_gf (ALTREF → GOLDEN, pre-refresh state) precedes
2945 // refresh_last.
2946 if promote {
2947 self.golden = self.altref.clone();
2948 }
2949 self.last = Some(recon);
2950 out.push(AltrefStreamPacket {
2951 bytes,
2952 kind: AltrefPacketKind::Inter,
2953 source_index: Some(start + j as u64),
2954 });
2955 }
2956 Ok(())
2957 }
2958}
2959
2960// ─────────────────────────────────── tests ────────────────────────────────────
2961
2962#[cfg(test)]
2963mod tests {
2964 use super::*;
2965 use crate::state::Vp8DecoderState;
2966
2967 fn flat_frame(width: u32, height: u32, y: u8, u: u8, v: u8) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2968 let w = width as usize;
2969 let h = height as usize;
2970 let cw = width.div_ceil(2) as usize;
2971 let ch = height.div_ceil(2) as usize;
2972 (vec![y; w * h], vec![u; cw * ch], vec![v; cw * ch])
2973 }
2974
2975 #[test]
2976 fn fresh_stream_state() {
2977 let enc = Vp8KeyframeStreamEncoder::new(KeyframeParams::default());
2978 assert_eq!(enc.frame_count(), 0);
2979 assert!(enc.dimensions().is_none());
2980 assert!(enc.last().is_none());
2981 assert!(enc.golden().is_none());
2982 assert!(enc.altref().is_none());
2983 }
2984
2985 #[test]
2986 fn first_frame_locks_dimensions_and_populates_all_slots() {
2987 let mut enc = Vp8KeyframeStreamEncoder::new(KeyframeParams::default());
2988 let (y, u, v) = flat_frame(32, 32, 128, 128, 128);
2989 let frame = I420Frame::packed(32, 32, &y, &u, &v);
2990 let bytes = enc.encode_frame(&frame).expect("encode first frame");
2991 assert!(!bytes.is_empty(), "frame bytes non-empty");
2992 assert_eq!(enc.frame_count(), 1);
2993 assert_eq!(enc.dimensions(), Some((32, 32)));
2994 assert!(enc.last().is_some());
2995 assert!(enc.golden().is_some());
2996 assert!(enc.altref().is_some());
2997 // §9.7 / §9.8: a keyframe refreshes all three slots with the
2998 // same reconstruction.
2999 let last = enc.last().unwrap();
3000 let golden = enc.golden().unwrap();
3001 let altref = enc.altref().unwrap();
3002 assert_eq!(last.y, golden.y);
3003 assert_eq!(last.y, altref.y);
3004 assert_eq!(last.u, golden.u);
3005 assert_eq!(last.v, altref.v);
3006 }
3007
3008 #[test]
3009 fn dimensions_change_rejected() {
3010 let mut enc = Vp8KeyframeStreamEncoder::new(KeyframeParams::default());
3011 let (y, u, v) = flat_frame(32, 32, 128, 128, 128);
3012 let frame = I420Frame::packed(32, 32, &y, &u, &v);
3013 enc.encode_frame(&frame).expect("first frame");
3014 let (y2, u2, v2) = flat_frame(48, 48, 64, 200, 50);
3015 let frame2 = I420Frame::packed(48, 48, &y2, &u2, &v2);
3016 let err = enc
3017 .encode_frame(&frame2)
3018 .expect_err("differently-sized second frame");
3019 assert!(matches!(
3020 err,
3021 StreamEncodeError::DimensionsChanged {
3022 first: (32, 32),
3023 got: (48, 48)
3024 }
3025 ));
3026 // Failure must not advance the frame counter.
3027 assert_eq!(enc.frame_count(), 1);
3028 }
3029
3030 #[test]
3031 fn three_frame_stream_decodes_through_state_driver() {
3032 // Drive 3 trivial flat frames through the encoder, then replay
3033 // the bytes through `Vp8DecoderState::decode_frame` and
3034 // confirm each frame round-trips.
3035 let mut enc = Vp8KeyframeStreamEncoder::new(KeyframeParams::default());
3036 let pixels = [
3037 (100u8, 110u8, 120u8),
3038 (50u8, 200u8, 30u8),
3039 (180u8, 80u8, 200u8),
3040 ];
3041 let mut frames_bytes = Vec::new();
3042 for (y, u, v) in &pixels {
3043 let (yp, up, vp) = flat_frame(32, 32, *y, *u, *v);
3044 let frame = I420Frame::packed(32, 32, &yp, &up, &vp);
3045 frames_bytes.push(enc.encode_frame(&frame).expect("encode"));
3046 }
3047 assert_eq!(enc.frame_count(), 3);
3048
3049 let mut dec = Vp8DecoderState::new();
3050 for bytes in &frames_bytes {
3051 let out = dec.decode_frame(bytes).expect("decode");
3052 assert_eq!(out.width, 32);
3053 assert_eq!(out.height, 32);
3054 }
3055 }
3056
3057 #[test]
3058 fn inter_stream_rejects_zero_keyframe_interval() {
3059 assert!(Vp8InterStreamEncoder::new(KeyframeParams::default(), 0).is_none());
3060 }
3061
3062 #[test]
3063 fn inter_stream_first_frame_is_always_key() {
3064 let mut enc =
3065 Vp8InterStreamEncoder::new(KeyframeParams::default(), 4).expect("non-zero interval");
3066 assert_eq!(enc.next_frame_is_keyframe(), FrameKind::Key);
3067
3068 let (y, u, v) = flat_frame(32, 32, 128, 128, 128);
3069 let frame = I420Frame::packed(32, 32, &y, &u, &v);
3070 let out = enc.encode_frame(&frame).expect("encode first frame");
3071 assert!(out.is_keyframe(), "first frame must be a key frame");
3072 assert_eq!(out.frame_index, 0);
3073 // §9.1 bit 0 of byte 0 = frame_type; key frame ⇒ 0.
3074 assert_eq!(out.bytes[0] & 0x01, 0, "key frame frame_type bit");
3075 // §9.1 keyframe start code at bytes 3..6.
3076 assert_eq!(
3077 &out.bytes[3..6],
3078 &[0x9d, 0x01, 0x2a],
3079 "key frame start code"
3080 );
3081 assert_eq!(enc.last_keyframe_index(), Some(0));
3082 }
3083
3084 #[test]
3085 fn inter_stream_picks_p_after_first_with_interval_4() {
3086 let mut enc =
3087 Vp8InterStreamEncoder::new(KeyframeParams::default(), 4).expect("non-zero interval");
3088 let (y, u, v) = flat_frame(32, 32, 64, 128, 192);
3089 let frame = I420Frame::packed(32, 32, &y, &u, &v);
3090
3091 // Frame 0 — K
3092 let f0 = enc.encode_frame(&frame).expect("frame 0");
3093 assert_eq!(f0.kind, FrameKind::Key);
3094 // Frame 1, 2, 3 — P
3095 for i in 1..=3u64 {
3096 assert_eq!(
3097 enc.next_frame_is_keyframe(),
3098 FrameKind::InterZeroMv,
3099 "frame {i} should be P"
3100 );
3101 let f = enc.encode_frame(&frame).expect("p frame");
3102 assert_eq!(f.kind, FrameKind::InterZeroMv, "frame {i}");
3103 assert_eq!(f.frame_index, i);
3104 // §9.1 bit 0 of byte 0 = 1 for inter.
3105 assert_eq!(f.bytes[0] & 0x01, 0x01, "P-frame frame_type bit");
3106 }
3107 // Frame 4 — K again.
3108 assert_eq!(enc.next_frame_is_keyframe(), FrameKind::Key);
3109 let f4 = enc.encode_frame(&frame).expect("frame 4");
3110 assert!(f4.is_keyframe(), "frame 4 must be K at interval 4");
3111 assert_eq!(enc.last_keyframe_index(), Some(4));
3112 }
3113
3114 #[test]
3115 fn inter_stream_force_keyframe_reanchors_interval() {
3116 let mut enc =
3117 Vp8InterStreamEncoder::new(KeyframeParams::default(), 4).expect("non-zero interval");
3118 let (y, u, v) = flat_frame(32, 32, 100, 110, 120);
3119 let frame = I420Frame::packed(32, 32, &y, &u, &v);
3120
3121 // K, P, P-forced-K, P, P, P, K (re-anchored at frame 2)
3122 let kinds = [
3123 (false, FrameKind::Key), // 0 — first-ever
3124 (false, FrameKind::InterZeroMv), // 1
3125 (true, FrameKind::Key), // 2 — forced
3126 (false, FrameKind::InterZeroMv), // 3
3127 (false, FrameKind::InterZeroMv), // 4 (would be K w/o re-anchor)
3128 (false, FrameKind::InterZeroMv), // 5
3129 (false, FrameKind::Key), // 6 — re-anchored interval
3130 ];
3131 for (i, (force, expected)) in kinds.iter().enumerate() {
3132 let out = enc
3133 .encode_frame_with_force(&frame, *force)
3134 .unwrap_or_else(|e| panic!("frame {i}: {e}"));
3135 assert_eq!(out.kind, *expected, "frame {i} kind mismatch");
3136 }
3137 assert_eq!(enc.last_keyframe_index(), Some(6));
3138 }
3139
3140 #[test]
3141 fn inter_stream_p_frame_refreshes_last_only() {
3142 let mut enc =
3143 Vp8InterStreamEncoder::new(KeyframeParams::default(), 100).expect("non-zero interval");
3144 let (y0, u0, v0) = flat_frame(32, 32, 60, 130, 200);
3145 let frame0 = I420Frame::packed(32, 32, &y0, &u0, &v0);
3146 enc.encode_frame(&frame0).expect("frame 0 K");
3147 let golden_after_k = enc.golden().expect("golden after K").clone();
3148 let altref_after_k = enc.altref().expect("altref after K").clone();
3149
3150 // Big content change so the P-frame residual genuinely reshapes
3151 // LAST.
3152 let (y1, u1, v1) = flat_frame(32, 32, 200, 50, 90);
3153 let frame1 = I420Frame::packed(32, 32, &y1, &u1, &v1);
3154 enc.encode_frame(&frame1).expect("frame 1 P");
3155
3156 // GOLDEN and ALTREF must be byte-identical to their state
3157 // after the K (the P-frame's §9.7 ladder leaves them alone).
3158 assert_eq!(enc.golden().expect("golden present").y, golden_after_k.y);
3159 assert_eq!(enc.golden().expect("golden present").u, golden_after_k.u);
3160 assert_eq!(enc.golden().expect("golden present").v, golden_after_k.v);
3161 assert_eq!(enc.altref().expect("altref present").y, altref_after_k.y);
3162 assert_eq!(enc.altref().expect("altref present").u, altref_after_k.u);
3163 assert_eq!(enc.altref().expect("altref present").v, altref_after_k.v);
3164
3165 // LAST should now reflect the P-frame's reconstruction, which
3166 // for this big content change is no longer equal to the K's
3167 // reconstruction (= golden's contents).
3168 let last_after_p = enc.last().expect("last after P");
3169 assert_ne!(
3170 last_after_p.y, golden_after_k.y,
3171 "LAST must change after a P-frame, GOLDEN must not"
3172 );
3173 }
3174
3175 #[test]
3176 fn golden_interval_zero_is_default_and_disables_auto_refresh() {
3177 let enc =
3178 Vp8InterStreamEncoder::new(KeyframeParams::default(), 100).expect("non-zero interval");
3179 assert_eq!(enc.golden_interval(), 0, "default cadence is disabled");
3180 assert!(
3181 !enc.next_p_frame_refreshes_golden(),
3182 "first frame is a key frame, never an auto golden refresh"
3183 );
3184 }
3185
3186 #[test]
3187 fn auto_golden_refresh_updates_golden_on_scheduled_p_frame() {
3188 // keyframe_interval large so frames 1.. are all P; golden every
3189 // 2nd P-frame after the key frame.
3190 let mut enc = Vp8InterStreamEncoder::new(KeyframeParams::default(), 100)
3191 .expect("non-zero interval")
3192 .with_golden_interval(2);
3193 assert_eq!(enc.golden_interval(), 2);
3194
3195 // Frame 0: key — refreshes every slot, resets the cadence.
3196 let (y0, u0, v0) = flat_frame(32, 32, 60, 130, 200);
3197 let f0 = I420Frame::packed(32, 32, &y0, &u0, &v0);
3198 assert!(!enc.next_p_frame_refreshes_golden(), "next is a key frame");
3199 enc.encode_frame(&f0).expect("frame 0 K");
3200 let golden_after_k = enc.golden().expect("golden after K").y.clone();
3201
3202 // Frame 1: 1st P after K (1 % 2 != 0) — golden NOT refreshed.
3203 assert!(
3204 !enc.next_p_frame_refreshes_golden(),
3205 "1st P-frame is not a golden boundary"
3206 );
3207 let (y1, u1, v1) = flat_frame(32, 32, 200, 50, 90);
3208 let f1 = I420Frame::packed(32, 32, &y1, &u1, &v1);
3209 enc.encode_frame(&f1).expect("frame 1 P");
3210 assert_eq!(
3211 enc.golden().expect("golden present").y,
3212 golden_after_k,
3213 "GOLDEN must stay frozen on the 1st P-frame"
3214 );
3215
3216 // Frame 2: 2nd P after K (2 % 2 == 0) — golden refreshed to this
3217 // frame's reconstruction.
3218 assert!(
3219 enc.next_p_frame_refreshes_golden(),
3220 "2nd P-frame is a golden boundary"
3221 );
3222 let (y2, u2, v2) = flat_frame(32, 32, 30, 220, 40);
3223 let f2 = I420Frame::packed(32, 32, &y2, &u2, &v2);
3224 enc.encode_frame(&f2).expect("frame 2 P");
3225 let golden_after_p2 = enc.golden().expect("golden present").y.clone();
3226 assert_ne!(
3227 golden_after_p2, golden_after_k,
3228 "GOLDEN must change on the 2nd P-frame (auto refresh)"
3229 );
3230 // GOLDEN now equals LAST: both took this frame's reconstruction.
3231 assert_eq!(
3232 golden_after_p2,
3233 enc.last().expect("last present").y,
3234 "scheduled golden refresh writes the same reconstruction as LAST"
3235 );
3236 }
3237
3238 #[test]
3239 fn auto_golden_refresh_cadence_resets_on_keyframe() {
3240 // interval 3 keyframes, golden every 2nd P-frame. The forced
3241 // key frame mid-stream must restart the P-frame counter so the
3242 // golden boundary re-anchors to the new key frame.
3243 let mut enc = Vp8InterStreamEncoder::new(KeyframeParams::default(), 100)
3244 .expect("non-zero interval")
3245 .with_golden_interval(2);
3246 let (y, u, v) = flat_frame(32, 32, 128, 128, 128);
3247 let f = I420Frame::packed(32, 32, &y, &u, &v);
3248
3249 // Key frame, then one P-frame (P#1 — not a golden boundary).
3250 enc.encode_frame(&f).expect("f0 K");
3251 enc.encode_frame(&f).expect("f1 P");
3252 // Force a key frame; cadence resets.
3253 enc.encode_frame_with_force(&f, true).expect("f2 forced K");
3254 // Now P#1 after the new key frame — must NOT be a golden boundary.
3255 assert!(
3256 !enc.next_p_frame_refreshes_golden(),
3257 "cadence must re-anchor after a key frame"
3258 );
3259 enc.encode_frame(&f).expect("f3 P#1"); // no golden
3260 assert!(
3261 enc.next_p_frame_refreshes_golden(),
3262 "P#2 after the re-anchored key frame is a golden boundary"
3263 );
3264 }
3265
3266 #[test]
3267 fn auto_golden_refresh_stream_decodes_through_state_driver() {
3268 // The encoder writes refresh_golden_frame = 1 on scheduled
3269 // P-frames; the decoder must read it back and keep its own GOLDEN
3270 // slot in lockstep. A 1K + 4P stream with golden every 2nd P
3271 // exercises one scheduled refresh; all frames must decode.
3272 let mut enc = Vp8InterStreamEncoder::new(KeyframeParams::default(), 100)
3273 .expect("non-zero interval")
3274 .with_golden_interval(2);
3275 let mut dec = Vp8DecoderState::new();
3276 for i in 0..5u8 {
3277 let (yp, up, vp) = flat_frame(32, 32, 40 + i * 30, 120, 110 + i * 20);
3278 let frame = I420Frame::packed(32, 32, &yp, &up, &vp);
3279 let out = enc.encode_frame(&frame).expect("encode");
3280 let decoded = dec.decode_frame(&out.bytes).expect("decode");
3281 assert_eq!(decoded.width, 32);
3282 assert_eq!(decoded.height, 32);
3283 }
3284 }
3285
3286 #[test]
3287 fn auto_golden_refresh_disabled_matches_plain_auto_path_byte_for_byte() {
3288 // golden_interval = 0 must reproduce the historical
3289 // refresh_last-only auto path exactly. Encode the same stream
3290 // with the default encoder and confirm every emitted frame is
3291 // byte-identical.
3292 let mut plain =
3293 Vp8InterStreamEncoder::new(KeyframeParams::default(), 100).expect("interval");
3294 let mut also_disabled = Vp8InterStreamEncoder::new(KeyframeParams::default(), 100)
3295 .expect("interval")
3296 .with_golden_interval(0);
3297 for i in 0..4u8 {
3298 let (yp, up, vp) = flat_frame(32, 32, 50 + i * 25, 130, 90 + i * 15);
3299 let frame = I420Frame::packed(32, 32, &yp, &up, &vp);
3300 let a = plain.encode_frame(&frame).expect("plain");
3301 let b = also_disabled.encode_frame(&frame).expect("disabled");
3302 assert_eq!(a.bytes, b.bytes, "golden_interval=0 must be byte-identical");
3303 }
3304 }
3305
3306 #[test]
3307 fn inter_stream_dimensions_change_rejected() {
3308 let mut enc =
3309 Vp8InterStreamEncoder::new(KeyframeParams::default(), 4).expect("non-zero interval");
3310 let (y, u, v) = flat_frame(32, 32, 128, 128, 128);
3311 let frame = I420Frame::packed(32, 32, &y, &u, &v);
3312 enc.encode_frame(&frame).expect("first");
3313 let (y2, u2, v2) = flat_frame(48, 48, 64, 200, 50);
3314 let frame2 = I420Frame::packed(48, 48, &y2, &u2, &v2);
3315 let err = enc
3316 .encode_frame(&frame2)
3317 .expect_err("resize should be rejected");
3318 assert!(matches!(
3319 err,
3320 StreamEncodeError::DimensionsChanged {
3321 first: (32, 32),
3322 got: (48, 48),
3323 }
3324 ));
3325 assert_eq!(enc.frame_count(), 1);
3326 }
3327
3328 #[test]
3329 fn slot_state_replaced_each_frame() {
3330 // Each frame should overwrite the previous slot contents
3331 // (not append, not preserve). Encode two distinctly-colored
3332 // flat frames and confirm the slots reflect the *second*
3333 // frame's reconstruction.
3334 let mut enc = Vp8KeyframeStreamEncoder::new(KeyframeParams::default());
3335 let (y1, u1, v1) = flat_frame(16, 16, 50, 50, 50);
3336 let frame1 = I420Frame::packed(16, 16, &y1, &u1, &v1);
3337 enc.encode_frame(&frame1).expect("frame 1");
3338 let after_first = enc.last().unwrap().y.clone();
3339
3340 let (y2, u2, v2) = flat_frame(16, 16, 200, 200, 200);
3341 let frame2 = I420Frame::packed(16, 16, &y2, &u2, &v2);
3342 enc.encode_frame(&frame2).expect("frame 2");
3343 let after_second = enc.last().unwrap().y.clone();
3344
3345 assert_ne!(
3346 after_first, after_second,
3347 "slot must reflect the second frame, not the first"
3348 );
3349 }
3350}