forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-lossless' (7da63eb1): lossless key frames decode sample-exact (WHT, TX_4X4 forcing, no tx_type, CfL narrowed, 4x4 chroma walk); lossless inter frames refused by name

Browse files at this commit

f60365c2544db3003ab027ca500630c006948cf3Ahmet Kaan GümüşParent: 5f3e71048bde73
crates/ec-av1/src/cdf.rsmodified+18 -0
@@ -3860,6 +3860,24 @@ pub const TXB_SKIP_LUMA_8: [u16; 3] = [31957, 32768, 0];
38603860 /// TXB_SKIP_LUMA_8_Q3, q-context 3: the same table as [`TXB_SKIP_LUMA_8`], for `base_q_idx` 121..=255.
38613861 pub const TXB_SKIP_LUMA_8_Q3: [u16; 3] = [31903, 32768, 0];
38623862
3863+/// lane-lossless: `av1_default_txb_skip_cdfs[q][TX_4X4][10..13]`
3864+/// (`av1/common/token_cdfs.h:76`), the chroma `txb_skip` rows libaom's
3865+/// `get_txb_ctx` reaches through the `+10` offset -- a chroma plane block
3866+/// LARGER than its transform. At TX_4X4 that only happens on a lossless
3867+/// frame, which is why every q-context but 0 (`base_q_idx <= 20`) leaves
3868+/// them at the neutral 16384.
3869+pub const TXB_SKIP_CHROMA_4_BIG_Q0: [[u16; 3]; 3] =
3870+ [[9961, 32768, 0], [30242, 32768, 0], [32117, 32768, 0]];
3871+/// [`TXB_SKIP_CHROMA_4_BIG_Q0`] for q-context 1.
3872+pub const TXB_SKIP_CHROMA_4_BIG_Q1: [[u16; 3]; 3] =
3873+ [[16384, 32768, 0], [16384, 32768, 0], [16384, 32768, 0]];
3874+/// [`TXB_SKIP_CHROMA_4_BIG_Q0`] for q-context 2.
3875+pub const TXB_SKIP_CHROMA_4_BIG: [[u16; 3]; 3] =
3876+ [[16384, 32768, 0], [16384, 32768, 0], [16384, 32768, 0]];
3877+/// [`TXB_SKIP_CHROMA_4_BIG_Q0`] for q-context 3.
3878+pub const TXB_SKIP_CHROMA_4_BIG_Q3: [[u16; 3]; 3] =
3879+ [[16384, 32768, 0], [16384, 32768, 0], [16384, 32768, 0]];
3880+
38633881 /// TXB_SKIP_CHROMA_4_Q0, q-context 0: the same table as [`TXB_SKIP_CHROMA_4`], for `base_q_idx` 0..=20.
38643882 pub const TXB_SKIP_CHROMA_4_Q0: [[u16; 3]; 3] =
38653883 [[7654, 32768, 0], [19473, 32768, 0], [29984, 32768, 0]];
crates/ec-av1/src/cdf_state.rsmodified+22 -8
@@ -364,7 +364,11 @@ pub(crate) struct Cdfs {
364364 /// The all-zero flag of an 8x8 chroma transform.
365365 pub txb_skip_chroma_8: [[u16; 3]; 3],
366366 /// The all-zero flag of a 4x4 chroma transform.
367- pub txb_skip_chroma_4: [[u16; 3]; 3],
367+ /// lane-lossless: SIX rows, like [`Self::txb_skip_chroma_32`] -- the last
368+ /// three are `get_txb_ctx`'s `+10` rows (chroma plane block bigger than
369+ /// its transform), which a lossless frame's TX_4X4 chroma reaches at
370+ /// every block above 8x8.
371+ pub txb_skip_chroma_4: [[u16; 3]; 6],
368372 /// The end-of-block group of a 16x16 luma transform.
369373 pub eob_pt_256_luma: [u16; 10],
370374 /// The end-of-block group of an 8x8 luma transform.
@@ -1031,13 +1035,23 @@ impl Cdfs {
10311035 cdf::TXB_SKIP_CHROMA_8,
10321036 cdf::TXB_SKIP_CHROMA_8_Q3,
10331037 ),
1034- txb_skip_chroma_4: pick(
1035- q_ctx,
1036- cdf::TXB_SKIP_CHROMA_4_Q0,
1037- cdf::TXB_SKIP_CHROMA_4_Q1,
1038- cdf::TXB_SKIP_CHROMA_4,
1039- cdf::TXB_SKIP_CHROMA_4_Q3,
1040- ),
1038+ txb_skip_chroma_4: {
1039+ let small = pick(
1040+ q_ctx,
1041+ cdf::TXB_SKIP_CHROMA_4_Q0,
1042+ cdf::TXB_SKIP_CHROMA_4_Q1,
1043+ cdf::TXB_SKIP_CHROMA_4,
1044+ cdf::TXB_SKIP_CHROMA_4_Q3,
1045+ );
1046+ let big = pick(
1047+ q_ctx,
1048+ cdf::TXB_SKIP_CHROMA_4_BIG_Q0,
1049+ cdf::TXB_SKIP_CHROMA_4_BIG_Q1,
1050+ cdf::TXB_SKIP_CHROMA_4_BIG,
1051+ cdf::TXB_SKIP_CHROMA_4_BIG_Q3,
1052+ );
1053+ [small[0], small[1], small[2], big[0], big[1], big[2]]
1054+ },
10411055 eob_pt_256_luma: pick(
10421056 q_ctx,
10431057 cdf::EOB_PT_256_LUMA_Q0,
crates/ec-av1/src/decode.rsmodified+211 -27
@@ -69,6 +69,13 @@ pub(crate) struct FrameCtx {
6969 pub(crate) capture_stages: std::cell::Cell<bool>,
7070 pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
7171 pub(crate) sb128_flag: std::cell::Cell<bool>,
72+ /// lane-lossless: this frame's `CodedLossless` (spec 5.9.12) -- every
73+ /// segment at `qindex == 0` with zero plane deltas. It forces TX_4X4 with
74+ /// the Walsh-Hadamard transform on every plane, drops the `tx_type`
75+ /// symbol and narrows `is_cfl_allowed` (libaom `read_tx_size`
76+ /// (`decodeframe.c`), `read_tx_type` (`decodetxb.c`), `is_cfl_allowed`
77+ /// (`blockd.h`)).
78+ pub(crate) lossless_flag: std::cell::Cell<bool>,
7279 pub(crate) cdef_bits: std::cell::Cell<u8>,
7380 pub(crate) bit_depth: std::cell::Cell<u8>,
7481 pub(crate) superres: std::cell::Cell<(u32, u32)>,
@@ -152,6 +159,7 @@ impl FrameCtx {
152159 pub(crate) fn new() -> Self {
153160 Self {
154161 sb128_flag: std::cell::Cell::new(false),
162+ lossless_flag: std::cell::Cell::new(false),
155163 cdef_bits: std::cell::Cell::new(0),
156164 bit_depth: std::cell::Cell::new(8),
157165 superres: std::cell::Cell::new((0, 8)),
@@ -325,6 +333,38 @@ pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
325333 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
326334 }
327335
336+/// Sets [`FrameCtx::lossless_flag`] (called once per frame from `stream.rs`).
337+pub(crate) fn set_lossless(v: bool, fctx: &crate::decode::FrameCtx) {
338+ fctx.lossless_flag.with(|c| c.set(v));
339+}
340+
341+/// This frame's `CodedLossless` -- see [`FrameCtx::lossless_flag`].
342+pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
343+ fctx.lossless_flag.with(|c| c.get())
344+}
345+
346+/// The transform side a block of `side` pixels codes: its own (capped at the
347+/// caller's own largest) normally, 4 on a lossless frame, where libaom's
348+/// `read_tx_size` returns TX_4X4 before it looks at anything else
349+/// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
350+/// TX_4X4;`).
351+pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
352+ if lossless(fctx) { 4 } else { px }
353+}
354+
355+/// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
356+/// 32x32 -- but on a LOSSLESS frame only when the block's CHROMA plane block
357+/// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
358+/// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
359+/// picks the 13-symbol one (class `wrong-alphabet-same-value`).
360+pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool {
361+ if lossless(fctx) {
362+ bw <= 8 && bh <= 8
363+ } else {
364+ bw <= 32 && bh <= 32
365+ }
366+}
367+
328368 fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
329369 fctx.sb128_flag.with(|c| c.get())
330370 }
@@ -2131,6 +2171,11 @@ pub(crate) struct TxParams {
21312171 pub(crate) ac_delta: i32,
21322172 pub(crate) tx_type: TxType,
21332173 pub(crate) stride: usize,
2174+ /// lane-lossless: this transform unit belongs to a lossless frame, so the
2175+ /// residual comes off the 4x4 Walsh-Hadamard
2176+ /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
2177+ /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
2178+ pub(crate) lossless: bool,
21342179 }
21352180
21362181 impl TxParams {
@@ -2138,10 +2183,18 @@ impl TxParams {
21382183 /// on the parse thread, the wavefront worker calls it on its own, so both
21392184 /// are the same function on the same inputs and byte-identical.
21402185 fn run(self, grid: &[i32]) -> Vec<i32> {
2141- let residual = dequant_and_inverse_typed_wh(
2142- grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2143- self.tx_type,
2144- );
2186+ let residual = if self.lossless {
2187+ debug_assert_eq!((self.w, self.h), (4, 4));
2188+ debug_assert_eq!(self.tx_type, TxType::DctDct);
2189+ crate::transform::dequant_and_inverse_wht4x4(
2190+ grid, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2191+ )
2192+ } else {
2193+ dequant_and_inverse_typed_wh(
2194+ grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2195+ self.tx_type,
2196+ )
2197+ };
21452198 // An all-zero grid transforms to the empty marker, and a strided copy
21462199 // of zeros is still zeros: the marker passes straight through.
21472200 if residual.is_empty() {
@@ -8848,7 +8901,7 @@ fn read_intra_mode_rect(
88488901 // through -- a caller passing `true` for a >32 strip used to pick the
88498902 // 14-symbol CFL CDF, same value but a different range (class
88508903 // wrong-alphabet-same-value).
8851- let cfl = cfl && bw <= 32 && bh <= 32;
8904+ let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
88528905 let uv_mode = if !has_chroma {
88538906 DC_PRED
88548907 } else if cfl {
@@ -9100,7 +9153,18 @@ struct RectStripModes {
91009153 /// TX_32X16`) and only the second reaches a square -- the reason
91019154 /// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
91029155 /// already square) mis-tiled 1:4 strips.
9103-fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) {
9156+fn depth_to_tx_wh(
9157+ bw: usize,
9158+ bh: usize,
9159+ depth: usize,
9160+ fctx: &crate::decode::FrameCtx,
9161+) -> (usize, usize) {
9162+ // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
9163+ // `read_tx_size`: the lossless early return comes before
9164+ // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
9165+ if lossless(fctx) {
9166+ return (4, 4);
9167+ }
91049168 let (mut w, mut h) = (bw.min(64), bh.min(64));
91059169 for _ in 0..depth {
91069170 match w.cmp(&h) {
@@ -9501,6 +9565,58 @@ fn decode_rect_split(
95019565 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
95029566 );
95039567 (zero.clone(), zero)
9568+ } else if lossless(fctx) {
9569+ // lane-lossless: the strip's chroma plane block is coded as 4x4
9570+ // transform units too (libaom `read_tx_size` returns TX_4X4 for every
9571+ // plane), PLANE-MAJOR inside the block -- U's units first, then V's
9572+ // (`decode_token_recon_block`'s mu-chunk loop, measured against
9573+ // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
9574+ // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
9575+ // offset (our `+3` row base) whenever the plane block is bigger than
9576+ // the transform.
9577+ let scan4 = default_scan(4);
9578+ let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
9579+ let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
9580+ let mut last = [Grid::Zero(16), Grid::Zero(16)];
9581+ for plane_idx in 1..=2 {
9582+ for cu_row in 0..ch_n {
9583+ for cu_col in 0..cw_n {
9584+ let luma_span = 8;
9585+ let cu_mi = (
9586+ mi_r + cu_row * (luma_span / MI),
9587+ mi_c + cu_col * (luma_span / MI),
9588+ );
9589+ let cu_around = neighbours.around_mi(cu_mi, luma_span);
9590+ let cu_reach = tu_reach(
9591+ bw, bh,
9592+ cu_col * luma_span, cu_row * luma_span, luma_span,
9593+ block_reach, px, py, y.width, y.height, fctx,
9594+ );
9595+ let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
9596+ if let Some((ub, vb)) = &m.palette_uv {
9597+ set_palette_pred(
9598+ if plane_idx == 1 { ub.clone() } else { vb.clone() },
9599+ fctx,
9600+ );
9601+ }
9602+ let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
9603+ let grid = read_plane(
9604+ dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx,
9605+ cu_around[plane_idx], m.mode, m.uv_predict_mode,
9606+ m.angle_delta_uv, cu_reach, plane, cu_x, cu_y, 4, 4,
9607+ base_q_idx,
9608+ m.alpha.zip(ac).map(|((au, av), ac)| {
9609+ (if plane_idx == 1 { au } else { av }, ac)
9610+ }),
9611+ None, offset, m.smooth_neighbor_uv, fctx,
9612+ )?;
9613+ neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_idx, &grid);
9614+ last[plane_idx - 1] = grid;
9615+ }
9616+ }
9617+ }
9618+ let [ug, vg] = last;
9619+ (ug, vg)
95049620 } else {
95059621 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
95069622 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
@@ -10073,7 +10189,7 @@ fn decode_intra_rect_in_inter(
1007310189 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
1007410190 // superblock-level strip reads the no-CFL alphabet -- the same split
1007510191 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
10076- let cfl_allowed = bw.max(bh) <= 32;
10192+ let cfl_allowed = cfl_allowed_px(bw, bh, fctx);
1007710193 let uv_mode = if cfl_allowed {
1007810194 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
1007910195 } else {
@@ -10217,7 +10333,7 @@ fn decode_intra_rect_in_inter(
1021710333 } else {
1021810334 0
1021910335 };
10220- if depth != 0 {
10336+ if depth != 0 || lossless(fctx) {
1022110337 hit!(TX_DEPTH_HITS);
1022210338 // lane-intrasplit r1: a split intra strip in an inter frame walks the
1022310339 // key frame's own per-TU path ([`decode_rect_split`] below); what was
@@ -10236,7 +10352,7 @@ fn decode_intra_rect_in_inter(
1023610352 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
1023710353 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
1023810354 }
10239- let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10355+ let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
1024010356 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
1024110357 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
1024210358 // of an inter frame, intra ones included -- with the skip term 0 it
@@ -10430,13 +10546,13 @@ fn decode_block_rect(
1043010546 } else {
1043110547 0
1043210548 };
10433- if depth != 0 {
10549+ if depth != 0 || lossless(fctx) {
1043410550 hit!(TX_DEPTH_HITS);
1043510551 // lane-rectsplit r1: a split transform is predicted and reconstructed
1043610552 // per transform unit, each unit taking its edges from the previous
1043710553 // unit's reconstruction inside this same strip (spec 5.11.36) --
1043810554 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
10439- let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10555+ let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
1044010556 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
1044110557 eprintln!(
1044210558 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
@@ -10936,13 +11052,13 @@ fn decode_leaf_rect(
1093611052 } else {
1093711053 0
1093811054 };
10939- if depth != 0 {
11055+ if depth != 0 || lossless(fctx) {
1094011056 // The same per-transform-unit walk the bigger strips take
1094111057 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
1094211058 // depth 2), addressed at this leaf's own mi position.
1094311059 hit!(TX_DEPTH_HITS);
1094411060 hit!(SUB16_SPLIT_HITS);
10945- let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
11061+ let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
1094611062 let modes = RectStripModes {
1094711063 skip,
1094811064 mode,
@@ -11275,17 +11391,17 @@ fn decode_block_rect4(
1127511391 publish_txfm_bands_if_in_inter(
1127611392 neighbours,
1127711393 (mi_r, mi_c),
11278- depth_to_tx_wh(bw, bh, depth),
11394+ depth_to_tx_wh(bw, bh, depth, fctx),
1127911395 (bw, bh), fctx,
1128011396 );
11281- if depth != 0 {
11397+ if depth != 0 || lossless(fctx) {
1128211398 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
1128311399 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
1128411400 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
1128511401 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
1128611402 // both interleave in every real stream.
1128711403 hit!(TX_DEPTH_HITS);
11288- let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
11404+ let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
1128911405 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
1129011406 // predicted -- depth 1 fires FIRST in every attempt that splits at
1129111407 // all, so a depth-2-only lift could never be gated. The r1 mismatch
@@ -11800,7 +11916,7 @@ fn decode_rect4_16_strip(
1180011916 hit!(TX_DEPTH_HITS);
1180111917 hit!(RECT4_16_SPLIT_HITS);
1180211918 }
11803- let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
11919+ let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
1180411920 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
1180511921 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
1180611922 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
@@ -12291,17 +12407,17 @@ fn decode_block_rect64(
1229112407 publish_txfm_bands_if_in_inter(
1229212408 neighbours,
1229312409 (mi_r, mi_c),
12294- depth_to_tx_wh(bw, bh, depth),
12410+ depth_to_tx_wh(bw, bh, depth, fctx),
1229512411 (bw, bh), fctx,
1229612412 );
12297- if depth != 0 {
12413+ if depth != 0 || lossless(fctx) {
1229812414 hit!(TX_DEPTH_HITS);
1229912415 // lane-rectsplit r1/r4: the superblock-level strip splits its
1230012416 // transform through the very same per-unit path as its 32x32-level
1230112417 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
1230212418 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
1230312419 // measured the old square formula mis-tiling exactly that strip).
12304- let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
12420+ let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
1230512421 if bw.max(bh) / bw.min(bh) == 4 {
1230612422 let which = if depth == 1 {
1230712423 &RECT4_SPLIT_DEPTH1_HITS
@@ -12888,7 +13004,7 @@ fn read_intra_mode(
1288813004 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
1288913005 // here so every `decode_block` caller (64x64 and 128x128 roots included)
1289013006 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
12891- let cfl = cfl && side <= 32;
13007+ let cfl = cfl && cfl_allowed_px(side, side, fctx);
1289213008 let uv_mode = if cfl {
1289313009 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
1289413010 } else {
@@ -13654,6 +13770,14 @@ fn read_plane(
1365413770 // filter-intra in AV1).
1365513771 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
1365613772 let mut coding = cdfs.txb(set, tx_mode);
13773+ // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
13774+ // transform type for lossless mode(qindex==0)" -- the symbol is not coded
13775+ // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
13776+ // plane of a lossless block (the residual then goes through the WHT, so
13777+ // the type only picks the scan, which is the default one).
13778+ if lossless(fctx) {
13779+ coding.tx_type = None;
13780+ }
1365713781 // Luma's `default_tx_type` is only a fallback for the sizes whose
1365813782 // `TxbSet` carries no symbol at all (32-point and up), which the spec
1365913783 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
@@ -13678,6 +13802,9 @@ fn read_plane(
1367813802 } else {
1367913803 default_intra_tx_type(predict_mode as u8)
1368013804 };
13805+ // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
13806+ // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
13807+ let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
1368113808 let (grid, tx_type) = read_coeffs(
1368213809 dec,
1368313810 &mut coding,
@@ -13703,7 +13830,7 @@ fn read_plane(
1370313830 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
1370413831 let tx = TxParams {
1370513832 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
13706- ac_delta, tx_type, stride: 0,
13833+ ac_delta, tx_type, stride: 0, lossless: lossless(fctx),
1370713834 };
1370813835 if crate::envflags::env_flag!("EC_AV1_TRACE") {
1370913836 let residual = tx.run(&levels);
@@ -13765,6 +13892,15 @@ fn decode_block(
1376513892 tx_select: bool,
1376613893 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
1376713894 ) -> Result<()> {
13895+ // lane-lossless: a lossless frame's transform is TX_4X4 on every plane
13896+ // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
13897+ // tables/scans are replaced by the 4x4 ones and the block always takes the
13898+ // multi-transform-unit path below.
13899+ let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) {
13900+ (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4))
13901+ } else {
13902+ (luma_set, chroma_set, luma_tx, chroma_tx, scans)
13903+ };
1376813904 let (r, c) = at;
1376913905 let (px, py) = (c * SUB, r * SUB);
1377013906 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
@@ -13879,7 +14015,7 @@ fn decode_block(
1387914015 // TX_64X64, so a 128x128 block is always FOUR luma transform units
1388014016 // even with `tx_select` off -- the TU loop below, never the
1388114017 // single-unit path.
13882- (side.min(64), luma_tx)
14018+ (lossless_tx(side.min(64), fctx), luma_tx)
1388314019 };
1388414020 if tx_select && logical_tx < side && uv_mode != DC_PRED {
1388514021 hit!(SQ_CHROMA_TX_HITS);
@@ -14972,7 +15108,9 @@ fn decode_leaf8(
1497215108 } else if tx_select && intrabc_dv.is_none() {
1497315109 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
1497415110 } else {
14975- 8
15111+ // lane-lossless: TX_4X4 on a lossless frame, no symbol
15112+ // (libaom `read_tx_size`).
15113+ lossless_tx(8, fctx)
1497615114 };
1497715115 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
1497815116 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
@@ -17395,6 +17533,18 @@ fn read_block_tx_size(
1739517533 is_inter: bool,
1739617534 skip: bool, fctx: &crate::decode::FrameCtx,
1739717535 ) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
17536+ // lane-lossless: TX_4X4 over the whole block, and NO var-tx tree -- libaom
17537+ // `read_block_tx_size` (`decodeframe.c`) sends a lossless block down the
17538+ // `read_tx_size` arm, which returns TX_4X4 before it reads anything.
17539+ if lossless(fctx) {
17540+ let mut leaves = Vec::new();
17541+ for row in 0..side / MI {
17542+ for col in 0..side / MI {
17543+ leaves.push((row, col, 4, 4));
17544+ }
17545+ }
17546+ return Ok((4, Some(leaves)));
17547+ }
1739817548 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
1739917549 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
1740017550 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
@@ -17834,6 +17984,15 @@ fn read_block_tx_size_rect(
1783417984 (mi_cols, mi_rows): (usize, usize),
1783517985 skip: bool, fctx: &crate::decode::FrameCtx,
1783617986 ) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
17987+ if lossless(fctx) {
17988+ let mut leaves = Vec::new();
17989+ for row in 0..bh / MI {
17990+ for col in 0..bw / MI {
17991+ leaves.push((row, col, 4, 4));
17992+ }
17993+ }
17994+ return Ok(Some(leaves));
17995+ }
1783717996 if skip {
1783817997 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
1783917998 // its own BLOCK size -- width above, height left -- not a transform.
@@ -17993,12 +18152,23 @@ fn read_inter_plane_rect(
1799318152 usize::from(around.0) + usize::from(around.1)
1799418153 };
1799518154 let mut coding = cdfs.txb(set, tx_mode);
18155+ // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
18156+ // transform type for lossless mode(qindex==0)" -- the symbol is not coded
18157+ // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
18158+ // plane of a lossless block (the residual then goes through the WHT, so
18159+ // the type only picks the scan, which is the default one).
18160+ if lossless(fctx) {
18161+ coding.tx_type = None;
18162+ }
1799618163 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
1799718164 // the *longer* side of this rect transform.
1799818165 let default_tx_type = match inherited_luma_tx_type {
1799918166 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
1800018167 None => TxType::DctDct,
1800118168 };
18169+ // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
18170+ // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
18171+ let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
1800218172 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
1800318173 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
1800418174 // corner, zero-extended into the true `w x h` grid before the inverse
@@ -18053,7 +18223,7 @@ fn read_inter_plane_rect(
1805318223 // (`TxParams::stride`) after the inverse transform.
1805418224 let tx = TxParams {
1805518225 w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type,
18056- stride,
18226+ stride, lossless: lossless(fctx),
1805718227 };
1805818228 push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx);
1805918229 Ok((grid, tx_type))
@@ -18112,6 +18282,9 @@ fn read_inter_luma8(
1811218282 reduced_tx_set: bool,
1811318283 split: bool, fctx: &crate::decode::FrameCtx,
1811418284 ) -> Result<(Grid, TxType)> {
18285+ // lane-lossless: an 8x8 inter block is FOUR 4x4 units (libaom
18286+ // `read_block_tx_size`'s lossless TX_4X4), tree or no tree.
18287+ let split = split || lossless(fctx);
1811518288 if !split {
1811618289 return read_inter_plane(
1811718290 dec,
@@ -24208,10 +24381,21 @@ fn read_inter_plane(
2420824381 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
2420924382 };
2421024383 let mut coding = cdfs.txb(set, tx_mode);
24384+ // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
24385+ // transform type for lossless mode(qindex==0)" -- the symbol is not coded
24386+ // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
24387+ // plane of a lossless block (the residual then goes through the WHT, so
24388+ // the type only picks the scan, which is the default one).
24389+ if lossless(fctx) {
24390+ coding.tx_type = None;
24391+ }
2421124392 let default_tx_type = match inherited_luma_tx_type {
2421224393 Some(t) => reduce_inherited_chroma_tx_type(t, side, side, fctx),
2421324394 None => TxType::DctDct,
2421424395 };
24396+ // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
24397+ // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
24398+ let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
2421524399 let (grid, tx_type) = read_coeffs(
2421624400 dec,
2421724401 &mut coding,
@@ -24237,7 +24421,7 @@ fn read_inter_plane(
2423724421 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
2423824422 let tx = TxParams {
2423924423 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
24240- ac_delta, tx_type, stride: 0,
24424+ ac_delta, tx_type, stride: 0, lossless: lossless(fctx),
2424124425 };
2424224426 push_mc_rect_tx(plane_idx, x, y, side, side, side, prediction, tx, &grid, fctx);
2424324427 Ok((grid, tx_type))
@@ -28910,7 +29094,7 @@ fn decode_inter_block(
2891029094 // the 14-symbol CFL one gave the same DC_PRED VALUE but narrowed the
2891129095 // arithmetic coder by the wrong interval, desyncing the tile from this
2891229096 // block on.
28913- let cfl_allowed = write_w.max(write_h) <= 32;
29097+ let cfl_allowed = cfl_allowed_px(write_w, write_h, fctx);
2891429098 if !cfl_allowed {
2891529099 hit!(NOCFL_UV_MODE_HITS);
2891629100 }
crates/ec-av1/src/refusal_inventory.rsmodified+12 -11
@@ -57,15 +57,16 @@ const REFUSALS: &[&str] = &[
5757 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
5858 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
5959 "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)",
60- // lane-dpm1: libaom codes his screen-capture row at `-crf 5` with
61- // `base_q_idx == 0`, i.e. LOSSLESS -- TX_4X4 with the Walsh-Hadamard
62- // transform over every block (no `tx_depth` symbol at all) and
63- // `is_cfl_allowed` narrowed to `plane_bsize == BLOCK_4X4`, which changes
64- // the `uv_mode` alphabet. Nothing here consumes the header's `lossless`,
65- // so the first block of such a frame read `uv_mode` = UV_CFL_PRED where
66- // aomdec reads V_PRED. Refused by name (gate
67- // `a_lossless_libaom_stream_is_refused_by_name`) until the path exists.
68- "a lossless frame (qindex 0): the TX_4X4 Walsh-Hadamard tile syntax and the lossless CfL rule are unimplemented",
60+ // lane-lossless: the KEY/intra-only half of a lossless frame (base_q_idx
61+ // 0) now decodes sample-exact -- TX_4X4 with the Walsh-Hadamard transform
62+ // on every plane, no `tx_type` symbol, `is_cfl_allowed` narrowed to a
63+ // BLOCK_4X4 chroma plane block. What is left is the INTER chroma walk: an
64+ // inter block's chroma plane is still read as ONE transform per block
65+ // here, so a lossless inter frame is refused by name (gate
66+ // `a_lossless_inter_frame_is_refused_by_name`). A frame whose segments
67+ // disagree is refused separately: every lossless rule is per segment.
68+ "a lossless INTER frame (its chroma plane is still coded as one transform per block here)",
69+ "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)",
6970 "a frame OBU with no tile group",
7071 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
7172 "a frame with no mode-info grid",
@@ -285,8 +286,8 @@ const PROVEN: &[(&str, &str)] = &[
285286 "an_inter_frame_opening_a_stream_is_refused_by_name",
286287 ),
287288 (
288- "a lossless frame (qindex 0): the TX_4X4 Walsh-Hadamard tile syntax and the lossless CfL rule are unimplemented",
289- "a_lossless_libaom_stream_is_refused_by_name",
289+ "a lossless INTER frame (its chroma plane is still coded as one transform per block here)",
290+ "a_lossless_inter_frame_is_refused_by_name",
290291 ),
291292 // lane-t900 r25, enumeration: a motion_mode/obmc symbol is read only under
292293 // `is_motion_variation_allowed_bsize` (min side >= 8), and each of the 17
crates/ec-av1/src/stream.rsmodified+110 -29
@@ -1603,12 +1603,34 @@ fn decode_frame(
16031603 // symbol four of the frame. Refuse by name rather than return a picture
16041604 // that is silently wrong from luma sample 0 (class `refusal-hides-a-defect`
16051605 // read the other way: a silent wrong decode is worse than a named gap).
1606- if header.lossless.iter().any(|&l| l) {
1606+ // lane-lossless: `CodedLossless` (spec 5.9.12) -- every segment at
1607+ // `qindex == 0` with zero plane deltas. The tile reader then forces TX_4X4
1608+ // with the Walsh-Hadamard transform on every plane, codes no `tx_type`
1609+ // symbol and narrows `is_cfl_allowed` to `plane_bsize == BLOCK_4X4`
1610+ // (libaom `read_tx_size`/`read_tx_type`/`is_cfl_allowed`). A frame whose
1611+ // segments DISAGREE is still refused by name: every one of those rules is
1612+ // per segment there, and no gate covers a mixed frame.
1613+ let coded_lossless = header.lossless.iter().all(|&l| l);
1614+ if header.lossless.iter().any(|&l| l) && !coded_lossless {
16071615 return Err(Error::unsupported(
16081616 "AV1 decode_stream",
1609- "a lossless frame (qindex 0): the TX_4X4 Walsh-Hadamard tile syntax and the lossless CfL rule are unimplemented",
1617+ "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)",
16101618 ));
16111619 }
1620+ // lane-lossless r1 ships the KEY/intra-only half: an inter block's chroma
1621+ // plane is still read as ONE transform per block here, where a lossless
1622+ // frame codes it as 4x4 units like everything else (libaom
1623+ // `read_block_tx_size` returns TX_4X4 for every plane). The luma side of
1624+ // the inter path is already converted (`read_block_tx_size`'s synthesized
1625+ // leaves); the chroma walk and its mu-chunk order are the remaining work,
1626+ // so refuse by name rather than return silently wrong pixels.
1627+ if coded_lossless && header.frame_type == FrameType::Inter {
1628+ return Err(Error::unsupported(
1629+ "AV1 decode_stream",
1630+ "a lossless INTER frame (its chroma plane is still coded as one transform per block here)",
1631+ ));
1632+ }
1633+ crate::decode::set_lossless(coded_lossless, fctx);
16121634 crate::decode::set_bit_depth(bit_depth, fctx);
16131635 // spec 7.16: this frame's superres state, for the filter chain --
16141636 // `decode.rs` upscales between CDEF and loop restoration and sizes
@@ -3985,18 +4007,20 @@ pub(crate) mod tests {
39854007 }
39864008 }
39874009
3988- /// lane-dpm1: the lossless refusal is a CLAIM, so it gets a stream that
3989- /// reaches it. libaom at `-crf 0` codes `base_q_idx == 0` -- the same
3990- /// lossless frame his screen-capture row gets at `-crf 5` -- where the tile
3991- /// syntax is TX_4X4 + Walsh-Hadamard and `is_cfl_allowed` narrows to
3992- /// `plane_bsize == BLOCK_4X4`. Before the refusal our decoder returned a
3993- /// picture that was wrong from luma sample 0 (measured on that row: 126
3994- /// against ffmpeg's 33, the first block's `uv_mode` read off the CfL
3995- /// alphabet). The gate asserts the stream really is lossless and that we
3996- /// refuse it BY NAME rather than decode it wrong.
4010+ /// lane-lossless: the refusal became an implementation, so its gate became
4011+ /// a DECODE-EXACT one (class `refusal-lifted-without-a-gate`). libaom at
4012+ /// `-crf 0` codes `base_q_idx == 0` -- the same lossless frame his
4013+ /// screen-capture row gets at `-crf 5` -- where every plane is TX_4X4 with
4014+ /// the Walsh-Hadamard transform, no `tx_type` symbol is coded
4015+ /// (`read_tx_type`, `decodetxb.c`: "No need to read transform type for
4016+ /// lossless mode(qindex==0)") and `is_cfl_allowed` (`blockd.h`) narrows to
4017+ /// a BLOCK_4X4 chroma plane block. The gate asserts the stream really is
4018+ /// lossless (class `gate-blind-to-feature`), that every KEY frame decodes
4019+ /// sample-exact against ffmpeg, and that the still-unimplemented lossless
4020+ /// INTER frame is refused BY NAME rather than decoded wrong.
39974021 #[test]
3998- fn a_lossless_libaom_stream_is_refused_by_name() {
3999- const NAME: &str = "a_lossless_libaom_stream_is_refused_by_name";
4022+ fn a_lossless_libaom_key_frame_decodes_sample_exact() {
4023+ const NAME: &str = "a_lossless_libaom_key_frame_decodes_sample_exact";
40004024 if !have_ffmpeg() {
40014025 eprintln!("SKIP {NAME}: no ffmpeg");
40024026 return;
@@ -4014,17 +4038,21 @@ pub(crate) mod tests {
40144038 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
40154039 let src = std::env::temp_dir().join(format!("ec-av1-lossless-{}.yuv", std::process::id()));
40164040 std::fs::write(&src, &raw).expect("raw source");
4017- let out = Command::new("ffmpeg")
4018- .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
4019- .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
4020- .arg(&src)
4021- .args(["-an", "-threads", "1", "-g", "2", "-c:v", "libaom-av1"])
4022- .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"])
4023- .stdin(Stdio::null())
4024- .stdout(Stdio::piped())
4025- .stderr(Stdio::piped())
4026- .output()
4027- .expect("ffmpeg failed to run");
4041+ let encode = |gop: &str| {
4042+ let out = Command::new("ffmpeg")
4043+ .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
4044+ .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
4045+ .arg(&src)
4046+ .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
4047+ .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"])
4048+ .stdin(Stdio::null())
4049+ .stdout(Stdio::piped())
4050+ .stderr(Stdio::piped())
4051+ .output()
4052+ .expect("ffmpeg failed to run");
4053+ out
4054+ };
4055+ let out = encode("1");
40284056 let _ = std::fs::remove_file(&src);
40294057 if !out.status.success() {
40304058 eprintln!(
@@ -4045,15 +4073,68 @@ pub(crate) mod tests {
40454073 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
40464074 _ => continue,
40474075 };
4048- if header.lossless.iter().any(|&l| l) {
4076+ if header.lossless.iter().all(|&l| l) {
40494077 lossless += 1;
40504078 }
40514079 }
4052- assert!(lossless > 0, "{NAME} went blind: libaom coded no lossless frame at -crf 0");
4053- match decode_stream(&stream) {
4054- Ok(_) => panic!("{NAME}: a lossless stream decoded instead of being refused"),
4080+ assert_eq!(lossless, frames, "{NAME} went blind: libaom coded no lossless key frame at -crf 0");
4081+ let ours = decode_stream(&stream).expect("a lossless key-frame stream decodes");
4082+ let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
4083+ assert_eq!(ours.len(), frames, "{NAME}: frame count");
4084+ for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
4085+ for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
4086+ .iter()
4087+ .enumerate()
4088+ {
4089+ let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
4090+ assert_eq!(bad, 0, "{NAME}: frame {i} plane {plane}: {bad} samples differ");
4091+ }
4092+ }
4093+ }
4094+
4095+ /// The other half of lane-lossless r1: a lossless INTER frame is refused BY
4096+ /// NAME (its chroma plane is still one transform per block here), never
4097+ /// decoded into silently wrong pixels -- the refusal this gate pins is the
4098+ /// one `refusal_inventory` carries.
4099+ #[test]
4100+ fn a_lossless_inter_frame_is_refused_by_name() {
4101+ const NAME: &str = "a_lossless_inter_frame_is_refused_by_name";
4102+ if !have_ffmpeg() {
4103+ eprintln!("SKIP {NAME}: no ffmpeg");
4104+ return;
4105+ }
4106+ let (w, h, frames) = (128usize, 64usize, 4usize);
4107+ let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
4108+ for f in 0..frames {
4109+ for row in 0..h {
4110+ for col in 0..w {
4111+ raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8);
4112+ }
4113+ }
4114+ raw.extend(std::iter::repeat_n(128u8, w * h / 2));
4115+ }
4116+ let src = std::env::temp_dir().join(format!("ec-av1-lossless-i-{}.yuv", std::process::id()));
4117+ std::fs::write(&src, &raw).expect("raw source");
4118+ let out = Command::new("ffmpeg")
4119+ .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
4120+ .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
4121+ .arg(&src)
4122+ .args(["-an", "-threads", "1", "-g", "4", "-c:v", "libaom-av1"])
4123+ .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"])
4124+ .stdin(Stdio::null())
4125+ .stdout(Stdio::piped())
4126+ .stderr(Stdio::piped())
4127+ .output()
4128+ .expect("ffmpeg failed to run");
4129+ let _ = std::fs::remove_file(&src);
4130+ if !out.status.success() {
4131+ eprintln!("SKIP {NAME}: ffmpeg has no libaom-av1 encoder");
4132+ return;
4133+ }
4134+ match decode_stream(&out.stdout) {
4135+ Ok(_) => panic!("{NAME}: a lossless inter stream decoded instead of being refused"),
40554136 Err(e) => assert!(
4056- format!("{e}").contains("a lossless frame (qindex 0)"),
4137+ format!("{e}").contains("a lossless INTER frame"),
40574138 "{NAME}: refused for the wrong reason: {e}"
40584139 ),
40594140 }
crates/ec-av1/src/transform.rsmodified+131 -0
@@ -2836,3 +2836,134 @@ mod tests {
28362836 }
28372837
28382838 }
2839+
2840+/// The lossless inverse transform: libaom `av1_iwht4x4_16_add_c`
2841+/// (`aom_dsp/inv_txfm.c:22`), the 4x4 Walsh-Hadamard a frame with
2842+/// `Lossless == 1` uses for every plane instead of the DCT/ADST network
2843+/// (`inv_txfm_add`, `av1/common/idct.c:69`: `if (txfm_param->lossless) {
2844+/// assert(tx_type == DCT_DCT); av1_iwht4x4_add(...); return; }`).
2845+///
2846+/// `dq` is the DEQUANTIZED grid; each input is shifted down by
2847+/// `UNIT_QUANT_SHIFT` (2, `aom_dsp/inv_txfm.h`) before the row pass, which at
2848+/// `qindex == 0` (`dc_q(0) == ac_q(0) == 4` at every bit depth) undoes the
2849+/// dequantization exactly -- that is what makes the round trip lossless.
2850+pub fn inverse_wht4x4(dq: &[i32]) -> Vec<i32> {
2851+ debug_assert_eq!(dq.len(), 16);
2852+ // libaom runs pass 1 down the COLUMNS (`ip[4 * k]`, `ip++`) and pass 2
2853+ // along the intermediate's ROWS writing dest COLUMNS (`dest[stride * k]`,
2854+ // `dest++`); transposing both passes -- rows first, then columns, output
2855+ // in place -- is the same map and is what a raster `dq`/residual pair
2856+ // wants here. MEASURED: the other orientation reconstructs sample 0 and
2857+ // the DC-only units correctly and drifts by +-1 everywhere else.
2858+ let mut out = [0i32; 16];
2859+ for i in 0..4 {
2860+ let (mut a1, mut c1, mut d1, mut b1) =
2861+ (dq[i * 4] >> 2, dq[i * 4 + 1] >> 2, dq[i * 4 + 2] >> 2, dq[i * 4 + 3] >> 2);
2862+ a1 += c1;
2863+ d1 -= b1;
2864+ let e1 = (a1 - d1) >> 1;
2865+ b1 = e1 - b1;
2866+ c1 = e1 - c1;
2867+ a1 -= b1;
2868+ d1 += c1;
2869+ out[i * 4] = a1;
2870+ out[i * 4 + 1] = b1;
2871+ out[i * 4 + 2] = c1;
2872+ out[i * 4 + 3] = d1;
2873+ }
2874+ let mut res = vec![0i32; 16];
2875+ for i in 0..4 {
2876+ let (mut a1, mut c1, mut d1, mut b1) =
2877+ (out[i], out[4 + i], out[8 + i], out[12 + i]);
2878+ a1 += c1;
2879+ d1 -= b1;
2880+ let e1 = (a1 - d1) >> 1;
2881+ b1 = e1 - b1;
2882+ c1 = e1 - c1;
2883+ a1 -= b1;
2884+ d1 += c1;
2885+ res[i] = a1;
2886+ res[4 + i] = b1;
2887+ res[8 + i] = c1;
2888+ res[12 + i] = d1;
2889+ }
2890+ res
2891+}
2892+
2893+/// [`inverse_wht4x4`] with the spec 7.12.3 dequantization in front of it, the
2894+/// lossless twin of [`dequant_and_inverse_typed_wh`] (same empty-grid
2895+/// marker contract).
2896+pub fn dequant_and_inverse_wht4x4(
2897+ levels: &[i32],
2898+ bit_depth: u8,
2899+ q_idx: i32,
2900+ dc_delta: i32,
2901+ ac_delta: i32,
2902+) -> Vec<i32> {
2903+ if crate::decode::is_zero_grid(levels) {
2904+ return Vec::new();
2905+ }
2906+ DQ_SCRATCH.with(|cell| {
2907+ let mut dq = cell.borrow_mut();
2908+ crate::quant::dequant_wh_into(levels, &mut dq, 4, 4, bit_depth, q_idx, dc_delta, ac_delta);
2909+ inverse_wht4x4(&dq[..16])
2910+ })
2911+}
2912+
2913+#[cfg(test)]
2914+mod lossless_tx_tests {
2915+ /// The WHT is its own inverse up to the `UNIT_QUANT_SHIFT` scaling: a
2916+ /// forward pass (libaom `av1_fwht4x4_c`, which scales UP by 4 through
2917+ /// `output[i] * UNIT_QUANT_SHIFT`) followed by [`super::inverse_wht4x4`]
2918+ /// on the dequantized levels (`q == 4` at qindex 0) returns the residual
2919+ /// EXACTLY -- that identity is the whole lossless claim.
2920+ #[test]
2921+ fn the_walsh_hadamard_round_trip_is_exact() {
2922+ // The exact integer inverse of [`super::inverse_wht4x4`]'s two
2923+ // butterflies, run in the opposite order (columns then rows) and
2924+ // scaled back up by `UNIT_QUANT_SHIFT` -- the encoder side of the
2925+ // lossless pair (libaom `av1_fwht4x4_c`).
2926+ fn undo(a2: i32, b2: i32, c2: i32, d2: i32) -> (i32, i32, i32, i32) {
2927+ let a1 = a2 + b2;
2928+ let d1 = d2 - c2;
2929+ let e1 = (a1 - d1) >> 1;
2930+ let b = e1 - b2;
2931+ let c = e1 - c2;
2932+ (a1 - c, b, c, d1 + b)
2933+ }
2934+ fn fwht(residual: &[i32]) -> Vec<i32> {
2935+ let mut t = [0i32; 16];
2936+ for i in 0..4 {
2937+ let (a, b, c, d) =
2938+ undo(residual[i], residual[4 + i], residual[8 + i], residual[12 + i]);
2939+ t[i] = a;
2940+ t[4 + i] = c;
2941+ t[8 + i] = d;
2942+ t[12 + i] = b;
2943+ }
2944+ let mut dq = vec![0i32; 16];
2945+ for i in 0..4 {
2946+ let (a, b, c, d) = undo(t[i * 4], t[i * 4 + 1], t[i * 4 + 2], t[i * 4 + 3]);
2947+ dq[i * 4] = a * 4;
2948+ dq[i * 4 + 1] = c * 4;
2949+ dq[i * 4 + 2] = d * 4;
2950+ dq[i * 4 + 3] = b * 4;
2951+ }
2952+ dq
2953+ }
2954+ let mut state = 0x1234_5678u32;
2955+ for _ in 0..200 {
2956+ let residual: Vec<i32> = (0..16)
2957+ .map(|_| {
2958+ state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
2959+ ((state >> 20) as i32 % 511) - 255
2960+ })
2961+ .collect();
2962+ let levels = fwht(&residual);
2963+ // The forward pass already carries libaom's `UNIT_QUANT_SHIFT`
2964+ // scale-up, so the coded level is `levels / 4` and qindex 0's
2965+ // dequantization (times 4) hands `levels` straight back.
2966+ assert_eq!(super::inverse_wht4x4(&levels), residual, "levels={levels:?}");
2967+ }
2968+ }
2969+}
lanes/lossless.report.mdadded+33 -0
@@ -0,0 +1,33 @@
1+# lane-lossless — AV1 lossless (qindex 0) decode
2+
3+Branch `lane-lossless`, base `7ba28bcd`. Suite: 556 passed / 0 failed / 43 ignored (`cargo test -p ec-av1 --lib -- --test-threads=1`, 3611 s). `cargo check --workspace --all-targets -j4`: 0 errors, 0 ec-av1 warnings. Native `bd_rate_screen_native` NOT run: its crf-5 point has inter frames and now hits the named lossless-inter refusal (still red on that point).
4+
5+## Rules implemented (each with its libaom reference)
6+| rule | libaom | where |
7+|---|---|---|
8+| TX_4X4 on every plane, no `tx_depth`/`txfm_split` symbol | `read_tx_size` (`av1/decoder/decodeframe.c`): `if (xd->lossless[..]) return TX_4X4;` before `max_txsize_rect_lookup` | `decode::lossless_tx`, `decode_block`, `decode_leaf8`, `depth_to_tx_wh`, `read_block_tx_size`(+`_rect`), `read_inter_luma8` |
9+| Walsh-Hadamard inverse instead of DCT/ADST | `inv_txfm_add` (`av1/common/idct.c`): `if (txfm_param->lossless) { assert(tx_type == DCT_DCT); av1_iwht4x4_add(...); }`; kernel `av1_highbd_iwht4x4_16_add_c` (`av1/common/av1_inv_txfm2d.c:20`), inputs `>> UNIT_QUANT_SHIFT` (2) | `transform::inverse_wht4x4` / `dequant_and_inverse_wht4x4`, `TxParams::lossless` |
10+| no `tx_type` symbol | `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read transform type for lossless mode(qindex==0)" | `read_plane`/`read_inter_plane`/`read_inter_plane_rect`: `coding.tx_type = None` |
11+| DCT_DCT on every plane (so the default scan) | `av1_get_tx_type` (`av1/common/blockd.h`): lossless returns DCT_DCT | same three readers' `default_tx_type` |
12+| `is_cfl_allowed` narrows to a BLOCK_4X4 chroma plane block (luma <= 8x8 at 4:2:0) | `is_cfl_allowed` (`av1/common/blockd.h`) | `decode::cfl_allowed_px`, used by every intra mode reader |
13+| chroma coded as 4x4 units, plane-major, with `get_txb_ctx`'s `+10` rows | `decode_token_recon_block` mu-chunk loop; `av1_default_txb_skip_cdfs[0][TX_4X4][10..13]` = 9961/30242/32117 (neutral 16384 in every other q-context) | `decode_rect_split` lossless chroma branch; `cdf_state::txb_skip_chroma_4` widened 3 -> 6 rows |
14+| loop filter / CDEF / LR off | header-level (`coded_lossless`/`all_lossless`), already handled by the frame-header parser | unchanged |
15+| a frame mixing lossless and lossy segments | every rule above is per segment | refused by name |
16+
17+WHT orientation is pinned by MEASUREMENT: libaom's column-then-row-with-transpose
18+loop equals rows-then-columns in place on a raster grid; the other orientation
19+reconstructs sample 0 and DC-only units correctly and drifts +-1 elsewhere.
20+
21+## Fixtures and results (all `ffmpeg -c:v libaom-av1 -crf 0 -b:v 0`, synthetic source)
22+| fixture | result |
23+|---|---|
24+| 64x64, 1 key frame, 8-bit | EXACT vs ffmpeg (0/6144 samples differ); 6488 entropy steps identical to aomdec `EC_TRACE_COEFF` |
25+| 256x128, 2 key frames (`-g 1`), 8-bit | EXACT both frames — pinned as `stream::tests::a_lossless_libaom_key_frame_decodes_sample_exact` |
26+| 192x96, 2 key frames, 10-bit | EXACT both frames |
27+| 128x64, 4 frames (`-g 4`, inter) | refused by name — pinned as `stream::tests::a_lossless_inter_frame_is_refused_by_name` |
28+
29+## Deferred
30+- `deferred: lossless INTER frames — an inter block's chroma plane is still read as one transform per block (decode_inter_block's two chroma sites + the 128 mu-chunk loop); its luma leaves are already synthesized as TX_4X4 — unblocks: port the 4x4 chroma unit walk (the shape decode_rect_split's lossless branch already has) into decode_inter_block/decode_inter_block8/the sub8 readers.`
31+- `deferred: the 12-frame bd_rate_screen_native gate's libaom crf-5 point — that stream's inter frames now hit the named refusal instead of decoding, so the deciding gate cannot be green this round — unblocks: the inter chroma walk above.`
32+- `deferred: mixed lossless/lossy segments — refused by name; no libaom recipe emits one — unblocks: a segmentation fixture with per-segment qindex.`
33+- `deferred: 4:4:4 / monochrome lossless — the crate is 4:2:0 only.`