forge
Explore
Log in

Don't you dare go Hollow

audit: assert equal lengths before every ours-vs-oracle walk (68 sites)

Browse files at this commit

b7b2e07f227a6f7b6bcc2c45c81a4d60629bad51Ahmet Kaan GümüşParent: e772a72
The prefix-truncation false PASS: an ours-vs-oracle compare that walks
`got.iter().zip(want)` without first asserting equal lengths reports EXACT
for any defect outside the compared prefix, because zip stops at the shorter
operand. A frame-count assert says nothing about a plane's byte length.

Audited 124 sites across ec-av1/ec-h264/ec-h265/ec-vp9/ec-alac/ec-flac/
ec-aac/ec-ac3 and tools/oracle: 68 UNSAFE, 38 SAFE, 18 N/A. 68 fixed by
inserting the length assert AFTER the existing diff assert, on the same
buffers, so a real divergence still fails for the same reason with the same
message and only the previously-silent short-plane case becomes loud. The
canonical shape already in the tree is decode_all_frames_vs_oracle.

encode.rs::first_difference returned None ("exact") for any length
mismatch; it now returns Some, copying first_plane_mismatch. encode.rs's
nine `encoded.frames` vs ffmpeg loops and two GOP zips gained the count
assert they never had. ec-h264's round_trip rejected only an over-long
frame, so a short one zipped to zero and four call sites printed
"bit-exact".

Truthfulness: a comment above stream.rs:29006 claimed the gate compared
every decode-order frame when it compares the shown ones; the pinned-
scratch loop truncated a three-way .min() silently; a message called a
shown-frame count "decode-order"; two frame-count asserts were tautological
and are now a comment; examples/dump_yuv.rs wears a decode-index filename
on a display index.

Red/green per crate in lanes/av1cmpaudit.report.md. Not pushed.

7 changed files +4637 -1990

