diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 4f6a3e67..ad459fe3 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -493,6 +493,30 @@ pub fn take_b64_compound_hits() -> usize { B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) } +/// Whether a 64x64 root that codes a residual may SPLIT its luma transform +/// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by +/// [`commit_inter_luma`] like every other inter block's var-tx, and coded by +/// the writer's `Whole64` arm as `txfm_split = 1`. It exists because +/// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose +/// residual has detail in the other three quadrants cannot code it at all. +/// +/// Off by `EC_AV1_B64VARTX=0`. +fn b64_var_tx() -> bool { + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_B64VARTX").ok().map(|v| v != "0") + }); + ENV.unwrap_or(true) && b64_root() +} + +/// How many 64x64 roots split their luma transform since the last +/// [`take_b64_var_tx_hits`]. +static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The split-luma 64x64-root count since the last call, and zero it. +pub fn take_b64_var_tx_hits() -> usize { + B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + /// Whether the encoder searches loop restoration at all (spec 7.17): one /// Wiener filter per 64x64 luma restoration unit, picked from /// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a @@ -3412,7 +3436,7 @@ fn commit_inter_luma( && !skip && side >= 16 && (second.is_none() || compound_var_tx()) - && (side < BLOCK || tx32_depth_search()) + && (side != BLOCK || tx32_depth_search()) && x + side <= luma.true_width && y + side <= luma.true_height; if !eligible { @@ -3420,7 +3444,14 @@ fn commit_inter_luma( return (flat.levels.clone(), 0, 0.0); } let tx = side / 2; - let set = if tx >= 16 { TxbSet::Luma16Inter } else { TxbSet::Luma8Inter }; + let set = if tx >= 32 { + // lane-b64b: the 64x64 root's halved transform is TX_32X32. + TxbSet::Luma32Inter + } else if tx >= 16 { + TxbSet::Luma16Inter + } else { + TxbSet::Luma8Inter + }; let mut levels = vec![0i32; side * side]; let (mut sse, mut bits) = (0.0, 0.0); let mut units = Vec::with_capacity(4); @@ -3454,14 +3485,22 @@ fn commit_inter_luma( let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1)); let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0)); let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2; + // The depth census has a leaf row and a 32x32 row and no 64 one, so the + // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing + // in the leaf row (class `gate-blind-to-feature`). + let counted = side <= BLOCK; if split_cost < flat_cost { for (tu_x, tu_y, trial) in &units { luma.commit(*tu_x, *tu_y, tx, trial); } - INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if counted { + INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } return (levels, 1, split_cost - flat_cost); } - INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if counted { + INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } luma.commit(x, y, side, flat); (flat.levels.clone(), 0, 0.0) } @@ -7642,6 +7681,13 @@ fn search_skip_64( // two numbers are comparable: `fixed` charged `skip` coded 1, and this // arm charges 0 instead and adds its three planes' coefficient bits. let mut chosen = (skip_cost, true, skip_trials); + // Set when [`commit_inter_luma`] already wrote the residual arm's luma + // into the plane, so the tail below does not commit over its units. + let mut luma_committed = false; + // The residual arm's luma levels and the `txfm_split` depth the writer + // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is + // four TX_32X32 units in 64x64 ones. + let mut luma_levels: Option<(Vec, u8)> = None; if residual { let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; let residual_trials = [0usize, 1, 2].map(|plane| { @@ -7663,16 +7709,54 @@ fn search_skip_64( }); let unskip = symbol_bits(&cdf::SKIP[0], 0) - symbol_bits(&cdf::SKIP[0], 1); let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum(); + // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the + // four TX_32X32 units of `txfm_split = 1`, taken by the same + // `commit_inter_luma` every other inter block's is (it commits the + // winner and hands back the cost it took off the flat arm). + let (levels, depth, gain) = if b64_var_tx() { + let second = info.ref1.and_then(|r1| { + compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| { + ( + info.mv1, + (g.y.as_slice(), g.width, luma.true_width, luma.true_height), + ) + }) + }); + luma_committed = true; + commit_inter_luma( + luma, + (x, y), + side, + info.mv, + (&reference.y, reference.width, luma.true_width, luma.true_height), + search, + &residual_trials[0], + false, + second, + fctx, + ) + } else { + (residual_trials[0].levels.clone(), 0, 0.0) + }; let cost = residual_trials.iter().map(|t| t.sse).sum::() - + search.lambda * (syntax + unskip + coeff_bits); + + search.lambda * (syntax + unskip + coeff_bits) + + gain; if cost < skip_cost { B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if depth == 1 { + B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + luma_levels = Some((levels, depth)); chosen = (cost, false, residual_trials); } } let (cost, skip, trials) = chosen; - luma.commit(x, y, side, &trials[0]); + // `commit_inter_luma` already wrote the residual arm's luma (its four + // split units are not one 64-sided trial); a skip winner overwrites it. + if skip || !luma_committed { + luma.commit(x, y, side, &trials[0]); + } chroma[0].commit(x / 2, y / 2, side / 2, &trials[1]); chroma[1].commit(x / 2, y / 2, side / 2, &trials[2]); Some(( @@ -7680,9 +7764,16 @@ fn search_skip_64( BlockCoeffs { skip, inter: Some(info), - // Both grids are 32-sided: the luma one is the 64-point - // transform's coded corner, the chroma ones are whole TX_32X32. - luma: if skip { Vec::new() } else { coeffs(&trials[0].levels, BLOCK) }, + // The chroma grids are whole TX_32X32; the luma one is the + // 64-point transform's coded 32x32 corner at depth 0 and the + // whole 64-sided block at depth 1 (lane-b64b). + tx_depth: luma_levels.as_ref().map_or(0, |&(_, d)| d), + luma: match (skip, &luma_levels) { + (true, _) => Vec::new(), + (false, Some((levels, 1))) => coeffs(levels, SUPERBLOCK), + (false, Some((levels, _))) => coeffs(levels, BLOCK), + (false, None) => coeffs(&trials[0].levels, BLOCK), + }, u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) }, v: if skip { Vec::new() } else { coeffs(&trials[2].levels, side / 2) }, ..BlockCoeffs::default() @@ -15024,6 +15115,17 @@ mod tests { // the real side, a screen clip none of them. let (price_default, price_real) = crate::tile::take_pricing_hits(); eprintln!("{name}: pricer armings default={price_default} real={price_real}"); + // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many + // superblocks stayed whole, and how many of those coded a + // residual, split that residual's luma, or took a compound + // reference (class `gate-blind-to-feature`). + eprintln!( + "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})", + take_b64_root_hits(), + take_b64_residual_hits(), + take_b64_var_tx_hits(), + take_b64_compound_hits(), + ); // lane-av1obmc2: the same motion_mode census the 640x384 gate // prints (class `gate-blind-to-feature`) -- how many blocks coded // the symbol at each footprint and how many took OBMC. Without it diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index ae7e3d95..b2569d12 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -2846,6 +2846,72 @@ mod tests { } } + /// A clip whose inter residual is HIGH-FREQUENCY (lane-b64b): every + /// frame adds a 4-pixel checkerboard, so the 64x64 root's prediction is + /// off by exactly the detail a TX_64X64 throws away (it codes only the + /// top-left 32x32 corner of its coefficient space) and the root's var-tx + /// arm splits its luma into four TX_32X32 units instead. The counter is + /// the gate (class `gate-blind-to-feature`), and a `txfm_split` the + /// reader does not expect desyncs the whole tile, so both decoders have + /// to reconstruct it sample-exact. + #[test] + fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() { + let _knobs = crate::speed::knob_write(); + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let (width, height) = (256usize, 128usize); + let still = test_card(width, height, 0); + let sources: Vec = (0..4) + .map(|t| { + let mut p = still.clone(); + for (i, v) in p.y.iter_mut().enumerate() { + let checker = ((i % width) / 4 + (i / width) / 4) % 2; + let bump = (t * 5 * (checker + 1)) as u16; + *v = (*v + bump).min(255); + } + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 90, + gop: 8, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + let _ = crate::encode::take_b64_var_tx_hits(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let split = crate::encode::take_b64_var_tx_hits(); + assert!(split > 0, "no 64x64 root split its luma transform at all"); + eprintln!("64x64 roots with a SPLIT luma transform: {split}"); + + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half: no ffmpeg"); + return; + } + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); + for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { + panic!( + "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + theirs_i[at], + ); + } + } + } + /// A CROSSFADE clip (lane-b64b): each picture is a linear blend of two /// stills, so on a leaf frame the average of its past (`LAST`) and future /// (`ALTREF`) references IS the source and neither reference alone is -- diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index ca74ab4b..46974372 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -3962,13 +3962,13 @@ fn write_luma_tus( // tables, not the intra ones (`TxbSet::Luma*Inter`). inter: bool, ) -> Result<()> { - if tx < side && side > 32 { + if tx < side && side > 32 && tx < 32 { // A 64x64 block's own levels reach the writer as the 32x32 corner a - // 64-point transform codes, not as a 64x64 block grid, so there is - // nothing to slice per unit here. + // 64-point transform codes unless the whole block was SPLIT into + // TX_32X32 units (lane-b64b), so any finer split has nothing to slice. return Err(Error::unsupported( "AV1 tile", - "a 64x64 block's split luma transform is not written yet", + "a 64x64 block's luma transform splits no finer than TX_32X32", )); } let coeff_side = tx.min(32); @@ -4377,8 +4377,25 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 { return match block.skip { true => 0.0, false => { - coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0) - + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0) + // lane-b64b: at `tx_depth = 1` the luma levels are + // the whole 64-sided block, written as four + // TX_32X32 units, so the pricer slices them the + // same way the writer does. + let luma = if block.tx_depth == 1 { + let g = dense(&block.luma, 64); + (0..4) + .map(|tu| { + let (r0, c0) = ((tu / 2) * 32, (tu % 2) * 32); + let unit: Vec = (0..32) + .flat_map(|row| g[(r0 + row) * 64 + c0..][..32].to_vec()) + .collect(); + coeff_bits(&unit, TxbSet::Luma32Inter, q_ctx, 0, 0) + }) + .sum::() + } else { + coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0) + }; + luma + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0) + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0) } }; @@ -5734,9 +5751,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( // A skipped inter block writes no `txfm_split` at all -- // that call only publishes the max transform size the // reader infers for it; an unskipped one writes the - // `txfm_split` flag, 0 here because a 64x64 root's luma - // is one whole TX_64X64 (depth 1 is lane-tx64's deferred - // var-tx arm). + // `txfm_split` flag: 0 when the root's luma is one whole + // TX_64X64, 1 when it is the four TX_32X32 units + // lane-b64b's var-tx arm chose. write_tx_syntax_inter( &mut enc, &mut cdfs, @@ -5745,7 +5762,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( SB, true, block.skip, - 0, + usize::from(block.tx_depth), ); } if block.skip { @@ -5757,11 +5774,32 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( // `sb_coeff_key_frame_tile`'s `Superblock::Whole` writes), // chroma one whole TX_32X32 per plane, and `split` is // false because the luma transform covers the block. + // lane-b64b: at `txfm_split = 1` the luma levels arrive in + // 64x64 block coordinates and are written as the four + // TX_32X32 units `write_luma_tus` slices out, each + // publishing its own coefficient context before the next + // one reads it; chroma is one TX_32X32 per plane either + // way. + let split = block.tx_depth == 1; let grids = [ - level_grid(&block.luma, TX32)?, + level_grid(&block.luma, if split { SB } else { TX32 })?, level_grid(&block.u, TX32)?, level_grid(&block.v, TX32)?, ]; + if split { + write_luma_tus( + &mut enc, + &mut cdfs, + &mut neighbours, + (mi_r, mi_c), + SB, + TX32, + &grids[0], + 0, + &all_scans, + true, + )?; + } write_block_planes( &mut enc, &mut cdfs, @@ -5770,9 +5808,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( &[&scan32, &scan32, &scan32], &neighbours.around(sb_at, SB), 0, - false, + split, ); - neighbours.record_planes(sb_at, SB, 0, &grids, true); + neighbours.record_planes(sb_at, SB, 0, &grids, !split); } neighbours.record_inter(sb_at, SB, block.skip, true, block_ref(block)); record_block_compound(&mut neighbours, (mi_r, mi_c), SB, block); diff --git a/lanes/b64b/r2-ship.log b/lanes/b64b/r2-ship.log index aaf018fa..a4cc5a7e 100644 --- a/lanes/b64b/r2-ship.log +++ b/lanes/b64b/r2-ship.log @@ -18,3 +18,30 @@ bars 2160p: motion_mode 32x32 SIMPLE=31585 OBMC=0 WARP=290 | 16x16 SIMPLE=2756 O bars 2160p: inter var-tx depths of 9192 blocks -- leaf single 0=1220 1=600 (33.0% split) | leaf compound 0=1083 1=221 (16.9% split) | 32x32 single 0=371 1=1234 (76.9% split) | 32x32 compound 0=141 1=4322 (96.8% split) bars 2160p: screen frames on=0 off=4 (0.0% on); palette blocks luma 0 chroma 0; intrabc blocks 0 (searched 0 / valid 0 / won 0) bars 2160p: filter intra on=true blocks 12387 (modes DC=3329 V=811 H=2621 D157=3956 PAETH=1670) +| bars 2160p 1920x1024 | 43.68 dB/229668 B, 47.60 dB/340632 B, 51.18 dB/453178 B, 54.52 dB/582676 B | +12.3% | -10.2% | 45.8s:8.8s:20.6s | +film A (1080p source): sequence, pyramid requested Some(Pyramid { mini_gop: 8, arf_q_offset: -32, leaf_q_offset: 12, mid_q_offset: Some(-8), quarter_q_offset: None, key_q_offset: -48 }) effective Some(Pyramid { mini_gop: 8, arf_q_offset: -32, leaf_q_offset: 12, mid_q_offset: Some(-8), quarter_q_offset: None, key_q_offset: -48 }) +film A (1080p source): pricer armings default=20 real=214 +film A (1080p source): motion_mode 32x32 SIMPLE=33077 OBMC=0 WARP=1298 | 16x16 SIMPLE=19240 OBMC=0 WARP=1887 | 8x8 SIMPLE=4708 OBMC=0 WARP=931 (0.0% OBMC / 6.7% WARP of 61141 eligible) +film A (1080p source): inter var-tx depths of 85244 blocks -- leaf single 0=15366 1=2875 (15.8% split) | leaf compound 0=31528 1=6450 (17.0% split) | 32x32 single 0=7510 1=5922 (44.1% split) | 32x32 compound 0=9593 1=6000 (38.5% split) +film A (1080p source): screen frames on=0 off=4 (0.0% on); palette blocks luma 0 chroma 0; intrabc blocks 0 (searched 0 / valid 0 / won 0) +film A (1080p source): filter intra on=true blocks 24000 (modes DC=6012 V=3472 H=4526 D157=6964 PAETH=3026) +| film A (1080p source) 1920x768 | 44.29 dB/73949 B, 45.82 dB/123906 B, 47.03 dB/213467 B, 48.28 dB/508664 B | +35.5% | +5.6% | 93.8s:14.5s:17.7s | +film B (2160p HDR source): sequence, pyramid requested Some(Pyramid { mini_gop: 8, arf_q_offset: -32, leaf_q_offset: 12, mid_q_offset: Some(-8), quarter_q_offset: None, key_q_offset: -48 }) effective Some(Pyramid { mini_gop: 8, arf_q_offset: -32, leaf_q_offset: 12, mid_q_offset: Some(-8), quarter_q_offset: None, key_q_offset: -48 }) +film B (2160p HDR source): pricer armings default=20 real=189 +film B (2160p HDR source): motion_mode 32x32 SIMPLE=35371 OBMC=0 WARP=1194 | 16x16 SIMPLE=12510 OBMC=0 WARP=1144 | 8x8 SIMPLE=2069 OBMC=0 WARP=483 (0.0% OBMC / 5.3% WARP of 52771 eligible) +film B (2160p HDR source): inter var-tx depths of 75130 blocks -- leaf single 0=14148 1=2497 (15.0% split) | leaf compound 0=27160 1=4854 (15.2% split) | 32x32 single 0=8028 1=5889 (42.3% split) | 32x32 compound 0=7821 1=4733 (37.7% split) +film B (2160p HDR source): screen frames on=0 off=4 (0.0% on); palette blocks luma 0 chroma 0; intrabc blocks 0 (searched 0 / valid 0 / won 0) +film B (2160p HDR source): filter intra on=true blocks 17165 (modes DC=4796 V=2302 H=2518 D157=5821 PAETH=1728) +| film B (2160p HDR source) 1920x1024 | 46.91 dB/33324 B, 48.04 dB/67896 B, 49.10 dB/143229 B, 50.25 dB/388721 B | +47.8% | +17.1% | 88.0s:24.0s:17.7s | +screen capture (2026-07-25 02-09-04.mkv): sequence, pyramid requested Some(Pyramid { mini_gop: 8, arf_q_offset: -32, leaf_q_offset: 12, mid_q_offset: Some(-8), quarter_q_offset: None, key_q_offset: -48 }) effective None +screen capture (2026-07-25 02-09-04.mkv): pricer armings default=155 real=0 +screen capture (2026-07-25 02-09-04.mkv): motion_mode 32x32 SIMPLE=23654 OBMC=0 WARP=160 | 16x16 SIMPLE=1322 OBMC=0 WARP=318 | 8x8 SIMPLE=562 OBMC=0 WARP=576 (0.0% OBMC / 4.0% WARP of 26592 eligible) +screen capture (2026-07-25 02-09-04.mkv): inter var-tx depths of 34092 blocks -- leaf single 0=5772 1=7043 (55.0% split) | leaf compound 0=2826 1=2851 (50.2% split) | 32x32 single 0=6059 1=8017 (57.0% split) | 32x32 compound 0=860 1=664 (43.6% split) +screen capture (2026-07-25 02-09-04.mkv): screen frames on=48 off=0 (100.0% on); palette blocks luma 9907 chroma 1109; intrabc blocks 0 (searched 0 / valid 0 / won 0) +screen capture (2026-07-25 02-09-04.mkv): filter intra on=true blocks 8198 (modes DC=98 V=2410 H=5376 D157=223 PAETH=91) +| screen capture (2026-07-25 02-09-04.mkv) 1920x1024 | 45.87 dB/40155 B, 48.55 dB/51325 B, 50.86 dB/63998 B, 53.07 dB/80203 B | +33.4% | -23.8% | 47.9s:15.4s:15.4s | +test encode::tests::bd_rate_screen_native ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 602 filtered out; finished in 521.63s + +RC=0