Skip to main content

oxideav_vp8/encoder/
effort.rs

1//! Search-effort levels for the intra (key-frame) encoder and the
2//! model-driven per-macroblock search the reduced levels run.
3//!
4//! RFC 6386 specifies decoding only; how much work an encoder spends
5//! choosing among the §12 prediction modes is its own business. The
6//! exhaustive search ([`EncodeEffort::Thorough`]) carries
7//! every candidate mode through transform, §13 trellis quantisation,
8//! reconstruction and exact token pricing. The reduced levels replace
9//! that per-candidate chain with a closed-form cost model:
10//!
11//! * **distortion** — the squared quantisation error of each transform
12//!   coefficient under plain rounding, weighted by the energy its basis
13//!   vector carries into the pixel domain (the same weights the trellis
14//!   uses for 4×4 DCT blocks; a flat `1/16` for the Y2 block, whose
15//!   coefficients each spread over all 256 luma pixels through the
16//!   inverse WHT and the DC-only inverse DCT);
17//! * **rate** — the §13.3 token bits of the rounded levels, read from the
18//!   per-frame rate tables along the real context chain.
19//!
20//! Only the winning mode is then quantised for real (through the trellis
21//! where the level keeps it). The fastest levels additionally shortlist
22//! candidates by the squared prediction error before the model sees them.
23//!
24//! Every level produces a conformant stream; for a given level the bytes
25//! do not depend on the thread budget.
26
27use super::{
28    BMODE_CANDIDATES, BlockType, COEFF_BANDS, ENC_BPRED_ORIGIN, ENC_BPRED_STRIDE,
29    IDCT_BASIS_NORM_SQ, IntraBmode, IntraUvMode, IntraYMode, KF_BMODE_BITS, KF_UV_MODE_PROB,
30    KF_YMODE_PATHS, KF_YMODE_PROB, MbAnalysis, MbCoeffs, MbPixels, MbRdCtx, TrellisBlockSpec,
31    TrellisRateTables, TrellisStrength, UV_MODE_PATHS, block_ssd, build_enc_bpred_buffer,
32    forward_dct_4x4, forward_wht_4x4, predict_b4x4, predict_uv8x8, predict_y16x16,
33    reconstruct_block_4x4, rounded_level, transform_chroma_plane_rd, transform_whole_block_luma_rd,
34    treed_bits_cached, trellis_quantize_block,
35};
36use crate::coded_header::TokenProbUpdates;
37use crate::intra_predict::DEFAULT_ABOVE_PIXEL;
38use crate::reconstruct::MbNeighbors;
39
40/// How much mode search the key-frame encoder spends per macroblock.
41///
42/// The levels trade output size for encode time; all of them emit a
43/// conformant RFC 6386 key frame that this crate's decoder (and any
44/// other) reconstructs to exactly the picture the encoder predicted
45/// from. [`Balanced`](Self::Balanced) is the default;
46/// [`Thorough`](Self::Thorough) is the search of the option-less entry
47/// points. See the crate README for the measured time / size / quality
48/// of each level.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
50#[non_exhaustive]
51pub enum EncodeEffort {
52    /// Level 0. Modes are shortlisted by squared prediction error (the
53    /// best two of the ten §12.3 sub-block modes, the single best §12.2
54    /// luma and chroma mode); the survivors are compared with the cost
55    /// model; coefficients are plain-rounded — the §13 trellis is off
56    /// regardless of [`TrellisStrength`]. `B_PRED` is not searched for a
57    /// macroblock whose best whole-block mode leaves no luma AC residual.
58    Fastest,
59    /// Level 1. As [`Fastest`](Self::Fastest) but the cost model sees the
60    /// best four sub-block modes and all §12.2 luma / chroma modes, and
61    /// the winners are trellis-quantised.
62    Fast,
63    /// Level 2 (default). Every candidate mode is compared with the cost
64    /// model; only the winners go through the trellis and
65    /// reconstruction. About half the time of
66    /// [`Thorough`](Self::Thorough) for the same picture quality within
67    /// a percent of its size.
68    #[default]
69    Balanced,
70    /// Level 3. Exhaustive rate-distortion search: every candidate is
71    /// transformed, trellis-quantised, reconstructed and priced exactly
72    /// — the search of the option-less entry points.
73    Thorough,
74}
75
76impl EncodeEffort {
77    /// The numeric level, `0` (fastest) ..= `3` (thorough).
78    pub const fn level(self) -> u8 {
79        match self {
80            EncodeEffort::Fastest => 0,
81            EncodeEffort::Fast => 1,
82            EncodeEffort::Balanced => 2,
83            EncodeEffort::Thorough => 3,
84        }
85    }
86
87    /// The level for a number: `0`, `1`, `2`, and [`Thorough`](Self::Thorough)
88    /// for `3` and anything above.
89    pub const fn from_level(level: u8) -> Self {
90        match level {
91            0 => EncodeEffort::Fastest,
92            1 => EncodeEffort::Fast,
93            2 => EncodeEffort::Balanced,
94            _ => EncodeEffort::Thorough,
95        }
96    }
97
98    /// The level's lower-case name (`"fastest"`, `"fast"`, `"balanced"`,
99    /// `"thorough"`) — the spelling the registry `effort` option accepts.
100    pub const fn name(self) -> &'static str {
101        match self {
102            EncodeEffort::Fastest => "fastest",
103            EncodeEffort::Fast => "fast",
104            EncodeEffort::Balanced => "balanced",
105            EncodeEffort::Thorough => "thorough",
106        }
107    }
108
109    /// Parse a level from its [`name`](Self::name) or its decimal number.
110    pub fn parse(text: &str) -> Option<Self> {
111        match text {
112            "fastest" | "0" => Some(EncodeEffort::Fastest),
113            "fast" | "1" => Some(EncodeEffort::Fast),
114            "balanced" | "2" => Some(EncodeEffort::Balanced),
115            "thorough" | "3" => Some(EncodeEffort::Thorough),
116            _ => None,
117        }
118    }
119
120    /// All levels, fastest first.
121    pub const ALL: [EncodeEffort; 4] = [
122        EncodeEffort::Fastest,
123        EncodeEffort::Fast,
124        EncodeEffort::Balanced,
125        EncodeEffort::Thorough,
126    ];
127
128    /// The model-search shape of a reduced level (`None` for
129    /// [`Thorough`](Self::Thorough), which does not use the model).
130    fn model_search(self) -> Option<ModelSearch> {
131        match self {
132            EncodeEffort::Fastest => Some(ModelSearch {
133                bmode_shortlist: 2,
134                whole_modes_by_prediction_error: true,
135                skip_bpred_without_luma_ac: true,
136                trellis: false,
137            }),
138            EncodeEffort::Fast => Some(ModelSearch {
139                bmode_shortlist: 4,
140                whole_modes_by_prediction_error: false,
141                skip_bpred_without_luma_ac: true,
142                trellis: true,
143            }),
144            EncodeEffort::Balanced => Some(ModelSearch {
145                bmode_shortlist: BMODE_CANDIDATES.len(),
146                whole_modes_by_prediction_error: false,
147                skip_bpred_without_luma_ac: false,
148                trellis: true,
149            }),
150            EncodeEffort::Thorough => None,
151        }
152    }
153}
154
155/// Controls for one key-frame encode — the options the
156/// `encode_keyframe_with_options` family takes next to
157/// [`KeyframeParams`](super::KeyframeParams).
158///
159/// `Default` is the recommended still-picture encode: the default
160/// [`EncodeEffort`], serial, the loop filter of the `KeyframeParams`,
161/// and the §13.4 token probabilities fitted to the picture within the
162/// one search ([`token_prob_fit`](Self::token_prob_fit)).
163/// [`KeyframeEncodeOptions::exhaustive`] is the option-less
164/// [`encode_keyframe`](super::encode_keyframe), byte for byte.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166#[non_exhaustive]
167pub struct KeyframeEncodeOptions {
168    /// Mode-search effort.
169    pub effort: EncodeEffort,
170    /// Thread budget for the encode. `0` and `1` both mean serial (the
171    /// default); with `n > 1` the macroblock analysis runs as a
172    /// macroblock-row wavefront on up to `n` threads (scoped
173    /// `std::thread`s that end with the call). The output bytes are the
174    /// same for every budget.
175    pub threads: usize,
176    /// Measure every §9.4 loop-filter level / sharpness candidate on the
177    /// reconstruction and keep the best (ignoring
178    /// `KeyframeParams::loop_filter_level`), as
179    /// [`encode_keyframe_auto_loop_filter`](super::encode_keyframe_auto_loop_filter) does.
180    pub auto_loop_filter: bool,
181    /// Run the mode search a second time against the token probabilities
182    /// fitted to the first search, and keep the smaller stream (roughly
183    /// doubles the encode time for a further few tenths of a percent;
184    /// [`encode_keyframe_with_fitted_token_prob_updates`](super::encode_keyframe_with_fitted_token_prob_updates)
185    /// is this with the exhaustive search).
186    pub fitted_token_prob_updates: bool,
187    /// Fit the §13.4 token-probability updates to the token statistics
188    /// of the search itself and code the tokens against the fitted
189    /// table (on by default). The search records its token decisions
190    /// instead of bits, so this costs one walk over the recorded
191    /// decisions — no second search — and never enlarges the stream:
192    /// an update ships only where it saves more bits than it costs.
193    pub token_prob_fit: bool,
194    /// §13.4 updates the mode search prices tokens against instead of
195    /// the §13.5 defaults — typically the
196    /// [`KeyframeEncoded::token_prob_updates`] a similar picture (the
197    /// previous frame, a neighbouring tile, a first quick encode) came
198    /// out with. With [`token_prob_fit`](Self::token_prob_fit) they only
199    /// steer the search and the stream carries this picture's own fit;
200    /// without it they are shipped as given.
201    pub search_token_probs: Option<TokenProbUpdates>,
202    /// Choose the §9.4 loop-filter level and sharpness on a sample of
203    /// the picture (three to six bands of macroblock rows spread over
204    /// its height, searched coarse to fine), ignoring
205    /// `KeyframeParams::loop_filter_level` — most of the gain of
206    /// [`auto_loop_filter`](Self::auto_loop_filter) for a small fraction
207    /// of its time. `auto_loop_filter` takes precedence when both are
208    /// set.
209    pub sampled_loop_filter: bool,
210}
211
212impl Default for KeyframeEncodeOptions {
213    fn default() -> Self {
214        KeyframeEncodeOptions {
215            effort: EncodeEffort::default(),
216            threads: 0,
217            auto_loop_filter: false,
218            fitted_token_prob_updates: false,
219            token_prob_fit: true,
220            search_token_probs: None,
221            sampled_loop_filter: false,
222        }
223    }
224}
225
226impl KeyframeEncodeOptions {
227    /// The defaults: the default [`EncodeEffort`], serial, token
228    /// probabilities fitted in the one search.
229    pub fn new() -> Self {
230        Self::default()
231    }
232
233    /// The exhaustive encode of the option-less entry points:
234    /// [`EncodeEffort::Thorough`], serial, the §13.5 default token
235    /// probabilities — the bytes of
236    /// [`encode_keyframe`](super::encode_keyframe).
237    pub fn exhaustive() -> Self {
238        Self::default()
239            .with_effort(EncodeEffort::Thorough)
240            .with_token_prob_fit(false)
241    }
242
243    /// Set `effort`.
244    #[must_use]
245    pub fn with_effort(mut self, v: EncodeEffort) -> Self {
246        self.effort = v;
247        self
248    }
249
250    /// Set `threads`.
251    #[must_use]
252    pub fn with_threads(mut self, v: usize) -> Self {
253        self.threads = v;
254        self
255    }
256
257    /// Set `auto_loop_filter`.
258    #[must_use]
259    pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
260        self.auto_loop_filter = v;
261        self
262    }
263
264    /// Set `fitted_token_prob_updates`.
265    #[must_use]
266    pub fn with_fitted_token_prob_updates(mut self, v: bool) -> Self {
267        self.fitted_token_prob_updates = v;
268        self
269    }
270
271    /// Set `token_prob_fit`.
272    #[must_use]
273    pub fn with_token_prob_fit(mut self, v: bool) -> Self {
274        self.token_prob_fit = v;
275        self
276    }
277
278    /// Set `search_token_probs`.
279    #[must_use]
280    pub fn with_search_token_probs(mut self, v: Option<TokenProbUpdates>) -> Self {
281        self.search_token_probs = v;
282        self
283    }
284
285    /// Set `sampled_loop_filter`.
286    #[must_use]
287    pub fn with_sampled_loop_filter(mut self, v: bool) -> Self {
288        self.sampled_loop_filter = v;
289        self
290    }
291}
292
293/// A finished key-frame encode with what the encoder settled on along
294/// the way — the result of
295/// [`encode_keyframe_detailed`](super::encode_keyframe_detailed).
296#[derive(Debug, Clone)]
297#[non_exhaustive]
298pub struct KeyframeEncoded {
299    /// The VP8 key frame.
300    pub bytes: Vec<u8>,
301    /// The macroblock-aligned post-§15 reconstruction — the planes a
302    /// decoder rebuilds from `bytes`.
303    pub reconstruction: crate::frame::KeyframePlanes,
304    /// The §13.4 token-probability updates the frame carries (`None`
305    /// when it codes against the §13.5 defaults). Feed them to
306    /// [`KeyframeEncodeOptions::with_search_token_probs`] for the next
307    /// similar picture.
308    pub token_prob_updates: Option<TokenProbUpdates>,
309    /// The §9.4 `loop_filter_level` in the frame header.
310    pub loop_filter_level: u8,
311    /// The §9.4 `sharpness_level` in the frame header.
312    pub sharpness_level: u8,
313}
314
315/// Shape of the model-driven search at one reduced effort level.
316#[derive(Clone, Copy)]
317struct ModelSearch {
318    /// How many §12.3 sub-block modes (ranked by squared prediction
319    /// error plus mode-signal cost) the cost model compares; all ten
320    /// when equal to the candidate count.
321    bmode_shortlist: usize,
322    /// Choose the §12.2 luma and chroma modes by squared prediction
323    /// error (plus mode-signal cost) instead of the cost model.
324    whole_modes_by_prediction_error: bool,
325    /// Do not search `B_PRED` when the whole-block winner quantises to
326    /// no luma AC coefficient.
327    skip_bpred_without_luma_ac: bool,
328    /// Trellis-quantise the winners (else plain rounding).
329    trellis: bool,
330}
331
332/// Fixed-point scale of the model's distortion weights.
333pub(super) const WEIGHT_SCALE: f64 = 4096.0;
334
335/// The trellis's inverse-DCT basis energies ([`IDCT_BASIS_NORM_SQ`], by
336/// scan position) in `1/4096` fixed point, so the model's distortion is
337/// an exact integer sum.
338pub(super) static DCT_WEIGHTS: std::sync::LazyLock<[u64; 16]> = std::sync::LazyLock::new(|| {
339    let norms = &*IDCT_BASIS_NORM_SQ;
340    core::array::from_fn(|k| (norms[k] * WEIGHT_SCALE).round() as u64)
341});
342
343/// Pixel-domain energy one unit of error in a Y2 (WHT) coefficient
344/// injects, in `1/4096` fixed point: the inverse WHT moves each of the
345/// sixteen sub-block DCs by `1/8`, and a DC-only inverse DCT moves each
346/// of that sub-block's sixteen pixels by a further `1/8` — 256 pixels at
347/// `1/64` each, i.e. `1/16` per unit squared.
348pub(super) const Y2_WEIGHTS: [u64; 16] = [(WEIGHT_SCALE / 16.0) as u64; 16];
349
350/// What the cost model says about one plain-rounded block.
351pub(super) struct BlockModel {
352    /// Weighted squared rounding error of the coded positions, in
353    /// `1/4096` units ([`WEIGHT_SCALE`]).
354    pub(super) dist: u64,
355    /// The same error with every level forced to zero.
356    pub(super) dist_zero: u64,
357    /// §13.3 token bits of the rounded levels, through the end-of-block
358    /// token.
359    pub(super) rate: f64,
360    /// Whether any level is non-zero.
361    pub(super) nonzero: bool,
362}
363
364/// Plain-round one raster-order coefficient block in place and model its
365/// cost: the weighted squared rounding error over the coded positions
366/// (`first_coeff..16`) and the §13.3 token bits of the rounded levels
367/// from `spec.entry_ctx3` through the end-of-block token. The levels
368/// written are exactly what [`enc_quantize_block`](super::enc_quantize_block)
369/// produces (positions below `first_coeff` are zeroed).
370pub(super) fn model_block_parts(
371    block: &mut [i16; 16],
372    spec: TrellisBlockSpec,
373    weights: &[u64; 16],
374    tables: &TrellisRateTables,
375) -> BlockModel {
376    let first = spec.first_coeff;
377    debug_assert!(first <= 1, "§13.3 blocks start at coefficient 0 or 1");
378    let (dc_q, ac_q) = (spec.dc as u32, spec.ac as u32);
379    // Magnitudes in scan order (an uncoded position 0 counts as zero),
380    // the all-zero distortion, and whether any coded position rounds to
381    // a level (`|x| + q/2 >= q`, i.e. `|x| >= q − q/2`). All-zero is the
382    // common case on inter residue and is settled here without a
383    // division.
384    let zigzag = &crate::dct_tokens::ZIGZAG;
385    let mut magnitude = [0u32; 16];
386    for (m, &pos) in magnitude.iter_mut().zip(zigzag.iter()) {
387        *m = block[pos].unsigned_abs() as u32;
388    }
389    if first != 0 {
390        magnitude[0] = 0;
391    }
392    let mut thresholds = [ac_q - ac_q / 2; 16];
393    thresholds[0] = dc_q - dc_q / 2;
394    let mut dist_zero = 0u64;
395    let mut any_level = false;
396    for k in 0..16 {
397        let ax = magnitude[k];
398        dist_zero += weights[k] * (ax as u64 * ax as u64);
399        any_level |= ax >= thresholds[k];
400    }
401    let mut ctx3 = spec.entry_ctx3;
402    if !any_level {
403        let rate = tables.eob[spec.plane][COEFF_BANDS[first]][ctx3];
404        *block = [0i16; 16];
405        return BlockModel {
406            dist: dist_zero,
407            dist_zero,
408            rate,
409            nonzero: false,
410        };
411    }
412    let mut levels = [0u32; 16];
413    let mut negative = 0u32;
414    let mut coded = 0u32;
415    let mut dist = 0u64;
416    for k in first..16 {
417        let ax = magnitude[k];
418        let q = if k == 0 { dc_q } else { ac_q };
419        let level = rounded_level(ax, q);
420        let err = (ax as i64 - level as i64 * q as i64).unsigned_abs();
421        dist += weights[k] * err * err;
422        levels[k] = level;
423        negative |= ((block[crate::dct_tokens::ZIGZAG[k]] < 0) as u32) << k;
424        coded |= ((level != 0) as u32) << k;
425    }
426    *block = [0i16; 16];
427    let small = &tables.small[spec.plane];
428    debug_assert!(coded != 0, "a level at or past half a step rounds up");
429    let end = 32 - coded.leading_zeros() as usize;
430
431    let mut rate = 0.0;
432    let mut prev_was_zero = 0usize;
433    for k in first..end {
434        let level = levels[k];
435        let band = COEFF_BANDS[k];
436        rate += if level <= super::TRELLIS_SMALL_LEVEL_MAX as u32 {
437            small[band][ctx3][prev_was_zero][level as usize]
438        } else {
439            TrellisRateTables::level_rate(
440                &small[band],
441                &tables.cat_path[spec.plane][band],
442                ctx3,
443                prev_was_zero == 1,
444                level,
445            )
446        };
447        ctx3 = (level as usize).min(2);
448        prev_was_zero = (level == 0) as usize;
449        let signed = level as i16;
450        block[crate::dct_tokens::ZIGZAG[k]] = if (negative >> k) & 1 != 0 {
451            -signed
452        } else {
453            signed
454        };
455    }
456    if end < 16 {
457        rate += tables.eob[spec.plane][COEFF_BANDS[end]][ctx3];
458    }
459    BlockModel {
460        dist,
461        dist_zero,
462        rate,
463        nonzero: true,
464    }
465}
466
467/// The cost `D + lambda·R` [`model_block_parts`] models for a block and
468/// whether any level is non-zero, without writing the levels — the form
469/// the key-frame search compares candidates with.
470///
471/// Same model, evaluated through the block's sparsity: a position whose
472/// magnitude rounds to zero contributes its full squared magnitude to
473/// the distortion and a `DCT_0` token to the rate, so the all-zero
474/// totals are formed first (one branch-free pass that also marks the
475/// positions that round to a level), and only the marked positions are
476/// then visited to exchange their zero terms for the real ones. The
477/// zeros between two levels are priced from the per-plane run table.
478/// (The rate is summed in a different order than `model_block_parts`
479/// sums it, so the two agree to rounding, not bit for bit.)
480#[inline]
481pub(super) fn model_block_cost(
482    block: &[i16; 16],
483    spec: TrellisBlockSpec,
484    weights: &[u64; 16],
485    tables: &TrellisRateTables,
486    lambda: f64,
487) -> (f64, bool) {
488    let first = spec.first_coeff;
489    debug_assert!(first <= 1, "§13.3 blocks start at coefficient 0 or 1");
490    let (dc_q, ac_q) = (spec.dc as u32, spec.ac as u32);
491    let mut magnitude = [0u32; 16];
492    for (m, &pos) in magnitude.iter_mut().zip(crate::dct_tokens::ZIGZAG.iter()) {
493        *m = block[pos].unsigned_abs() as u32;
494    }
495    if first != 0 {
496        magnitude[0] = 0;
497    }
498    // `|x| + q/2 >= q` ⇔ the magnitude rounds to a level.
499    let mut thresholds = [ac_q - ac_q / 2; 16];
500    thresholds[0] = dc_q - dc_q / 2;
501    let mut dist = 0u64;
502    let mut coded = 0u32;
503    for k in 0..16 {
504        let ax = magnitude[k];
505        dist += weights[k] * (ax as u64 * ax as u64);
506        coded |= ((ax >= thresholds[k]) as u32) << k;
507    }
508    let plane = spec.plane;
509    let eob = &tables.eob[plane];
510    let mut ctx3 = spec.entry_ctx3;
511    if coded == 0 {
512        let rate = eob[COEFF_BANDS[first]][ctx3];
513        return (dist as f64 / WEIGHT_SCALE + lambda * rate, false);
514    }
515    let small = &tables.small[plane];
516    let zero_run = &tables.zero_run[plane];
517    let mut rate = 0.0;
518    let mut pos = first;
519    let mut after_zero = 0usize;
520    let mut pending = coded;
521    while pending != 0 {
522        let k = pending.trailing_zeros() as usize;
523        pending &= pending - 1;
524        if k > pos {
525            // The first zero of the run sees the carried context; the
526            // rest follow a zero.
527            rate += small[COEFF_BANDS[pos]][ctx3][after_zero][0];
528            rate += zero_run[k] - zero_run[pos + 1];
529            ctx3 = 0;
530            after_zero = 1;
531        }
532        let ax = magnitude[k];
533        let q = if k == 0 { dc_q } else { ac_q };
534        let level = rounded_level(ax, q);
535        let err = (ax as i64 - level as i64 * q as i64).unsigned_abs();
536        // `|err| <= q/2 <= ax`, so the exchange never underflows.
537        dist -= weights[k] * (ax as u64 * ax as u64 - err * err);
538        let band = COEFF_BANDS[k];
539        rate += if level <= super::TRELLIS_SMALL_LEVEL_MAX as u32 {
540            small[band][ctx3][after_zero][level as usize]
541        } else {
542            TrellisRateTables::level_rate(
543                &small[band],
544                &tables.cat_path[plane][band],
545                ctx3,
546                after_zero == 1,
547                level,
548            )
549        };
550        ctx3 = (level as usize).min(2);
551        after_zero = 0;
552        pos = k + 1;
553    }
554    if pos < 16 {
555        rate += eob[COEFF_BANDS[pos]][ctx3];
556    }
557    (dist as f64 / WEIGHT_SCALE + lambda * rate, true)
558}
559
560/// Forward-DCT the 4×4 residual `src − pred` at `(row, col)` of two
561/// equally laid out `stride`-wide pixel blocks.
562#[inline]
563pub(super) fn residual_dct(
564    src: &[u8],
565    pred: &[u8],
566    stride: usize,
567    row: usize,
568    col: usize,
569) -> [i16; 16] {
570    let mut residual = [0i16; 16];
571    for r in 0..4 {
572        let off = (row + r) * stride + col;
573        for c in 0..4 {
574            residual[r * 4 + c] = src[off + c] as i16 - pred[off + c] as i16;
575        }
576    }
577    let mut coeffs = [0i16; 16];
578    forward_dct_4x4(&residual, &mut coeffs);
579    coeffs
580}
581
582/// Model cost of coding the luma plane with one §12.2 whole-block
583/// prediction (mode-signal bits excluded), and whether any luma AC
584/// level survives rounding — or `None` as soon as the running cost
585/// reaches `budget` (block costs are non-negative, so the total could
586/// only be at or above it: the candidate cannot win a strict comparison
587/// against a cost of `budget`).
588fn model_whole_luma(
589    src: &[u8; 256],
590    pred: &[u8; 256],
591    rd: &MbRdCtx,
592    tables: &TrellisRateTables,
593    budget: f64,
594) -> Option<(f64, bool)> {
595    let factors = rd.factors;
596    let dct_weights = &*DCT_WEIGHTS;
597    let mut dcs = [0i16; 16];
598    let mut above = [false; 4];
599    let mut left = [false; 4];
600    let mut cost = 0.0;
601    let mut any_ac = false;
602    for i in 0..4 {
603        for j in 0..4 {
604            let mut coeffs = residual_dct(src, pred, 16, i * 4, j * 4);
605            dcs[i * 4 + j] = coeffs[0];
606            coeffs[0] = 0;
607            let (c, nonzero) = model_block_cost(
608                &coeffs,
609                TrellisBlockSpec {
610                    dc: factors.y1_dc,
611                    ac: factors.y1_ac,
612                    first_coeff: BlockType::YAfterY2.first_coeff(),
613                    entry_ctx3: above[j] as usize + left[i] as usize,
614                    plane: BlockType::YAfterY2.plane_index(),
615                },
616                dct_weights,
617                tables,
618                rd.lambda,
619            );
620            cost += c;
621            above[j] = nonzero;
622            left[i] = nonzero;
623            any_ac |= nonzero;
624        }
625        if cost >= budget {
626            return None;
627        }
628    }
629    let mut y2 = [0i16; 16];
630    forward_wht_4x4(&dcs, &mut y2);
631    let (c, _) = model_block_cost(
632        &y2,
633        TrellisBlockSpec {
634            dc: factors.y2_dc,
635            ac: factors.y2_ac,
636            first_coeff: BlockType::Y2.first_coeff(),
637            entry_ctx3: 0,
638            plane: BlockType::Y2.plane_index(),
639        },
640        &Y2_WEIGHTS,
641        tables,
642        rd.lambda,
643    );
644    Some((cost + c, any_ac))
645}
646
647/// Model cost of coding one 8×8 chroma plane against `pred`.
648fn model_chroma_plane(
649    src: &[u8; 64],
650    pred: &[u8; 64],
651    rd: &MbRdCtx,
652    tables: &TrellisRateTables,
653) -> f64 {
654    let factors = rd.factors;
655    let dct_weights = &*DCT_WEIGHTS;
656    let mut above = [false; 2];
657    let mut left = [false; 2];
658    let mut cost = 0.0;
659    for (i, left_nonzero) in left.iter_mut().enumerate() {
660        for (j, above_nonzero) in above.iter_mut().enumerate() {
661            let coeffs = residual_dct(src, pred, 8, i * 4, j * 4);
662            let (c, nonzero) = model_block_cost(
663                &coeffs,
664                TrellisBlockSpec {
665                    dc: factors.uv_dc,
666                    ac: factors.uv_ac,
667                    first_coeff: BlockType::UV.first_coeff(),
668                    entry_ctx3: *above_nonzero as usize + *left_nonzero as usize,
669                    plane: BlockType::UV.plane_index(),
670                },
671                dct_weights,
672                tables,
673                rd.lambda,
674            );
675            cost += c;
676            *above_nonzero = nonzero;
677            *left_nonzero = nonzero;
678        }
679    }
680    cost
681}
682
683/// The §11.3 sub-block-mode contexts a macroblock inherits: the modes
684/// of the four sub-blocks directly above it and directly to its left
685/// (a whole-block neighbour contributes the §11.3 projection of its
686/// mode, a neighbour outside the frame `B_DC_PRED`) — the contexts the
687/// mode layer codes the top-row and left-column sub-modes against.
688pub(super) struct BmodeContext {
689    pub(super) above: [IntraBmode; 4],
690    pub(super) left: [IntraBmode; 4],
691}
692
693/// Outcome of the model-driven `B_PRED` pass.
694struct ModelBpred {
695    modes: [IntraBmode; 16],
696    y_coeffs: [[i16; 16]; 16],
697    cost: f64,
698}
699
700/// `B_PRED` with model-driven sub-mode choice. The sub-mode signal cost
701/// is priced against the real §11.3 contexts, including the neighbouring
702/// macroblocks' (`bmode_ctx`). Per sub-block the
703/// candidate modes (all ten, or the `shortlist` best by squared
704/// prediction error plus mode-signal cost) are compared by model cost;
705/// the winner is then quantised for real against the §13.3 neighbour
706/// context, reconstructed, and written back so later sub-blocks predict
707/// from the pixels the decoder will hold. Returns `None` as soon as the
708/// running cost reaches `budget` (sub-block costs are non-negative).
709fn model_bpred_luma(
710    src: &[u8; 256],
711    neighbors: &MbNeighbors,
712    bmode_ctx: &BmodeContext,
713    rd: &MbRdCtx,
714    tables: &TrellisRateTables,
715    search: ModelSearch,
716    budget: f64,
717) -> Option<ModelBpred> {
718    let factors = rd.factors;
719    let mut buf = build_enc_bpred_buffer(neighbors);
720    let mut modes = [IntraBmode::Dc; 16];
721    let mut y_coeffs = [[0i16; 16]; 16];
722    let mut total = 0.0;
723    let mut tok_above = [false; 4];
724    let mut tok_left = [false; 4];
725    let trellis = search.trellis && rd.trellis_active();
726    let bmode_bits = &*KF_BMODE_BITS;
727    let dct_weights = &*DCT_WEIGHTS;
728
729    for i in 0..4 {
730        for j in 0..4 {
731            let idx = i * 4 + j;
732            let sb_base = ENC_BPRED_ORIGIN + (i * 4) * ENC_BPRED_STRIDE + (j * 4);
733            let above_base = sb_base - ENC_BPRED_STRIDE;
734            let mut above = [0u8; 8];
735            above.copy_from_slice(&buf[above_base..above_base + 8]);
736            let mut left = [0u8; 4];
737            for (r, slot) in left.iter_mut().enumerate() {
738                *slot = buf[sb_base + r * ENC_BPRED_STRIDE - 1];
739            }
740            let corner = buf[above_base - 1];
741            let mut sb_src = [0u8; 16];
742            for r in 0..4 {
743                let off = (i * 4 + r) * 16 + j * 4;
744                sb_src[r * 4..r * 4 + 4].copy_from_slice(&src[off..off + 4]);
745            }
746            let above_mode = if i == 0 {
747                bmode_ctx.above[j]
748            } else {
749                modes[(i - 1) * 4 + j]
750            };
751            let left_mode = if j == 0 {
752                bmode_ctx.left[i]
753            } else {
754                modes[i * 4 + (j - 1)]
755            };
756            let mode_bits = &bmode_bits[above_mode.idx()][left_mode.idx()];
757
758            // Predictions, mode-signal cost, and (for a shortlist) the
759            // squared-prediction-error ranking key of every sub-mode.
760            let mut preds = [[0u8; 16]; 10];
761            let mut mode_cost = [0f64; 10];
762            let mut order = [0usize; 10];
763            let mut rank = [0f64; 10];
764            let shortlisted = search.bmode_shortlist < BMODE_CANDIDATES.len();
765            for (n, &mode) in BMODE_CANDIDATES.iter().enumerate() {
766                predict_b4x4(&mut preds[n], mode, &above, &left, corner);
767                mode_cost[n] = rd.lambda * mode_bits[mode.idx()];
768                order[n] = n;
769                if shortlisted {
770                    rank[n] = block_ssd(&preds[n], &sb_src) as f64 + mode_cost[n];
771                }
772            }
773            let considered = if shortlisted {
774                // Stable selection of the `bmode_shortlist` smallest keys
775                // (ties keep `BMODE_CANDIDATES` order).
776                for slot in 0..search.bmode_shortlist {
777                    let mut best = slot;
778                    for probe in slot + 1..order.len() {
779                        if rank[order[probe]] < rank[order[best]] {
780                            best = probe;
781                        }
782                    }
783                    order[slot..=best].rotate_right(1);
784                }
785                search.bmode_shortlist
786            } else {
787                order.len()
788            };
789
790            let entry_ctx3 = tok_above[j] as usize + tok_left[i] as usize;
791            let spec = TrellisBlockSpec {
792                dc: factors.y1_dc,
793                ac: factors.y1_ac,
794                first_coeff: BlockType::YNoY2.first_coeff(),
795                entry_ctx3,
796                plane: BlockType::YNoY2.plane_index(),
797            };
798            let mut best_n = order[0];
799            let mut best_cost = f64::INFINITY;
800            let mut best_dct = [0i16; 16];
801            for &n in &order[..considered] {
802                let mut residual = [0i16; 16];
803                for k in 0..16 {
804                    residual[k] = sb_src[k] as i16 - preds[n][k] as i16;
805                }
806                let mut dct = [0i16; 16];
807                forward_dct_4x4(&residual, &mut dct);
808                let (c, _) = model_block_cost(&dct, spec, dct_weights, tables, rd.lambda);
809                let cost = c + mode_cost[n];
810                if cost < best_cost {
811                    best_cost = cost;
812                    best_n = n;
813                    best_dct = dct;
814                }
815            }
816
817            if total + best_cost >= budget {
818                return None;
819            }
820            // Quantise the winner for real.
821            let coeffs = if trellis {
822                let mut c = best_dct;
823                trellis_quantize_block(
824                    &mut c,
825                    spec,
826                    rd.coeff_probs,
827                    Some(tables),
828                    rd.trellis_lambda(),
829                );
830                c
831            } else {
832                let mut c = best_dct;
833                super::enc_quantize_block_range(&mut c, spec.dc, spec.ac, spec.first_coeff);
834                c
835            };
836            let recon =
837                reconstruct_block_4x4(&preds[best_n], &coeffs, factors.y1_dc, factors.y1_ac);
838            modes[idx] = BMODE_CANDIDATES[best_n];
839            y_coeffs[idx] = coeffs;
840            total += best_cost;
841            let nonzero = coeffs.iter().any(|&v| v != 0);
842            tok_above[j] = nonzero;
843            tok_left[i] = nonzero;
844            for r in 0..4 {
845                let dst = sb_base + r * ENC_BPRED_STRIDE;
846                buf[dst..dst + 4].copy_from_slice(&recon[r * 4..r * 4 + 4]);
847            }
848        }
849    }
850    Some(ModelBpred {
851        modes,
852        y_coeffs,
853        cost: total,
854    })
855}
856
857/// The model-driven per-macroblock search of the reduced effort levels.
858/// `rd.rate_tables` must be present (every frame driver attaches them).
859pub(super) fn analyze_mb_model(
860    pixels: &MbPixels,
861    neighbors: &MbNeighbors,
862    bmode_ctx: &BmodeContext,
863    rd: &MbRdCtx,
864    effort: EncodeEffort,
865) -> MbAnalysis {
866    let search = effort
867        .model_search()
868        .expect("the exhaustive level does not use the model search");
869    let tables = rd
870        .rate_tables
871        .expect("frame drivers attach the per-frame rate tables");
872    // The context the winners are quantised with: the caller's, or the
873    // same with the trellis switched off.
874    let plain = MbRdCtx {
875        factors: rd.factors,
876        coeff_probs: rd.coeff_probs,
877        rate_tables: rd.rate_tables,
878        lambda: rd.lambda,
879        trellis: TrellisStrength::OFF,
880    };
881    let final_rd = if search.trellis { rd } else { &plain };
882    let corner = DEFAULT_ABOVE_PIXEL;
883
884    // ---- §12.2 whole-block luma ------------------------------------
885    const Y_MODES: [IntraYMode; 4] = [IntraYMode::Dc, IntraYMode::V, IntraYMode::H, IntraYMode::Tm];
886    let ymode_paths = &*KF_YMODE_PATHS;
887    let y_mode_cost = |mode: IntraYMode| {
888        rd.lambda * treed_bits_cached(ymode_paths, |i| KF_YMODE_PROB[i], mode.leaf())
889    };
890    let mut y_preds = [[0u8; 256]; 4];
891    for (pred, &mode) in y_preds.iter_mut().zip(&Y_MODES) {
892        predict_y16x16(
893            pred,
894            mode,
895            neighbors.y_above.as_ref(),
896            neighbors.y_left.as_ref(),
897            neighbors.y_topleft.unwrap_or(corner),
898        )
899        .expect("whole-block modes only");
900    }
901    let mut whole_n = 0usize;
902    let mut whole_cost = f64::INFINITY;
903    let mut whole_has_ac = false;
904    if search.whole_modes_by_prediction_error {
905        let mut best_key = f64::INFINITY;
906        for (n, &mode) in Y_MODES.iter().enumerate() {
907            let key = block_ssd(&y_preds[n], &pixels.y) as f64 + y_mode_cost(mode);
908            if key < best_key {
909                best_key = key;
910                whole_n = n;
911            }
912        }
913        let (c, has_ac) = model_whole_luma(&pixels.y, &y_preds[whole_n], rd, tables, f64::INFINITY)
914            .expect("no budget");
915        whole_cost = c + y_mode_cost(Y_MODES[whole_n]);
916        whole_has_ac = has_ac;
917    } else {
918        for (n, &mode) in Y_MODES.iter().enumerate() {
919            // A mode whose partial cost already reaches the best total
920            // cannot replace it.
921            let signal = y_mode_cost(mode);
922            let Some((c, has_ac)) =
923                model_whole_luma(&pixels.y, &y_preds[n], rd, tables, whole_cost - signal)
924            else {
925                continue;
926            };
927            let cost = c + signal;
928            if cost < whole_cost {
929                whole_cost = cost;
930                whole_n = n;
931                whole_has_ac = has_ac;
932            }
933        }
934    }
935
936    // ---- §12.3 B_PRED ----------------------------------------------
937    let bpred = if search.skip_bpred_without_luma_ac && !whole_has_ac {
938        None
939    } else {
940        // `B_PRED` must come in strictly under the whole-block winner;
941        // the pass stops as soon as its running cost rules that out.
942        let signal = y_mode_cost(IntraYMode::B);
943        model_bpred_luma(
944            &pixels.y,
945            neighbors,
946            bmode_ctx,
947            final_rd,
948            tables,
949            search,
950            whole_cost - signal,
951        )
952        .filter(|pass| pass.cost + signal < whole_cost)
953    };
954
955    // ---- §12.2 chroma ----------------------------------------------
956    const UV_MODES: [IntraUvMode; 4] = [
957        IntraUvMode::Dc,
958        IntraUvMode::V,
959        IntraUvMode::H,
960        IntraUvMode::Tm,
961    ];
962    let uv_paths = &*UV_MODE_PATHS;
963    let mut uv_n = 0usize;
964    let mut uv_best = f64::INFINITY;
965    let mut u_preds = [[0u8; 64]; 4];
966    let mut v_preds = [[0u8; 64]; 4];
967    for (n, &mode) in UV_MODES.iter().enumerate() {
968        predict_uv8x8(
969            &mut u_preds[n],
970            mode,
971            neighbors.u_above.as_ref(),
972            neighbors.u_left.as_ref(),
973            neighbors.u_topleft.unwrap_or(corner),
974        );
975        predict_uv8x8(
976            &mut v_preds[n],
977            mode,
978            neighbors.v_above.as_ref(),
979            neighbors.v_left.as_ref(),
980            neighbors.v_topleft.unwrap_or(corner),
981        );
982        let mode_cost =
983            rd.lambda * treed_bits_cached(uv_paths, |i| KF_UV_MODE_PROB[i], mode.leaf());
984        let cost = mode_cost
985            + if search.whole_modes_by_prediction_error {
986                (block_ssd(&u_preds[n], &pixels.u) + block_ssd(&v_preds[n], &pixels.v)) as f64
987            } else {
988                // The second plane is only worth modelling while the
989                // mode can still come in under the best one.
990                let u_cost = model_chroma_plane(&pixels.u, &u_preds[n], rd, tables);
991                if mode_cost + u_cost >= uv_best {
992                    continue;
993                }
994                u_cost + model_chroma_plane(&pixels.v, &v_preds[n], rd, tables)
995            };
996        if cost < uv_best {
997            uv_best = cost;
998            uv_n = n;
999        }
1000    }
1001
1002    // ---- Quantise the winners --------------------------------------
1003    let mut coeffs = MbCoeffs::default();
1004    let (y_mode, b_modes) = match bpred {
1005        Some(pass) => {
1006            coeffs.y = pass.y_coeffs;
1007            (IntraYMode::B, Some(pass.modes))
1008        }
1009        None => {
1010            let (y, y2) = transform_whole_block_luma_rd(
1011                &pixels.y,
1012                &y_preds[whole_n],
1013                rd.factors,
1014                Some(final_rd),
1015            );
1016            coeffs.y = y;
1017            coeffs.y2 = y2;
1018            (Y_MODES[whole_n], None)
1019        }
1020    };
1021    coeffs.u = transform_chroma_plane_rd(&pixels.u, &u_preds[uv_n], rd.factors, Some(final_rd));
1022    coeffs.v = transform_chroma_plane_rd(&pixels.v, &v_preds[uv_n], rd.factors, Some(final_rd));
1023    MbAnalysis::from_coeffs(coeffs, y_mode, UV_MODES[uv_n], b_modes)
1024}
1025
1026#[cfg(test)]
1027mod tests {
1028    use super::super::enc_quantize_block;
1029    use super::*;
1030
1031    #[test]
1032    fn effort_levels_round_trip() {
1033        for (n, effort) in EncodeEffort::ALL.into_iter().enumerate() {
1034            assert_eq!(effort.level() as usize, n);
1035            assert_eq!(EncodeEffort::from_level(n as u8), effort);
1036            assert_eq!(EncodeEffort::parse(effort.name()), Some(effort));
1037            assert_eq!(EncodeEffort::parse(&n.to_string()), Some(effort));
1038        }
1039        assert_eq!(EncodeEffort::from_level(200), EncodeEffort::Thorough);
1040        assert_eq!(EncodeEffort::default(), EncodeEffort::Balanced);
1041        assert_eq!(EncodeEffort::parse("turbo"), None);
1042        assert!(EncodeEffort::Fastest < EncodeEffort::Thorough);
1043    }
1044
1045    /// The model's plain-rounded levels are the ones the reference
1046    /// rounding quantiser writes.
1047    #[test]
1048    fn model_levels_match_plain_rounding() {
1049        let tables = TrellisRateTables::for_probs(&crate::DEFAULT_COEFF_PROBS);
1050        let mut lcg = 0x2468_ACE1u32;
1051        for case in 0..4000 {
1052            let mut block = [0i16; 16];
1053            for c in block.iter_mut() {
1054                lcg = lcg.wrapping_mul(1_103_515_245).wrapping_add(12345);
1055                let span = [3i32, 40, 300, 4000][case % 4];
1056                *c = (((lcg >> 12) as i32).rem_euclid(2 * span + 1) - span) as i16;
1057            }
1058            let (dc, ac) = (
1059                [4i16, 9, 31, 157][case % 4],
1060                [4i16, 12, 37, 157][(case / 4) % 4],
1061            );
1062            for (block_type, first) in [(BlockType::YNoY2, 0usize), (BlockType::YAfterY2, 1)] {
1063                let mut want = block;
1064                if first == 1 {
1065                    want[0] = 0;
1066                }
1067                enc_quantize_block(&mut want, dc, ac);
1068                let mut got = block;
1069                let parts = model_block_parts(
1070                    &mut got,
1071                    TrellisBlockSpec {
1072                        dc,
1073                        ac,
1074                        first_coeff: first,
1075                        entry_ctx3: case % 3,
1076                        plane: block_type.plane_index(),
1077                    },
1078                    &DCT_WEIGHTS,
1079                    &tables,
1080                );
1081                let (cost, nonzero) = (
1082                    parts.dist as f64 / WEIGHT_SCALE + 7.5 * parts.rate,
1083                    parts.nonzero,
1084                );
1085                assert_eq!(got, want);
1086                assert_eq!(nonzero, want.iter().any(|&v| v != 0));
1087                assert!(cost.is_finite() && cost >= 0.0);
1088                // The sparse form prices the same model.
1089                let (sparse, sparse_nonzero) = model_block_cost(
1090                    &block,
1091                    TrellisBlockSpec {
1092                        dc,
1093                        ac,
1094                        first_coeff: first,
1095                        entry_ctx3: case % 3,
1096                        plane: block_type.plane_index(),
1097                    },
1098                    &DCT_WEIGHTS,
1099                    &tables,
1100                    7.5,
1101                );
1102                assert_eq!(sparse_nonzero, nonzero);
1103                assert!(
1104                    (sparse - cost).abs() <= 1e-9 * cost.max(1.0),
1105                    "sparse {sparse} vs reference {cost}"
1106                );
1107            }
1108        }
1109    }
1110}