crates/ec-av1/examples/dump_yuv.rsmodified+7 -0
@@ -36,6 +36,13 @@ fn main() {
3636 buf.extend_from_slice(&s.to_le_bytes());
3737 }
3838 }
39+ // `i` indexes `decode_stream`'s output, which is DISPLAY order and
40+ // SHOWN frames only -- hidden alt-refs are never emitted. Every other
41+ // `.f{N}` in this crate (EC_AV1_FINAL_DUMP, EC_AV1_DECODE_ORDER_DUMP,
42+ // EC_AV1_PREFILT_DUMP) uses a DECODE index, so this file does NOT line
43+ // up with an aomdec dump past frame 0 on a stream with altref. Compare
44+ // against ffmpeg rawvideo, or against aomdec via
45+ // `decode_all_frames_vs_oracle`.
3946 let name = format!("{out}.f{i}.yuv");
4047 if let Err(e) = std::fs::write(&name, &buf) {
4148 eprintln!("{name}: {e}");
crates/ec-av1/src/encode.rsmodified+3574 -1835

Diff too large; view file

@@ -40,12 +40,12 @@ use crate::sequence::sequence_header_obu;
4040 use crate::tile::{
4141 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
4242 };
43+#[cfg(test)]
44+use crate::transform::forward_and_quantize;
4345 use crate::transform::{
4446 TxType, dequant_and_inverse_typed_wh, forward_and_quantize_typed,
4547 forward_and_quantize_typed_scaled,
4648 };
47-#[cfg(test)]
48-use crate::transform::forward_and_quantize;
4949
5050 /// The side of the larger of the two luma blocks this encoder codes, in
5151 /// samples.
@@ -153,7 +153,10 @@ const HIDDEN_LAMBDA_FACTOR: f64 = 1.0;
153153
154154 /// [`HIDDEN_LAMBDA_FACTOR`], swept by `EC_AV1_LAMBDA_HIDDEN` in any build.
155155 fn hidden_lambda_factor() -> f64 {
156- match std::env::var("EC_AV1_LAMBDA_HIDDEN").ok().and_then(|v| v.parse().ok()) {
156+ match std::env::var("EC_AV1_LAMBDA_HIDDEN")
157+ .ok()
158+ .and_then(|v| v.parse().ok())
159+ {
157160 Some(f) => f,
158161 None => HIDDEN_LAMBDA_FACTOR,
159162 }
@@ -200,7 +203,10 @@ const KEY_LAMBDA_FACTOR: f64 = 1.0;
200203
201204 /// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build.
202205 fn key_lambda_factor() -> f64 {
203- match std::env::var("EC_AV1_LAMBDA_KEY").ok().and_then(|v| v.parse::<f64>().ok()) {
206+ match std::env::var("EC_AV1_LAMBDA_KEY")
207+ .ok()
208+ .and_then(|v| v.parse::<f64>().ok())
209+ {
204210 Some(k) if cfg!(test) => k,
205211 _ => KEY_LAMBDA_FACTOR,
206212 }
@@ -290,21 +296,13 @@ pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType]
290296 TxType::Idtx,
291297 ];
292298 match set {
293- TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4
294- if intra_tx_search_on(screen) =>
295- {
296- &INTRA2
297- }
299+ TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4 if intra_tx_search_on(screen) => &INTRA2,
298300 // lane-txi: a `reduced_tx_set == 0` frame's intra 8x8/4x4 reads the
299301 // SEVEN-type `TX_SET_INTRA_1` (`decode::txbset_for`'s `Luma{8,4}Set1`;
300302 // 16x16 stays `TX_SET_INTRA_2`, there is no `Luma16Set1`). The two
301303 // extra members are the 1-D DCTs, and the order is the reader's own
302304 // map (`decode::tx_type_from_symbol`, 8-wide CDF).
303- TxbSet::Luma8Set1 | TxbSet::Luma4Set1
304- if intra_tx_search_on(screen) =>
305- {
306- &INTRA1
307- }
305+ TxbSet::Luma8Set1 | TxbSet::Luma4Set1 if intra_tx_search_on(screen) => &INTRA1,
308306 _ => &DCT,
309307 }
310308 }
@@ -375,11 +373,13 @@ pub(crate) fn wide_tx_set(screen: bool) -> bool {
375373 _ => {}
376374 }
377375 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
378- crate::envflags::var("EC_AV1_TXSET_WIDE").ok().map(|v| match v.as_str() {
379- "0" | "off" => InterTxSearch::Off,
380- "screen" => InterTxSearch::Screen,
381- _ => InterTxSearch::All,
382- })
376+ crate::envflags::var("EC_AV1_TXSET_WIDE")
377+ .ok()
378+ .map(|v| match v.as_str() {
379+ "0" | "off" => InterTxSearch::Off,
380+ "screen" => InterTxSearch::Screen,
381+ _ => InterTxSearch::All,
382+ })
383383 });
384384 match ENV.unwrap_or(if crate::speed::at(&crate::speed::WIDE_TX_SET) {
385385 InterTxSearch::Screen
@@ -397,8 +397,7 @@ pub(crate) fn wide_tx_set(screen: bool) -> bool {
397397 /// [`set_inter_tx_search`] has: the lever is OFF at every preset, so the
398398 /// witness that has to see the wider alphabets turns it on through this while
399399 /// holding [`crate::speed::knob_write`].
400-static WIDE_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
401- std::sync::atomic::AtomicU8::new(u8::MAX);
400+static WIDE_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
402401
403402 /// Sets [`WIDE_TX_OVERRIDE`]; `None` clears it.
404403 #[allow(dead_code)] // set only from the `#[cfg(test)]` gates
@@ -414,11 +413,7 @@ pub(crate) fn set_wide_tx_set(on: Option<bool>) {
414413 /// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read
415414 /// the same alphabet or the two disagree on what a `tx_type` symbol costs.
416415 pub(crate) fn luma_set_for(set: TxbSet, screen: bool) -> TxbSet {
417- if wide_tx_set(screen) {
418- set.wide()
419- } else {
420- set
421- }
416+ if wide_tx_set(screen) { set.wide() } else { set }
422417 }
423418
424419 #[derive(Clone, Copy, PartialEq)]
@@ -435,8 +430,7 @@ pub(crate) enum InterTxSearch {
435430 /// [`set_deltaq_res`] has: the lever is OFF at every preset, so the witness
436431 /// that has to see a non-`DCT_DCT` inter unit turns it on through this while
437432 /// holding [`crate::speed::knob_write`].
438-static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
439- std::sync::atomic::AtomicU8::new(u8::MAX);
433+static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
440434
441435 /// Sets [`INTER_TX_OVERRIDE`]; `None` clears it.
442436 #[allow(dead_code)] // set only from the `#[cfg(test)]` gates
@@ -454,12 +448,14 @@ fn inter_tx_type_search() -> InterTxSearch {
454448 _ => {}
455449 }
456450 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
457- crate::envflags::var("EC_AV1_TXSET_INTER").ok().map(|v| match v.as_str() {
458- "0" | "off" => InterTxSearch::Off,
459- "screen" => InterTxSearch::Screen,
460- "le16" => InterTxSearch::Le16,
461- _ => InterTxSearch::All,
462- })
451+ crate::envflags::var("EC_AV1_TXSET_INTER")
452+ .ok()
453+ .map(|v| match v.as_str() {
454+ "0" | "off" => InterTxSearch::Off,
455+ "screen" => InterTxSearch::Screen,
456+ "le16" => InterTxSearch::Le16,
457+ _ => InterTxSearch::All,
458+ })
463459 });
464460 ENV.unwrap_or_else(|| {
465461 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH_INTER) {
@@ -525,8 +521,7 @@ fn intra_tx_search_on(screen: bool) -> bool {
525521
526522 /// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the
527523 /// shape [`set_inter_tx_search`] has.
528-static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
529- std::sync::atomic::AtomicU8::new(u8::MAX);
524+static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
530525
531526 /// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it.
532527 #[allow(dead_code)] // set only from the `#[cfg(test)]` gates
@@ -542,9 +537,8 @@ pub(crate) fn set_intra_tx_search(on: Option<bool>) {
542537 /// content gate [`tx_type_candidates`] ships behind. Any other value keeps
543538 /// the gate (`0`/`off` still switches the search off entirely).
544539 fn intra_tx_all_frames() -> bool {
545- static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
546- crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all")
547- });
540+ static ENV: std::sync::LazyLock<bool> =
541+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all"));
548542 *ENV
549543 }
550544
@@ -731,7 +725,9 @@ pub fn take_b64_root_hits() -> usize {
731725 /// what the SIZE costs from what the 128x128 BLOCK buys.
732726 fn b128_root() -> bool {
733727 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
734- crate::envflags::var("EC_AV1_B128").ok().is_none_or(|v| v != "0")
728+ crate::envflags::var("EC_AV1_B128")
729+ .ok()
730+ .is_none_or(|v| v != "0")
735731 });
736732 *ENV
737733 }
@@ -758,7 +754,9 @@ fn b128_root() -> bool {
758754 /// defect flag.
759755 fn b128_residual() -> bool {
760756 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
761- crate::envflags::var("EC_AV1_B128RES").ok().map(|v| v != "0")
757+ crate::envflags::var("EC_AV1_B128RES")
758+ .ok()
759+ .map(|v| v != "0")
762760 });
763761 (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
764762 && b128_root()
@@ -799,8 +797,7 @@ pub(crate) fn force_b128_rectres(on: bool) {
799797 /// How many rect/AB pieces the search left WITH a residual rather than
800798 /// skipped, since the last [`take_b128_rectres_hits`] (class
801799 /// `gate-blind-to-feature`).
802-static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize =
803- std::sync::atomic::AtomicUsize::new(0);
800+static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
804801
805802 /// The rect/AB-piece-residual count since the last call, and zero it.
806803 pub fn take_b128_rectres_hits() -> usize {
@@ -816,15 +813,16 @@ pub fn take_b128_rectres_hits() -> usize {
816813 /// names a second reference).
817814 fn b128_compound() -> bool {
818815 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
819- crate::envflags::var("EC_AV1_B128COMP").ok().map(|v| v != "0")
816+ crate::envflags::var("EC_AV1_B128COMP")
817+ .ok()
818+ .map(|v| v != "0")
820819 });
821820 ENV.unwrap_or(true) && b128_root()
822821 }
823822
824823 /// How many 128 roots came out COMPOUND since the last
825824 /// [`take_b128_compound_hits`] (class `gate-blind-to-feature`).
826-static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize =
827- std::sync::atomic::AtomicUsize::new(0);
825+static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
828826
829827 /// The compound-128 count since the last call, and zero it.
830828 pub fn take_b128_compound_hits() -> usize {
@@ -837,9 +835,8 @@ pub fn take_b128_compound_hits() -> usize {
837835 /// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`).
838836 /// `EC_AV1_B128HV=0` is this arm's attribution control.
839837 fn b128_rect() -> bool {
840- static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
841- crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0")
842- });
838+ static ENV: std::sync::LazyLock<Option<bool>> =
839+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0"));
843840 ENV.unwrap_or(true) && b128_root()
844841 }
845842
@@ -848,9 +845,8 @@ fn b128_rect() -> bool {
848845 /// attribution control (the pre-lane pricing, where a 128 rect root and the
849846 /// four-superblock arm were both priced as if the group were free).
850847 fn rectdq() -> bool {
851- static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
852- crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0")
853- });
848+ static ENV: std::sync::LazyLock<Option<bool>> =
849+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0"));
854850 ENV.unwrap_or(true)
855851 }
856852
@@ -978,9 +974,8 @@ pub(crate) fn force_b128_rect(which: u8) {
978974 /// 64x64 pieces could carry the 64 root's residual, which is where libaom's
979975 /// AB shapes earn their keep) or a cheaper partition price.
980976 fn b128_ab() -> bool {
981- static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
982- crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0")
983- });
977+ static ENV: std::sync::LazyLock<Option<bool>> =
978+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0"));
984979 ENV.unwrap_or(false) && b128_root()
985980 }
986981
@@ -1043,8 +1038,7 @@ static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool =
10431038 /// the 128 root whenever it produced a candidate at all, whatever its four
10441039 /// cells cost, so a witness codes the block it is about rather than waiting
10451040 /// for content on which the root also wins its own comparison.
1046-static FORCE_B128_ROOT: std::sync::atomic::AtomicBool =
1047- std::sync::atomic::AtomicBool::new(false);
1041+static FORCE_B128_ROOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
10481042
10491043 /// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a
10501044 /// forced residual block only reaches the writer if its root is taken.
@@ -1062,8 +1056,7 @@ pub(crate) fn force_b128_root(on: bool) {
10621056
10631057 /// How many 128 roots came out cheaper WITH a residual than skipped, since
10641058 /// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
1065-static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize =
1066- std::sync::atomic::AtomicUsize::new(0);
1059+static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
10671060
10681061 /// The 128-residual count since the last call, and zero it.
10691062 pub fn take_b128_residual_hits() -> usize {
@@ -1087,9 +1080,8 @@ pub fn take_b128_none_hits() -> usize {
10871080 /// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser --
10881081 /// which is what the byte pins are taken under when they name it.
10891082 fn rdoq_on() -> bool {
1090- static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1091- crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0")
1092- });
1083+ static ENV: std::sync::LazyLock<Option<bool>> =
1084+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0"));
10931085 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ))
10941086 }
10951087
@@ -1143,9 +1135,8 @@ fn rdoq_lambda() -> f64 {
11431135
11441136 /// [`B64_ROOT`], or what `EC_AV1_B64` names.
11451137 fn b64_root() -> bool {
1146- static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1147- crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0")
1148- });
1138+ static ENV: std::sync::LazyLock<Option<bool>> =
1139+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0"));
11491140 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
11501141 }
11511142
@@ -1189,9 +1180,8 @@ pub fn take_i64_root_hits() -> [usize; 3] {
11891180
11901181 /// [`I64_ROOT`], or what `EC_AV1_I64` names.
11911182 fn i64_root() -> bool {
1192- static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1193- crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0")
1194- });
1183+ static ENV: std::sync::LazyLock<Option<bool>> =
1184+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0"));
11951185 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::I64_ROOT))
11961186 }
11971187
@@ -1230,9 +1220,8 @@ fn i64_root() -> bool {
12301220 /// transforms per superblock: a root that wins is four quadrant searches that
12311221 /// never run.
12321222 fn b64_residual() -> bool {
1233- static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1234- crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0")
1235- });
1223+ static ENV: std::sync::LazyLock<Option<bool>> =
1224+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0"));
12361225 ENV.unwrap_or(true) && b64_root()
12371226 }
12381227
@@ -1258,7 +1247,9 @@ pub fn take_b64_residual_hits() -> usize {
12581247 /// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build.
12591248 fn b64_compound() -> bool {
12601249 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1261- crate::envflags::var("EC_AV1_B64COMP").ok().map(|v| v != "0")
1250+ crate::envflags::var("EC_AV1_B64COMP")
1251+ .ok()
1252+ .map(|v| v != "0")
12621253 });
12631254 ENV.unwrap_or(true) && b64_root()
12641255 }
@@ -1282,7 +1273,9 @@ pub fn take_b64_compound_hits() -> usize {
12821273 /// Off by `EC_AV1_B64VARTX=0`.
12831274 fn b64_var_tx() -> bool {
12841275 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1285- crate::envflags::var("EC_AV1_B64VARTX").ok().map(|v| v != "0")
1276+ crate::envflags::var("EC_AV1_B64VARTX")
1277+ .ok()
1278+ .map(|v| v != "0")
12861279 });
12871280 ENV.unwrap_or(true) && b64_root()
12881281 }
@@ -1315,7 +1308,9 @@ fn b64_edge() -> bool {
13151308 /// but is gated by [`i64_root`].
13161309 fn edge_root_enabled() -> bool {
13171310 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1318- crate::envflags::var("EC_AV1_B64EDGE").ok().map(|v| v != "0")
1311+ crate::envflags::var("EC_AV1_B64EDGE")
1312+ .ok()
1313+ .map(|v| v != "0")
13191314 });
13201315 ENV.unwrap_or(true)
13211316 }
@@ -1388,7 +1383,9 @@ pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125;
13881383 /// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
13891384 fn split_rd_threshold() -> f64 {
13901385 static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| {
1391- crate::envflags::var("EC_AV1_SPLIT_RD").ok().and_then(|v| v.parse().ok())
1386+ crate::envflags::var("EC_AV1_SPLIT_RD")
1387+ .ok()
1388+ .and_then(|v| v.parse().ok())
13921389 });
13931390 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD))
13941391 }
@@ -1674,7 +1671,8 @@ fn intra_predict_u8(
16741671 bh: usize,
16751672 enable_edge_filter: bool,
16761673 smooth_neighbor: bool,
1677- dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1674+ dst: &mut [u8],
1675+ fctx: &crate::decode::FrameCtx,
16781676 ) {
16791677 // Three heap allocations per call became three stack buffers: this runs
16801678 // once per mode per trial, and an edge is at most `bw + bh` samples while
@@ -1713,7 +1711,8 @@ fn intra_predict_u8(
17131711 bh,
17141712 enable_edge_filter,
17151713 smooth_neighbor,
1716- dst16, fctx,
1714+ dst16,
1715+ fctx,
17171716 );
17181717 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
17191718 *d = s as u8;
@@ -1740,7 +1739,8 @@ fn filter_intra_predict_u8(
17401739 left: Option<&[u8]>,
17411740 corner: Option<u8>,
17421741 side: usize,
1743- dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1742+ dst: &mut [u8],
1743+ fctx: &crate::decode::FrameCtx,
17441744 ) {
17451745 let mut above_buf = [0u16; 2 * BLOCK];
17461746 let mut left_buf = [0u16; 2 * BLOCK];
@@ -1764,7 +1764,8 @@ fn filter_intra_predict_u8(
17641764 corner.map(u16::from),
17651765 side,
17661766 side,
1767- &mut dst16[..n], fctx,
1767+ &mut dst16[..n],
1768+ fctx,
17681769 );
17691770 for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) {
17701771 *d = v as u8;
@@ -2354,8 +2355,7 @@ pub const GOLDEN_SLOT: u8 = 1;
23542355 /// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has:
23552356 /// the witness that has to see a non-REGULAR kernel coded and decoded turns
23562357 /// it on through this while holding [`crate::speed::knob_write`].
2357-static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 =
2358- std::sync::atomic::AtomicU8::new(u8::MAX);
2358+static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
23592359
23602360 /// Sets [`INTERP_OVERRIDE`]; `None` clears it.
23612361 #[allow(dead_code)] // set only from the `#[cfg(test)]` gates
@@ -2375,11 +2375,13 @@ fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter {
23752375 _ => {}
23762376 }
23772377 static ENV: std::sync::LazyLock<Option<F>> = std::sync::LazyLock::new(|| {
2378- crate::envflags::var("EC_AV1_INTERP").ok().map(|v| match v.as_str() {
2379- "smooth" => F::EighttapSmooth,
2380- "sharp" => F::EighttapSharp,
2381- _ => F::Eighttap,
2382- })
2378+ crate::envflags::var("EC_AV1_INTERP")
2379+ .ok()
2380+ .map(|v| match v.as_str() {
2381+ "smooth" => F::EighttapSmooth,
2382+ "sharp" => F::EighttapSharp,
2383+ _ => F::Eighttap,
2384+ })
23832385 });
23842386 ENV.unwrap_or(F::Eighttap)
23852387 }
@@ -2398,7 +2400,9 @@ pub fn inter_frame_headers(
23982400 order_hint: u32,
23992401 last_slot: u8,
24002402 ) -> Result<(SequenceHeader, FrameHeader)> {
2401- inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
2403+ inter_frame_headers_slots(
2404+ width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot,
2405+ )
24022406 }
24032407
24042408 /// [`inter_frame_headers`] with the three slots named apart: the one read as
@@ -2472,8 +2476,7 @@ pub fn inter_frame_headers_slots(
24722476 // `allow_warped_motion` besides -- which is what makes an eligible
24732477 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
24742478 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
2475- is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC")
2476- || warp_on(),
2479+ is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on(),
24772480 allow_warped_motion: warp_on(),
24782481 use_ref_frame_mvs: false,
24792482 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
@@ -2546,8 +2549,11 @@ struct CoefCtxMap {
25462549 /// padding-inclusive score the search used before lane-sse, which is how the
25472550 /// before/after arms of the straddling gate rows are read off ONE binary.
25482551 fn edge_sse() -> bool {
2549- static ENV: std::sync::LazyLock<Option<bool>> =
2550- std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGESSE").ok().map(|v| v != "0"));
2552+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
2553+ crate::envflags::var("EC_AV1_EDGESSE")
2554+ .ok()
2555+ .map(|v| v != "0")
2556+ });
25512557 ENV.unwrap_or(true)
25522558 }
25532559
@@ -2558,8 +2564,9 @@ fn edge_sse() -> bool {
25582564 /// `gate-blind-to-feature` -- both gate films are superblock-aligned, so
25592565 /// without this census no gate row can say the clip fires at all).
25602566 fn edge_census() -> bool {
2561- static ENV: std::sync::LazyLock<bool> =
2562- std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1"));
2567+ static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
2568+ crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1")
2569+ });
25632570 *ENV
25642571 }
25652572
@@ -2698,8 +2705,7 @@ impl Plane<'_> {
26982705 let down = down.min(self.tile_y1);
26992706 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
27002707 if let Some(n) = above_n {
2701- above_buf[..n]
2702- .copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
2708+ above_buf[..n].copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
27032709 }
27042710 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
27052711 if let Some(n) = left_n {
@@ -2719,8 +2725,24 @@ impl Plane<'_> {
27192725 /// Codes one block under one mode without committing it: hands back the
27202726 /// levels, the block the decoder would reconstruct, the squared error
27212727 /// against the source and an estimate of what the levels cost in bits.
2722- fn trial(&self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
2723- self.trial_typed(at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx)
2728+ fn trial(
2729+ &self,
2730+ at: At,
2731+ mode: u8,
2732+ angle_delta: i32,
2733+ base_q_idx: u8,
2734+ deadzone: f64,
2735+ fctx: &crate::decode::FrameCtx,
2736+ ) -> Trial {
2737+ self.trial_typed(
2738+ at,
2739+ mode,
2740+ angle_delta,
2741+ base_q_idx,
2742+ deadzone,
2743+ TxType::DctDct,
2744+ fctx,
2745+ )
27242746 }
27252747
27262748 /// [`Self::trial`] under a named transform type -- what an intra chroma
@@ -2785,8 +2807,10 @@ impl Plane<'_> {
27852807 let (mut inside, mut whole) = (0u64, 0u64);
27862808 for row in 0..side {
27872809 let source = &self.source[(y + row) * self.width + x..][..side];
2788- for (col, (&s, &r)) in
2789- source.iter().zip(&reconstruction[row * side..][..side]).enumerate()
2810+ for (col, (&s, &r)) in source
2811+ .iter()
2812+ .zip(&reconstruction[row * side..][..side])
2813+ .enumerate()
27902814 {
27912815 let d = u64::from(u32::from(s.abs_diff(r)).pow(2));
27922816 whole += d;
@@ -2834,7 +2858,8 @@ impl Plane<'_> {
28342858 side,
28352859 false,
28362860 false,
2837- prediction, fctx,
2861+ prediction,
2862+ fctx,
28382863 );
28392864
28402865 let mut residual = [0i32; BLOCK * BLOCK];
@@ -2853,18 +2878,35 @@ impl Plane<'_> {
28532878 // grid this trial would really code.
28542879 let (levels, rdoq_bits) = if rdoq_on() {
28552880 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
2856- residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2881+ residual,
2882+ side,
2883+ 8,
2884+ i32::from(base_q_idx),
2885+ deadzone,
2886+ tx_type,
28572887 );
28582888 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
28592889 let bits = crate::tile::rdoq(
2860- &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(),
2890+ &mut levels,
2891+ &scaled,
2892+ side,
2893+ base_q_idx,
2894+ at.set,
2895+ skip_ctx,
2896+ sign_ctx,
2897+ rdoq_lambda(),
28612898 tx_type,
28622899 );
28632900 (levels, Some(bits))
28642901 } else {
28652902 (
28662903 forward_and_quantize_typed(
2867- residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2904+ residual,
2905+ side,
2906+ 8,
2907+ i32::from(base_q_idx),
2908+ deadzone,
2909+ tx_type,
28682910 ),
28692911 None,
28702912 )
@@ -2877,7 +2919,15 @@ impl Plane<'_> {
28772919 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
28782920 // `p` for a `u8`, so the bytes are the same.
28792921 let coded = dequant_and_inverse_typed_wh(
2880- &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type, None,
2922+ &levels,
2923+ side,
2924+ side,
2925+ 8,
2926+ i32::from(base_q_idx),
2927+ 0,
2928+ 0,
2929+ tx_type,
2930+ None,
28812931 );
28822932 #[cfg(test)]
28832933 stage_since(2, t);
@@ -2952,7 +3002,15 @@ impl Plane<'_> {
29523002 set: TxbSet,
29533003 ) -> Trial {
29543004 self.code_from_prediction_typed(
2955- x, y, side, prediction, skip, base_q_idx, deadzone, set, TxType::DctDct,
3005+ x,
3006+ y,
3007+ side,
3008+ prediction,
3009+ skip,
3010+ base_q_idx,
3011+ deadzone,
3012+ set,
3013+ TxType::DctDct,
29563014 )
29573015 }
29583016
@@ -3007,20 +3065,36 @@ impl Plane<'_> {
30073065 let t = stage_start();
30083066 // lane-rdoq, as in [`Self::trial_typed`].
30093067 let (levels, rdoq_bits) = if rdoq_on() {
3010- let (mut levels, scaled) =
3011- forward_and_quantize_typed_scaled(
3012- residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
3013- );
3068+ let (mut levels, scaled) = forward_and_quantize_typed_scaled(
3069+ residual,
3070+ side,
3071+ 8,
3072+ i32::from(base_q_idx),
3073+ deadzone,
3074+ tx_type,
3075+ );
30143076 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
30153077 let bits = crate::tile::rdoq(
3016- &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(),
3078+ &mut levels,
3079+ &scaled,
3080+ side,
3081+ base_q_idx,
3082+ set,
3083+ skip_ctx,
3084+ sign_ctx,
3085+ rdoq_lambda(),
30173086 tx_type,
30183087 );
30193088 (levels, Some(bits))
30203089 } else {
30213090 (
30223091 forward_and_quantize_typed(
3023- residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
3092+ residual,
3093+ side,
3094+ 8,
3095+ i32::from(base_q_idx),
3096+ deadzone,
3097+ tx_type,
30243098 ),
30253099 None,
30263100 )
@@ -3113,9 +3187,12 @@ impl Plane<'_> {
31133187 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
31143188 // `filter_intra`), not once over the whole block.
31153189 filter_intra: Option<u8>,
3116- search: &Search, fctx: &crate::decode::FrameCtx,
3190+ search: &Search,
3191+ fctx: &crate::decode::FrameCtx,
31173192 ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
3118- let At { x, y, side, reach, .. } = at;
3193+ let At {
3194+ x, y, side, reach, ..
3195+ } = at;
31193196 let tx = side >> depth;
31203197 let n = 1usize << depth;
31213198 let set = luma_set_for(
@@ -3150,9 +3227,16 @@ impl Plane<'_> {
31503227 };
31513228 let trial = match filter_intra {
31523229 Some(fi) => {
3153- let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3154- let (above, left, corner) =
3155- self.edges_into(tu.x, tu.y, tx, tu.reach, &mut above_buf, &mut left_buf);
3230+ let (mut above_buf, mut left_buf) =
3231+ ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3232+ let (above, left, corner) = self.edges_into(
3233+ tu.x,
3234+ tu.y,
3235+ tx,
3236+ tu.reach,
3237+ &mut above_buf,
3238+ &mut left_buf,
3239+ );
31563240 let mut prediction = vec![0u8; tx * tx];
31573241 filter_intra_predict_u8(
31583242 usize::from(fi),
@@ -3182,8 +3266,13 @@ impl Plane<'_> {
31823266 let mut best: Option<(f64, TxType, Trial)> = None;
31833267 for &tx_type in tx_type_candidates(set, search.screen) {
31843268 let candidate = self.trial_typed(
3185- tu, mode, angle_delta, search.base_q_idx, search.deadzone,
3186- tx_type, fctx,
3269+ tu,
3270+ mode,
3271+ angle_delta,
3272+ search.base_q_idx,
3273+ search.deadzone,
3274+ tx_type,
3275+ fctx,
31873276 );
31883277 // lane-txi: a non-`DCT_DCT` type is charged its
31893278 // bits at `EC_AV1_TXRD_LAMBDA` times the mode
@@ -3201,8 +3290,7 @@ impl Plane<'_> {
32013290 best = Some((cost, tx_type, candidate));
32023291 }
32033292 }
3204- let (_, tx_type, trial) =
3205- best.expect("the candidate list is never empty");
3293+ let (_, tx_type, trial) = best.expect("the candidate list is never empty");
32063294 tx_types[tu_row * n + tu_col] = tx_type;
32073295 TX_TYPE_HITS[tx_type as usize]
32083296 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -3343,8 +3431,7 @@ impl Plane<'_> {
33433431 fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
33443432 let mut out = vec![0u8; w * h];
33453433 for row in 0..h {
3346- out[row * w..][..w]
3347- .copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
3434+ out[row * w..][..w].copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
33483435 }
33493436 out
33503437 }
@@ -3403,7 +3490,8 @@ impl Plane<'_> {
34033490 at: At,
34043491 modes: &[u8],
34053492 mode_bits: &[f64; 13],
3406- lambda: f64, fctx: &crate::decode::FrameCtx,
3493+ lambda: f64,
3494+ fctx: &crate::decode::FrameCtx,
34073495 ) -> Vec<(f64, u8)> {
34083496 let At {
34093497 x, y, side, reach, ..
@@ -3425,7 +3513,8 @@ impl Plane<'_> {
34253513 side,
34263514 false,
34273515 false,
3428- &mut prediction, fctx,
3516+ &mut prediction,
3517+ fctx,
34293518 );
34303519 let sad = self.block_sad(x, y, side, &prediction);
34313520 (sad + lambda * mode_bits[usize::from(mode)], mode)
@@ -3447,7 +3536,8 @@ impl Plane<'_> {
34473536 &mut self,
34483537 at: At,
34493538 search: &Search,
3450- mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
3539+ mode_bits: &[f64; 13],
3540+ fctx: &crate::decode::FrameCtx,
34513541 ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
34523542 let At {
34533543 x, y, side, reach, ..
@@ -3475,7 +3565,8 @@ impl Plane<'_> {
34753565 side,
34763566 false,
34773567 false,
3478- &mut prediction, fctx,
3568+ &mut prediction,
3569+ fctx,
34793570 );
34803571 let sad = if want_sad {
34813572 self.block_sad(x, y, side, &prediction)
@@ -3505,7 +3596,10 @@ impl Plane<'_> {
35053596 }
35063597 }
35073598 let ranking: Vec<(f64, u8)> = if census_on() {
3508- scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
3599+ scored
3600+ .iter()
3601+ .map(|&(score, mode, _)| (score, mode))
3602+ .collect()
35093603 } else {
35103604 Vec::new()
35113605 };
@@ -3563,7 +3657,8 @@ impl Plane<'_> {
35633657 side,
35643658 false,
35653659 false,
3566- &mut prediction, fctx,
3660+ &mut prediction,
3661+ fctx,
35673662 );
35683663 let candidate = self.code_from_prediction(
35693664 x,
@@ -3575,8 +3670,9 @@ impl Plane<'_> {
35753670 search.deadzone,
35763671 at.set,
35773672 );
3578- let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
3579- - zero_bits;
3673+ let bits =
3674+ symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
3675+ - zero_bits;
35803676 let cost_d = candidate.sse
35813677 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
35823678 if cost_d < cost {
@@ -3594,7 +3690,13 @@ impl Plane<'_> {
35943690 let mut tx_type = TxType::DctDct;
35953691 for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) {
35963692 let candidate = self.trial_typed(
3597- at, mode, angle_delta, search.base_q_idx, search.deadzone, candidate_type, fctx,
3693+ at,
3694+ mode,
3695+ angle_delta,
3696+ search.base_q_idx,
3697+ search.deadzone,
3698+ candidate_type,
3699+ fctx,
35983700 );
35993701 let cost_t =
36003702 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
@@ -3615,7 +3717,13 @@ impl Plane<'_> {
36153717 self.commit(x, y, side, &trial);
36163718 // A 64-point transform codes only its top-left 32x32 corner, which is
36173719 // the grid `code_from_prediction` hands back (lane-i64).
3618- (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost, tx_type)
3720+ (
3721+ coeffs(&trial.levels, side.min(BLOCK)),
3722+ mode,
3723+ angle_delta,
3724+ cost,
3725+ tx_type,
3726+ )
36193727 }
36203728 }
36213729
@@ -3662,7 +3770,6 @@ const HAS_TOP_RIGHT: [&[u8]; 4] = [
36623770 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
36633771 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
36643772 ],
3665-
36663773 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
36673774 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
36683775 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
@@ -3691,7 +3798,6 @@ const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
36913798 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
36923799 84, 85, 16, 17, 84, 85, 0, 0,
36933800 ],
3694-
36953801 // has_bl_4x4 (same source, same order).
36963802 &[
36973803 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
@@ -3770,21 +3876,42 @@ impl Drop for VertAbGuard {
37703876 /// 10 of the 21 reachable superblock positions for above-right and 7 for
37713877 /// below-left.
37723878 /// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3773-const HAS_TR_4X8: [u8; 64] = [255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119];
3879+const HAS_TR_4X8: [u8; 64] = [
3880+ 255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255,
3881+ 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119,
3882+ 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127,
3883+ 127, 127, 127, 119, 119, 119, 119,
3884+];
37743885 /// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3775-const HAS_BL_4X8: [u8; 64] = [16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0];
3886+const HAS_BL_4X8: [u8; 64] = [
3887+ 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17,
3888+ 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1,
3889+ 1, 1, 16, 17, 17, 17, 0, 0, 0, 0,
3890+];
37763891 /// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3777-const HAS_TR_8X4: [u8; 64] = [255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0];
3892+const HAS_TR_8X4: [u8; 64] = [
3893+ 255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119,
3894+ 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127,
3895+ 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0,
3896+];
37783897 /// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3779-const HAS_BL_8X4: [u8; 64] = [254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0];
3898+const HAS_BL_8X4: [u8; 64] = [
3899+ 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254,
3900+ 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255,
3901+ 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0,
3902+];
37803903 /// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3781-const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
3904+const HAS_TR_8X16: [u8; 16] = [
3905+ 255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119,
3906+];
37823907 /// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
37833908 const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
37843909 /// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
37853910 const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
37863911 /// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3787-const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
3912+const HAS_BL_16X8: [u8; 16] = [
3913+ 254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0,
3914+];
37883915 /// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
37893916 const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
37903917 /// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
@@ -3802,13 +3929,24 @@ const HAS_TR_64X32: [u8; 1] = [19];
38023929 /// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
38033930 const HAS_BL_64X32: [u8; 1] = [34];
38043931 /// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3805-const HAS_TR_4X16: [u8; 32] = [255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255, 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127];
3932+const HAS_TR_4X16: [u8; 32] = [
3933+ 255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255,
3934+ 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127,
3935+];
38063936 /// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3807-const HAS_BL_4X16: [u8; 32] = [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0];
3937+const HAS_BL_4X16: [u8; 32] = [
3938+ 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0,
3939+];
38083940 /// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3809-const HAS_TR_16X4: [u8; 32] = [255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0];
3941+const HAS_TR_16X4: [u8; 32] = [
3942+ 255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0,
3943+ 85, 0, 0, 0,
3944+];
38103945 /// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3811-const HAS_BL_16X4: [u8; 32] = [254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0];
3946+const HAS_BL_16X4: [u8; 32] = [
3947+ 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84,
3948+ 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0,
3949+];
38123950 /// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
38133951 const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
38143952 /// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
@@ -3911,7 +4049,14 @@ impl Reach {
39114049
39124050 /// What a block of `side` samples at `(x, y)` may read past its own edges,
39134051 /// in a frame of `width` by `height`.
3914- pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
4052+ pub(crate) fn of(
4053+ side: usize,
4054+ x: usize,
4055+ y: usize,
4056+ width: usize,
4057+ height: usize,
4058+ fctx: &crate::decode::FrameCtx,
4059+ ) -> Self {
39154060 Self {
39164061 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
39174062 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
@@ -3929,7 +4074,8 @@ impl Reach {
39294074 x: usize,
39304075 y: usize,
39314076 width: usize,
3932- height: usize, fctx: &crate::decode::FrameCtx,
4077+ height: usize,
4078+ fctx: &crate::decode::FrameCtx,
39334079 ) -> Self {
39344080 Self {
39354081 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
@@ -3948,10 +4094,16 @@ impl Reach {
39484094 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
39494095 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
39504096 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
3951- /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
4097+ /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
39524098 /// the transform covering the whole block, luma): everything before the
39534099 /// table lookup is that function's own early-exit ladder.
3954- fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4100+ fn top_right_rect(
4101+ bw: usize,
4102+ bh: usize,
4103+ x: usize,
4104+ y: usize,
4105+ fctx: &crate::decode::FrameCtx,
4106+ ) -> bool {
39554107 let sb_mi: usize = reach_sb_px(fctx) / 4;
39564108 let (mi_row, mi_col) = (y / 4, x / 4);
39574109 let bw_log2 = (bw / 4).trailing_zeros() as usize;
@@ -3984,7 +4136,13 @@ impl Reach {
39844136 }
39854137
39864138 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
3987- fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4139+ fn bottom_left_rect(
4140+ bw: usize,
4141+ bh: usize,
4142+ x: usize,
4143+ y: usize,
4144+ fctx: &crate::decode::FrameCtx,
4145+ ) -> bool {
39884146 let sb_mi: usize = reach_sb_px(fctx) / 4;
39894147 let (mi_row, mi_col) = (y / 4, x / 4);
39904148 let bw_log2 = (bw / 4).trailing_zeros() as usize;
@@ -4054,7 +4212,9 @@ impl Reach {
40544212 // position inside the superblock and is what the bit index below
40554213 // steps by (a merge that shadowed it desynced every block size).
40564214 let table_row = Self::table(side);
4057- let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
4215+ let table = if VERT_AB_PARTITION.with(std::cell::Cell::get)
4216+ && table_row < HAS_TOP_RIGHT_VERT.len()
4217+ {
40584218 HAS_TOP_RIGHT_VERT[table_row]
40594219 } else {
40604220 HAS_TOP_RIGHT[table_row]
@@ -4089,7 +4249,9 @@ impl Reach {
40894249 // position inside the superblock and is what the bit index below
40904250 // steps by (a merge that shadowed it desynced every block size).
40914251 let table_row = Self::table(side);
4092- let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
4252+ let table = if VERT_AB_PARTITION.with(std::cell::Cell::get)
4253+ && table_row < HAS_BOTTOM_LEFT_VERT.len()
4254+ {
40934255 HAS_BOTTOM_LEFT_VERT[table_row]
40944256 } else {
40954257 HAS_BOTTOM_LEFT[table_row]
@@ -4102,7 +4264,12 @@ impl Reach {
41024264
41034265 /// Where a block sits inside its superblock, in blocks of its own size,
41044266 /// and how many of them a superblock is across.
4105- fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
4267+ fn position(
4268+ side: usize,
4269+ x: usize,
4270+ y: usize,
4271+ fctx: &crate::decode::FrameCtx,
4272+ ) -> (usize, usize, usize) {
41064273 let sb = reach_sb_px(fctx);
41074274 ((y % sb) / side, (x % sb) / side, sb / side)
41084275 }
@@ -4147,7 +4314,9 @@ impl Reach {
41474314 /// bits -- back off for an A/B on one build.
41484315 pub(crate) fn warp_on() -> bool {
41494316 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4150- crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
4317+ crate::envflags::var("EC_AV1_WARP")
4318+ .ok()
4319+ .map(|v| !matches!(v.as_str(), "0" | "off"))
41514320 });
41524321 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
41534322 }
@@ -4400,12 +4569,9 @@ fn warp_prediction(
44004569 /// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or
44014570 /// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the
44024571 /// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN.
4403-pub(crate) fn compound_ref_bits(
4404- (ref0, ref1): (i8, i8),
4405- stack: &crate::mvstack::MvStack,
4406-) -> f64 {
4572+pub(crate) fn compound_ref_bits((ref0, ref1): (i8, i8), stack: &crate::mvstack::MvStack) -> f64 {
44074573 use crate::mvstack::{
4408- ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4574+ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
44094575 comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx,
44104576 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
44114577 uni_comp_ref_p1_ctx,
@@ -4526,7 +4692,7 @@ fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 {
45264692 /// paid nothing at all, so compound was overcharged by the whole symbol.
45274693 pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 {
45284694 use crate::mvstack::{
4529- ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4695+ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
45304696 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
45314697 single_ref_p5_ctx, single_ref_p6_ctx,
45324698 };
@@ -4557,20 +4723,23 @@ pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) ->
45574723 };
45584724 }
45594725 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
4560- comp_mode + p1 + symbol_bits(
4561- &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
4562- usize::from(far),
4563- ) + if far {
4564- symbol_bits(
4565- &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
4566- usize::from(ref_frame == GOLDEN_FRAME),
4567- )
4568- } else {
4569- symbol_bits(
4570- &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
4571- usize::from(ref_frame == LAST2_FRAME),
4726+ comp_mode
4727+ + p1
4728+ + symbol_bits(
4729+ &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
4730+ usize::from(far),
45724731 )
4573- }
4732+ + if far {
4733+ symbol_bits(
4734+ &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
4735+ usize::from(ref_frame == GOLDEN_FRAME),
4736+ )
4737+ } else {
4738+ symbol_bits(
4739+ &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
4740+ usize::from(ref_frame == LAST2_FRAME),
4741+ )
4742+ }
45744743 }
45754744
45764745 pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
@@ -4698,7 +4867,11 @@ fn split_census(
46984867 } else {
46994868 6
47004869 };
4701- let (win, lose) = if split_won { (split, flat) } else { (flat, split) };
4870+ let (win, lose) = if split_won {
4871+ (split, flat)
4872+ } else {
4873+ (flat, split)
4874+ };
47024875 add(off, (win.0 * 64.0).max(0.0) as u64);
47034876 add(off + 1, win.1.max(0.0) as u64);
47044877 add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
@@ -4831,7 +5004,10 @@ fn newmv_census_block(
48315004 } else {
48325005 add(4, (new_cost - other_cost).max(0.0) as u64);
48335006 }
4834- add(5, ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64);
5007+ add(
5008+ 5,
5009+ ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64,
5010+ );
48355011 if mv == nearest {
48365012 add(6, 1);
48375013 }
@@ -4886,8 +5062,16 @@ pub(crate) fn dump_newmv_census() {
48865062 g[2],
48875063 100.0 * g[3] as f64 / g[2].max(1) as f64,
48885064 );
4889- let [calls, evals, _subpel, rounds, near_pred, unmoved, widest, widest_moves] =
4890- crate::motion::take_census();
5065+ let [
5066+ calls,
5067+ evals,
5068+ _subpel,
5069+ rounds,
5070+ near_pred,
5071+ unmoved,
5072+ widest,
5073+ widest_moves,
5074+ ] = crate::motion::take_census();
48915075 let per = |n: u64| n as f64 / calls.max(1) as f64;
48925076 eprintln!(
48935077 "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
@@ -5019,7 +5203,9 @@ static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
50195203 /// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
50205204 fn tx32_depth_search() -> bool {
50215205 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5022- crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
5206+ crate::envflags::var("EC_AV1_TX32_DEPTH")
5207+ .ok()
5208+ .map(|v| !matches!(v.as_str(), "0" | "off"))
50235209 });
50245210 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
50255211 }
@@ -5034,7 +5220,9 @@ fn tx32_depth_search() -> bool {
50345220 /// `EC_AV1_COMP_VARTX`.
50355221 fn compound_var_tx() -> bool {
50365222 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5037- crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
5223+ crate::envflags::var("EC_AV1_COMP_VARTX")
5224+ .ok()
5225+ .map(|v| !matches!(v.as_str(), "0" | "off"))
50385226 });
50395227 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
50405228 }
@@ -5112,18 +5300,44 @@ fn recode_inter_chroma(
51125300 fctx: &crate::decode::FrameCtx,
51135301 ) -> Option<[Trial; 2]> {
51145302 let c = side / 2;
5115- let tx = crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
5303+ let tx =
5304+ crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
51165305 if tx == TxType::DctDct {
51175306 return None;
51185307 }
51195308 Some([0usize, 1].map(|p| match second {
51205309 Some((mv1, r1)) => mc_trial_compound_typed(
5121- &chroma[p], x / 2, y / 2, c, (mv, mv1), false, refs[p], r1[p], search.base_q_idx,
5122- search.deadzone, set, tx, fctx,
5310+ &chroma[p],
5311+ x / 2,
5312+ y / 2,
5313+ c,
5314+ (mv, mv1),
5315+ false,
5316+ refs[p],
5317+ r1[p],
5318+ search.base_q_idx,
5319+ search.deadzone,
5320+ set,
5321+ tx,
5322+ fctx,
51235323 ),
51245324 None => mc_trial_typed(
5125- &chroma[p], x / 2, y / 2, c, mv, false, refs[p].0, refs[p].1, refs[p].2, refs[p].3,
5126- false, search.base_q_idx, search.deadzone, set, tx, fctx,
5325+ &chroma[p],
5326+ x / 2,
5327+ y / 2,
5328+ c,
5329+ mv,
5330+ false,
5331+ refs[p].0,
5332+ refs[p].1,
5333+ refs[p].2,
5334+ refs[p].3,
5335+ false,
5336+ search.base_q_idx,
5337+ search.deadzone,
5338+ set,
5339+ tx,
5340+ fctx,
51275341 ),
51285342 }))
51295343 }
@@ -5172,9 +5386,7 @@ fn commit_inter_luma(
51725386 // seven-type candidate list below reachable -- and prices every
51735387 // candidate, `IDTX` included, in the alphabet its symbol is really
51745388 // coded into.
5175- if let Some(fset) =
5176- inter_luma_set(side).map(|set| luma_set_for(set, search.screen))
5177- {
5389+ if let Some(fset) = inter_luma_set(side).map(|set| luma_set_for(set, search.screen)) {
51785390 let lambda = search.lambda * tx_type_lambda_mult();
51795391 let cost = |t: &Trial| t.sse + lambda * t.bits;
51805392 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
@@ -5183,12 +5395,36 @@ fn commit_inter_luma(
51835395 }
51845396 let candidate = match second {
51855397 Some((mv1, ref1)) => mc_trial_compound_typed(
5186- luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
5187- search.deadzone, fset, tx_type, fctx,
5398+ luma,
5399+ x,
5400+ y,
5401+ side,
5402+ (mv, mv1),
5403+ true,
5404+ reference,
5405+ ref1,
5406+ search.base_q_idx,
5407+ search.deadzone,
5408+ fset,
5409+ tx_type,
5410+ fctx,
51885411 ),
51895412 None => mc_trial_typed(
5190- luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
5191- reference.3, false, search.base_q_idx, search.deadzone, fset, tx_type,
5413+ luma,
5414+ x,
5415+ y,
5416+ side,
5417+ mv,
5418+ true,
5419+ reference.0,
5420+ reference.1,
5421+ reference.2,
5422+ reference.3,
5423+ false,
5424+ search.base_q_idx,
5425+ search.deadzone,
5426+ fset,
5427+ tx_type,
51925428 fctx,
51935429 ),
51945430 };
@@ -5223,13 +5459,37 @@ fn commit_inter_luma(
52235459 if let Some(fset) = inter_luma_set(side) {
52245460 let here = match second {
52255461 Some((mv1, ref1)) => mc_trial_compound_typed(
5226- luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
5227- search.deadzone, fset, TxType::DctDct, fctx,
5462+ luma,
5463+ x,
5464+ y,
5465+ side,
5466+ (mv, mv1),
5467+ true,
5468+ reference,
5469+ ref1,
5470+ search.base_q_idx,
5471+ search.deadzone,
5472+ fset,
5473+ TxType::DctDct,
5474+ fctx,
52285475 ),
52295476 None => mc_trial_typed(
5230- luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
5231- reference.3, false, search.base_q_idx, search.deadzone, fset,
5232- TxType::DctDct, fctx,
5477+ luma,
5478+ x,
5479+ y,
5480+ side,
5481+ mv,
5482+ true,
5483+ reference.0,
5484+ reference.1,
5485+ reference.2,
5486+ reference.3,
5487+ false,
5488+ search.base_q_idx,
5489+ search.deadzone,
5490+ fset,
5491+ TxType::DctDct,
5492+ fctx,
52335493 ),
52345494 };
52355495 TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed);
@@ -5241,16 +5501,21 @@ fn commit_inter_luma(
52415501 "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \
52425502 flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \
52435503 sse={:.0} bits={:.1}",
5244- second.is_some(), flat.sse, flat.bits, here.sse, here.bits,
5245- flat_ref.sse, flat_ref.bits,
5504+ second.is_some(),
5505+ flat.sse,
5506+ flat.bits,
5507+ here.sse,
5508+ here.bits,
5509+ flat_ref.sse,
5510+ flat_ref.bits,
52465511 );
52475512 }
52485513 }
52495514 }
52505515 // What the caller's already-counted `flat` cost has to be corrected by
52515516 // when a non-`DCT_DCT` type won it, the same way the split delta below is.
5252- let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits)
5253- - (flat.sse + search.lambda * flat.bits);
5517+ let flat_gain =
5518+ (flat_ref.sse + search.lambda * flat_ref.bits) - (flat.sse + search.lambda * flat.bits);
52545519 let eligible = tx_select()
52555520 && tx_select_inter()
52565521 && !skip
@@ -5291,14 +5556,39 @@ fn commit_inter_luma(
52915556 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
52925557 let unit = |tx_type: TxType| match second {
52935558 Some((mv1, ref1)) => mc_trial_compound_typed(
5294- luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1,
5295- search.base_q_idx, search.deadzone, set, tx_type, fctx,
5559+ luma,
5560+ tu_x,
5561+ tu_y,
5562+ tx,
5563+ (mv, mv1),
5564+ true,
5565+ reference,
5566+ ref1,
5567+ search.base_q_idx,
5568+ search.deadzone,
5569+ set,
5570+ tx_type,
5571+ fctx,
52965572 ),
52975573 None => mc_trial_typed(
5298- luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
5299- reference.3, false, search.base_q_idx, search.deadzone, set, tx_type, fctx,
5300- ),
5301- };
5574+ luma,
5575+ tu_x,
5576+ tu_y,
5577+ tx,
5578+ mv,
5579+ true,
5580+ reference.0,
5581+ reference.1,
5582+ reference.2,
5583+ reference.3,
5584+ false,
5585+ search.base_q_idx,
5586+ search.deadzone,
5587+ set,
5588+ tx_type,
5589+ fctx,
5590+ ),
5591+ };
53025592 let mut best: Option<(f64, TxType, Trial)> = None;
53035593 for &tx_type in inter_tx_type_candidates(set, search.screen) {
53045594 let candidate = unit(tx_type);
@@ -5324,7 +5614,14 @@ fn commit_inter_luma(
53245614 let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
53255615 let flat_cost = flat_ref.sse + search.lambda * flat_rate;
53265616 if split_census_on() {
5327- split_census(1, false, side, split_cost < flat_cost, (split_rate, sse), (flat_rate, flat_ref.sse));
5617+ split_census(
5618+ 1,
5619+ false,
5620+ side,
5621+ split_cost < flat_cost,
5622+ (split_rate, sse),
5623+ (flat_rate, flat_ref.sse),
5624+ );
53285625 }
53295626 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
53305627 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
@@ -5384,7 +5681,9 @@ fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
53845681 for &v in block {
53855682 histogram[usize::from(v)] += 1;
53865683 }
5387- let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
5684+ let present: Vec<u16> = (0..256u16)
5685+ .filter(|&v| histogram[usize::from(v)] > 0)
5686+ .collect();
53885687 if present.len() < 2 {
53895688 return Vec::new();
53905689 }
@@ -5402,7 +5701,11 @@ fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
54025701 .expect("a palette holds at least two colours")
54035702 })
54045703 .collect();
5405- crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
5704+ crate::tile::PaletteY {
5705+ size: colors.len() as u8,
5706+ colors: base,
5707+ map,
5708+ }
54065709 };
54075710 if present.len() <= 8 {
54085711 return vec![exact(&present)];
@@ -5410,10 +5713,7 @@ fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
54105713 if present.len() > palette_max_colors() {
54115714 return Vec::new();
54125715 }
5413- let (lo, hi) = (
5414- i32::from(present[0]),
5415- i32::from(present[present.len() - 1]),
5416- );
5716+ let (lo, hi) = (i32::from(present[0]), i32::from(present[present.len() - 1]));
54175717 let mut out = Vec::with_capacity(2);
54185718 for n in [8usize, 4] {
54195719 // Even seeding across the block's own range, then four Lloyd passes
@@ -5595,7 +5895,10 @@ fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usiz
55955895 while bx + IBC_HASH <= true_width {
55965896 total += 1;
55975897 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
5598- if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
5898+ if hits
5899+ .iter()
5900+ .any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by))
5901+ {
55995902 matched += 1;
56005903 }
56015904 }
@@ -5603,7 +5906,11 @@ fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usiz
56035906 }
56045907 by += IBC_HASH;
56055908 }
5606- let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
5909+ let share = if total == 0 {
5910+ 0.0
5911+ } else {
5912+ matched as f64 / total as f64
5913+ };
56075914 (share * 100.0 >= intrabc_pct() as f64, share)
56085915 }
56095916
@@ -5637,7 +5944,13 @@ struct Ibc {
56375944 impl Ibc {
56385945 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
56395946 let mut table = std::collections::HashMap::new();
5640- ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
5947+ ibc_index(
5948+ &mut table,
5949+ source,
5950+ width,
5951+ (tile.0, tile.1),
5952+ (tile.2, tile.3),
5953+ );
56415954 Self {
56425955 table,
56435956 tile,
@@ -5677,7 +5990,11 @@ impl Ibc {
56775990 // Counting 64s under a 128 superblock let the search take a source
56785991 // from a 64 row the 128 visit order had not reconstructed yet.
56795992 let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 };
5680- let delay: i32 = if sb_log2 == 7 { INTRABC_DELAY_SB64 / 2 } else { INTRABC_DELAY_SB64 };
5993+ let delay: i32 = if sb_log2 == 7 {
5994+ INTRABC_DELAY_SB64 / 2
5995+ } else {
5996+ INTRABC_DELAY_SB64
5997+ };
56815998 let active_sb_row = (y as i32 - ty0) >> sb_log2;
56825999 let active_sb_col = (x as i32 - tx0) >> sb_log2;
56836000 let src_sb_row = (sy + h - 1 - ty0) >> sb_log2;
@@ -5705,7 +6022,10 @@ static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
57056022
57066023 impl Drop for Ibc {
57076024 fn drop(&mut self) {
5708- for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
6025+ for (slot, n) in [self.lookups, self.found, self.hits]
6026+ .into_iter()
6027+ .enumerate()
6028+ {
57096029 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
57106030 }
57116031 }
@@ -5850,19 +6170,17 @@ fn ibc_search(
58506170 ) -> Option<((i32, i32), f64, (usize, usize))> {
58516171 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
58526172 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
5853- let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
5854- let dv = (
5855- (sy as i32 - y as i32) * 8,
5856- (sx as i32 - x as i32) * 8,
5857- );
5858- if !ibc.dv_valid(x, y, side, side, dv) {
5859- return;
5860- }
5861- let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
5862- if best.as_ref().is_none_or(|b| cost < b.1) {
5863- *best = Some((dv, cost, (sx, sy)));
5864- }
5865- };
6173+ let consider =
6174+ |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
6175+ let dv = ((sy as i32 - y as i32) * 8, (sx as i32 - x as i32) * 8);
6176+ if !ibc.dv_valid(x, y, side, side, dv) {
6177+ return;
6178+ }
6179+ let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
6180+ if best.as_ref().is_none_or(|b| cost < b.1) {
6181+ *best = Some((dv, cost, (sx, sy)));
6182+ }
6183+ };
58666184 ibc.lookups += 1;
58676185 let key = ibc_hash(luma.source, luma.width, x, y);
58686186 // The table is filled in raster order, so the entries BEFORE this block's
@@ -5984,13 +6302,19 @@ fn code_square(
59846302 let cost_d = sse + search.lambda * split_lambda_mult() * rate;
59856303 if census_flat.is_some() {
59866304 let c = (bits + tx_depth_bits(side, depth), sse);
5987- if census_split.is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
6305+ if census_split
6306+ .is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
59886307 {
59896308 census_split = Some(c);
59906309 }
59916310 }
59926311 if cost_d < best.0 {
5993- best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
6312+ best = (
6313+ cost_d,
6314+ depth,
6315+ luma.snapshot(x, y, side),
6316+ coeffs(&levels, side),
6317+ );
59946318 best_types = types;
59956319 }
59966320 }
@@ -6050,7 +6374,11 @@ fn code_square(
60506374 * (trial.bits
60516375 + mode_bits[DC_PRED as usize]
60526376 + crate::tile::palette_bits(&pal, side, on)
6053- + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
6377+ + if tx_select {
6378+ tx_depth_bits(side, 0)
6379+ } else {
6380+ 0.0
6381+ });
60546382 if cost_p < cost {
60556383 cost = cost_p;
60566384 mode = DC_PRED as u8;
@@ -6101,7 +6429,11 @@ fn code_square(
61016429 }
61026430 let one_bits = symbol_bits(row, 1);
61036431 let kept = luma.snapshot(x, y, side);
6104- let max_depth = if tx_select && search.screen { max_tx_depth(side) } else { 0 };
6432+ let max_depth = if tx_select && search.screen {
6433+ max_tx_depth(side)
6434+ } else {
6435+ 0
6436+ };
61056437 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
61066438 for fi in 0..5u8 {
61076439 for depth in 0..=max_depth {
@@ -6116,7 +6448,11 @@ fn code_square(
61166448 + mode_bits[DC_PRED as usize]
61176449 + one_bits
61186450 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
6119- + if tx_select { tx_depth_bits(side, depth) } else { 0.0 });
6451+ + if tx_select {
6452+ tx_depth_bits(side, depth)
6453+ } else {
6454+ 0.0
6455+ });
61206456 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
61216457 best = Some((
61226458 cost_f,
@@ -6214,8 +6550,8 @@ const CHROMA_MODES: [u8; 7] = [
62146550 /// The thirteen intra mode names, for the chroma fire count's print.
62156551 #[cfg(test)]
62166552 const UV_MODE_NAMES: [&str; 14] = [
6217- "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
6218- "SMOOTH_H", "PAETH", "CFL",
6553+ "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", "SMOOTH_H",
6554+ "PAETH", "CFL",
62196555 ];
62206556
62216557 /// How many blocks each chroma mode has won, indexed by the mode itself --
@@ -6253,18 +6589,16 @@ pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
62536589 /// Whether the luma search refines a directional winner's `angle_delta_y`
62546590 /// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
62556591 fn angle_delta_on() -> bool {
6256- static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6257- crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0")
6258- });
6592+ static ENV: std::sync::LazyLock<Option<bool>> =
6593+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0"));
62596594 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
62606595 }
62616596
62626597 /// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
62636598 /// switches it off, which is how the lane measured its own on/off pair).
62646599 fn cfl_on() -> bool {
6265- static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6266- crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0")
6267- });
6600+ static ENV: std::sync::LazyLock<Option<bool>> =
6601+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0"));
62686602 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
62696603 }
62706604
@@ -6347,7 +6681,9 @@ pub(crate) fn filter_intra_on() -> bool {
63476681 return forced;
63486682 }
63496683 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6350- crate::envflags::var("EC_AV1_FILTER_INTRA").ok().map(|v| v != "0")
6684+ crate::envflags::var("EC_AV1_FILTER_INTRA")
6685+ .ok()
6686+ .map(|v| v != "0")
63516687 });
63526688 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
63536689 }
@@ -6470,8 +6806,24 @@ fn search_chroma(
64706806 } else {
64716807 crate::decode::default_intra_tx_type(mode)
64726808 };
6473- let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6474- let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6809+ let u = chroma[0].trial_typed(
6810+ at,
6811+ mode,
6812+ 0,
6813+ search.base_q_idx,
6814+ search.deadzone,
6815+ tx_type,
6816+ fctx,
6817+ );
6818+ let v = chroma[1].trial_typed(
6819+ at,
6820+ mode,
6821+ 0,
6822+ search.base_q_idx,
6823+ search.deadzone,
6824+ tx_type,
6825+ fctx,
6826+ );
64756827 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
64766828 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
64776829 best = Some((cost, mode, u, v));
@@ -6543,10 +6895,24 @@ fn search_chroma(
65436895 };
65446896 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
65456897 let u_trial = chroma[0].code_from_prediction(
6546- at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
6898+ at.x,
6899+ at.y,
6900+ at.side,
6901+ &pu,
6902+ false,
6903+ search.base_q_idx,
6904+ search.deadzone,
6905+ set,
65476906 );
65486907 let v_trial = chroma[1].code_from_prediction(
6549- at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
6908+ at.x,
6909+ at.y,
6910+ at.side,
6911+ &pv,
6912+ false,
6913+ search.base_q_idx,
6914+ search.deadzone,
6915+ set,
65506916 );
65516917 let cost_p = u_trial.sse
65526918 + v_trial.sse
@@ -6583,7 +6949,16 @@ fn search_chroma(
65836949 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
65846950 let mut prediction = vec![0u8; at.side * at.side];
65856951 intra_predict_u8(
6586- DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction,
6952+ DC_PRED,
6953+ 0,
6954+ above,
6955+ left,
6956+ corner,
6957+ at.side,
6958+ at.side,
6959+ false,
6960+ false,
6961+ &mut prediction,
65876962 fctx,
65886963 );
65896964 prediction
@@ -6660,11 +7035,7 @@ fn search_chroma(
66607035 };
66617036 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
66627037 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
6663- let combos: [(i32, i32); 3] = [
6664- (picked[0], picked[1]),
6665- (picked[0], 0),
6666- (0, picked[1]),
6667- ];
7038+ let combos: [(i32, i32); 3] = [(picked[0], picked[1]), (picked[0], 0), (0, picked[1])];
66687039 for &(alpha_u, alpha_v) in &combos {
66697040 if (alpha_u, alpha_v) == (0, 0) {
66707041 continue;
@@ -6752,9 +7123,17 @@ fn leaf_compound_stacks<'a>(
67527123 r,
67537124 p,
67547125 crate::mvstack::find_mv_stack_compound(
6755- grid, mi_row, mi_col, bw4, bh4,
6756- (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6757- grid.sign_bias_table(), &[(0, 0); 7], None,
7126+ grid,
7127+ mi_row,
7128+ mi_col,
7129+ bw4,
7130+ bh4,
7131+ (crate::mvstack::LAST_FRAME, r),
7132+ mi_cols,
7133+ mi_rows,
7134+ grid.sign_bias_table(),
7135+ &[(0, 0); 7],
7136+ None,
67587137 ),
67597138 )
67607139 })
@@ -6945,7 +7324,8 @@ fn code_square_inter(
69457324 false,
69467325 search.base_q_idx,
69477326 search.deadzone,
6948- luma_set, fctx,
7327+ luma_set,
7328+ fctx,
69497329 );
69507330 let u = mc_trial(
69517331 &chroma[0],
@@ -6961,7 +7341,8 @@ fn code_square_inter(
69617341 false,
69627342 search.base_q_idx,
69637343 search.deadzone,
6964- chroma_set, fctx,
7344+ chroma_set,
7345+ fctx,
69657346 );
69667347 let v = mc_trial(
69677348 &chroma[1],
@@ -6977,7 +7358,8 @@ fn code_square_inter(
69777358 false,
69787359 search.base_q_idx,
69797360 search.deadzone,
6980- chroma_set, fctx,
7361+ chroma_set,
7362+ fctx,
69817363 );
69827364 let skip = luma_trial.levels.iter().all(|&l| l == 0)
69837365 && u.levels.iter().all(|&l| l == 0)
@@ -7055,7 +7437,8 @@ fn code_square_inter(
70557437 side,
70567438 stack.pred_mv,
70577439 &seeds[..seed_n],
7058- search.lambda, fctx,
7440+ search.lambda,
7441+ fctx,
70597442 1,
70607443 );
70617444 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
@@ -7063,7 +7446,15 @@ fn code_square_inter(
70637446 let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
70647447 if mv_residual.is_none() {
70657448 // lane-newmv: a vector the writer cannot name never reaches RD.
7066- newmv_census_block(side, false, f64::INFINITY, best.0, new_mv, stack.nearest_mv, 0.0);
7449+ newmv_census_block(
7450+ side,
7451+ false,
7452+ f64::INFINITY,
7453+ best.0,
7454+ new_mv,
7455+ stack.nearest_mv,
7456+ 0.0,
7457+ );
70677458 }
70687459 if let Some(mv_bits) = mv_residual {
70697460 searched_new = Some(new_mv);
@@ -7074,17 +7465,54 @@ fn code_square_inter(
70747465 } else {
70757466 (
70767467 mc_trial(
7077- luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
7078- ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
7468+ luma,
7469+ x,
7470+ y,
7471+ side,
7472+ new_mv,
7473+ true,
7474+ ref_luma.0,
7475+ ref_luma.1,
7476+ ref_luma.2,
7477+ ref_luma.3,
7478+ false,
7479+ search.base_q_idx,
7480+ search.deadzone,
7481+ luma_set,
7482+ fctx,
70797483 ),
70807484 mc_trial(
7081- &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
7082- ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
7485+ &chroma[0],
7486+ x / 2,
7487+ y / 2,
7488+ side / 2,
7489+ new_mv,
7490+ false,
7491+ ref_u.0,
7492+ ref_u.1,
7493+ ref_u.2,
7494+ ref_u.3,
7495+ false,
7496+ search.base_q_idx,
7497+ search.deadzone,
7498+ chroma_set,
70837499 fctx,
70847500 ),
70857501 mc_trial(
7086- &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
7087- ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
7502+ &chroma[1],
7503+ x / 2,
7504+ y / 2,
7505+ side / 2,
7506+ new_mv,
7507+ false,
7508+ ref_v.0,
7509+ ref_v.1,
7510+ ref_v.2,
7511+ ref_v.3,
7512+ false,
7513+ search.base_q_idx,
7514+ search.deadzone,
7515+ chroma_set,
70887516 fctx,
70897517 ),
70907518 )
@@ -7113,7 +7541,15 @@ fn code_square_inter(
71137541 } else {
71147542 luma_new.bits + u_new.bits + v_new.bits
71157543 });
7116- newmv_census_block(side, true, cost_new, best.0, new_mv, stack.nearest_mv, mv_bits);
7544+ newmv_census_block(
7545+ side,
7546+ true,
7547+ cost_new,
7548+ best.0,
7549+ new_mv,
7550+ stack.nearest_mv,
7551+ mv_bits,
7552+ );
71177553 if cost_new < best.0 {
71187554 single_syntax = intra_inter_bits(true)
71197555 + single_ref_bits
@@ -7154,13 +7590,15 @@ fn code_square_inter(
71547590 // above stay.
71557591 arfmode_hit(2);
71567592 }
7157- for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound() && search.arf_leaf_compound) {
7593+ for (ref1, g, cstack) in compound
7594+ .iter()
7595+ .filter(|_| leaf_compound() && search.arf_leaf_compound)
7596+ {
71587597 let (ref1, g) = (*ref1, *g);
71597598 // The whole `comp_mode` + reference-pair tree at the writer's own
71607599 // contexts, for THIS pair (lane-ctx).
71617600 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
7162- let mode_ctx =
7163- cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
7601+ let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
71647602 let mode_bits_of =
71657603 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
71667604 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
@@ -7213,8 +7651,19 @@ fn code_square_inter(
72137651 let skip = margin > 0.0
72147652 && searched_new_cost.is_some_and(|last| {
72157653 motion::cost_at(
7216- &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y,
7217- side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx,
7654+ &g.y,
7655+ g.width,
7656+ luma.true_width,
7657+ luma.true_height,
7658+ &source_block,
7659+ x,
7660+ y,
7661+ side,
7662+ side,
7663+ cstack.nearest_mv.1,
7664+ cbase.1,
7665+ search.lambda,
7666+ fctx,
72187667 ) * margin
72197668 <= last
72207669 });
@@ -7229,8 +7678,20 @@ fn code_square_inter(
72297678 seed_n += 1;
72307679 }
72317680 let found = motion::search(
7232- &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side,
7233- side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1),
7681+ &g.y,
7682+ g.width,
7683+ luma.true_width,
7684+ luma.true_height,
7685+ &source_block,
7686+ x,
7687+ y,
7688+ side,
7689+ side,
7690+ cbase.1,
7691+ &seeds[..seed_n],
7692+ search.lambda,
7693+ fctx,
7694+ ref_distance(ref1),
72347695 );
72357696 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
72367697 }
@@ -7302,19 +7763,46 @@ fn code_square_inter(
73027763 );
73037764 for (mvs, bits, info) in ccands {
73047765 let luma_c = mc_trial_compound(
7305- luma, x, y, side, mvs, true,
7306- (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
7307- search.base_q_idx, search.deadzone, luma_set, fctx,
7766+ luma,
7767+ x,
7768+ y,
7769+ side,
7770+ mvs,
7771+ true,
7772+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7773+ g_luma,
7774+ search.base_q_idx,
7775+ search.deadzone,
7776+ luma_set,
7777+ fctx,
73087778 );
73097779 let u_c = mc_trial_compound(
7310- &chroma[0], x / 2, y / 2, side / 2, mvs, false,
7311- (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
7312- search.base_q_idx, search.deadzone, chroma_set, fctx,
7780+ &chroma[0],
7781+ x / 2,
7782+ y / 2,
7783+ side / 2,
7784+ mvs,
7785+ false,
7786+ (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7787+ g_u,
7788+ search.base_q_idx,
7789+ search.deadzone,
7790+ chroma_set,
7791+ fctx,
73137792 );
73147793 let v_c = mc_trial_compound(
7315- &chroma[1], x / 2, y / 2, side / 2, mvs, false,
7316- (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
7317- search.base_q_idx, search.deadzone, chroma_set, fctx,
7794+ &chroma[1],
7795+ x / 2,
7796+ y / 2,
7797+ side / 2,
7798+ mvs,
7799+ false,
7800+ (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7801+ g_v,
7802+ search.base_q_idx,
7803+ search.deadzone,
7804+ chroma_set,
7805+ fctx,
73187806 );
73197807 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
73207808 && u_c.levels.iter().all(|&l| l == 0)
@@ -7326,7 +7814,11 @@ fn code_square_inter(
73267814 * (skip_bits(skip_c)
73277815 + intra_inter_bits(true)
73287816 + bits
7329- + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
7817+ + if skip_c {
7818+ 0.0
7819+ } else {
7820+ luma_c.bits + u_c.bits + v_c.bits
7821+ });
73307822 if cost_c < best.0 {
73317823 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
73327824 }
@@ -7409,14 +7901,33 @@ fn code_square_inter(
74097901 }
74107902 for (motion, pred) in candidates {
74117903 let luma_o = luma.code_from_prediction(
7412- x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set,
7904+ x,
7905+ y,
7906+ side,
7907+ &pred[0],
7908+ false,
7909+ search.base_q_idx,
7910+ search.deadzone,
7911+ luma_set,
74137912 );
74147913 let u_o = chroma[0].code_from_prediction(
7415- x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone,
7914+ x / 2,
7915+ y / 2,
7916+ side / 2,
7917+ &pred[1],
7918+ false,
7919+ search.base_q_idx,
7920+ search.deadzone,
74167921 chroma_set,
74177922 );
74187923 let v_o = chroma[1].code_from_prediction(
7419- x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone,
7924+ x / 2,
7925+ y / 2,
7926+ side / 2,
7927+ &pred[2],
7928+ false,
7929+ search.base_q_idx,
7930+ search.deadzone,
74207931 chroma_set,
74217932 );
74227933 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
@@ -7429,7 +7940,11 @@ fn code_square_inter(
74297940 * (skip_bits(skip_o)
74307941 + single_syntax
74317942 + mm(motion)
7432- + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits });
7943+ + if skip_o {
7944+ 0.0
7945+ } else {
7946+ luma_o.bits + u_o.bits + v_o.bits
7947+ });
74337948 // The incumbent pays the motion_mode symbol IT would code, so
74347949 // both sides of the comparison carry that syntax.
74357950 if cost_o < best.0 + search.lambda * mm(motion_won) {
@@ -7487,22 +8002,31 @@ fn code_square_inter(
74878002 )
74888003 })
74898004 });
7490- let (levels, tx_depth, dcost, luma_tx_types) = if motion_won != 0
7491- || (info.ref1.is_some() && second.is_none())
7492- {
7493- luma.commit(x, y, side, &luma_new);
7494- (luma_new.levels.clone(), 0, 0.0, Vec::new())
7495- } else {
7496- commit_inter_luma(
7497- luma, (x, y), side, info.mv,
7498- (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7499- search, &luma_new, skip_new, second, fctx,
7500- )
7501- };
8005+ let (levels, tx_depth, dcost, luma_tx_types) =
8006+ if motion_won != 0 || (info.ref1.is_some() && second.is_none()) {
8007+ luma.commit(x, y, side, &luma_new);
8008+ (luma_new.levels.clone(), 0, 0.0, Vec::new())
8009+ } else {
8010+ commit_inter_luma(
8011+ luma,
8012+ (x, y),
8013+ side,
8014+ info.mv,
8015+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
8016+ search,
8017+ &luma_new,
8018+ skip_new,
8019+ second,
8020+ fctx,
8021+ )
8022+ };
75028023 // lane-txrd: chroma follows the luma type the search just chose.
75038024 let [u_new, v_new] = match luma_tx_types.first().copied() {
75048025 Some(t) => recode_inter_chroma(
7505- chroma, (x, y), side, info.mv,
8026+ chroma,
8027+ (x, y),
8028+ side,
8029+ info.mv,
75068030 [
75078031 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
75088032 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
@@ -7512,13 +8036,26 @@ fn code_square_inter(
75128036 (
75138037 info.mv1,
75148038 [
7515- (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
7516- (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
8039+ (
8040+ g.u.as_slice(),
8041+ g.width / 2,
8042+ chroma[0].true_width,
8043+ chroma[0].true_height,
8044+ ),
8045+ (
8046+ g.v.as_slice(),
8047+ g.width / 2,
8048+ chroma[1].true_width,
8049+ chroma[1].true_height,
8050+ ),
75178051 ],
75188052 )
75198053 })
75208054 }),
7521- search, chroma_set, t, fctx,
8055+ search,
8056+ chroma_set,
8057+ t,
8058+ fctx,
75228059 )
75238060 .unwrap_or([u_new, v_new]),
75248061 None => [u_new, v_new],
@@ -7539,7 +8076,7 @@ fn code_square_inter(
75398076 eight: None,
crates/ec-av1/src/encoder.rsmodified+478 -139
@@ -205,7 +205,14 @@ struct LevelPlan {
205205
206206 impl LevelPlan {
207207 fn new(slot: usize, offset: i16, weight: f64) -> Self {
208- Self { slot, offset, weight, left: weight, bound: false, rate: 0.0 }
208+ Self {
209+ slot,
210+ offset,
211+ weight,
212+ left: weight,
213+ bound: false,
214+ rate: 0.0,
215+ }
209216 }
210217 }
211218
@@ -325,9 +332,8 @@ impl RateLoop {
325332 };
326333 let (hidden, leaves) = gop_shape(p, gop);
327334 let key = KEY_WEIGHT * w(p.key_q_offset);
328- let total: f64 = key
329- + leaves as f64
330- + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::<f64>();
335+ let total: f64 =
336+ key + leaves as f64 + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::<f64>();
331337 // One leaf's byte target: the run is worth `gop` frame targets and
332338 // `total` leaves.
333339 let scale = target_bytes * gop.max(1) as f64 / total.max(f64::EPSILON);
@@ -441,7 +447,10 @@ impl RateLoop {
441447 };
442448 self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0);
443449 let bound = !(1..=255).contains(&raw_q);
444- if let Some(plan) = self.plan_of(slot, offset).and_then(|i| self.plans[i].as_mut()) {
450+ if let Some(plan) = self
451+ .plan_of(slot, offset)
452+ .and_then(|i| self.plans[i].as_mut())
453+ {
445454 plan.bound = bound;
446455 plan.rate = actual_bytes as f64 / frame_weight.max(f64::EPSILON);
447456 }
@@ -478,7 +487,14 @@ impl RateLoop {
478487 /// clamped proportional step, the re-plan only moves the TARGET the next
479488 /// frame is measured against, and every key frame resets the whole plan,
480489 /// so no debt outlives one run.
481- fn replan(&mut self, level: Level, slot: usize, offset: i16, frame_weight: f64, actual_bytes: f64) {
490+ fn replan(
491+ &mut self,
492+ level: Level,
493+ slot: usize,
494+ offset: i16,
495+ frame_weight: f64,
496+ actual_bytes: f64,
497+ ) {
482498 if !self.per_level {
483499 return;
484500 }
@@ -491,7 +507,10 @@ impl RateLoop {
491507 }
492508 self.left_weight -= frame_weight;
493509 self.left_bytes -= actual_bytes;
494- if let Some(plan) = self.plan_of(slot, offset).and_then(|i| self.plans[i].as_mut()) {
510+ if let Some(plan) = self
511+ .plan_of(slot, offset)
512+ .and_then(|i| self.plans[i].as_mut())
513+ {
495514 plan.left = (plan.left - frame_weight).max(0.0);
496515 }
497516 // The tail of a run is not re-planned: under a leaf's worth of weight
@@ -526,8 +545,10 @@ impl RateLoop {
526545 // Every movable level is spent: nothing left to re-solve over.
527546 return;
528547 }
529- let scale = (bytes / weight)
530- .clamp(self.scale0 * Self::REPLAN_FLOOR, self.scale0 * Self::REPLAN_CLAMP);
548+ let scale = (bytes / weight).clamp(
549+ self.scale0 * Self::REPLAN_FLOOR,
550+ self.scale0 * Self::REPLAN_CLAMP,
551+ );
531552 self.target = [scale * self.key_weight, scale, scale];
532553 }
533554 }
@@ -759,8 +780,14 @@ impl Pyramid {
759780 }
760781 Some(Self {
761782 mini_gop,
762- arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset),
763- leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset),
783+ arf_q_offset: f
784+ .next()
785+ .and_then(|v| v.parse().ok())
786+ .unwrap_or(d.arf_q_offset),
787+ leaf_q_offset: f
788+ .next()
789+ .and_then(|v| v.parse().ok())
790+ .unwrap_or(d.leaf_q_offset),
764791 // A fourth field is the mid-level offset; the literal `off` asks
765792 // for the two-level pyramid at the same shape (the A/B arm the
766793 // sweep needs), and no field at all keeps the default's.
@@ -770,7 +797,10 @@ impl Pyramid {
770797 Some(v) => v.parse().ok().or(d.mid_q_offset),
771798 },
772799 // A fifth field is the key frame's own offset.
773- key_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.key_q_offset),
800+ key_q_offset: f
801+ .next()
802+ .and_then(|v| v.parse().ok())
803+ .unwrap_or(d.key_q_offset),
774804 // A sixth field is the quarter level's offset, `off` for none.
775805 quarter_q_offset: match f.next() {
776806 None => d.quarter_q_offset,
@@ -1128,8 +1158,7 @@ fn last2() -> bool {
11281158 /// this crate's tests never call `set_var` (`crate::envflags`), so the
11291159 /// witness turns the lever on through this while holding
11301160 /// [`crate::speed::knob_write`].
1131-static LAST2_OVERRIDE: std::sync::atomic::AtomicU8 =
1132- std::sync::atomic::AtomicU8::new(u8::MAX);
1161+static LAST2_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
11331162
11341163 /// Sets [`LAST2_OVERRIDE`]; `None` clears it.
11351164 #[allow(dead_code)] // set only from the `#[cfg(test)]` witness
@@ -1256,8 +1285,7 @@ pub(crate) fn arf_tf_window_future() -> usize {
12561285 /// [`set_last2`] has (this crate's tests never call `set_var`); `u8::MAX` /
12571286 /// `usize::MAX` is unset, and a witness holds [`crate::speed::knob_write`]
12581287 /// while it uses them.
1259-static LOOKAHEAD_OVERRIDE: std::sync::atomic::AtomicU8 =
1260- std::sync::atomic::AtomicU8::new(u8::MAX);
1288+static LOOKAHEAD_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
12611289 static ARF_TF_FUT_OVERRIDE: std::sync::atomic::AtomicUsize =
12621290 std::sync::atomic::AtomicUsize::new(usize::MAX);
12631291 static TPL_FUT_OVERRIDE: std::sync::atomic::AtomicUsize =
@@ -1275,13 +1303,19 @@ pub(crate) fn set_lookahead(on: Option<bool>) {
12751303 /// Sets [`ARF_TF_FUT_OVERRIDE`]; `None` clears it.
12761304 #[allow(dead_code)] // set only from the `#[cfg(test)]` witness
12771305 pub(crate) fn set_arf_tf_future(n: Option<usize>) {
1278- ARF_TF_FUT_OVERRIDE.store(n.unwrap_or(usize::MAX), std::sync::atomic::Ordering::Relaxed);
1306+ ARF_TF_FUT_OVERRIDE.store(
1307+ n.unwrap_or(usize::MAX),
1308+ std::sync::atomic::Ordering::Relaxed,
1309+ );
12791310 }
12801311
12811312 /// Sets [`TPL_FUT_OVERRIDE`]; `None` clears it.
12821313 #[allow(dead_code)] // set only from the `#[cfg(test)]` witness
12831314 pub(crate) fn set_tpl_fut(n: Option<usize>) {
1284- TPL_FUT_OVERRIDE.store(n.unwrap_or(usize::MAX), std::sync::atomic::Ordering::Relaxed);
1315+ TPL_FUT_OVERRIDE.store(
1316+ n.unwrap_or(usize::MAX),
1317+ std::sync::atomic::Ordering::Relaxed,
1318+ );
12851319 }
12861320
12871321 /// lane-tplfut: which window the TOP ARF's temporal lambda map propagates
@@ -1816,7 +1850,10 @@ impl Av1Encoder {
18161850 None,
18171851 &self.fctx,
18181852 None,
1819- &lookahead.iter().map(|n| n.padded_to(SUPERBLOCK)).collect::<Vec<_>>(),
1853+ &lookahead
1854+ .iter()
1855+ .map(|n| n.padded_to(SUPERBLOCK))
1856+ .collect::<Vec<_>>(),
18201857 )?
18211858 };
18221859
@@ -1892,15 +1929,18 @@ impl Av1Encoder {
18921929 let mut collected = encoder.collected.take().expect("collecting");
18931930 // Every source picture is coded exactly once, so a frame's display
18941931 // order IS its index once the list is sorted by it.
1895- let coding_order: Vec<usize> =
1896- collected.iter().map(|(order, _)| *order as usize).collect();
1932+ let coding_order: Vec<usize> = collected.iter().map(|(order, _)| *order as usize).collect();
18971933 collected.sort_by_key(|(order, _)| *order);
18981934 let frames: Vec<Encoded> = collected.into_iter().map(|(_, encoded)| encoded).collect();
18991935 assert!(
19001936 coding_order.iter().all(|&i| i < frames.len()),
19011937 "a coded frame's display position is outside the sequence"
19021938 );
1903- Ok(crate::encode::EncodedSequence { stream, frames, coding_order })
1939+ Ok(crate::encode::EncodedSequence {
1940+ stream,
1941+ frames,
1942+ coding_order,
1943+ })
19041944 }
19051945
19061946 /// Stamps a packet with its display and coding positions and advances the
@@ -1938,7 +1978,9 @@ impl Av1Encoder {
19381978 let base = self
19391979 .rate_loop
19401980 .as_ref()
1941- .map_or(i16::from(self.config.base_q_idx), |r| i16::from(r.q_idx(Level::Key)));
1981+ .map_or(i16::from(self.config.base_q_idx), |r| {
1982+ i16::from(r.q_idx(Level::Key))
1983+ });
19421984 let offset = self.pyramid.map_or(0, |p| p.key_q_offset);
19431985 let base_q_idx = (base + offset).clamp(1, 255) as u8;
19441986 let encoded = encode_key_frame_inner(
@@ -2030,8 +2072,7 @@ impl Av1Encoder {
20302072 // A LAST2 slot only counts when it holds a picture that is not the
20312073 // one `LAST_FRAME` already names; otherwise the frame codes the
20322074 // reference set it always did.
2033- let last2_slot = last2_slot
2034- .filter(|&s| s != last_slot && self.dpb[s as usize].is_some());
2075+ let last2_slot = last2_slot.filter(|&s| s != last_slot && self.dpb[s as usize].is_some());
20352076 let slots = [
20362077 last_slot,
20372078 last2_slot.unwrap_or(last_slot),
@@ -2055,14 +2096,26 @@ impl Av1Encoder {
20552096 .as_ref()
20562097 .map(|s| s.picture.clone())
20572098 .ok_or_else(|| {
2058- Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction")
2099+ Error::unsupported(
2100+ "AV1 encode",
2101+ "an inter frame needs a previous reconstruction",
2102+ )
20592103 })?;
2060- let last2 = last2_slot.and_then(|s| self.dpb[s as usize].as_ref().map(|d| d.picture.clone()));
2061- let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone());
2104+ let last2 =
2105+ last2_slot.and_then(|s| self.dpb[s as usize].as_ref().map(|d| d.picture.clone()));
2106+ let golden = self.dpb[GOLDEN_SLOT as usize]
2107+ .as_ref()
2108+ .map(|s| s.picture.clone());
20622109 let altref = (altref_slot != GOLDEN_SLOT)
2063- .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone()))
2110+ .then(|| {
2111+ self.dpb[altref_slot as usize]
2112+ .as_ref()
2113+ .map(|s| s.picture.clone())
2114+ })
20642115 .flatten();
2065- let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone());
2116+ let start_cdfs = self.dpb[last_slot as usize]
2117+ .as_ref()
2118+ .map(|s| s.cdfs.0.clone());
20662119 // lane-arfpred: the top ARF is coded from a TEMPORALLY FILTERED
20672120 // source when `speed::ARF_TF` is non-zero -- the grain it would
20682121 // otherwise spend its residual on is averaged out against the
@@ -2097,33 +2150,35 @@ impl Av1Encoder {
20972150 }
20982151 false => source,
20992152 };
2100- let encoded = || -> Result<Encoded> { encode_inter_frame(
2101- &source,
2102- &reference,
2103- base_q_idx,
2104- DEADZONE,
2105- order_hint,
2106- order_hints,
2107- render,
2108- start_cdfs.as_ref(),
2109- golden.as_ref(),
2110- altref.as_ref(),
2111- last2.as_ref(),
2112- &self.fctx,
2113- Some(crate::encode::PyramidFrame {
2114- last_slot,
2115- self_slot,
2116- altref_slot,
2117- last2_slot,
2118- show_frame,
2119- sign_bias,
2120- dq_level,
2121- }),
2122- // lane-arfcen: the group's own sources ARE this frame's window
2123- // (`tpl_window`); it was `&[]` here, which switched the temporal
2124- // lambda map off on every frame the default stream codes.
2125- lookahead,
2126- ) }();
2153+ let encoded = || -> Result<Encoded> {
2154+ encode_inter_frame(
2155+ &source,
2156+ &reference,
2157+ base_q_idx,
2158+ DEADZONE,
2159+ order_hint,
2160+ order_hints,
2161+ render,
2162+ start_cdfs.as_ref(),
2163+ golden.as_ref(),
2164+ altref.as_ref(),
2165+ last2.as_ref(),
2166+ &self.fctx,
2167+ Some(crate::encode::PyramidFrame {
2168+ last_slot,
2169+ self_slot,
2170+ altref_slot,
2171+ last2_slot,
2172+ show_frame,
2173+ sign_bias,
2174+ dq_level,
2175+ }),
2176+ // lane-arfcen: the group's own sources ARE this frame's window
2177+ // (`tpl_window`); it was `&[]` here, which switched the temporal
2178+ // lambda map off on every frame the default stream codes.
2179+ lookahead,
2180+ )
2181+ }();
21272182 // Name the pyramid position in any failure: an error out of the tile
21282183 // writer or the filter search is otherwise indistinguishable between
21292184 // the hidden frame and the leaves that read it.
@@ -2212,14 +2267,20 @@ impl Av1Encoder {
22122267 false => group[pos + 1..].iter().map(|(_, p)| p).collect(),
22132268 true => group[..pos].iter().rev().map(|(_, p)| p).collect(),
22142269 };
2215- window.into_iter().take(depth - 1).map(|p| p.padded_to(SUPERBLOCK)).collect()
2270+ window
2271+ .into_iter()
2272+ .take(depth - 1)
2273+ .map(|p| p.padded_to(SUPERBLOCK))
2274+ .collect()
22162275 };
22172276 // lane-last2: the slot a frame reading `last_slot` as `LAST_FRAME`
22182277 // names as `LAST2_FRAME` -- the most recent shown leaf that is not
22192278 // the one it already reads. `None` with the lever off, or before two
22202279 // distinct past pictures exist.
22212280 let last2_of = |hist: &[u8], last_slot: u8| -> Option<u8> {
2222- last2().then(|| hist.iter().copied().find(|&s| s != last_slot)).flatten()
2281+ last2()
2282+ .then(|| hist.iter().copied().find(|&s| s != last_slot))
2283+ .flatten()
22232284 };
22242285 let anchor_slot = ANCHOR_SLOTS[self.anchor];
22252286 let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor];
@@ -2263,7 +2324,11 @@ impl Av1Encoder {
22632324 // `n` of the buffered display-future sources, nearest first, padded
22642325 // like the frame being coded.
22652326 let arf_tpl_future = |n: usize| -> Vec<Picture> {
2266- future.iter().take(n).map(|(_, p)| p.padded_to(SUPERBLOCK)).collect()
2327+ future
2328+ .iter()
2329+ .take(n)
2330+ .map(|(_, p)| p.padded_to(SUPERBLOCK))
2331+ .collect()
22672332 };
22682333 let arf_tpl: Vec<Picture> = {
22692334 let depth = crate::encode::tpl_depth();
@@ -2332,10 +2397,13 @@ impl Av1Encoder {
23322397 // third level is switched on by the RUN's length, not by the group's:
23332398 // the same GOP-length dependence `group_target` itself was built for.
23342399 let long_run = self.config.gop > pyramid.mini_gop + pyramid.mini_gop / 2;
2335- let mid = pyramid.mid_q_offset.filter(|_| leaves >= 3 && long_run).map(|offset| {
2336- let at = (leaves - 1) / 2;
2337- (at, offset)
2338- });
2400+ let mid = pyramid
2401+ .mid_q_offset
2402+ .filter(|_| leaves >= 3 && long_run)
2403+ .map(|offset| {
2404+ let at = (leaves - 1) / 2;
2405+ (at, offset)
2406+ });
23392407 if let Some((at, offset)) = mid {
23402408 let (order, picture) = group[at].clone();
23412409 packets.push(self.encode_pyramid_inter(
@@ -2571,8 +2639,7 @@ mod tests {
25712639 tile_rows_log2: 0,
25722640 };
25732641 let rate = RateTarget::BytesPerFrame(2_000);
2574- let mut enc =
2575- Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap();
2642+ let mut enc = Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap();
25762643 let packets = encode_all(&mut enc, &pictures[..gop]);
25772644 let coded = |level: Level| packets.iter().filter(|p| p.level == level).count();
25782645 let (hidden, leaves) = gop_shape(pyramid, gop);
@@ -2592,8 +2659,12 @@ mod tests {
25922659 let target_bytes = 2_000.0;
25932660 let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
25942661 let planned = loop_.target[0]
2595- + loop_.target[2] * (leaves as f64
2596- + hidden.iter().map(|&(o, n)| n as f64 * loop_.weight(o)).sum::<f64>());
2662+ + loop_.target[2]
2663+ * (leaves as f64
2664+ + hidden
2665+ .iter()
2666+ .map(|&(o, n)| n as f64 * loop_.weight(o))
2667+ .sum::<f64>());
25972668 assert!(
25982669 (planned - target_bytes * gop as f64).abs() < 1.0,
25992670 "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run",
@@ -2646,7 +2717,8 @@ mod tests {
26462717 "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \
26472718 give {:.3})",
26482719 rl.target[2],
2649- (run_bytes - key_bytes - arf_bytes) / (leaves as f64 + hidden_weight - rl.weight(offset))
2720+ (run_bytes - key_bytes - arf_bytes)
2721+ / (leaves as f64 + hidden_weight - rl.weight(offset))
26502722 );
26512723 // And the re-plan stays BOUNDED: hidden levels that spend nothing at
26522724 // all cannot run the leaves' target away.
@@ -2758,7 +2830,11 @@ mod tests {
27582830 let tail = enc.flush().unwrap();
27592831 assert_eq!(tail.len() as u64, delay, "flush yields the whole queue");
27602832 for (i, p) in tail.iter().enumerate() {
2761- assert_eq!(p.order, pictures - delay + i as u64, "flushed packet {i}: order");
2833+ assert_eq!(
2834+ p.order,
2835+ pictures - delay + i as u64,
2836+ "flushed packet {i}: order"
2837+ );
27622838 assert!(!p.data.is_empty(), "flushed packet {i}: empty");
27632839 }
27642840 assert!(enc.flush().unwrap().is_empty(), "nothing is held twice");
@@ -2808,9 +2884,7 @@ mod tests {
28082884 });
28092885 let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect();
28102886 let pyramid = Pyramid::from_env().expect("the pyramid is this build's default");
2811- for (content, pictures, is_screen) in
2812- [("film", &film, false), ("screen", &screen, true)]
2813- {
2887+ for (content, pictures, is_screen) in [("film", &film, false), ("screen", &screen, true)] {
28142888 let (width, height) = (pictures[0].width, pictures[0].height);
28152889 for q in [150u8, 60] {
28162890 let config = EncoderConfig {
@@ -2838,7 +2912,10 @@ mod tests {
28382912 );
28392913 let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap();
28402914 assert_eq!(
2841- (packets.iter().map(|p| p.data.len()).sum::<usize>(), concat(&packets)),
2915+ (
2916+ packets.iter().map(|p| p.data.len()).sum::<usize>(),
2917+ concat(&packets)
2918+ ),
28422919 (sequence.stream.len(), sequence.stream.clone()),
28432920 "{content} q={q}: the facade's stream is not the sequence path's"
28442921 );
@@ -2848,7 +2925,11 @@ mod tests {
28482925 "{content} q={q}: one entry per picture, in display order"
28492926 );
28502927 if is_screen {
2851- assert_eq!(packets.len(), frames, "{content} q={q}: one packet per picture");
2928+ assert_eq!(
2929+ packets.len(),
2930+ frames,
2931+ "{content} q={q}: one packet per picture"
2932+ );
28522933 for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() {
28532934 let cropped = crate::encode::crop_encoded(coded, width, height);
28542935 assert_eq!(
@@ -2894,7 +2975,11 @@ mod tests {
28942975 let flat_packets = encode_all(&mut flat, &pictures);
28952976 let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
28962977 let gated_packets = encode_all(&mut gated, &pictures);
2897- assert_eq!(gated.pyramid(), None, "the gate left a screen stream on the pyramid");
2978+ assert_eq!(
2979+ gated.pyramid(),
2980+ None,
2981+ "the gate left a screen stream on the pyramid"
2982+ );
28982983 assert_eq!(
28992984 concat(&gated_packets),
29002985 concat(&flat_packets),
@@ -2903,7 +2988,11 @@ mod tests {
29032988 crate::encode::force_screen(Some(false));
29042989 let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
29052990 let kept_packets = encode_all(&mut kept, &pictures);
2906- assert_eq!(kept.pyramid(), Some(Pyramid::default()), "the gate ate a film stream");
2991+ assert_eq!(
2992+ kept.pyramid(),
2993+ Some(Pyramid::default()),
2994+ "the gate ate a film stream"
2995+ );
29072996 assert!(
29082997 kept_packets.iter().any(|p| p.level == Level::Arf),
29092998 "a non-screen stream coded no hidden frame"
@@ -3203,8 +3292,14 @@ mod tests {
32033292 width,
32043293 height,
32053294 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
3206- u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
3207- v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
3295+ u: bytes[luma..luma + chroma]
3296+ .iter()
3297+ .map(|&v| u16::from(v))
3298+ .collect(),
3299+ v: bytes[luma + chroma..]
3300+ .iter()
3301+ .map(|&v| u16::from(v))
3302+ .collect(),
32083303 }
32093304 })
32103305 .collect(),
@@ -3270,7 +3365,9 @@ mod tests {
32703365 let _knobs = crate::speed::knob_read();
32713366 let (width, height, frames) = (640usize, 384usize, 48usize);
32723367 let Some(pictures) = h264_clip_frames(width, height, frames) else {
3273- eprintln!("SKIP bitrate_target_lands_within_5_percent_over_48_frames: no ffmpeg/fixture");
3368+ eprintln!(
3369+ "SKIP bitrate_target_lands_within_5_percent_over_48_frames: no ffmpeg/fixture"
3370+ );
32743371 return;
32753372 };
32763373 let fps = 24.0;
@@ -3522,7 +3619,10 @@ mod tests {
35223619 for packet in encode_all(&mut enc, &sources) {
35233620 stream.extend_from_slice(&packet.data);
35243621 }
3525- eprintln!("{NAME}: {} cut colour-index maps written", crate::tile::palette_cut_maps_written());
3622+ eprintln!(
3623+ "{NAME}: {} cut colour-index maps written",
3624+ crate::tile::palette_cut_maps_written()
3625+ );
35263626 assert!(
35273627 crate::tile::palette_cut_maps_written() > 0,
35283628 "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind"
@@ -3536,11 +3636,7 @@ mod tests {
35363636 let theirs = ffmpeg_decode_planes(&stream, width, height);
35373637 assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames");
35383638 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3539- for (plane, got, want) in [
3540- ("luma", &a.y, &b.0),
3541- ("U", &a.u, &b.1),
3542- ("V", &a.v, &b.2),
3543- ] {
3639+ for (plane, got, want) in [("luma", &a.y, &b.0), ("U", &a.u, &b.1), ("V", &a.v, &b.2)] {
35443640 let got: Vec<u8> = got.iter().map(|&v| v as u8).collect();
35453641 if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) {
35463642 let w = if plane == "luma" { width } else { width / 2 };
@@ -3552,6 +3648,13 @@ mod tests {
35523648 want[at],
35533649 );
35543650 }
3651+ assert_eq!(
3652+ got.len(),
3653+ want.len(),
3654+ "{NAME}: frame {i} {plane} is {} samples, ffmpeg's is {}",
3655+ got.len(),
3656+ want.len()
3657+ );
35553658 }
35563659 }
35573660 }
@@ -3573,7 +3676,14 @@ mod tests {
35733676 // our read (seen once: LAST 0 GOLDEN 0 ALTREF 0), so this takes the
35743677 // exclusive lock.
35753678 let _knobs = crate::speed::knob_write();
3576- pyramid_round_trip(Pyramid { mini_gop: 4, mid_q_offset: None, ..Pyramid::default() }, 2);
3679+ pyramid_round_trip(
3680+ Pyramid {
3681+ mini_gop: 4,
3682+ mid_q_offset: None,
3683+ ..Pyramid::default()
3684+ },
3685+ 2,
3686+ );
35773687 }
35783688
35793689 /// The same round trip over a THREE-level group (`mid_q_offset`): each
@@ -3586,7 +3696,11 @@ mod tests {
35863696 fn a_three_level_pyramid_stream_decodes_in_display_order() {
35873697 let _knobs = crate::speed::knob_write();
35883698 pyramid_round_trip(
3589- Pyramid { mini_gop: 8, mid_q_offset: Some(-8), ..Pyramid::default() },
3699+ Pyramid {
3700+ mini_gop: 8,
3701+ mid_q_offset: Some(-8),
3702+ ..Pyramid::default()
3703+ },
35903704 2,
35913705 );
35923706 }
@@ -3631,15 +3745,24 @@ mod tests {
36313745 tile_cols_log2: 0,
36323746 tile_rows_log2: 0,
36333747 };
3634- let pyramid = Pyramid { key_q_offset: offset, ..Pyramid::default() };
3748+ let pyramid = Pyramid {
3749+ key_q_offset: offset,
3750+ ..Pyramid::default()
3751+ };
36353752 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
36363753 let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap();
3637- let key = packets.iter().find(|p| p.level == Level::Key).expect("key frame");
3754+ let key = packets
3755+ .iter()
3756+ .find(|p| p.level == Level::Key)
3757+ .expect("key frame");
36383758 key.data.len()
36393759 };
36403760 let (base, finer) = (key_bytes(0), key_bytes(-48));
36413761 eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes");
3642- assert!(finer > base, "key_q_offset -48 did not reach the key frame ({finer} <= {base})");
3762+ assert!(
3763+ finer > base,
3764+ "key_q_offset -48 did not reach the key frame ({finer} <= {base})"
3765+ );
36433766 }
36443767
36453768 /// lane-last2's witness: a clip whose pictures ALTERNATE between two
@@ -3658,8 +3781,9 @@ mod tests {
36583781 let _knobs = crate::speed::knob_write();
36593782 crate::encode::force_screen(Some(false));
36603783 let (width, height) = (128usize, 128usize);
3661- let sources: Vec<Picture> =
3662- (0..9).map(|t| test_card(width, height, (t % 2) * 24)).collect();
3784+ let sources: Vec<Picture> = (0..9)
3785+ .map(|t| test_card(width, height, (t % 2) * 24))
3786+ .collect();
36633787 let run = |on: bool| -> ([usize; 8], Vec<u8>, Vec<Packet>) {
36643788 set_last2(Some(on));
36653789 let config = EncoderConfig {
@@ -3671,7 +3795,11 @@ mod tests {
36713795 tile_cols_log2: 0,
36723796 tile_rows_log2: 0,
36733797 };
3674- let pyramid = Pyramid { mini_gop: 4, mid_q_offset: None, ..Pyramid::default() };
3798+ let pyramid = Pyramid {
3799+ mini_gop: 4,
3800+ mid_q_offset: None,
3801+ ..Pyramid::default()
3802+ };
36753803 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
36763804 let _ = crate::encode::take_ref_frame_hits();
36773805 let mut packets = Vec::new();
@@ -3688,8 +3816,16 @@ mod tests {
36883816 eprintln!(
36893817 "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \
36903818 on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)",
3691- off_hits[1], off_hits[2], off_hits[4], off_hits[7], off_stream.len(),
3692- on_hits[1], on_hits[2], on_hits[4], on_hits[7], stream.len(),
3819+ off_hits[1],
3820+ off_hits[2],
3821+ off_hits[4],
3822+ off_hits[7],
3823+ off_stream.len(),
3824+ on_hits[1],
3825+ on_hits[2],
3826+ on_hits[4],
3827+ on_hits[7],
3828+ stream.len(),
36933829 );
36943830 assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF");
36953831 assert!(
@@ -3701,7 +3837,11 @@ mod tests {
37013837 // Display order and sample-exactness, both decoders (the same shape
37023838 // `pyramid_round_trip` gates the hidden frames with).
37033839 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3704- assert_eq!(ours.len(), sources.len(), "our decoder's display-order count");
3840+ assert_eq!(
3841+ ours.len(),
3842+ sources.len(),
3843+ "our decoder's display-order count"
3844+ );
37053845 if !have_ffmpeg() {
37063846 eprintln!("SKIP the ffmpeg half of the LAST2 witness: no ffmpeg");
37073847 return;
@@ -3722,7 +3862,10 @@ mod tests {
37223862 }
37233863 }
37243864 // The reordering itself is unchanged by the second leaf slot.
3725- let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count();
3865+ let shown = packets
3866+ .iter()
3867+ .filter(|p| p.level == Level::ShowExisting)
3868+ .count();
37263869 let arfs = packets.iter().filter(|p| p.level == Level::Arf).count();
37273870 assert_eq!(shown, arfs, "one show_existing_frame per hidden frame");
37283871 }
@@ -3826,14 +3969,27 @@ mod tests {
38263969 held.len(),
38273970 "{n} pictures at gop {gop}: the lookahead changed the stream LENGTH"
38283971 );
3829- assert!(flat == held, "{n} pictures at gop {gop}: the stream is not byte-identical");
3972+ assert!(
3973+ flat == held,
3974+ "{n} pictures at gop {gop}: the stream is not byte-identical"
3975+ );
38303976 assert_eq!(
3831- packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(),
3832- flat_packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(),
3977+ packets
3978+ .iter()
3979+ .map(|p| (p.order, p.key, p.level))
3980+ .collect::<Vec<_>>(),
3981+ flat_packets
3982+ .iter()
3983+ .map(|p| (p.order, p.key, p.level))
3984+ .collect::<Vec<_>>(),
38333985 "{n} pictures at gop {gop}: coding order/levels moved"
38343986 );
38353987 let ours = crate::stream::decode_stream(&held).expect("our decoder");
3836- assert_eq!(ours.len(), n, "{n} pictures at gop {gop}: our decoder's count");
3988+ assert_eq!(
3989+ ours.len(),
3990+ n,
3991+ "{n} pictures at gop {gop}: our decoder's count"
3992+ );
38373993 if !have_ffmpeg() {
38383994 continue;
38393995 }
@@ -3870,7 +4026,10 @@ mod tests {
38704026 assert_eq!(theirs.len(), 17, "the symmetric arm's ffmpeg count");
38714027 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
38724028 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3873- assert!(got == *b, "symmetric arm, display frame {i}: ours differs from ffmpeg");
4029+ assert!(
4030+ got == *b,
4031+ "symmetric arm, display frame {i}: ours differs from ffmpeg"
4032+ );
38744033 }
38754034 }
38764035 crate::speed::set_speed(was);
@@ -3921,17 +4080,31 @@ mod tests {
39214080 for mode in [1usize, 2, 3] {
39224081 let (on, packets) = run(n, gop, mode);
39234082 assert_eq!(
3924- packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(),
3925- off_packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(),
4083+ packets
4084+ .iter()
4085+ .map(|p| (p.order, p.key, p.level))
4086+ .collect::<Vec<_>>(),
4087+ off_packets
4088+ .iter()
4089+ .map(|p| (p.order, p.key, p.level))
4090+ .collect::<Vec<_>>(),
39264091 "{n} pictures at gop {gop} mode {mode}: coding order/levels moved"
39274092 );
39284093 let ours = crate::stream::decode_stream(&on).expect("our decoder");
3929- assert_eq!(ours.len(), n, "{n} pictures at gop {gop} mode {mode}: our count");
4094+ assert_eq!(
4095+ ours.len(),
4096+ n,
4097+ "{n} pictures at gop {gop} mode {mode}: our count"
4098+ );
39304099 if !have_ffmpeg() {
39314100 continue;
39324101 }
39334102 let theirs = ffmpeg_decode_luma(&on, width, height);
3934- assert_eq!(theirs.len(), n, "{n} pictures at gop {gop} mode {mode}: ffmpeg count");
4103+ assert_eq!(
4104+ theirs.len(),
4105+ n,
4106+ "{n} pictures at gop {gop} mode {mode}: ffmpeg count"
4107+ );
39354108 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
39364109 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
39374110 assert!(
@@ -4028,13 +4201,22 @@ mod tests {
40284201 };
40294202 let (off, off_packets) = run(None);
40304203 let (explicit_off, _) = run(Some(0));
4031- assert_eq!(off, explicit_off, "mode 0 is not bit-exact with the default");
4204+ assert_eq!(
4205+ off, explicit_off,
4206+ "mode 0 is not bit-exact with the default"
4207+ );
40324208 for (mode, arm) in [(1u8, 0usize), (2, 1), (4, 2)] {
40334209 let (on, packets) = run(Some(mode));
40344210 let hits = crate::encode::take_arfmode_hits();
40354211 assert_eq!(
4036- packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(),
4037- off_packets.iter().map(|p| (p.order, p.key, p.level)).collect::<Vec<_>>(),
4212+ packets
4213+ .iter()
4214+ .map(|p| (p.order, p.key, p.level))
4215+ .collect::<Vec<_>>(),
4216+ off_packets
4217+ .iter()
4218+ .map(|p| (p.order, p.key, p.level))
4219+ .collect::<Vec<_>>(),
40384220 "mode {mode}: coding order/levels moved"
40394221 );
40404222 assert!(
@@ -4047,7 +4229,11 @@ mod tests {
40474229 "mode {mode} left the stream byte-identical despite {} firing hits",
40484230 hits[arm],
40494231 );
4050- eprintln!("mode {mode}: {} -> {} B, hits {hits:?}", off.len(), on.len());
4232+ eprintln!(
4233+ "mode {mode}: {} -> {} B, hits {hits:?}",
4234+ off.len(),
4235+ on.len()
4236+ );
40514237 let ours = crate::stream::decode_stream(&on).expect("our decoder");
40524238 assert_eq!(ours.len(), 17, "mode {mode}: our decoder's picture count");
40534239 if !have_ffmpeg() {
@@ -4057,7 +4243,10 @@ mod tests {
40574243 assert_eq!(theirs.len(), 17, "mode {mode}: ffmpeg's picture count");
40584244 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
40594245 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4060- assert!(got == *b, "mode {mode}, frame {i}: ours differs from ffmpeg");
4246+ assert!(
4247+ got == *b,
4248+ "mode {mode}, frame {i}: ours differs from ffmpeg"
4249+ );
40614250 }
40624251 }
40634252 crate::encode::set_arfmode(None);
@@ -4098,9 +4287,16 @@ mod tests {
40984287 .collect();
40994288 let mut sorted = coded.clone();
41004289 sorted.sort_unstable();
4101- assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture");
4290+ assert_eq!(
4291+ sorted,
4292+ (0..9).collect::<Vec<u64>>(),
4293+ "one packet per picture"
4294+ );
41024295 assert_ne!(coded, sorted, "the pyramid never reordered anything");
4103- let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count();
4296+ let shown = packets
4297+ .iter()
4298+ .filter(|p| p.level == Level::ShowExisting)
4299+ .count();
41044300 assert_eq!(shown, hidden, "one show_existing_frame per hidden frame");
41054301 for (i, p) in packets.iter().enumerate() {
41064302 assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position");
@@ -4133,7 +4329,11 @@ mod tests {
41334329
41344330 let stream = concat(&packets);
41354331 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4136- assert_eq!(ours.len(), sources.len(), "our decoder's display-order count");
4332+ assert_eq!(
4333+ ours.len(),
4334+ sources.len(),
4335+ "our decoder's display-order count"
4336+ );
41374337 if !have_ffmpeg() {
41384338 eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg");
41394339 return;
@@ -4286,6 +4486,13 @@ mod tests {
42864486 b[at],
42874487 );
42884488 }
4489+ assert_eq!(
4490+ got.len(),
4491+ b.len(),
4492+ "frame {i}: luma is {} samples, ffmpeg's is {}",
4493+ got.len(),
4494+ b.len()
4495+ );
42894496 }
42904497 }
42914498
@@ -4356,6 +4563,13 @@ mod tests {
43564563 b[at],
43574564 );
43584565 }
4566+ assert_eq!(
4567+ got.len(),
4568+ b.len(),
4569+ "frame {i}: luma is {} samples, ffmpeg's is {}",
4570+ got.len(),
4571+ b.len()
4572+ );
43594573 }
43604574 }
43614575
@@ -4389,7 +4603,10 @@ mod tests {
43894603 stream.extend_from_slice(&packet.data);
43904604 }
43914605 let edges = crate::encode::take_b64_edge_hits();
4392- assert!(edges > 0, "no 64x64 root was taken at a superblock the frame edge cuts");
4606+ assert!(
4607+ edges > 0,
4608+ "no 64x64 root was taken at a superblock the frame edge cuts"
4609+ );
43934610 eprintln!("edge 64x64 roots: {edges}");
43944611
43954612 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
@@ -4411,6 +4628,13 @@ mod tests {
44114628 theirs_i[at],
44124629 );
44134630 }
4631+ assert_eq!(
4632+ got.len(),
4633+ theirs_i.len(),
4634+ "frame {i}: luma is {} samples, ffmpeg's is {}",
4635+ got.len(),
4636+ theirs_i.len()
4637+ );
44144638 }
44154639 }
44164640
@@ -4461,6 +4685,13 @@ mod tests {
44614685 theirs_i[at],
44624686 );
44634687 }
4688+ assert_eq!(
4689+ got.len(),
4690+ theirs_i.len(),
4691+ "frame {i}: luma is {} samples, ffmpeg's is {}",
4692+ got.len(),
4693+ theirs_i.len()
4694+ );
44644695 }
44654696 }
44664697
@@ -4527,6 +4758,13 @@ mod tests {
45274758 theirs_i[at],
45284759 );
45294760 }
4761+ assert_eq!(
4762+ got.len(),
4763+ theirs_i.len(),
4764+ "frame {i}: luma is {} samples, ffmpeg's is {}",
4765+ got.len(),
4766+ theirs_i.len()
4767+ );
45304768 }
45314769 }
45324770
@@ -4570,7 +4808,10 @@ mod tests {
45704808 stream.extend_from_slice(&packet.data);
45714809 }
45724810 let compound = crate::encode::take_b64_compound_hits();
4573- assert!(compound > 0, "a crossfade clip coded no COMPOUND 64x64 root at all");
4811+ assert!(
4812+ compound > 0,
4813+ "a crossfade clip coded no COMPOUND 64x64 root at all"
4814+ );
45744815 eprintln!("compound 64x64 roots on a crossfade clip: {compound}");
45754816
45764817 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
@@ -4592,6 +4833,13 @@ mod tests {
45924833 theirs_i[at],
45934834 );
45944835 }
4836+ assert_eq!(
4837+ got.len(),
4838+ theirs_i.len(),
4839+ "frame {i}: luma is {} samples, ffmpeg's is {}",
4840+ got.len(),
4841+ theirs_i.len()
4842+ );
45954843 }
45964844 }
45974845
@@ -4715,8 +4963,7 @@ mod tests {
47154963 let x0 = 32 + t * 32;
47164964 for y in 128..256 {
47174965 for x in x0..x0 + 128 {
4718- p.y[y * width + x] =
4719- if (x / 2 + y / 3) % 2 == 0 { 40 } else { 210 };
4966+ p.y[y * width + x] = if (x / 2 + y / 3) % 2 == 0 { 40 } else { 210 };
47204967 }
47214968 }
47224969 p
@@ -4749,7 +4996,10 @@ mod tests {
47494996 "the quantizer grid was flat ({levels} level(s)): no delta_qindex was coded"
47504997 );
47514998 } else {
4752- eprintln!("SKIP the fire count at preset {}: no tpl map", crate::speed::speed());
4999+ eprintln!(
5000+ "SKIP the fire count at preset {}: no tpl map",
5001+ crate::speed::speed()
5002+ );
47535003 }
47545004 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
47555005 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
@@ -4767,12 +5017,22 @@ mod tests {
47675017 b[at],
47685018 );
47695019 }
5020+ assert_eq!(
5021+ got.len(),
5022+ b.len(),
5023+ "frame {i}: luma is {} samples, ffmpeg's is {}",
5024+ got.len(),
5025+ b.len()
5026+ );
47705027 }
47715028 } else {
47725029 eprintln!("SKIP the ffmpeg half: no ffmpeg");
47735030 }
47745031 crate::encode::set_deltaq_res(None);
4775- eprintln!("delta_q witness: {levels} quantizer levels, {} bytes", stream.len());
5032+ eprintln!(
5033+ "delta_q witness: {levels} quantizer levels, {} bytes",
5034+ stream.len()
5035+ );
47765036 }
47775037
47785038 /// lane-txset's witness: a clip of hard directional edges makes the intra
@@ -4837,8 +5097,8 @@ mod tests {
48375097 // still has to reach SOME non-`DCT_DCT` type -- that is the
48385098 // "reachable at all" statement, class `gate-blind-to-feature`.
48395099 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) {
4840- let non_dct: usize = hits.iter().sum::<usize>()
4841- - hits[crate::transform::TxType::DctDct as usize];
5100+ let non_dct: usize =
5101+ hits.iter().sum::<usize>() - hits[crate::transform::TxType::DctDct as usize];
48425102 assert!(
48435103 non_dct > 0,
48445104 "every luma transform unit took DCT_DCT: {hits:?}"
@@ -4879,6 +5139,13 @@ mod tests {
48795139 b[at],
48805140 );
48815141 }
5142+ assert_eq!(
5143+ got.len(),
5144+ b.len(),
5145+ "frame {i}: luma is {} samples, ffmpeg's is {}",
5146+ got.len(),
5147+ b.len()
5148+ );
48825149 }
48835150 } else {
48845151 eprintln!("SKIP the ffmpeg half: no ffmpeg");
@@ -4964,11 +5231,21 @@ mod tests {
49645231 b[at],
49655232 );
49665233 }
5234+ assert_eq!(
5235+ got.len(),
5236+ b.len(),
5237+ "frame {i}: luma is {} samples, ffmpeg's is {}",
5238+ got.len(),
5239+ b.len()
5240+ );
49675241 }
49685242 } else {
49695243 eprintln!("SKIP the ffmpeg half: no ffmpeg");
49705244 }
4971- eprintln!("inter tx_type witness: hits {hits:?}, {} bytes", stream.len());
5245+ eprintln!(
5246+ "inter tx_type witness: hits {hits:?}, {} bytes",
5247+ stream.len()
5248+ );
49725249 }
49735250
49745251 /// lane-txi's witness: a `reduced_tx_set = 0` frame codes the WIDER
@@ -5035,7 +5312,10 @@ mod tests {
50355312 crate::encode::set_wide_tx_set(None);
50365313 crate::encode::set_inter_tx_search(None);
50375314 crate::encode::set_intra_tx_search(None);
5038- eprintln!("wide tx_type witness: intra {intra:?} inter {inter:?}, {} bytes", stream.len());
5315+ eprintln!(
5316+ "wide tx_type witness: intra {intra:?} inter {inter:?}, {} bytes",
5317+ stream.len()
5318+ );
50395319 // The fire count is preset 0's, for the reason the five-type witness
50405320 // spells out: a faster preset prunes the modes and partitions a type
50415321 // wins on before it is ever priced (class `gate-blind-to-feature`).
@@ -5081,6 +5361,13 @@ mod tests {
50815361 b[at],
50825362 );
50835363 }
5364+ assert_eq!(
5365+ got.len(),
5366+ b.len(),
5367+ "frame {i}: luma is {} samples, ffmpeg's is {}",
5368+ got.len(),
5369+ b.len()
5370+ );
50845371 }
50855372 } else {
50865373 eprintln!("SKIP the ffmpeg half: no ffmpeg");
@@ -5167,9 +5454,11 @@ mod tests {
51675454 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
51685455 let (cw, ch) = (width / 2, height / 2);
51695456 for (i, (a, (y, u, v))) in ours.iter().zip(&theirs).enumerate() {
5170- for (name, got16, want, w) in
5171- [("y", &a.y, y, width), ("u", &a.u, u, cw), ("v", &a.v, v, ch)]
5172- {
5457+ for (name, got16, want, w) in [
5458+ ("y", &a.y, y, width),
5459+ ("u", &a.u, u, cw),
5460+ ("v", &a.v, v, ch),
5461+ ] {
51735462 let got: Vec<u8> = got16.iter().map(|&s| s as u8).collect();
51745463 assert_eq!(got.len(), want.len(), "frame {i} {name} plane size");
51755464 if let Some(at) = got.iter().zip(want.iter()).position(|(x, y)| x != y) {
@@ -5223,10 +5512,18 @@ mod tests {
52235512 stream.extend_from_slice(&packet.data);
52245513 }
52255514 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5226- assert_eq!(ours.len(), sources.len(), "speed {speed}: our decoder's frames");
5515+ assert_eq!(
5516+ ours.len(),
5517+ sources.len(),
5518+ "speed {speed}: our decoder's frames"
5519+ );
52275520 if have_ffmpeg() {
52285521 let theirs = ffmpeg_decode_luma(&stream, width, height);
5229- assert_eq!(theirs.len(), sources.len(), "speed {speed}: ffmpeg's frames");
5522+ assert_eq!(
5523+ theirs.len(),
5524+ sources.len(),
5525+ "speed {speed}: ffmpeg's frames"
5526+ );
52305527 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
52315528 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
52325529 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
@@ -5239,6 +5536,13 @@ mod tests {
52395536 b[at],
52405537 );
52415538 }
5539+ assert_eq!(
5540+ got.len(),
5541+ b.len(),
5542+ "speed {speed} frame {i}: luma is {} samples, ffmpeg's is {}",
5543+ got.len(),
5544+ b.len()
5545+ );
52425546 }
52435547 } else {
52445548 eprintln!("SKIP the ffmpeg half of speed {speed}: no ffmpeg");
@@ -5368,7 +5672,13 @@ mod tests {
53685672 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
53695673 fn tile_search_wall_1080p() {
53705674 let _knobs = crate::speed::knob_write();
5371- tile_search_wall(1920, 1080, 12, &[(0, 0), (1, 0), (1, 1), (2, 1)], &[1, 2, 4, 8]);
5675+ tile_search_wall(
5676+ 1920,
5677+ 1080,
5678+ 12,
5679+ &[(0, 0), (1, 0), (1, 1), (2, 1)],
5680+ &[1, 2, 4, 8],
5681+ );
53725682 }
53735683
53745684 /// The same table at the 4K frame size the editor exports (3840x1608),
@@ -5413,7 +5723,11 @@ mod tests {
54135723 // One tile, so only the filter stage can differ between these.
54145724 let one = coded(1);
54155725 for threads in [2usize, 4, 8] {
5416- assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads");
5726+ assert_eq!(
5727+ one,
5728+ coded(threads),
5729+ "the filter stage moved at {threads} threads"
5730+ );
54175731 }
54185732 crate::par::set_tile_threads(1);
54195733 }
@@ -5493,8 +5807,7 @@ mod tests {
54935807 // 320x160 crops (its coding surface is one superblock row taller);
54945808 // 320x192 is a whole number of superblocks.
54955809 for (width, height) in [(320usize, 160usize), (320, 192)] {
5496- let sources: Vec<Picture> =
5497- (0..4).map(|t| test_card(width, height, t * 3)).collect();
5810+ let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
54985811 run(&sources, width, height, (0, 0));
54995812 }
55005813 // Real gate content, where the CDEF preset search actually chooses
@@ -5649,7 +5962,12 @@ mod tests {
56495962 for _pass in 0..2 {
56505963 for (i, &((c, r), t)) in cells.iter().enumerate() {
56515964 let got = run(c, r, t);
5652- assert!(got.1 > 0, "{}x{} tiles at {t} threads: empty stream", 1 << c, 1 << r);
5965+ assert!(
5966+ got.1 > 0,
5967+ "{}x{} tiles at {t} threads: empty stream",
5968+ 1 << c,
5969+ 1 << r
5970+ );
56535971 if best[i].is_none_or(|(w, _)| got.0 < w) {
56545972 best[i] = Some(got);
56555973 }
@@ -5681,7 +5999,10 @@ mod tests {
56815999 .map(|i| best[i].expect("cell").0.as_secs_f64());
56826000 let Some(one) = one else { continue };
56836001 for &t in &threads[1..] {
5684- let i = cells.iter().position(|&(l, tt)| l == (c, r) && tt == t).expect("cell");
6002+ let i = cells
6003+ .iter()
6004+ .position(|&(l, tt)| l == (c, r) && tt == t)
6005+ .expect("cell");
56856006 let secs = best[i].expect("cell").0.as_secs_f64();
56866007 let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64;
56876008 let speedup = one / secs;
@@ -5709,7 +6030,9 @@ mod tests {
57096030 ) {
57106031 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
57116032 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
5712- let listed = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output();
6033+ let listed = Command::new("ffmpeg")
6034+ .args(["-hide_banner", "-encoders"])
6035+ .output();
57136036 let has_rav1e = listed
57146037 .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))
57156038 .unwrap_or(false);
@@ -5720,7 +6043,8 @@ mod tests {
57206043 eprintln!("| rav1e layout | threads | wall | fps | bytes |");
57216044 for &(c, r) in layouts {
57226045 for &t in threads {
5723- let out = std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id()));
6046+ let out =
6047+ std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id()));
57246048 let params = format!(
57256049 "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}",
57266050 1 << c,
@@ -5737,7 +6061,15 @@ mod tests {
57376061 .expect("ffmpeg failed to run");
57386062 let secs = start.elapsed().as_secs_f64();
57396063 if !status.status.success() {
5740- eprintln!("| {}x{} | {t} | FAILED: {} |", 1 << c, 1 << r, String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or(""));
6064+ eprintln!(
6065+ "| {}x{} | {t} | FAILED: {} |",
6066+ 1 << c,
6067+ 1 << r,
6068+ String::from_utf8_lossy(&status.stderr)
6069+ .lines()
6070+ .last()
6071+ .unwrap_or("")
6072+ );
57416073 continue;
57426074 }
57436075 let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
@@ -5798,6 +6130,13 @@ mod tests {
57986130 at / width
57996131 );
58006132 }
6133+ assert_eq!(
6134+ got.len(),
6135+ b.len(),
6136+ "1080p {layout} frame {i}: luma is {} samples, ffmpeg's is {}",
6137+ got.len(),
6138+ b.len()
6139+ );
58016140 }
58026141 eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len());
58036142 }
crates/ec-av1/src/stream.rsmodified+280 -16
@@ -2671,7 +2671,6 @@ pub(crate) mod tests {
26712671 );
26722672 }
26732673
2674-
26752674 /// lane-av1-qmatrix: WITNESS for the lifted `using_qmatrix` refusal (the
26762675 /// old gate `a_frame_using_quantisation_matrices_is_refused_by_name` is
26772676 /// its mirror image -- its own panic said "flip this gate to a witness"
@@ -3524,6 +3523,15 @@ pub(crate) mod tests {
35243523 bad, 0,
35253524 "{NAME}: arm {extra:?} frame {i} plane {plane}: {bad} samples differ"
35263525 );
3526+ assert_eq!(
3527+ g.len(),
3528+ r.len(),
3529+ "{NAME}: arm {extra:?} frame {i} plane {plane}: ours has {} samples, \
3530+ ffmpeg's has {} -- a short plane would zip-truncate the compare above \
3531+ and hide a chroma-span defect",
3532+ g.len(),
3533+ r.len()
3534+ );
35273535 }
35283536 }
35293537 assert!(
@@ -5975,6 +5983,14 @@ pub(crate) mod tests {
59755983 ({int_mv_inter} force_integer_mv inter frames in this stream)",
59765984 first.unwrap()
59775985 );
5986+ assert_eq!(
5987+ l.len(),
5988+ r.len(),
5989+ "frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a short \
5990+ plane would zip-truncate the compare above and hide a chroma-span defect",
5991+ l.len(),
5992+ r.len()
5993+ );
59785994 }
59795995 }
59805996 }
@@ -6079,6 +6095,14 @@ pub(crate) mod tests {
60796095 "frame {i} plane {plane} differs from ffmpeg at sample {}",
60806096 first.unwrap()
60816097 );
6098+ assert_eq!(
6099+ l.len(),
6100+ r.len(),
6101+ "frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a short \
6102+ plane would zip-truncate the compare above and hide a chroma-span defect",
6103+ l.len(),
6104+ r.len()
6105+ );
60826106 }
60836107 }
60846108 }
@@ -6183,6 +6207,15 @@ pub(crate) mod tests {
61836207 bad, 0,
61846208 "{NAME}: frame {i} plane {plane}: {bad} samples differ"
61856209 );
6210+ assert_eq!(
6211+ g.len(),
6212+ r.len(),
6213+ "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
6214+ short plane would zip-truncate the compare above and hide a chroma-span \
6215+ defect",
6216+ g.len(),
6217+ r.len()
6218+ );
61866219 }
61876220 }
61886221 }
@@ -6357,6 +6390,15 @@ pub(crate) mod tests {
63576390 bad, 0,
63586391 "{NAME} [{tag}]: frame {i} plane {plane}: {bad} samples differ"
63596392 );
6393+ assert_eq!(
6394+ g.len(),
6395+ r.len(),
6396+ "{NAME} [{tag}]: frame {i} plane {plane}: ours has {} samples, ffmpeg's has \
6397+ {} -- a short plane would zip-truncate the compare above and hide a \
6398+ chroma-span defect",
6399+ g.len(),
6400+ r.len()
6401+ );
63606402 }
63616403 }
63626404 }
@@ -6596,6 +6638,15 @@ pub(crate) mod tests {
65966638 bad, 0,
65976639 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ"
65986640 );
6641+ assert_eq!(
6642+ plane.len(),
6643+ want.len(),
6644+ "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
6645+ has {} -- a short plane would zip-truncate the compare above and hide \
6646+ a chroma-span defect",
6647+ plane.len(),
6648+ want.len()
6649+ );
65996650 }
66006651 }
66016652 } else {
@@ -6618,6 +6669,15 @@ pub(crate) mod tests {
66186669 bad, 0,
66196670 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
66206671 );
6672+ assert_eq!(
6673+ g.len(),
6674+ r.len(),
6675+ "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
6676+ -- a short plane would zip-truncate the compare above and hide a \
6677+ chroma-span defect",
6678+ g.len(),
6679+ r.len()
6680+ );
66216681 }
66226682 }
66236683 } else {
@@ -6722,6 +6782,15 @@ pub(crate) mod tests {
67226782 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
67236783 (class obmc-ss-blind-chroma-above)"
67246784 );
6785+ assert_eq!(
6786+ plane.len(),
6787+ want.len(),
6788+ "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
6789+ has {} -- a short plane would zip-truncate the compare above and hide \
6790+ a chroma-span defect",
6791+ plane.len(),
6792+ want.len()
6793+ );
67256794 }
67266795 }
67276796 } else {
@@ -6744,6 +6813,15 @@ pub(crate) mod tests {
67446813 bad, 0,
67456814 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
67466815 );
6816+ assert_eq!(
6817+ g.len(),
6818+ r.len(),
6819+ "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
6820+ -- a short plane would zip-truncate the compare above and hide a \
6821+ chroma-span defect",
6822+ g.len(),
6823+ r.len()
6824+ );
67476825 }
67486826 }
67496827 } else {
@@ -6898,6 +6976,15 @@ pub(crate) mod tests {
68986976 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
68996977 (class 444-128rect-chroma-span)"
69006978 );
6979+ assert_eq!(
6980+ plane.len(),
6981+ want.len(),
6982+ "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
6983+ has {} -- a short plane would zip-truncate the compare above and hide \
6984+ a chroma-span defect",
6985+ plane.len(),
6986+ want.len()
6987+ );
69016988 }
69026989 }
69036990 } else {
@@ -6921,6 +7008,15 @@ pub(crate) mod tests {
69217008 bad, 0,
69227009 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
69237010 );
7011+ assert_eq!(
7012+ g.len(),
7013+ r.len(),
7014+ "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
7015+ -- a short plane would zip-truncate the compare above and hide a \
7016+ chroma-span defect",
7017+ g.len(),
7018+ r.len()
7019+ );
69247020 }
69257021 }
69267022 } else {
@@ -7065,6 +7161,15 @@ pub(crate) mod tests {
70657161 "{NAME}: aomdec frame {i} plane {p} THROUGH THE PIPELINE: \
70667162 {bad} samples differ (class lr-band-release)"
70677163 );
7164+ assert_eq!(
7165+ plane.len(),
7166+ want.len(),
7167+ "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
7168+ has {} -- a short plane would zip-truncate the compare above and hide \
7169+ a chroma-span defect",
7170+ plane.len(),
7171+ want.len()
7172+ );
70687173 }
70697174 }
70707175 } else {
@@ -7086,6 +7191,15 @@ pub(crate) mod tests {
70867191 "{NAME}: ffmpeg frame {i} plane {p} THROUGH THE PIPELINE: \
70877192 {bad} samples differ"
70887193 );
7194+ assert_eq!(
7195+ g.len(),
7196+ r.len(),
7197+ "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
7198+ -- a short plane would zip-truncate the compare above and hide a \
7199+ chroma-span defect",
7200+ g.len(),
7201+ r.len()
7202+ );
70897203 }
70907204 }
70917205 } else {
@@ -7412,7 +7526,7 @@ pub(crate) mod tests {
74127526 return;
74137527 }
74147528 let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
7415- assert_eq!(ours.len(), frames, "{NAME}: decode-order frame count");
7529+ assert_eq!(ours.len(), frames, "{NAME}: shown/display frame count");
74167530 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
74177531 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
74187532 .iter()
@@ -7423,6 +7537,15 @@ pub(crate) mod tests {
74237537 bad, 0,
74247538 "{NAME}: frame {i} plane {plane}: {bad} samples differ from ffmpeg"
74257539 );
7540+ assert_eq!(
7541+ g.len(),
7542+ r.len(),
7543+ "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
7544+ short plane would zip-truncate the compare above and hide a chroma-span \
7545+ defect",
7546+ g.len(),
7547+ r.len()
7548+ );
74267549 }
74277550 }
74287551 eprintln!("{NAME}: {frames} frames sample-exact, intra128_lossless hits {hits}");
@@ -7556,6 +7679,15 @@ pub(crate) mod tests {
75567679 bad, 0,
75577680 "{NAME}: arm {arm} plane {plane}: {bad} samples differ from ffmpeg"
75587681 );
7682+ assert_eq!(
7683+ g.len(),
7684+ r.len(),
7685+ "{NAME}: arm {arm} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
7686+ short plane would zip-truncate the compare above and hide a chroma-span \
7687+ defect",
7688+ g.len(),
7689+ r.len()
7690+ );
75597691 }
75607692 }
75617693 eprintln!("{NAME}: 2 arms full-frame exact, {clips_total} chroma units clipped");
@@ -7625,6 +7757,14 @@ pub(crate) mod tests {
76257757 bad, 0,
76267758 "{NAME}: plane {plane}: {bad} samples differ from ffmpeg"
76277759 );
7760+ assert_eq!(
7761+ g.len(),
7762+ r.len(),
7763+ "{NAME}: plane {plane}: ours has {} samples, ffmpeg's has {} -- a short plane \
7764+ would zip-truncate the compare above and hide a chroma-span defect",
7765+ g.len(),
7766+ r.len()
7767+ );
76287768 }
76297769 eprintln!(
76307770 "{NAME}: full-frame exact, {resets} band resets, \
@@ -7860,6 +8000,15 @@ pub(crate) mod tests {
78608000 "{NAME}: frame {i} plane {plane} differs from ffmpeg at sample {}",
78618001 first.unwrap()
78628002 );
8003+ assert_eq!(
8004+ l.len(),
8005+ r.len(),
8006+ "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
8007+ short plane would zip-truncate the compare above and hide a chroma-span \
8008+ defect",
8009+ l.len(),
8010+ r.len()
8011+ );
78638012 }
78648013 }
78658014 }
@@ -9295,11 +9444,10 @@ pub(crate) mod tests {
92959444 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
92969445 let ffmpeg_frames =
92979446 ffmpeg_decode_sequence(&stream, width, height, frames.len());
9298- assert_eq!(
9299- frames.len(),
9300- ffmpeg_frames.len(),
9301- "{NAME}: {arm} frame count"
9302- );
9447+ // No frame-count assert here: `ffmpeg_decode_sequence` was
9448+ // handed `frames.len()` as its frame budget, so
9449+ // `ffmpeg_frames.len() == frames.len()` holds by
9450+ // construction and the assert was tautological.
93039451 // EVERY frame is compared; an arm whose decode never hit an
93049452 // intrabc block proves nothing about the DV/prediction path,
93059453 // so it is counted OUT OF SCOPE -- but a mismatch there is
@@ -10697,7 +10845,29 @@ pub(crate) mod tests {
1069710845 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
1069810846 assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count");
1069910847 let mut mismatched = 0usize;
10700- for (ours, ref_frame) in frames.iter().zip(theirs.iter()) {
10848+ for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
10849+ // A size mismatch makes every number this ladder prints
10850+ // meaningless -- the `zip` walks below would truncate to the
10851+ // shorter plane and report a clean ladder over what is
10852+ // really a plane-shape defect -- so it is LOUD. A PIXEL
10853+ // mismatch stays report-only: this gate deliberately
10854+ // tolerates the pinned second defect (see the doc comment).
10855+ for (plane, a, b) in [
10856+ ("Y", &ours.y, &ref_frame.y),
10857+ ("U", &ours.u, &ref_frame.u),
10858+ ("V", &ours.v, &ref_frame.v),
10859+ ] {
10860+ assert_eq!(
10861+ a.len(),
10862+ b.len(),
10863+ "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has \
10864+ {} -- a size mismatch makes this whole diagnostic ladder \
10865+ meaningless, so it is loud while a pixel mismatch stays \
10866+ report-only",
10867+ a.len(),
10868+ b.len()
10869+ );
10870+ }
1070110871 mismatched += ours
1070210872 .y
1070310873 .iter()
@@ -11245,11 +11415,10 @@ pub(crate) mod tests {
1124511415 } else {
1124611416 ffmpeg_decode_sequence(&stream, width, height, frames.len())
1124711417 };
11248- assert_eq!(
11249- frames.len(),
11250- ffmpeg_frames.len(),
11251- "{NAME}: {arm} at {depth}-bit -- frame count"
11252- );
11418+ // No frame-count assert here: `ffmpeg_decode_sequence{,_10bit}`
11419+ // was handed `frames.len()` as its frame budget, so
11420+ // `ffmpeg_frames.len() == frames.len()` holds by construction
11421+ // and the assert was tautological.
1125311422 assert!(
1125411423 !frames.is_empty(),
1125511424 "{NAME}: {arm} at {depth}-bit decoded no frame"
@@ -12987,6 +13156,15 @@ pub(crate) mod tests {
1298713156 if let Some(d) = first_diff(a, b, w) {
1298813157 panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]");
1298913158 }
13159+ assert_eq!(
13160+ a.len(),
13161+ b.len(),
13162+ "{name}: seed {seed} frame {i} plane {plane}: ours has {} samples, \
13163+ ffmpeg's has {} -- a short plane would zip-truncate the walk above \
13164+ and hide a chroma-span defect",
13165+ a.len(),
13166+ b.len()
13167+ );
1299013168 }
1299113169 }
1299213170 compared += 1;
@@ -28138,6 +28316,22 @@ pub(crate) mod tests {
2813828316 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} frame \
2813928317 {i} differs from ffmpeg"
2814028318 );
28319+ for (plane, a, b) in [
28320+ ("Y", &ours.y, &theirs.y),
28321+ ("U", &ours.u, &theirs.u),
28322+ ("V", &ours.v, &theirs.v),
28323+ ] {
28324+ assert_eq!(
28325+ a.len(),
28326+ b.len(),
28327+ "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
28328+ frame {i} plane {plane}: ours has {} samples, ffmpeg's has \
28329+ {} -- a short plane would zip-truncate the diff count \
28330+ above and hide a chroma-span defect",
28331+ a.len(),
28332+ b.len()
28333+ );
28334+ }
2814128335 }
2814228336 // Every compared attempt must carry the case, so no
2814328337 // compared attempt is out of scope and
@@ -29003,8 +29197,11 @@ pub(crate) mod tests {
2900329197 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2900429198 };
2900529199 assert_eq!(frames.len(), frame_count);
29006- // EVERY decode-order frame compared, never just the shown ones
29007- // (class [[gate-blind-to-hidden-frames]]).
29200+ // Every SHOWN/display frame `decode_stream` returned is compared --
29201+ // that is decode_stream's whole output, and nothing else is.
29202+ // HIDDEN frames are NOT covered here: they are never emitted as
29203+ // pictures, so no ffmpeg picture corresponds to them (class
29204+ // [[gate-blind-to-hidden-frames]]).
2900829205 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2900929206 assert_eq!(
2901029207 got.y, want.y,
@@ -29168,7 +29365,20 @@ pub(crate) mod tests {
2916829365 .unwrap_or(4);
2916929366 let frames = decode_stream(&stream).expect("our decode");
2917029367 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
29171- for f in 0..frame_count.min(frames.len()).min(ffmpeg_frames.len()) {
29368+ // The `.min()` chain below is a scratch diagnostic that tolerates a
29369+ // pinned stream whose counts disagree, but a SILENT shortfall reads as
29370+ // "these frames matched" for frames nobody compared. Say how many are
29371+ // actually walked.
29372+ let walked = frame_count.min(frames.len()).min(ffmpeg_frames.len());
29373+ if walked < frame_count {
29374+ eprintln!(
29375+ "pinned stream: asked for {frame_count} frames (EC_AV1_PIN_N), we show {}, ffmpeg \
29376+ shows {} -- comparing the first {walked} only",
29377+ frames.len(),
29378+ ffmpeg_frames.len()
29379+ );
29380+ }
29381+ for f in 0..walked {
2917229382 let ours = &frames[f];
2917329383 let theirs = &ffmpeg_frames[f];
2917429384 for (plane_name, a, b, w) in [
@@ -29176,6 +29386,15 @@ pub(crate) mod tests {
2917629386 ("u", &ours.u, &theirs.u, width / 2),
2917729387 ("v", &ours.v, &theirs.v, width / 2),
2917829388 ] {
29389+ // A short plane would zip-truncate the walk below and report
29390+ // MATCH over the prefix the two share.
29391+ assert_eq!(
29392+ a.len(),
29393+ b.len(),
29394+ "frame {f} plane {plane_name}: ours has {} samples, ffmpeg's has {}",
29395+ a.len(),
29396+ b.len()
29397+ );
2917929398 let mut first = None;
2918029399 let mut count = 0;
2918129400 let mut worst = 0i32;
@@ -33244,6 +33463,15 @@ pub(crate) mod tests {
3324433463 first.map(|k| a[k]),
3324533464 first.map(|k| b[k]),
3324633465 );
33466+ assert_eq!(
33467+ a.len(),
33468+ b.len(),
33469+ "{NAME} frame {i} {name} vs ffmpeg (seed {seed}): ours has {} samples, \
33470+ ffmpeg's has {} -- a short plane would zip-truncate the walk above \
33471+ and hide a chroma-span defect",
33472+ a.len(),
33473+ b.len()
33474+ );
3324733475 }
3324833476 }
3324933477 let hits = crate::decode::part128_none_hits() - before;
@@ -34838,6 +35066,15 @@ pub(crate) mod tests {
3483835066 b[d]
3483935067 );
3484035068 }
35069+ assert_eq!(
35070+ a.len(),
35071+ b.len(),
35072+ "{name}: {tag} frame {i} plane {plane}: ours has {} samples, \
35073+ ffmpeg's has {} -- a short plane would zip-truncate the walk above \
35074+ and hide a chroma-span defect",
35075+ a.len(),
35076+ b.len()
35077+ );
3484135078 }
3484235079 }
3484335080 compared += 1;
@@ -41798,6 +42035,15 @@ pub(crate) mod tests {
4179842035 b[i],
4179942036 );
4180042037 }
42038+ assert_eq!(
42039+ a.len(),
42040+ b.len(),
42041+ "{NAME}: segmented {w}x{h} crf {crf}, frame {f} plane {plane}: ours \
42042+ has {} samples, ffmpeg's has {} -- a short plane would \
42043+ zip-truncate the walk above and hide a chroma-span defect",
42044+ a.len(),
42045+ b.len()
42046+ );
4180142047 }
4180242048 }
4180342049 eprintln!("{NAME}: segmented {w}x{h} crf {crf} exact, block q span {lo}..{hi}");
@@ -41911,6 +42157,15 @@ pub(crate) mod tests {
4191142157 b[i],
4191242158 );
4191342159 }
42160+ assert_eq!(
42161+ a.len(),
42162+ b.len(),
42163+ "{NAME}: {encoder} {point} at {w}x{h}, frame {f} plane {plane}: \
42164+ ours has {} samples, ffmpeg's has {} -- a short plane would \
42165+ zip-truncate the walk above and hide a chroma-span defect",
42166+ a.len(),
42167+ b.len()
42168+ );
4191442169 }
4191542170 }
4191642171 checked += 1;
@@ -42021,6 +42276,15 @@ pub(crate) mod tests {
4202142276 b[i],
4202242277 );
4202342278 }
42279+ assert_eq!(
42280+ a.len(),
42281+ b.len(),
42282+ "{NAME}: frame {f} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
42283+ short plane would zip-truncate the walk above and hide a chroma-span \
42284+ defect",
42285+ a.len(),
42286+ b.len()
42287+ );
4202442288 }
4202542289 }
4202642290 // The property is asserted, not hoped for: without more than one
crates/ec-h264/tests/conformance.rsmodified+53 -0
@@ -275,6 +275,13 @@ fn compare_sequence(stream: &Path) -> Result<usize, String> {
275275 a[pos], b[pos]
276276 ));
277277 }
278+ assert_eq!(
279+ a.len(),
280+ b.len(),
281+ "frame {i} is {} samples, ffmpeg gave {}",
282+ a.len(),
283+ b.len()
284+ );
278285 }
279286 Ok(ours.len())
280287 }
@@ -319,6 +326,12 @@ fn jvt_cavlc_first_idr_bit_exact() {
319326 );
320327 ok = false;
321328 }
329+ assert_eq!(
330+ ours.len(),
331+ frame_len,
332+ "{name}: frame is {} samples ({w}x{h}), the reference frame is {frame_len}",
333+ ours.len()
334+ );
322335 } else {
323336 eprintln!("WARN {name}: no reference YUV, ffmpeg only");
324337 }
@@ -332,6 +345,12 @@ fn jvt_cavlc_first_idr_bit_exact() {
332345 );
333346 ok = false;
334347 }
348+ assert_eq!(
349+ ours.len(),
350+ frame_len,
351+ "{name}: frame is {} samples ({w}x{h}), the ffmpeg frame is {frame_len}",
352+ ours.len()
353+ );
335354 }
336355 if ok {
337356 passed.push(name.to_string());
@@ -692,6 +711,13 @@ fn round_trip(dir: &Path, tag: &str, size: &str, extra: &[&str]) -> Result<usize
692711 expected.len()
693712 ));
694713 }
714+ if ours.len() < expected.len() {
715+ return Err(format!(
716+ "{tag}: {w}x{h} decoded to {} bytes, ffmpeg gave {}",
717+ ours.len(),
718+ expected.len()
719+ ));
720+ }
695721 Ok(ours
696722 .iter()
697723 .zip(&expected[..ours.len()])
@@ -1082,6 +1108,12 @@ fn jvt_full_sequence_bit_exact() {
10821108 bad = Some((i, pos));
10831109 break;
10841110 }
1111+ assert_eq!(
1112+ f.len(),
1113+ len,
1114+ "{name}: frame {i} is {} samples, {len} expected",
1115+ f.len()
1116+ );
10851117 }
10861118 match bad {
10871119 None if frames.len() == want => {
@@ -1301,6 +1333,13 @@ fn output_is_display_order_and_the_reorder_is_real() {
13011333 first_diff(a, b).is_none(),
13021334 "display-order frame {i} differs from ffmpeg"
13031335 );
1336+ assert_eq!(
1337+ a.len(),
1338+ b.len(),
1339+ "display-order frame {i} is {} samples, ffmpeg gave {}",
1340+ a.len(),
1341+ b.len()
1342+ );
13041343 }
13051344 // Every decode-order frame is somewhere in the display-order set: the two
13061345 // are permutations of one another, not different pictures.
@@ -2011,6 +2050,13 @@ fn packet_entry_surface_reorders_and_carries_timestamps() {
20112050 first_diff(ours, theirs).is_none(),
20122051 "packet-path frame {i} differs from ffmpeg"
20132052 );
2053+ assert_eq!(
2054+ ours.len(),
2055+ theirs.len(),
2056+ "packet-path frame {i} is {} samples, ffmpeg gave {}",
2057+ ours.len(),
2058+ theirs.len()
2059+ );
20142060 }
20152061 // Each packet was tagged with its own index in *decode* order, so the tag
20162062 // that comes back on a picture says which packet produced it. Decoding the
@@ -2026,6 +2072,13 @@ fn packet_entry_surface_reorders_and_carries_timestamps() {
20262072 "output position {position} carries the timestamp of packet {tag}, \
20272073 but its pixels are a different picture"
20282074 );
2075+ assert_eq!(
2076+ pixels.len(),
2077+ by_decode_order[tag].len(),
2078+ "output position {position} is {} samples, decode-order frame {tag} is {}",
2079+ pixels.len(),
2080+ by_decode_order[tag].len()
2081+ );
20292082 }
20302083 let order: Vec<i64> = out.iter().map(|(pts, _)| *pts).collect();
20312084 assert_ne!(
crates/ec-vp9/tests/intraonly_exact.rsmodified+5 -0
@@ -80,6 +80,11 @@ fn intra_only_frame_and_its_successors_match_ffmpeg() {
8080 got.extend(pic.y.iter().map(|&v| v as u8));
8181 got.extend(pic.u.iter().map(|&v| v as u8));
8282 got.extend(pic.v.iter().map(|&v| v as u8));
83+ assert_eq!(
84+ got.len(),
85+ frame_bytes,
86+ "frame {i}: our planes are {w}x{h} I420"
87+ );
8388 let diff = got.iter().zip(want).position(|(a, b)| a != b);
8489 assert!(
8590 diff.is_none(),
lanes/av1cmpaudit.report.mdadded+240 -0
@@ -0,0 +1,240 @@
1+# lane-av1cmpaudit — ours-vs-oracle compare honesty sweep
2+
3+## The class
4+
5+An ours-vs-oracle compare that walks `got.iter().zip(want)` **without first asserting
6+equal lengths** reports EXACT for any defect outside the compared prefix: `zip` stops at
7+the shorter operand, so the walk is silently truncated and the `filter(|(a, b)| a != b)
8+.count() == 0` form returns a PASS. Measured in this repo before the sweep: a comparator
9+hardcoded to a 128x96 geometry zipped 36864 samples against a 98304-byte oracle dump and
10+declared a 256x128 witness byte-exact while the divergence sat at x>=108.
11+
12+A frame-count assert (`ours.len() == sources.len()`) does **not** protect a plane compare.
13+The canonical SAFE shape already in the tree is `crates/ec-av1/src/stream.rs`'s
14+`decode_all_frames_vs_oracle` (~8129-8145): assert the frame counts, assert the byte
15+lengths, then walk.
16+
17+Second class, same inventory: **decode-order vs display-order indexing.** The instrumented
18+aomdec's `EC_AV1_FINAL_DUMP` writes one file per DECODED frame in DECODE order (7 files
19+for a 6-picture encode); `ffmpeg -f rawvideo` emits DISPLAY order (6). Indexing one
20+against the other fakes a divergence on a byte-exact stream.
21+
22+## Fix rule used everywhere
23+
24+A length assert is inserted **after** the existing diff/panic assert, on the same buffers.
25+That keeps every change behaviour-preserving: a real sample divergence still fails for the
26+same reason with the same message, and only the previously-silent "our side is short and
27+the compared prefix matches" case becomes a new loud failure. Frame-count asserts that
28+guard a loop over frames go **before** the loop, because with unequal counts the loop body
29+compares a mis-paired set and there is no "same reason" failure to preserve.
30+
31+## Inventory
32+
33+106 ours-vs-oracle compare sites. SAFE = a length assert (or a whole-slice `==`/`!=`
34+compare, which is length-aware) on the SAME buffers in the same block. UNSAFE = the walk
35+with no such assert. N/A = a zip that is not an ours-vs-oracle compare (production DSP,
36+iterator plumbing, ours-vs-ours). No site is SKIPPED-by-env: every gate is fixture
37+presence or an ffmpeg/aomdec binary check, and every one is exercisable in a normal run.
38+
39+| crate / file | sites | SAFE | UNSAFE | N/A |
40+|---|---|---|---|---|
41+| `crates/ec-av1/src/stream.rs` | 44 | 13 | 26 | 5 |
42+| `crates/ec-av1/src/encoder.rs` | 17 | 4 | 13 | 0 |
43+| `crates/ec-av1/src/encode.rs` | 22 | 2 | 20 | 0 |
44+| `crates/ec-h264/tests/conformance.rs` | 11 | 2 | 8 | 1 |
45+| `crates/ec-vp9/tests/*.rs` | 4 | 3 | 1 | 0 |
46+| `crates/ec-h265/tests/conformance.rs` | 8 | 8 | 0 | 0 |
47+| `crates/ec-alac/tests/*.rs` | 2 | 2 | 0 | 0 |
48+| `crates/ec-flac/tests/*.rs` | 2 | 2 | 0 | 0 |
49+| `tools/oracle/src/main.rs` | 1 | 1 | 0 | 0 |
50+| `crates/ec-aac/tests/*.rs`, `crates/ec-ac3/tests/*.rs` | 13 | 1 | 0 | 12 |
51+| **total** | **124** | **38** | **68** | **18** |
52+
53+`scripts/**` holds no ours-vs-oracle byte compare: `lr-sgr-pin-harness.c` and
54+`superres-pin-harness.c` are oracle-side instrumentation the instrumented aomdec calls,
55+`instrument-aom-oracle.sh` only patches oracle sources, and the `aac-tables/*.py` scripts
56+probe the reference decoder with an error-string oracle, not a sample compare.
57+
58+### The UNSAFE sites, by shape
59+
60+**`filter(|(a, b)| a != b).count() == 0` is the ONLY pixel check** — a short plane gives
61+0 and the gate passes. `stream.rs` 3522, 6181, 6355, 6616, 6742, 6919, 7083, 7421, 7554,
62+7623, 6590, 6715, 6891, 7058; `encode.rs` 17386, 17471, 17560, 17630, 17702, 17781, 17848,
63+17938, 18029, 18090.
64+
65+**`position(|(x, y)| x != y)` diff reporter with only a frame-count assert** —
66+`stream.rs` 5971, 6076, 7857, 12932, 33237, 34820, 41790, 41903, 42014, 28107;
67+`encoder.rs` 3545, 4280, 4350, 4405, 4455, 4521, 4586, 4761, 4873, 4958, 5075, 5232, 5794;
68+`ec-h264/tests/conformance.rs` 272, 314, 328, 1081, 1301, 2011, 2025;
69+`ec-vp9/tests/intraonly_exact.rs` 83.
70+
71+**A helper that returns `None` for "exact" with no length guard** —
72+`encode.rs::first_difference` (16565). Contrast `first_plane_mismatch` (19161), which
73+checks length after the zip and so cannot yield a false `None`; that is the model.
74+
75+**A one-sided length check** — `ec-h264/tests/conformance.rs::round_trip` (688): only
76+`if ours.len() > expected.len()` was rejected, so a SHORT frame zipped over
77+`&expected[..ours.len()]` and returned 0. Four call sites print "bit-exact" on `Ok(0)`.
78+
79+**A three-way `.min()` that truncates silently** — `stream.rs:29369`
80+(`frame_count.min(frames.len()).min(ffmpeg_frames.len())`), the only
81+decode-order/display-order-shaped site in the crate.
82+
83+**Frame pairing with no count assert on either side** — `encode.rs` 15617, 15622 (and the
84+nine `encoded.frames` vs `ffmpeg_decode_sequence` loops at 17396/17481/17565/17640/17712/
85+17786/17853/17943/18034 plus 17282).
86+
87+### Deliberately left alone
88+
89+- `ec-h264/tests/conformance.rs:157` `fn first_diff` — the primitive itself. Its two
90+ streamed call sites (1646, 1769) are already SAFE via `reference.resize(frame.len(), 0)`
91+ + `read_exact`; the seven loose call sites are fixed instead.
92+- `ec-h264/tests/conformance.rs:1313` — ours-vs-ours (decode order vs display order), an
93+ anti-vacuity claim (`moved > 0`), not an oracle compare.
94+- `stream.rs:10704-10718` `mismatched` — a PIXEL mismatch here stays report-only by design
95+ (the gate deliberately tolerates a pinned second defect). The PLANE SIZE now asserts
96+ loudly: with a size mismatch every number the ladder prints is meaningless, and that is
97+ not the defect the gate tolerates.
98+- `stream.rs:9298, 11248` — `assert_eq!(frames.len(), ffmpeg_frames.len(), ...)` was
99+ tautological (`ffmpeg_decode_sequence` was handed `frames.len()` as its budget). Deleted
100+ and replaced by a comment naming the tautology; the helper's own byte-length assert is
101+ the real guard.
102+- `ec-aac`, `ec-ac3` — Pearson/lag-correlation and RMS thresholds. A correlation claim is
103+ not an exactness claim, and shortening an operand changes a threshold result, it does
104+ not fake a PASS. Their one genuine exactness claim
105+ (`ec-aac/tests/oracle.rs:617`) is a full `assert_eq!(ours, theirs, ...)`.
106+- The ~250 remaining ffmpeg pairings in `stream.rs` — SAFE-DISP: `decode_stream` returns
107+ shown frames in display order and ffmpeg rawvideo is display order, and
108+ `ffmpeg_decode_sequence` hard-asserts `stdout.len() == frame_bytes * frames`, so passing
109+ our own `frames.len()` is still a real count assertion against ffmpeg's measured output.
110+
111+### Truthfulness fixes (no logic change)
112+
113+- `stream.rs:29006` claimed `// EVERY decode-order frame compared, never just the shown
114+ ones (class [[gate-blind-to-hidden-frames]])` directly above a loop over
115+ `decode_stream`'s output, which is the shown/display frames. The gate is exactly the
116+ class it claimed to cover. Rewritten to say what it covers and that hidden frames are
117+ NOT covered.
118+- `stream.rs:7415` — `"{NAME}: decode-order frame count"` on a shown-frame count. Message
119+ corrected; the assert itself is unchanged.
120+- `crates/ec-av1/examples/dump_yuv.rs:39` — writes `<out>.f{i}.yuv` where `i` is a DISPLAY
121+ index, wearing the `.f{N}` name that means DECODE index everywhere else in the crate.
122+ A comment now says so and points at `decode_all_frames_vs_oracle`.
123+
124+### Stale-dump hazard
125+
126+Already handled at the one in-tree site that reads dump files:
127+`decode_all_frames_vs_oracle` `remove_dir_all`s its scratch dir (~8087) before writing
128+both sides' `aom.f{i}` and `ours.f{i}`, so no `ours.f*` can survive from a previous run
129+next to a fresh `aom.f*`. The three other decode-order dump rungs
130+(`EC_AV1_DECODE_ORDER_DUMP`, `EC_AV1_PREFILT_DUMP`) have no in-repo consumer — the whole
131+hazard there lives in the manual procedure, not in a gate. Nothing to fix.
132+
133+## Proofs
134+
135+Every fix is a pure insertion, so the red proof is a counterfactual on the SAME code: drop
136+our side's last sample, run the gate. Red = the new length assert fires. Then revert only
137+the fix (scoped `git checkout -- <file>`) and re-run the identical mutated code: the gate
138+PASSES. That pass is the false PASS the fix kills.
139+
140+**`crates/ec-av1/src/stream.rs`** — `stream::tests::a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands`
141+(0.64s, not `#[ignore]`d). Mutation in `decode.rs:34785`: `probe_plane.pop()` on the
142+key-frame luma.
143+- red: `panicked at crates/ec-av1/src/stream.rs:7768: assertion 'left == right' failed:
144+ a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands: plane 0: ours has 77439
145+ samples, ffmpeg's has 77440 -- a short plane would zip-truncate the compare above and
146+ hide a chroma-span defect` / `left: 77439 right: 77440` / `FAILED. 0 passed; 1 failed`.
147+ The pre-existing `bad == 0` assert did NOT fire — that is the hole.
148+- false pass: same mutation, `stream.rs` reverted → `a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands:
149+ full-frame exact, 1 band resets, 3 skipped intrabc chroma predictions` / `ok`.
150+
151+**`crates/ec-av1/src/encoder.rs`** — `encoder::tests::a_static_clip_codes_64x64_roots_and_decodes_sample_exact`
152+(site 4280). Mutation: `g.pop()` on the luma collect.
153+- red: `panicked at crates/ec-av1/src/encoder.rs:4296: assertion 'left == right' failed:
154+ frame 0: luma is 32767 samples, ffmpeg's is 32768` / `FAILED. 0 passed; 1 failed; 702
155+ filtered out`.
156+- restored: `ok`.
157+
158+**`crates/ec-av1/src/encode.rs`** — `encode::tests::every_mode_decodes_to_what_the_encoder_predicted`
159+(the `first_difference` helper fix). Mutation: `let ours = &ours[..ours.len() - 1];`.
160+- red: `panicked at crates/ec-av1/src/encode.rs:16620: 128x96 mode 0, luma: no sample in the
161+ shared prefix differs, but ours is 12287 samples and theirs is 12288` / `FAILED`.
162+- restored: `ok`.
163+
164+**`crates/ec-vp9/tests/intraonly_exact.rs`** — `intra_only_frame_and_its_successors_match_ffmpeg`.
165+Mutation: `got.pop()`.
166+- red: `panicked at crates/ec-vp9/tests/intraonly_exact.rs:84: frame 0: our planes are
167+ 320x240 I420 / left: 115199 / right: 115200` / `FAILED. 0 passed; 1 failed`.
168+- false pass: same mutation, fix reverted → `ok ... 1 passed` — a 115199-vs-115200
169+ truncation reported EXACT for all 10 shown frames.
170+- restored: `ok`.
171+
172+**`crates/ec-h264/tests/conformance.rs`** — all seven sites proven red and all seven
173+proven to pass without the fix (each mutation truncated our frame or the oracle's by one
174+sample; the reverted runs printed `bit-exact` / `12 frames bit-exact` / `ok`).
175+- `jvt_scaling_matrices_decode_bit_exact` / `round_trip`: red `conformance.rs:865: cqm-jvt:
176+ 176x144 decoded to 38015 bytes, ffmpeg gave 38016`; false pass `cqm=jvt scaling matrices
177+ bit-exact`.
178+- `jvt_cavlc_first_idr_bit_exact` (two arms): red `conformance.rs:332: AUD_MW_E: frame is
179+ 38015 samples (176x144), the reference frame is 38016`; false pass `PASS table (26
180+ bit-exact, 9 refused by name)`.
181+- `jvt_full_sequence_bit_exact`: red `conformance.rs:1118: AUD_MW_E: frame 1 is 38015
182+ samples, 38016 expected`; false pass `ok`.
183+- `p_only_gop_matches_ffmpeg_every_frame` / `compare_sequence`: red `conformance.rs:282:
184+ frame 1 is 38016 samples, ffmpeg gave 38015`; false pass `cavlc-p: 12 frames bit-exact` /
185+ `cabac-p: 12 frames bit-exact`.
186+- `output_is_display_order_and_the_reorder_is_real`: red `conformance.rs:1340: display-order
187+ frame 1 is 38016 samples, ffmpeg gave 38015`. Note a mid-sequence truncation of OUR
188+ display frames is already caught pre-fix by the unrelated ours-vs-ours membership check
189+ at 1313, so the isolation mutation truncates the ORACLE frame.
190+- `packet_entry_surface_reorders_and_carries_timestamps` (two sites): red
191+ `conformance.rs:2062`; false pass `ok`.
192+
193+### Live green, after restore
194+
195+```
196+cargo test -p ec-av1 --release --lib -- stream::tests::a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands \
197+ encoder::tests::a_static_clip_codes_64x64_roots_and_decodes_sample_exact \
198+ encode::tests::every_mode_decodes_to_what_the_encoder_predicted
199+ test result: ok. 3 passed; 0 failed; 0 ignored; 700 filtered out; finished in 3.56s
200+cargo test -p ec-vp9 --test intraonly_exact --test inter_pixels_exact
201+ intra_only_frame_and_its_successors_match_ffmpeg ... ok (1 passed)
202+ inter_gop_matches_ffmpeg / inter_gop_with_tile_columns_matches_ffmpeg / corpus_1080p_60fps_matches_ffmpeg_past_frame_72 ... ok (3 passed)
203+cargo test -p ec-h264 --test conformance
204+ jvt_scaling_matrices_decode_bit_exact ok 0.17s; p_only_gop_matches_ffmpeg_every_frame ok
205+ 0.31s; output_is_display_order_and_the_reorder_is_real ok 0.23s;
206+ packet_entry_surface_reorders_and_carries_timestamps ok 0.22s;
207+ jvt_cavlc_first_idr_bit_exact ok 1.68s; jvt_full_sequence_bit_exact ok 5.77s
208+cargo check -p ec-av1 --lib --tests -> Finished, no errors, no warnings
209+cargo check -p ec-h264 -p ec-vp9 --tests -> Finished (5 pre-existing ec-vp9 lib warnings)
210+```
211+
212+Not executed live: the ~30 UNSAFE sites inside `#[ignore]`d ec-av1 gates (they need an
213+explicit `--ignored` run and aomenc-driven sweeps) and the `EC_AV1_PIN` scratch diagnostic
214+at `stream.rs:29369`. They are fixed by the identical insertion; the red proof is carried
215+by a non-`#[ignore]`d sibling in the same file exercising the same assert shape.
216+
217+## Notes for the parent
218+
219+- The repo's cargo target runner (`scripts/memguard-runner.sh`, wired in
220+ `.cargo/config.toml`) fails in this container with `Unit run-p...scope was already loaded
221+ or has a fragment file`. Pre-existing, unrelated to the diff; `EC_NOMEMGUARD=1` is the
222+ runner's own documented escape hatch and was used for every run above.
223+- A scratch `worktree/fixtures -> main checkout fixtures` symlink (untracked, gitignored)
224+ was needed to make the JVT-vector tests run in the worktree. It is not part of the diff.
225+- Nothing is pushed. The main checkout at `/home/user/Documents/Code/Rust/edith_codecs`
226+ is clean (`git status --porcelain` empty).
227+
228+## Reviewing this commit
229+
230+`core.hooksPath` points at `~/.omp/agent/hooks/git`, whose `pre-commit` runs
231+`format-staged.py` over the staged tree. That hook re-flowed `encode.rs` and `encoder.rs`
232+wholesale at commit time (the reflow is line-BREAK churn, so `git diff -w` does not hide
233+it: the semantic diff is the ~68 `assert_eq!` insertions, the `first_difference` rewrite,
234+ the three comment/message corrections and the `examples/dump_yuv.rs` note). Per skill
235+ `edith-format-churn-commit-hook` the committed, hook-formatted version is the canonical
236+ tree and is NOT reverted. The hook ran rustfmt with this workspace's edition: the
237+ committed tree still compiles clean
238+ (`cargo check -p ec-av1 --lib --tests` -> Finished, no errors, no warnings) and the three
239+ named green tests above still pass on the committed blobs
240+ (`test result: ok. 3 passed; 0 failed; 0 ignored; 700 filtered out`).