Skip to main content

rusty_h264_encoder/
lib.rs

1//! Pure-Rust H.264 encoder — raw I420 frames in, a conformant Annex-B stream out.
2//!
3//! Every frame it emits decodes **bit-exactly under ffmpeg across QP 0–51**,
4//! intra and inter. The crate is `#![forbid(unsafe_code)]`; the optional SIMD
5//! kernels behind the `asm` feature keep their `unsafe` quarantined in
6//! `rusty_h264-accel`, so that guarantee holds either way.
7//!
8//! Coding tools, default-on: `I_16x16`/`I_4x4`/`I_PCM` intra with λ-based
9//! RD/SATD mode decision; P-frames (`P_Skip`, 16×16/16×8/8×16) with quarter-pel
10//! motion compensation, rate-aware ME and a multi-reference DPB; **CABAC**
11//! entropy coding (Main profile — set `RUSTY_H264_LEGACY_CAVLC=1` to restore
12//! the Constrained Baseline + CAVLC bitstream byte-for-byte); **adaptive
13//! quantization**; the per-GOP I-frame QP cascade; in-loop deblocking; and
14//! average-bitrate rate control. Opt-in via [`EncoderConfig`]: B-frames (fixed
15//! or content-adaptive), the 8×8 transform, mb-tree temporal AQ, sub-8×8
16//! partitions and RD `P_Skip`.
17//!
18//! [`Preset`] picks the speed/quality trade-off — `Fast` (SAD, integer-pel),
19//! `Balanced` (adds sub-pel refinement; the default) or `Quality` (full RD
20//! trial-encode). The bitstream is valid either way; only the effort differs.
21//!
22//! ```
23//! use rusty_h264_encoder::{Encoder, EncoderConfig};
24//! use rusty_h264_common::YuvFrame;
25//!
26//! let cfg = EncoderConfig::new(16, 16);
27//! let mut enc = Encoder::new(cfg).unwrap();
28//! let frame = YuvFrame::black(16, 16);
29//! let bitstream = enc.encode(&frame); // Annex-B bytes for one access unit
30//! assert!(!bitstream.is_empty());
31//! ```
32
33pub mod bitacct;
34mod cabac;
35mod config;
36mod lookahead;
37mod mb16;
38mod mbtree;
39mod mvd_cost_tab;
40mod params;
41mod rc;
42mod slice;
43
44pub use crate::mb16::{EXT_MV, ME_PROBE, MVCMP, MVCMP_FRAME};
45pub use config::{EncoderConfig, LookaheadMode, Preset};
46pub use params::{Pps, Sps};
47pub use rc::RateControl;
48
49use rusty_h264_common::{BitWriter, ChromaFormat, NalUnit, NalUnitType, Profile, YuvFrame};
50
51/// Errors that can arise constructing or driving the encoder.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum EncodeError {
54    /// A feature outside the implemented Constrained Baseline subset was asked for.
55    Unsupported(&'static str),
56    /// The supplied frame's dimensions or plane sizes don't match the config.
57    FrameMismatch,
58}
59
60impl core::fmt::Display for EncodeError {
61    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62        match self {
63            EncodeError::Unsupported(s) => write!(f, "unsupported: {s}"),
64            EncodeError::FrameMismatch => write!(f, "frame dimensions do not match encoder config"),
65        }
66    }
67}
68
69impl std::error::Error for EncodeError {}
70
71/// A Constrained Baseline H.264 encoder.
72#[derive(Debug)]
73pub struct Encoder {
74    cfg: EncoderConfig,
75    sps: Sps,
76    pps: Pps,
77    /// Count of frames fed so far; drives IDR placement via `gop_size`.
78    frame_index: u32,
79    /// `frame_num` of the next picture (resets to 0 at each IDR).
80    next_frame_num: u32,
81    /// Index of the current picture within its GOP (0 at IDR), for POC.
82    gop_index: u32,
83    /// Decoded-picture buffer: recent **deblocked** reconstructions (coded size),
84    /// most-recent first, used as inter references (`ref_idx` 0 = front).
85    refs: Vec<RefFrame>,
86    /// Average-bitrate controller; `None` for constant-QP encoding.
87    rc: Option<RateControl>,
88    /// Per-MB QP offset for the NEXT `encode()` (mb-tree temporal AQ). Set by the
89    /// batch path before each frame; consumed (and cleared) by `try_encode`. Empty /
90    /// `None` → no offset (byte-identical).
91    pending_qpo: Option<Vec<i32>>,
92}
93
94/// A reference picture: deblocked reconstruction at coded (MB-grid) resolution.
95/// Stored now (4a); read by motion compensation in 4b.
96#[derive(Clone, Debug)]
97#[allow(dead_code)]
98pub(crate) struct RefFrame {
99    // 16-byte aligned (moved from the encoder's aligned rec planes) so the openh264
100    // MC asm can load aligned reference row chunks.
101    pub y: rusty_h264_common::aligned::AlignedBytes,
102    pub u: rusty_h264_common::aligned::AlignedBytes,
103    pub v: rusty_h264_common::aligned::AlignedBytes,
104    /// Picture Order Count — the DISPLAY position. B ref-lists order L0/L1 by POC
105    /// relative to the current picture; P ignores it.
106    pub poc: i32,
107    /// The picture's `frame_num` (reference frames only advance it).
108    pub frame_num: u32,
109    /// Per-4×4-block List-0 motion (raster, `mb_w*4` wide). Populated for anchors;
110    /// read as the co-located picture (`RefPicList1[0]`) when deriving a B-frame's
111    /// spatial-direct `colZeroFlag`. `ref_idx == -1` marks intra/uncoded blocks.
112    pub mv: Vec<(i32, i32)>,
113    pub ref_idx: Vec<i32>,
114    /// Blocks-wide (`mb_w*4`), so the co-located index is `by*w4 + bx`.
115    pub w4: usize,
116    /// Cached half-pel luma planes, built on first sub-pel motion-search use.
117    ///
118    /// ENCODER-SIDE ONLY, and lazily: the motion search makes ~300 `mc_luma` calls
119    /// per macroblock while final reconstruction makes ~1, so this pays enormously
120    /// in the search and would be pure tax anywhere else. `Arc` so cloning a
121    /// `RefFrame` (the DPB does) does not copy three frame-sized planes.
122    pub hpel: std::sync::OnceLock<std::sync::Arc<rusty_h264_common::inter::HpelPlanes>>,
123}
124
125impl RefFrame {
126    /// The half-pel planes for this picture, filtering them once on first use.
127    pub(crate) fn hpel(&self, cw: usize, ch: usize) -> &rusty_h264_common::inter::HpelPlanes {
128        self.hpel.get_or_init(|| {
129            std::sync::Arc::new(rusty_h264_common::inter::build_hpel_planes(&self.y, cw, ch))
130        })
131    }
132}
133
134/// Sets the sub-pel refinement pattern (U1) for subsequent encodes in this process.
135/// 0 = 8-point ring + iterate, 1 = 4-point diamond + iterate, 2 = 8-point single
136/// pass, 3 = 4-point single pass. Exposed so the pattern can be A/B'd inside ONE
137/// binary, which is the only comparison this machine can resolve.
138/// Enables/disables the U1 online sub-pel dispatcher for subsequent encodes.
139/// Sets the λ-normalised partition-split search threshold (U2). 0 = off.
140/// Enables the U5-struct deferred sub-pel refinement (search all partition shapes at
141/// full-pel, refine only the winner). Bitstream-changing → BD-gated.
142/// Descent B: ME cost-path census [interior-fullpel, edge-fullpel, sub-pel].
143#[cfg(feature = "profile")]
144pub fn satdpath_snapshot() -> Vec<u64> { crate::mb16::satdpath::snapshot() }
145#[cfg(not(feature = "profile"))]
146pub fn satdpath_snapshot() -> Vec<u64> { Vec::new() }
147#[cfg(feature = "profile")]
148pub fn satdpath_reset() { crate::mb16::satdpath::reset() }
149#[cfg(not(feature = "profile"))]
150pub fn satdpath_reset() {}
151
152/// Descent D-2: sub-pel evaluations that re-price an already-priced MV.
153#[cfg(feature = "profile")]
154pub fn spstats_redundant() -> u64 { crate::mb16::spstats::redundant_count() }
155#[cfg(not(feature = "profile"))]
156pub fn spstats_redundant() -> u64 { 0 }
157
158/// Descent D: sub-pel ring census (profile builds only).
159#[cfg(feature = "profile")]
160pub fn spstats_snapshot() -> (Vec<u64>, Vec<u64>) { crate::mb16::spstats::snapshot() }
161#[cfg(not(feature = "profile"))]
162pub fn spstats_snapshot() -> (Vec<u64>, Vec<u64>) { (Vec::new(), Vec::new()) }
163#[cfg(feature = "profile")]
164pub fn spstats_reset() { crate::mb16::spstats::reset() }
165#[cfg(not(feature = "profile"))]
166pub fn spstats_reset() {}
167
168/// Default diamond rung mask (`[16,8,4]`).
169pub const DIA_DEFAULT_MASK: u32 = crate::mb16::DIA_DEFAULT;
170
171/// Descent A: select which rungs of the [64,32,16,8,4] diamond ladder to walk.
172pub fn set_dia_mask(m: u32) { crate::mb16::set_dia_mask(m) }
173/// Track-B B2: SAD-domain full-pel search phase (SATD from sub-pel on) — x264's
174/// cost split. Bitstream-changing; BD-gated; off = byte-identical to pre-B2.
175pub fn set_me_sadfp(on: bool) { crate::mb16::set_me_sadfp(on) }
176/// B2 mode: 0 off, 1 dispatched per frame by the `b2_mgain` probe, 2 force-on.
177pub fn set_me_sadfp_mode(m: u32) { crate::mb16::set_me_sadfp_mode(m) }
178/// Fixed-centre batched diamond passes (both cost domains). Off = cascade.
179pub fn set_me_fc(on: bool) { crate::mb16::set_me_fc(on) }
180/// H-13 split-dispatch threshold in milli-units of the mgain probe (0 = always
181/// search splits, byte-identical to pre-gate). Default 30 (= 0.03).
182pub fn set_split_mg(milli: u32) { crate::mb16::set_split_mg(milli) }
183/// H-23: smooth (x264-shape) mvd cost model in ME. Off = Exp-Golomb step fn.
184pub fn set_mv_smooth(on: bool) { crate::mb16::set_mv_smooth(on) }
185/// H-24 mv-cost mode: 0 off, 1 dispatched per frame by mgain, 2 force-on.
186pub fn set_mv_smooth_mode(m: u32) { crate::mb16::set_mv_smooth_mode(m) }
187/// Fixed-centre batched HALF-PEL sub-pel ring (satd_x4p). Off = cascade.
188pub fn set_sp_fc(on: bool) { crate::mb16::set_sp_fc(on) }
189
190/// The x264-style SUB-PEL EFFORT LADDER (H-10): one level selects a priced
191/// (ring pattern × iteration budget) rung — closing the ~24-vs-9 eval-count gap
192/// vs x264 as a BUDGET choice instead of a blanket cut.
193///
194/// 5 = ring8, iterate to convergence (the quality preset's default — max effort);
195/// 4 = ring8, ≤3 iterations/step; 3 = ring8, ≤2 iterations/step;
196/// 2 = ring8, single pass (= today's balanced preset); 1 = ring4, single pass.
197/// Levels ≥5 restore the defaults. Equivalent env knobs: `RFF_SUBPEL_PAT` +
198/// `RFF_SP_MAXIT`.
199pub fn set_subme(level: u32) {
200    let (pat, cap) = match level {
201        1 => (3, 0),
202        2 => (2, 0),
203        3 => (0, 2),
204        4 => (0, 3),
205        _ => (0, 0),
206    };
207    set_subpel_pattern(pat);
208    crate::mb16::set_sp_maxit(cap);
209}
210
211/// The SUPERFAST-CLASS rung (H-11/H-12): the Quality preset at x264 superfast's
212/// partition SHAPE — P16×16-only (splits gated off), everything else (sub-pel
213/// ladder, B2 dispatch) at defaults. Measured fair-run on foreman: **1.81× faster
214/// than default quality and STILL −0.9% BD vs x264 superfast itself.** The
215/// further effort cuts (subme 2 + SAD-fp force) were measured and REJECTED from
216/// this rung: no speed on top of shape-only (0.27× vs 0.28×) while costing BD
217/// (+1.9% foreman / +8.4% bus) — compose them manually via `set_subme` /
218/// `set_me_sadfp_mode` if wanted. Split-heavy content (bus-class) pays more at
219/// this rung; the per-frame split DISPATCH (H-11 next-brick b) is the eventual
220/// no-tax answer. Env twin: `RFF_SPLIT_T=10000000`.
221pub fn set_turbo(on: bool) {
222    set_split_t(if on { 10_000_000 } else { 0 });
223}
224/// Track-B B3: sub-pel iteration budget (0 = unlimited = byte-identical) — the
225/// bounded walk x264's subme levels have; pairs with B2. BD-gated.
226pub fn set_sp_maxit(n: u32) { crate::mb16::set_sp_maxit(n) }
227
228/// Descent A: diamond per-step evaluation census (profile builds only).
229#[cfg(feature = "profile")]
230pub fn diastats_snapshot() -> Vec<(u64, u64)> { crate::mb16::diastats::snapshot() }
231#[cfg(not(feature = "profile"))]
232pub fn diastats_snapshot() -> Vec<(u64, u64)> { Vec::new() }
233#[cfg(feature = "profile")]
234pub fn diastats_reset() { crate::mb16::diastats::reset() }
235#[cfg(not(feature = "profile"))]
236pub fn diastats_reset() {}
237
238pub fn set_defer_subpel(on: bool) {
239    crate::mb16::DEFER_SUBPEL.store(if on { 1 } else { 0 }, std::sync::atomic::Ordering::Relaxed);
240}
241
242pub fn set_split_t(t: u32) {
243    crate::mb16::SPLIT_T.store(t, std::sync::atomic::Ordering::Relaxed);
244}
245
246pub fn set_subpel_dispatch(on: bool) {
247    crate::mb16::SP_DISPATCH.store(if on { 1 } else { 0 }, std::sync::atomic::Ordering::Relaxed);
248}
249
250pub fn set_subpel_pattern(p: u32) {
251    crate::mb16::SUBPEL_PAT.store(p, std::sync::atomic::Ordering::Relaxed);
252}
253
254impl Encoder {
255    /// Creates an encoder, validating that the configuration is within the
256    /// implemented subset.
257    pub fn new(cfg: EncoderConfig) -> Result<Self, EncodeError> {
258        if !matches!(
259            cfg.profile,
260            Profile::ConstrainedBaseline | Profile::Baseline | Profile::Main | Profile::High
261        ) {
262            return Err(EncodeError::Unsupported("unsupported profile"));
263        }
264        // The 8×8 transform is a High-profile CAVLC feature (our decoder has no CABAC 8×8).
265        if cfg.transform_8x8 && (!matches!(cfg.profile, Profile::High) || cfg.cabac) {
266            return Err(EncodeError::Unsupported("8x8 transform requires High profile + CAVLC"));
267        }
268        // B-frames are illegal in Baseline (the decoder enforces this too): Main only.
269        if cfg.bframes > 0 && !matches!(cfg.profile, Profile::Main) {
270            return Err(EncodeError::Unsupported("B-frames require Main profile"));
271        }
272        if cfg.chroma != ChromaFormat::Yuv420 {
273            return Err(EncodeError::Unsupported("only 4:2:0 chroma"));
274        }
275        if cfg.width == 0 || cfg.height == 0 || cfg.width % 2 != 0 || cfg.height % 2 != 0 {
276            return Err(EncodeError::Unsupported("dimensions must be positive and even"));
277        }
278        let sps = Sps::from_config(&cfg);
279        let pps = Pps::from_config(&cfg);
280        let rc = (cfg.bitrate > 0).then(|| RateControl::new(cfg.bitrate, cfg.framerate, cfg.qp));
281        Ok(Self {
282            cfg,
283            sps,
284            pps,
285            frame_index: 0,
286            next_frame_num: 0,
287            gop_index: 0,
288            refs: Vec::new(),
289            rc,
290            pending_qpo: None,
291        })
292    }
293
294    /// Sets the per-MB QP offset applied to the NEXT [`encode`](Self::encode) call
295    /// (mb-tree temporal AQ). One entry per macroblock (raster). Consumed once.
296    pub(crate) fn set_pending_qpo(&mut self, qpo: Vec<i32>) {
297        self.pending_qpo = Some(qpo);
298    }
299
300    /// The active configuration.
301    pub fn config(&self) -> &EncoderConfig {
302        &self.cfg
303    }
304
305    /// Encodes one frame, returning the Annex-B access unit. Every `gop_size`
306    /// frames (and always the first) is coded as an IDR, prefixed with SPS/PPS.
307    ///
308    /// Generation 1 codes *every* picture as an IDR (all-intra); inter frames
309    /// arrive with motion compensation later.
310    pub fn encode(&mut self, frame: &YuvFrame) -> Vec<u8> {
311        self.try_encode(frame).expect("frame matched config")
312    }
313
314    /// Fallible [`encode`](Self::encode): validates the frame against the config.
315    pub fn try_encode(&mut self, frame: &YuvFrame) -> Result<Vec<u8>, EncodeError> {
316        let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::Total);
317        if frame.width != self.cfg.width || frame.height != self.cfg.height || !frame.is_valid() {
318            return Err(EncodeError::FrameMismatch);
319        }
320
321        // B-frames need lookahead (a future anchor coded before the B), which the
322        // one-frame-in streaming API can't provide — use `encode_all` for B.
323        if self.cfg.bframes > 0 {
324            return Err(EncodeError::Unsupported("B-frames need encode_all (lookahead)"));
325        }
326        // GOP placement: an IDR at each `gop_size` boundary, P-frames between.
327        let is_idr = self.cfg.gop_size <= 1 || self.frame_index % self.cfg.gop_size == 0;
328        if is_idr {
329            self.gop_index = 0;
330            self.next_frame_num = 0;
331            self.refs.clear();
332        }
333        let frame_num = self.next_frame_num;
334        let poc_lsb = (2 * self.gop_index) % 16;
335        // mb-tree per-MB QP offset for this frame (empty = none / byte-identical).
336        let qpo = self.pending_qpo.take().unwrap_or_default();
337
338        // Rate control (if enabled) chooses this frame's QP from a cheap
339        // look-ahead complexity estimate; otherwise the QP is fixed.
340        let complexity = if self.rc.is_some() {
341            lookahead::complexity(&self.cfg, frame, if is_idr { None } else { self.refs.first() })
342        } else {
343            0.0
344        };
345        let qp = match &self.rc {
346            Some(rc) => rc.pick_qp(is_idr, complexity),
347            // Constant-QP: apply the per-GOP I-frame cascade offset (0 by default →
348            // byte-identical). Keeps the P-only path consistent with `code_picture`.
349            None if is_idr => (self.cfg.qp as i32 + self.cfg.i_qp_offset).clamp(0, 51) as u8,
350            None => self.cfg.qp,
351        };
352
353        let mut out = Vec::new();
354        // Pre-size the slice writer to a generous fraction of the raw frame so the
355        // CAVLC hot loop never reallocs mid-frame (byte-identical; just capacity).
356        let mut w = BitWriter::with_capacity(self.cfg.width * self.cfg.height / 2 + 4096);
357        let (nal_type, mut reference) = if is_idr {
358            // SPS/PPS precede every IDR so the stream is independently decodable.
359            self.sps.to_nal().write_annex_b(&mut out);
360            self.pps.to_nal().write_annex_b(&mut out);
361            slice::write_idr_slice_header(&mut w, &self.cfg, qp);
362            let r = if self.cfg.cabac {
363                mb16::encode_slice_data_cabac_intra(&mut w, &self.cfg, frame, qp, &qpo)
364            } else {
365                mb16::encode_slice_data(&mut w, &self.cfg, frame, qp, false, &[], &qpo)
366            };
367            (NalUnitType::IdrSlice, r)
368        } else {
369            slice::write_p_slice_header(&mut w, &self.cfg, qp, frame_num, poc_lsb, self.refs.len());
370            let r = if self.cfg.cabac {
371                mb16::encode_slice_data_cabac_p(&mut w, &self.cfg, frame, qp, &self.refs, &qpo)
372            } else {
373                mb16::encode_slice_data(&mut w, &self.cfg, frame, qp, true, &self.refs, &qpo)
374            };
375            (NalUnitType::NonIdrSlice, r)
376        };
377        // POC/frame_num carried on the reference so B-frame ref-lists (when enabled)
378        // can order L0/L1 by display position. Unused on the P-only path.
379        reference.poc = 2 * self.gop_index as i32;
380        reference.frame_num = frame_num;
381        let slice_bytes = w.into_bytes();
382        // Feed the coded slice size (the picture's own bits) back to the controller.
383        if let Some(rc) = &mut self.rc {
384            rc.update(is_idr, slice_bytes.len() * 8, qp, complexity);
385        }
386        {
387            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::EncNal);
388            NalUnit::new(3, nal_type, slice_bytes).write_annex_b(&mut out);
389        }
390
391        // The deblocked reconstruction enters the DPB (most-recent first), which
392        // is kept to `max_num_ref_frames` by a sliding window.
393        self.refs.insert(0, reference);
394        self.refs.truncate(self.cfg.num_ref_frames.max(1) as usize);
395        self.frame_index += 1;
396        self.gop_index += 1;
397        self.next_frame_num = (self.next_frame_num + 1) % 16;
398        Ok(out)
399    }
400
401    /// Batch-encodes every frame, returning one Annex-B access unit per frame.
402    ///
403    /// At constant QP the GOPs are independent — each begins with an IDR that
404    /// resets the DPB, `frame_num` and POC, and SPS/PPS precede every IDR — so they
405    /// are encoded **in parallel across CPU cores** and the result is
406    /// **byte-identical** to calling [`encode`](Self::encode) frame-by-frame. With
407    /// rate control enabled the per-frame QP depends on history, so this falls back
408    /// to sequential encoding. Within a GOP, P-frames are inherently sequential
409    /// (each predicts from the previous reconstruction); the parallelism is across
410    /// GOPs, so it scales with the number of GOPs in the clip.
411    pub fn encode_all(&self, frames: &[YuvFrame]) -> Result<Vec<Vec<u8>>, EncodeError> {
412        for f in frames {
413            if f.width != self.cfg.width || f.height != self.cfg.height || !f.is_valid() {
414                return Err(EncodeError::FrameMismatch);
415            }
416        }
417        // B-frames need a reorder pipeline (code the future anchor before the B's
418        // that reference it) — a separate sequential path.
419        if self.cfg.bframes > 0 {
420            // Content-adaptive dispatch, PER GOP (codec-content-adaptive-dispatch):
421            // code B-frames only in GOPs whose motion is predictable enough to pay,
422            // so a mixed clip gets B on its smooth segments and P on its busy ones.
423            let gop = self.cfg.gop_size.max(1) as usize;
424            let n_gops = frames.len().div_ceil(gop);
425            let (w, h) = (self.cfg.width, self.cfg.height);
426            // One cheap per-GOP signal drives BOTH content-adaptive knobs: the B/P
427            // structure dispatch AND the I-frame QP-cascade depth.
428            let gop_sig: Vec<f64> = (0..n_gops)
429                .map(|g| gop_bi_residual(&frames[g * gop..((g + 1) * gop).min(frames.len())], w, h, 1))
430                .collect();
431            let gop_fav: Vec<bool> = if self.cfg.bframes_adaptive {
432                gop_sig.iter().map(|&s| bframes_favorable(s)).collect()
433            } else {
434                vec![true; n_gops]
435            };
436            let gop_iqp: Vec<i32> = gop_sig.iter().map(|&s| gop_iqp_offset(s, self.cfg.i_qp_offset)).collect();
437            let gop_bqp: Vec<i32> = gop_sig.iter().map(|&s| gop_bframe_qp_offset(s, self.cfg.bframe_qp_offset)).collect();
438            // Adaptive B-COUNT: how many B's per anchor gap. Fixed `bframes` unless
439            // `auto`, where the 2-gap/1-gap bi-residual RATIO picks it — content that
440            // survives wider anchor spacing (low ratio) carries more cheap B's; simple
441            // translation (high ratio) wants a single equidistant B.
442            let bcount = if self.cfg.bframes_adaptive {
443                adaptive_bcount(frames, w, h, self.cfg.bframes as usize)
444            } else {
445                self.cfg.bframes as usize
446            };
447            if gop_fav.iter().any(|&f| f) {
448                return Ok(self.encode_all_bframes(frames, bcount, &gop_fav, &gop_iqp, &gop_bqp));
449            }
450            // No GOP is B-favorable → pure P-only (byte-identical to bframes=0).
451            let mut pcfg = self.cfg.clone();
452            pcfg.bframes = 0;
453            return Encoder::new(pcfg)?.encode_all(frames);
454        }
455        // Rate control threads state across frames → it must stay sequential. mb-tree
456        // runs in RC mode too: per-GOP lookahead → per-MB offsets (per-GOP centered, so
457        // rate-neutral per GOP), and the controller supplies each frame's base QP.
458        // (MEASURED: routing the cross-frame allocation through the RC's complexity
459        // instead of centering was worse — the centered offsets carry it correctly.)
460        if self.cfg.bitrate > 0 {
461            let mut enc = Encoder::new(self.cfg.clone())?;
462            let offs: Vec<Vec<i32>> = if self.cfg.mbtree {
463                let gop = self.cfg.gop_size.max(1) as usize;
464                frames
465                    .chunks(gop)
466                    .flat_map(|g| mbtree::gop_qp_offsets(&self.cfg, g, self.cfg.mbtree_strength))
467                    .collect()
468            } else {
469                Vec::new()
470            };
471            return frames
472                .iter()
473                .enumerate()
474                .map(|(i, f)| {
475                    if let Some(qpo) = offs.get(i) {
476                        enc.pending_qpo = Some(qpo.clone());
477                    }
478                    enc.try_encode(f)
479                })
480                .collect();
481        }
482        let gop = self.cfg.gop_size.max(1) as usize;
483        let gops: Vec<&[YuvFrame]> = frames.chunks(gop).collect();
484        if gops.is_empty() {
485            return Ok(Vec::new());
486        }
487        let n = std::env::var("RUSTY_THREADS")
488            .ok()
489            .and_then(|v| v.parse().ok())
490            .or_else(|| std::thread::available_parallelism().map(|n| n.get()).ok())
491            .unwrap_or(1)
492            .min(gops.len());
493        // Each GOP is encoded with a fresh encoder (an IDR resets all state), so
494        // GOPs distribute across `n` worker threads with no shared mutable state.
495        let mut out: Vec<Option<Vec<Vec<u8>>>> = (0..gops.len()).map(|_| None).collect();
496        let cfg = &self.cfg;
497        let gops_ref = &gops;
498        std::thread::scope(|s| {
499            let handles: Vec<_> = (0..n)
500                .map(|t| {
501                    s.spawn(move || {
502                        let mut local = Vec::new();
503                        let mut i = t;
504                        while i < gops_ref.len() {
505                            let mut enc = Encoder::new(cfg.clone()).expect("config");
506                            // mb-tree temporal AQ: a per-GOP lookahead over the GOP's
507                            // source frames yields per-frame per-MB QP offsets (the GOP
508                            // is the natural window — the IDR resets references). Off →
509                            // empty → byte-identical.
510                            let offs = if cfg.mbtree {
511                                mbtree::gop_qp_offsets(cfg, gops_ref[i], cfg.mbtree_strength)
512                            } else {
513                                Vec::new()
514                            };
515                            let aus: Vec<Vec<u8>> = gops_ref[i]
516                                .iter()
517                                .enumerate()
518                                .map(|(fi, f)| {
519                                    if let Some(o) = offs.get(fi) {
520                                        enc.set_pending_qpo(o.clone());
521                                    }
522                                    enc.encode(f)
523                                })
524                                .collect();
525                            local.push((i, aus));
526                            i += n;
527                        }
528                        local
529                    })
530                })
531                .collect();
532            for h in handles {
533                for (i, aus) in h.join().expect("encode worker panicked") {
534                    out[i] = Some(aus);
535                }
536            }
537        });
538        Ok(out.into_iter().flatten().flatten().collect())
539    }
540
541    /// B-frame reorder pipeline (sequential). Produces access units in **coding
542    /// order** (the decoder reorders to display order by POC). Structure: an IDR
543    /// at each `gop_size` boundary, a P anchor every `bframes+1` frames within a
544    /// GOP, `bframes` non-reference B-frames between consecutive anchors, and the
545    /// last frame forced to an anchor so trailing B's always have a future
546    /// reference. Each anchor is coded before the B's that reference it.
547    /// `gop_favorable[g]` (content-adaptive): GOP `g` codes B-frames only when
548    /// `true`; a `false` GOP is coded all-P (every frame an anchor) so busy segments
549    /// of a mixed clip don't regress. Non-adaptive callers pass all-`true`.
550    fn encode_all_bframes(&self, frames: &[YuvFrame], bcount: usize, gop_favorable: &[bool], gop_iqp: &[i32], gop_bqp: &[i32]) -> Vec<Vec<u8>> {
551        let n = frames.len();
552        if n == 0 {
553            return Vec::new();
554        }
555        let step = bcount.max(1) + 1; // B's per anchor gap + 1 (adaptive in `auto`)
556        let gop = self.cfg.gop_size.max(1) as usize;
557        // A B-capable config: Main profile + ≥2 refs so the DPB holds both anchors.
558        let mut cfg = self.cfg.clone();
559        cfg.num_ref_frames = cfg.num_ref_frames.max(2);
560        let sps = Sps::from_config(&cfg);
561        let pps = Pps::from_config(&cfg);
562
563        // Anchor display-indices: IDR at GOP starts, P anchors every `step`, plus
564        // the frame right before each IDR boundary and the clip's last frame — a
565        // trailing B with no future reference IN ITS OWN GOP would otherwise be
566        // coded after the next GOP's IDR (which clears the DPB), losing its anchors.
567        let mut is_anchor = vec![false; n];
568        for (d, a) in is_anchor.iter_mut().enumerate() {
569            // A non-favorable GOP is coded all-P (every frame an anchor); a favorable
570            // one uses the B structure.
571            *a = if gop_favorable.get(d / gop).copied().unwrap_or(true) {
572                d % gop == 0 || (d % gop) % step == 0 || (d + 1) % gop == 0
573            } else {
574                true
575            };
576        }
577        is_anchor[n - 1] = true;
578
579        // mb-tree temporal AQ over the ANCHOR reference chain: B-frames are
580        // non-reference leaves (mb-tree offsets them at ~0 anyway), so the lookahead
581        // runs over each GOP's anchor sub-sequence — the frames that actually form the
582        // reference chain — and only anchors receive an offset. `mbtree_off[d]` is that
583        // anchor's per-MB offset (empty for B's / when off → byte-identical).
584        let mbtree_off: Vec<Vec<i32>> = if cfg.mbtree {
585            let mut off = vec![Vec::new(); n];
586            let mut g = 0;
587            while g < n {
588                let gop_end = (g + gop).min(n);
589                let anchors: Vec<usize> = (g..gop_end).filter(|&d| is_anchor[d]).collect();
590                let aframes: Vec<YuvFrame> = anchors.iter().map(|&d| frames[d].clone()).collect();
591                let offs = mbtree::gop_qp_offsets(&cfg, &aframes, cfg.mbtree_strength);
592                for (i, &d) in anchors.iter().enumerate() {
593                    off[d] = offs[i].clone();
594                }
595                g = gop_end;
596            }
597            off
598        } else {
599            Vec::new()
600        };
601
602        // Coding order: each anchor (display order), then the B's before it.
603        let mut order: Vec<usize> = Vec::with_capacity(n);
604        let mut prev: Option<usize> = None;
605        for d in 0..n {
606            if !is_anchor[d] {
607                continue;
608            }
609            order.push(d);
610            if let Some(p) = prev {
611                order.extend((p + 1)..d);
612            }
613            prev = Some(d);
614        }
615
616        let mut dpb: Vec<RefFrame> = Vec::new();
617        let mut aus: Vec<Vec<u8>> = Vec::with_capacity(n);
618        let mut frame_num: u32 = 0;
619        for &d in &order {
620            let is_idr = d % gop == 0;
621            if is_idr {
622                dpb.clear();
623                frame_num = 0;
624            }
625            let is_b = !is_anchor[d];
626            let gop_start = (d / gop) * gop;
627            let poc = ((d - gop_start) as i32) * 2; // POC = display position within the GOP
628            let iqp = gop_iqp.get(d / gop).copied().unwrap_or(cfg.i_qp_offset);
629            let bqp = gop_bqp.get(d / gop).copied().unwrap_or(cfg.bframe_qp_offset);
630            let qpo: &[i32] = mbtree_off.get(d).map(|v| v.as_slice()).unwrap_or(&[]);
631            let (au, recon) =
632                code_picture(&cfg, &sps, &pps, &frames[d], is_idr, is_b, poc, frame_num, &dpb, iqp, bqp, qpo);
633            aus.push(au);
634            if !is_b {
635                if let Some(r) = recon {
636                    dpb.insert(0, r);
637                    dpb.truncate(cfg.num_ref_frames as usize);
638                }
639                frame_num = (frame_num + 1) % 16;
640            }
641        }
642        aus
643    }
644}
645
646/// Codes ONE picture (IDR / P anchor / B) with explicit POC + frame_num + DPB.
647/// Returns the access unit and, for reference pictures, the reconstruction to add
648/// to the DPB (B-frames are non-reference → `None`). `dpb` is most-recent-first.
649#[allow(clippy::too_many_arguments)]
650fn code_picture(
651    cfg: &EncoderConfig,
652    sps: &Sps,
653    pps: &Pps,
654    frame: &YuvFrame,
655    is_idr: bool,
656    is_b: bool,
657    poc: i32,
658    frame_num: u32,
659    dpb: &[RefFrame],
660    i_qp_offset: i32,
661    b_qp_offset: i32,
662    qpo: &[i32],
663) -> (Vec<u8>, Option<RefFrame>) {
664    let mut out = Vec::new();
665    let mut w = BitWriter::with_capacity(cfg.width * cfg.height / 2 + 4096);
666    let poc_lsb = (poc as u32) & 0xF; // log2_max_pic_order_cnt_lsb = 4
667    // Per-GOP QP cascade, both offsets content-adaptive: B-frames are non-reference →
668    // quantize HARDER (`b_qp_offset`, deeper on very predictable GOPs); the GOP's
669    // I-frame is the root reference → quantize FINER (`i_qp_offset`, deeper on
670    // predictable GOPs where the I dominates the bits).
671    let qp = if is_b {
672        (cfg.qp as i32 + b_qp_offset).clamp(0, 51) as u8
673    } else if is_idr {
674        (cfg.qp as i32 + i_qp_offset).clamp(0, 51) as u8
675    } else {
676        cfg.qp
677    };
678    let (nal_type, nal_ref_idc, recon) = if is_idr {
679        sps.to_nal().write_annex_b(&mut out);
680        pps.to_nal().write_annex_b(&mut out);
681        slice::write_idr_slice_header(&mut w, cfg, qp);
682        let mut r = if cfg.cabac {
683            mb16::encode_slice_data_cabac_intra(&mut w, cfg, frame, qp, qpo)
684        } else {
685            mb16::encode_slice_data(&mut w, cfg, frame, qp, false, &[], qpo)
686        };
687        r.poc = poc;
688        r.frame_num = frame_num;
689        (NalUnitType::IdrSlice, 3u8, Some(r))
690    } else if is_b {
691        // B is non-reference. We signal one active reference per list: L0[0] =
692        // nearest PAST anchor (highest poc < current), L1[0] = nearest FUTURE anchor
693        // (lowest poc > current) — the heads of the decoder's POC-ordered B lists.
694        let l0 = dpb.iter().filter(|r| r.poc < poc).max_by_key(|r| r.poc);
695        let l1 = dpb.iter().filter(|r| r.poc > poc).min_by_key(|r| r.poc);
696        slice::write_b_slice_header(&mut w, cfg, qp, frame_num, poc_lsb, 1, 1);
697        match (l0, l1) {
698            // B-frames are non-reference leaves — mb-tree offsets them at 0 anyway, so
699            // `qpo` is `&[]` here (the anchor reference chain carries the temporal AQ).
700            (Some(l0), Some(l1)) if cfg.cabac => {
701                mb16::encode_slice_data_cabac_b(&mut w, cfg, frame, qp, poc, l0, l1, &[])
702            }
703            (Some(l0), Some(l1)) => mb16::encode_slice_data_b(&mut w, cfg, frame, qp, poc, l0, l1, &[]),
704            // A B with no bracketing anchor pair can't be List-0/1 coded; fall back
705            // to an all-B_Skip slice (spatial-direct) so the stream stays legal.
706            _ => {
707                let n = cfg.mb_width() * cfg.mb_height();
708                if cfg.cabac {
709                    mb16::encode_all_skip_b_cabac(&mut w, cfg, qp, n);
710                } else {
711                    w.write_ue(n as u32);
712                    w.rbsp_trailing_bits();
713                }
714            }
715        }
716        (NalUnitType::NonIdrSlice, 0u8, None)
717    } else {
718        // P anchor: L0 = the DPB (past anchors), ordered most-recent-first. Both CAVLC
719        // and CABAC now code ref_idx_l0 (cb_ref_idx / parse_ref_idx_cabac), so a P slice
720        // searches + signals the full DPB (`--refs N`) under either entropy coder.
721        let p_dpb: &[RefFrame] = dpb;
722        slice::write_p_slice_header(&mut w, cfg, qp, frame_num, poc_lsb, p_dpb.len());
723        let mut r = if cfg.cabac {
724            mb16::encode_slice_data_cabac_p(&mut w, cfg, frame, qp, p_dpb, qpo)
725        } else {
726            mb16::encode_slice_data(&mut w, cfg, frame, qp, true, dpb, qpo)
727        };
728        r.poc = poc;
729        r.frame_num = frame_num;
730        (NalUnitType::NonIdrSlice, 3u8, Some(r))
731    };
732    let slice_bytes = w.into_bytes();
733    NalUnit::new(nal_ref_idc, nal_type, slice_bytes).write_annex_b(&mut out);
734    (out, recon)
735}
736
737/// The B-favorability threshold on the per-GOP signal (`gop_bi_residual`): below it,
738/// motion is predictable enough that B-frames pay AND the I-frame dominates the GOP's
739/// bits (so it wants a deeper QP cascade); above it the GOP is busy.
740const BI_THRESH: f64 = 4.0;
741
742/// Whether a GOP's temporal residual makes B-frames pay (predictable motion).
743fn bframes_favorable(residual: f64) -> bool {
744    residual < BI_THRESH
745}
746
747/// Content-adaptive per-GOP I-frame QP offset (the ip_ratio cascade, DISPATCHED by
748/// content). `base` is the busy-GOP offset (`cfg.i_qp_offset`, default −3); a
749/// predictable GOP — where the I-frame is a large fraction of the GOP's bits, so
750/// investing in it pays outsized — gets up to 2 QP steps FINER, ramping from `base`
751/// at the threshold to `base−2` at residual 0. Calibrated: busy ≈ −3, compressible
752/// ≈ −5 (−11.6% vs −7.3% at −3). `base == 0` (the opt-out) disables it entirely so
753/// the byte-identical escape hatch survives.
754fn gop_iqp_offset(residual: f64, base: i32) -> i32 {
755    if base == 0 {
756        return 0;
757    }
758    let bonus = (2.0 * ((BI_THRESH - residual) / BI_THRESH).clamp(0.0, 1.0)).round() as i32;
759    base - bonus
760}
761
762/// Content-adaptive per-GOP B-frame QP offset. B-frames are non-reference, so on a
763/// VERY predictable GOP (bi-pred + spatial-direct nail them → tiny residual) they can
764/// be quantized much HARDER for near-free bits. But the optimum is KNIFE-EDGE in the
765/// signal — measured ~+8 at residual 0.10 yet ~+2 by residual 0.29 (and a heavy LOSS
766/// at +12 there) — so unlike the I-cascade this ramp is STEEP and confined to the
767/// near-perfect-motion regime: `base` (default +2) everywhere, boosted up to +4 only
768/// as residual → 0 (decaying to `base` by ~0.3/px). Deliberately conservative — it
769/// helps near-static / clean-pan content and must never touch the common range.
770fn gop_bframe_qp_offset(residual: f64, base: i32) -> i32 {
771    const RAMP: f64 = 0.3; // residual above this gets no boost (steep — see calibration)
772    let boost = (4.0 * ((RAMP - residual) / RAMP).clamp(0.0, 1.0)).round() as i32;
773    base + boost
774}
775
776/// Adaptive B-COUNT (B-frames per anchor gap) for `auto` mode. The RATIO of the
777/// 2-gap to 1-gap bi-prediction residual measures how fast bi-pred degrades as the
778/// anchor spacing widens: LOW ratio (content survives wider gaps) carries MORE cheap
779/// non-reference B's; HIGH ratio (simple translation — degrades fast, so wider anchors
780/// cost more than the extra B's save) wants a single equidistant B. Calibrated on
781/// pans/zoom: ratio ≥ 1.8 → 1, ≥ 1.4 → 2, else 3. Capped at `max_b` (the `auto` cap).
782fn adaptive_bcount(frames: &[YuvFrame], w: usize, h: usize, max_b: usize) -> usize {
783    let cap = max_b.clamp(1, 3);
784    let g1 = gop_bi_residual(frames, w, h, 1);
785    let g2 = gop_bi_residual(frames, w, h, 2);
786    if !g1.is_finite() || !g2.is_finite() {
787        return 1;
788    }
789    let ratio = g2 / g1.max(1e-3);
790    // Calibrated on this encoder's (subsampled global-ME) ratios: a simple
791    // translation degrades to ~1.5 (→ 1 B), predictable-under-wide-gaps content sits
792    // ~1.3 or below (→ 3 B).
793    let c = if ratio >= 1.4 { 1 } else if ratio >= 1.3 { 2 } else { 3 };
794    c.clamp(1, cap)
795}
796
797/// Cheap content signal for the content-adaptive dispatch: the mean per-pixel
798/// residual of a coarse GLOBAL-motion BI-prediction, over a subsample of interior
799/// frames. Low = temporally predictable (bi-pred + spatial-direct cheap → B-frames
800/// WIN, and the I-frame dominates → deeper QP cascade); high = busy motion.
801/// `f64::INFINITY` when the GOP is too short to measure (treated as busy).
802///
803/// Global (not block) ME keeps it O(pixels)-cheap and biases toward "coherent
804/// motion", which is what spatial-direct/skip exploit. Thresholds calibrated on
805/// extremes (pan ~0.03/px, high-motion ~12.3/px); refine on a corpus.
806fn gop_bi_residual(frames: &[YuvFrame], w: usize, h: usize, gap: usize) -> f64 {
807    let n = frames.len();
808    if n < 2 * gap + 1 || w < 48 || h < 48 {
809        return f64::INFINITY;
810    }
811    // Subsampled SAD of `cur` vs `rf` shifted by (dx,dy): interior pixels only
812    // (|shift| ≤ 15 stays in-bounds, no clamping), every 4th pixel for speed.
813    let sad = |cur: &[u8], rf: &[u8], dx: isize, dy: isize| -> u64 {
814        let mut s = 0u64;
815        let mut y = 16;
816        while y < h - 16 {
817            let cbase = (y * w) as isize;
818            let rbase = ((y as isize + dy) * w as isize) + dx;
819            let mut x = 16isize;
820            while x < (w - 16) as isize {
821                let c = cur[(cbase + x) as usize] as i32;
822                let r = rf[(rbase + x) as usize] as i32;
823                s += (c - r).unsigned_abs() as u64;
824                x += 8;
825            }
826            y += 8;
827        }
828        s
829    };
830    // Coarse global ME: ±12 step 4, then refine ±3 step 1.
831    let global_me = |cur: &[u8], rf: &[u8]| -> (isize, isize) {
832        let (mut best, mut bc) = ((0isize, 0isize), u64::MAX);
833        let mut dy = -12;
834        while dy <= 12 {
835            let mut dx = -12;
836            while dx <= 12 {
837                let c = sad(cur, rf, dx, dy);
838                if c < bc {
839                    bc = c;
840                    best = (dx, dy);
841                }
842                dx += 4;
843            }
844            dy += 4;
845        }
846        for dy in best.1 - 3..=best.1 + 3 {
847            for dx in best.0 - 3..=best.0 + 3 {
848                let c = sad(cur, rf, dx, dy);
849                if c < bc {
850                    bc = c;
851                    best = (dx, dy);
852                }
853            }
854        }
855        best
856    };
857    let mut n_samp = 0usize;
858    {
859        let mut y = 16;
860        while y < h - 16 {
861            let mut x = 16;
862            while x < w - 16 {
863                n_samp += 1;
864                x += 8;
865            }
866            y += 8;
867        }
868    }
869    let step = (n / 5).max(1);
870    let (mut total, mut cnt) = (0f64, 0usize);
871    // `gap` frames each side (1 = adjacent, for the B/P dispatch; 2 probes how well
872    // bi-prediction survives WIDER anchor spacing, for the adaptive B-count).
873    let mut d = gap;
874    while d < n - gap {
875        let (cur, past, fut) = (&frames[d].y, &frames[d - gap].y, &frames[d + gap].y);
876        let (mpx, mpy) = global_me(cur, past);
877        let (mfx, mfy) = global_me(cur, fut);
878        let mut bi = 0u64;
879        let mut y = 16;
880        while y < h - 16 {
881            let mut x = 16isize;
882            while x < (w - 16) as isize {
883                let c = cur[y * w + x as usize] as i32;
884                let p = past[((y as isize + mpy) * w as isize + x + mpx) as usize] as i32;
885                let f = fut[((y as isize + mfy) * w as isize + x + mfx) as usize] as i32;
886                bi += (c - ((p + f + 1) >> 1)).unsigned_abs() as u64;
887                x += 8;
888            }
889            y += 8;
890        }
891        total += bi as f64 / n_samp as f64;
892        cnt += 1;
893        d += step;
894    }
895    if cnt > 0 {
896        total / cnt as f64
897    } else {
898        f64::INFINITY
899    }
900}
901
902#[cfg(test)]
903mod tests {
904    use super::*;
905
906    #[test]
907    fn rejects_unsupported_config() {
908        // High profile is supported (8x8 transform); a High-profile 8x8 stream must be
909        // CAVLC (our decoder has no CABAC 8x8) — that combination is rejected.
910        let mut cfg = EncoderConfig::new(16, 16);
911        cfg.profile = Profile::High;
912        cfg.transform_8x8 = true;
913        cfg.cabac = true;
914        assert!(matches!(Encoder::new(cfg), Err(EncodeError::Unsupported(_))));
915    }
916
917    #[test]
918    fn encodes_access_unit_with_sps_pps_idr() {
919        use rusty_h264_common::nal::split_annex_b;
920        let cfg = EncoderConfig::new(32, 32);
921        let mut enc = Encoder::new(cfg).unwrap();
922        let frame = YuvFrame::black(32, 32);
923        let au = enc.encode(&frame);
924
925        let nals = split_annex_b(&au);
926        assert_eq!(nals.len(), 3);
927        assert_eq!(NalUnitType::from_id(nals[0][0]), NalUnitType::Sps);
928        assert_eq!(NalUnitType::from_id(nals[1][0]), NalUnitType::Pps);
929        assert_eq!(NalUnitType::from_id(nals[2][0]), NalUnitType::IdrSlice);
930    }
931
932    #[test]
933    fn encode_all_matches_sequential_cqp() {
934        // GOP-parallel batch encoding must be byte-identical to frame-by-frame
935        // sequential encoding at constant QP (GOPs are independent).
936        let (w, h) = (48usize, 32usize);
937        let mut cfg = EncoderConfig::new(w, h);
938        cfg.gop_size = 4; // 10 frames → 3 GOPs (4,4,2)
939        let frames: Vec<YuvFrame> = (0..10u8)
940            .map(|t| YuvFrame {
941                width: w,
942                height: h,
943                y: (0..w * h).map(|i| (i as u8).wrapping_add(t.wrapping_mul(7))).collect(),
944                u: vec![128u8.wrapping_add(t); (w / 2) * (h / 2)],
945                v: vec![128u8.wrapping_sub(t); (w / 2) * (h / 2)],
946            })
947            .collect();
948        let mut seq_enc = Encoder::new(cfg.clone()).unwrap();
949        let seq: Vec<Vec<u8>> = frames.iter().map(|f| seq_enc.encode(f)).collect();
950        let par = Encoder::new(cfg).unwrap().encode_all(&frames).unwrap();
951        assert_eq!(seq, par, "GOP-parallel must equal sequential at CQP");
952    }
953
954    #[test]
955    fn encode_all_matches_sequential_quality_preset() {
956        // Same invariant on the QUALITY preset, whose per-frame dispatch decisions
957        // (b2_mgain SAD/mv-cost routing) once lived in a process-global and RACED
958        // across GOP workers — divergence only appears with >1 GOP in flight, which
959        // the single-GOP hash harness never exercised. Content varies per frame so
960        // the per-frame routing decisions actually differ between GOPs.
961        let (w, h) = (48usize, 32usize);
962        let mut cfg = EncoderConfig::new(w, h);
963        cfg.gop_size = 3; // 12 frames → 4 GOPs, several workers in flight
964        cfg.preset = crate::config::Preset::Quality;
965        let frames: Vec<YuvFrame> = (0..12u8)
966            .map(|t| YuvFrame {
967                width: w,
968                height: h,
969                y: (0..w * h)
970                    .map(|i| {
971                        // alternate calm and busy frames so the mgain probe flips
972                        let base = (i as u8).wrapping_add(t.wrapping_mul(3));
973                        if t % 2 == 0 { base } else { base.wrapping_mul(37).wrapping_add(i as u8) }
974                    })
975                    .collect(),
976                u: vec![128u8.wrapping_add(t); (w / 2) * (h / 2)],
977                v: vec![128u8.wrapping_sub(t); (w / 2) * (h / 2)],
978            })
979            .collect();
980        let mut seq_enc = Encoder::new(cfg.clone()).unwrap();
981        let seq: Vec<Vec<u8>> = frames.iter().map(|f| seq_enc.encode(f)).collect();
982        let par = Encoder::new(cfg).unwrap().encode_all(&frames).unwrap();
983        assert_eq!(seq, par, "quality-preset GOP-parallel must equal sequential");
984    }
985
986    #[test]
987    fn rejects_mismatched_frame() {
988        let cfg = EncoderConfig::new(16, 16);
989        let mut enc = Encoder::new(cfg).unwrap();
990        let frame = YuvFrame::black(32, 16);
991        assert_eq!(enc.try_encode(&frame), Err(EncodeError::FrameMismatch));
992    }
993}