diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 16c06bc9..6a52d579 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -2099,6 +2099,18 @@ pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] { /// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a /// site whose reconstruct never runs would be picked up by the NEXT block's /// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so +/// lane-lossless2: one transform unit's window on a block-sized palette +/// prediction buffer. A unit reads its prediction at ITS OWN stride, so +/// handing it the whole-block buffer makes every unit reconstruct the block's +/// top-left corner (the luma split-transform paths already window; the chroma +/// ones did not, which is invisible until a lossless frame codes a palette +/// block as 4x4 chroma units). +fn palette_window(buf: &[u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize) -> Vec { + (0..h) + .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied()) + .collect() +} + /// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site. #[track_caller] fn set_palette_pred(buf: Vec, fctx: &crate::decode::FrameCtx) { @@ -6172,7 +6184,7 @@ fn read_coeffs( if coeff_trace_on() { let (rng, _) = dec.debug_state(); eprintln!( - "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}", + "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}", coding.side, all_zero as i32 ); @@ -9546,6 +9558,13 @@ fn decode_rect_split( } } // CHROMA: one un-split rect transform for the whole strip. + // lane-lossless2: except on a lossless frame, where it is a raster of 4x4 + // units -- each stamps its own neighbour context as it is read, and the + // whole-block `record_split_luma_rect_mi` below would overwrite all of + // them with the LAST unit's state (class `override-slot-on-one-arm`: the + // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are + // collected here and replayed after that record. + let mut ll_chroma_units: Vec<((usize, usize), usize, Grid)> = Vec::new(); let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh)); let reach = block_reach; let (u_grid, v_grid) = if m.skip { @@ -9594,8 +9613,9 @@ fn decode_rect_split( ); let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4); if let Some((ub, vb)) = &m.palette_uv { + let pbuf = if plane_idx == 1 { ub } else { vb }; set_palette_pred( - if plane_idx == 1 { ub.clone() } else { vb.clone() }, + palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4), fctx, ); } @@ -9611,6 +9631,7 @@ fn decode_rect_split( None, offset, m.smooth_neighbor_uv, fctx, )?; neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_idx, &grid); + ll_chroma_units.push((cu_mi, plane_idx, grid.clone())); last[plane_idx - 1] = grid; } } @@ -9695,6 +9716,9 @@ fn decode_rect_split( m.uv_predict_mode, [&u_grid, &v_grid], ); + for (cu_mi, plane, unit) in &ll_chroma_units { + neighbours.record_mi_chroma(*cu_mi, 8, 8, *plane, unit); + } neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip); neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx); if crate::envflags::env_flag!("EC_AV1_TRACE") { @@ -14455,6 +14479,16 @@ fn decode_block( // identical at every size up to 64x64, but a 128x128 block's 64x64 uv // plane block adjusts TX_64X64 down to TX_32X32, so each plane is // FOUR units (lane-sb128b r2) -- one per mu chunk. + // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR + // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of + // the chunk, then every V unit. At one unit per plane per chunk -- + // every non-lossless case this decoder reaches -- that is the same + // symbol order as the interleaved pair this loop used to read; a + // lossless frame's 4x4 chroma units are the case where it differs + // (lane-lossless2). + let mut u_pass: Vec = Vec::new(); + for plane_pass in 1..=2usize { + let mut pass_idx = 0usize; for cu_row in ch_row * cpc..(ch_row + 1) * cpc { for cu_col in ch_col * cpc..(ch_col + 1) * cpc { // The chroma context arrays are indexed in LUMA mi, so this @@ -14476,24 +14510,25 @@ fn decode_block( ) }; let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx); - if let Some((ub, _)) = &palette_uv_bufs { - set_palette_pred(ub.clone(), fctx); - } - let u_grid = read_plane( - dec, cdfs, chroma_set, scans.1, 1, cu_around[1], mode, - uv_predict_mode, angle_delta_uv, cu_reach, u, cu_x, cu_y, - chroma_tx, chroma_tx, base_q_idx, - alpha.zip(ac).map(|((au, _), ac)| (au, ac)), - None, chroma_ctx_offset, smooth_neighbor_uv, fctx, - )?; - if let Some((_, vb)) = &palette_uv_bufs { - set_palette_pred(vb.clone(), fctx); + if let Some((ub, vb)) = &palette_uv_bufs { + let pbuf = if plane_pass == 1 { ub } else { vb }; + set_palette_pred( + palette_window( + pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx, + chroma_tx, chroma_tx, + ), + fctx, + ); } - let v_grid = read_plane( - dec, cdfs, chroma_set, scans.1, 2, cu_around[2], mode, - uv_predict_mode, angle_delta_uv, cu_reach, v, cu_x, cu_y, + let buf: &mut PlaneBuf<'static> = + if plane_pass == 1 { &mut *u } else { &mut *v }; + let cu_grid = read_plane( + dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode, + uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, - alpha.zip(ac).map(|((_, av), ac)| (av, ac)), + alpha.zip(ac).map(|((au, av), ac)| { + (if plane_pass == 1 { au } else { av }, ac) + }), None, chroma_ctx_offset, smooth_neighbor_uv, fctx, )?; if cn > 1 { @@ -14504,15 +14539,23 @@ fn decode_block( // 1 from this left neighbour -- measured against aomdec). // The same writes are replayed after `record_split_luma` // below, which would otherwise clobber them whole-block. - neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid); - neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid); - units.push((cu_mi, luma_span, u_grid.clone(), v_grid.clone())); + neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &cu_grid); + } + if plane_pass == 1 { + u_pass.push(cu_grid); + } else { + let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0)); + if cn > 1 { + units.push((cu_mi, luma_span, u_grid.clone(), cu_grid.clone())); + } + last_grids = [u_grid, cu_grid]; } - last_grids = [u_grid, v_grid]; + pass_idx += 1; } } } } + } // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma // context write; at `cn > 1` the per-unit writes above are what the // next block reads, so they run after this (last writer wins). @@ -24427,6 +24470,216 @@ fn read_inter_plane( Ok((grid, tx_type)) } +/// The intra twin of [`read_inter_chroma_lossless`]: an INTRA block inside a +/// lossless frame codes its chroma plane as 4x4 transform units, plane-major +/// inside each 64x64 mu chunk (libaom `decode_token_recon_block`'s +/// `for (plane..) for (blk_row..) for (blk_col..)` with `av1_get_tx_size` +/// returning TX_4X4 under `xd->lossless[..]`). CfL never rides here: +/// `is_cfl_allowed` (`blockd.h`) needs a BLOCK_4X4 chroma plane block, i.e. a +/// luma block of 8x8 or less, which the sub-8x8 readers own. +#[allow(clippy::too_many_arguments)] +fn read_intra_chroma_lossless( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + u: &mut PlaneBuf<'static>, + v: &mut PlaneBuf<'static>, + at_mi: (usize, usize), + (px, py): (usize, usize), + (cpx, cpy): (usize, usize), + side: usize, + (blk_w, blk_h): (usize, usize), + (org_x, org_y): (usize, usize), + (reg_w, reg_h): (usize, usize), + stride: usize, + reach: Reach, + (frame_w, frame_h): (usize, usize), + mode: usize, + uv_predict_mode: usize, + angle_delta_uv: i32, + palette_uv_bufs: Option<(&[u16], &[u16])>, + smooth_neighbor_uv: bool, + base_q_idx: u8, + u_out: &mut Vec, + v_out: &mut Vec, + fctx: &crate::decode::FrameCtx, +) -> Result<()> { + let scan4 = default_scan(4); + let offset = (blk_w > 4 || blk_h > 4).then_some(3); + for plane_idx in 1..3 { + for rr in 0..reg_h / 4 { + for cc in 0..reg_w / 4 { + let (ox, oy) = (org_x + cc * 4, org_y + rr * 4); + // libaom's `max_blocks_wide/high` clip: a unit whose origin is + // past the frame edge is not coded at all + // (`decode_token_recon_block`), same test `decode_block`'s + // luma loop already runs. + if cpx + ox >= u.true_width || cpy + oy >= u.true_height { + continue; + } + let cu_mi = (at_mi.0 + oy / 2, at_mi.1 + ox / 2); + // libaom's chroma entropy-context arrays are SUBSAMPLED: + // `get_txb_ctx` reads exactly one entry per plane for a + // TX_4X4 chroma unit (`a[0]`/`l[0]`). Our bands are luma-mi + // indexed and carry that one entry replicated over the unit's + // two cells, so one cell is the same answer -- and the second + // cell is past the band on a unit whose block hangs off the + // frame edge, which libaom still codes. + let cu_around = neighbours.around_mi(cu_mi, MI); + let cu_reach = tu_reach( + side, side, ox * 2, oy * 2, 8, reach, px, py, frame_w, frame_h, fctx, + ); + if let Some((ub, vb)) = palette_uv_bufs { + let buf = if plane_idx == 1 { ub } else { vb }; + set_palette_pred(palette_window(buf, stride, ox, oy, 4, 4), fctx); + } + let buf: &mut PlaneBuf<'static> = + if plane_idx == 1 { &mut *u } else { &mut *v }; + let cu_grid = read_plane( + dec, + cdfs, + TxbSet::Chroma4, + &scan4, + plane_idx, + cu_around[plane_idx], + mode, + uv_predict_mode, + angle_delta_uv, + cu_reach, + buf, + cpx + ox, + cpy + oy, + 4, + 4, + base_q_idx, + None, + None, + offset, + smooth_neighbor_uv, + fctx, + )?; + neighbours.record_mi_chroma(cu_mi, 8, 8, plane_idx, &cu_grid); + hit!(CHROMA_SPLIT_TX_HITS); + let dst = mu_units( + if plane_idx == 1 { &mut *u_out } else { &mut *v_out }, + stride * stride, + ); + for row in 0..4 { + let start = (oy + row) * stride + ox; + dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]); + } + } + } + } + Ok(()) +} + +/// lane-lossless2: the chroma half of a lossless INTER block. libaom's +/// `read_tx_size` (`av1/decoder/decodeframe.c`) returns TX_4X4 for EVERY +/// plane of a lossless block, so the chroma plane block is a raster of 4x4 +/// transform units instead of one whole-block transform, and +/// `decode_token_recon_block` walks them PLANE-MAJOR inside each 64x64 "mu" +/// chunk (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of +/// the chunk, then every V unit. Reads one chunk-sized region +/// (`org`/`reg`, chroma pixels relative to the block) and copies its units +/// into the block-sized `u_out`/`v_out` grids. +#[allow(clippy::too_many_arguments)] +fn read_inter_chroma_lossless( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + u: &mut PlaneBuf<'static>, + v: &mut PlaneBuf<'static>, + su: Pred<'_>, + sv: Pred<'_>, + at_mi: (usize, usize), + (cpx, cpy): (usize, usize), + (org_x, org_y): (usize, usize), + (reg_w, reg_h): (usize, usize), + // the whole block's chroma plane block -- what `get_txb_ctx`'s offset is + // decided on. + (blk_w, blk_h): (usize, usize), + // the stride the predictors and the block-sized `u_out`/`v_out` are read + // at (the block's square chroma side, even for a 2:1 strip, which embeds + // its narrower plane block in the same square grid). + stride: usize, + mode_for_tx: usize, + base_q_idx: u8, + u_out: &mut Vec, + v_out: &mut Vec, + fctx: &crate::decode::FrameCtx, +) -> Result<()> { + let scan4 = default_scan(4); + // `get_txb_ctx` (`av1/common/txb_common.h`): `ctx_offset` is 10 when the + // plane block is bigger than the transform and 7 when it is the + // transform -- our chroma tables carry the offset-10 rows at +3. + let offset = (blk_w > 4 || blk_h > 4).then_some(3); + for plane_idx in 1..3 { + for rr in 0..reg_h / 4 { + for cc in 0..reg_w / 4 { + let (ox, oy) = (org_x + cc * 4, org_y + rr * 4); + // libaom's `max_blocks_wide/high` clip: a unit whose origin is + // past the frame edge is not coded at all + // (`decode_token_recon_block`), same test `decode_block`'s + // luma loop already runs. + if cpx + ox >= u.true_width || cpy + oy >= u.true_height { + continue; + } + // The chroma neighbour bands are indexed in LUMA mi: 4 chroma + // pixels span 8 luma ones, i.e. 2 mi. + let cu_mi = (at_mi.0 + oy / 2, at_mi.1 + ox / 2); + // libaom's chroma entropy-context arrays are SUBSAMPLED: + // `get_txb_ctx` reads exactly one entry per plane for a + // TX_4X4 chroma unit (`a[0]`/`l[0]`). Our bands are luma-mi + // indexed and carry that one entry replicated over the unit's + // two cells, so one cell is the same answer -- and the second + // cell is past the band on a unit whose block hangs off the + // frame edge, which libaom still codes. + let cu_around = neighbours.around_mi(cu_mi, MI); + let (src, buf) = if plane_idx == 1 { + (su, &mut *u) + } else { + (sv, &mut *v) + }; + let cu_grid = read_inter_plane( + dec, + cdfs, + TxbSet::Chroma4, + &scan4, + plane_idx, + cu_around[plane_idx], + mode_for_tx, + buf, + cpx + ox, + cpy + oy, + 4, + base_q_idx, + src.offset(oy * stride + ox), + // A lossless block codes DCT_DCT on every plane + // (`av1_get_tx_type`, `blockd.h`), so nothing is + // inherited from the luma unit. + None, + offset, + fctx, + )? + .0; + // Immediately, so the NEXT unit reads this one's context. + neighbours.record_mi_chroma(cu_mi, 8, 8, plane_idx, &cu_grid); + hit!(CHROMA_SPLIT_TX_HITS); + let dst = mu_units( + if plane_idx == 1 { &mut *u_out } else { &mut *v_out }, + stride * stride, + ); + for row in 0..4 { + let start = (oy + row) * stride + ox; + dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]); + } + } + } + } + Ok(()) +} + /// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode` /// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with /// `reference_select` set before this is ever called, so that read is never @@ -27403,6 +27656,21 @@ fn decode_inter_block( let cu_around = neighbours.around_mi(cu_mi, luma_span); let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx); let cu_scan = default_scan(cu_tx); + if lossless(fctx) { + // lane-lossless2: this chunk's chroma is + // 8x8 TX_4X4 units per plane, not one + // TX_32X32 unit. + read_inter_chroma_lossless( + dec, cdfs, neighbours, u, v, su, sv, + at_mi, (cpx, cpy), + (cc * cu_tx, cr * cu_tx), (cu_tx, cu_tx), + (write_chroma_w, write_chroma_h), + chroma_side, mode_for_tx, base_q_idx, + &mut u_units, &mut v_units, fctx, + )?; + mu_chroma = true; + continue; + } for plane_idx in 1..3 { let (src, buf) = if plane_idx == 1 { (su, &mut *u) @@ -27513,6 +27781,23 @@ fn decode_inter_block( } else { Grid::Own(std::mem::take(&mut v_units)) }; + } else if lossless(fctx) { + // lane-lossless2: TX_4X4 chroma units, plane-major + // (libaom `read_tx_size` + `decode_token_recon_block`). + let (mut uo, mut vo) = (Vec::new(), Vec::new()); + read_inter_chroma_lossless( + dec, cdfs, neighbours, u, v, su, sv, at_mi, (cpx, cpy), + (0, 0), (write_chroma_w, write_chroma_h), + (write_chroma_w, write_chroma_h), chroma_side, + mode_for_tx, base_q_idx, &mut uo, &mut vo, fctx, + )?; + let zero = chroma_side * chroma_side; + u_grid = if uo.is_empty() { Grid::Zero(zero) } else { Grid::Own(uo) }; + v_grid = if vo.is_empty() { Grid::Zero(zero) } else { Grid::Own(vo) }; + // Every unit stamped its own neighbour context above; the + // whole-block record must not overwrite them with the + // assembled grid (class `override-slot-on-one-arm`). + mu_chroma = true; } else if rect_tu { // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a // 2:1 strip is the strip's own rect chroma size (16x8 / @@ -28700,6 +28985,21 @@ fn decode_inter_block( let cu_around = neighbours.around_mi(cu_mi, luma_span); let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx); let cu_scan = default_scan(cu_tx); + if lossless(fctx) { + // lane-lossless2: this chunk's chroma is + // 8x8 TX_4X4 units per plane, not one + // TX_32X32 unit. + read_inter_chroma_lossless( + dec, cdfs, neighbours, u, v, su, sv, + at_mi, (cpx, cpy), + (cc * cu_tx, cr * cu_tx), (cu_tx, cu_tx), + (write_chroma_w, write_chroma_h), + chroma_side, mode_for_tx, base_q_idx, + &mut u_units, &mut v_units, fctx, + )?; + mu_chroma = true; + continue; + } for plane_idx in 1..3 { let (src, buf) = if plane_idx == 1 { (su, &mut *u) @@ -28819,6 +29119,23 @@ fn decode_inter_block( } else { Grid::Own(std::mem::take(&mut v_units)) }; + } else if lossless(fctx) { + // lane-lossless2: TX_4X4 chroma units, plane-major + // (libaom `read_tx_size` + `decode_token_recon_block`). + let (mut uo, mut vo) = (Vec::new(), Vec::new()); + read_inter_chroma_lossless( + dec, cdfs, neighbours, u, v, su, sv, at_mi, (cpx, cpy), + (0, 0), (write_chroma_w, write_chroma_h), + (write_chroma_w, write_chroma_h), chroma_side, + mode_for_tx, base_q_idx, &mut uo, &mut vo, fctx, + )?; + let zero = chroma_side * chroma_side; + u_grid = if uo.is_empty() { Grid::Zero(zero) } else { Grid::Own(uo) }; + v_grid = if vo.is_empty() { Grid::Zero(zero) } else { Grid::Own(vo) }; + // Every unit stamped its own neighbour context above; the + // whole-block record must not overwrite them with the + // assembled grid (class `override-slot-on-one-arm`). + mu_chroma = true; } else if rect_tu { // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a // 2:1 strip is the strip's own rect chroma size (16x8 / @@ -29380,6 +29697,22 @@ fn decode_inter_block( reach, px, py, y.width, y.height, fctx, ); let cu_scan = default_scan(cu_tx); + if lossless(fctx) { + // lane-lossless2: 8x8 TX_4X4 units per plane in this + // chunk, not one TX_32X32 unit. + read_intra_chroma_lossless( + dec, cdfs, neighbours, u, v, at_mi, (px, py), + (cpx, cpy), side, (chroma_side, chroma_side), + (cc * cu_tx, cr * cu_tx), (cu_tx, cu_tx), + chroma_side, reach, (y.width, y.height), mode, + uv_predict_mode, angle_delta_uv, + palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), + smooth_neighbor_uv, base_q_idx, + &mut u_units, &mut v_units, fctx, + )?; + mu_chroma = true; + continue; + } for plane_idx in 1..3 { let buf: &mut PlaneBuf<'static> = if plane_idx == 1 { &mut *u } else { &mut *v }; let cu_grid = if skip { @@ -29552,6 +29885,23 @@ fn decode_inter_block( )?; } let ac = alpha.map(|_| cfl_src(px, py, side)); + if lossless(fctx) { + // lane-lossless2: the block's chroma plane is a raster of 4x4 + // units, plane-major (`read_intra_chroma_lossless`). + let (mut uo, mut vo) = (Vec::new(), Vec::new()); + read_intra_chroma_lossless( + dec, cdfs, neighbours, u, v, at_mi, (px, py), (cpx, cpy), + side, (chroma_side, chroma_side), (0, 0), + (chroma_side, chroma_side), chroma_side, reach, + (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, + palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), + smooth_neighbor_uv, base_q_idx, &mut uo, &mut vo, fctx, + )?; + let zero = chroma_side * chroma_side; + u_grid = if uo.is_empty() { Grid::Zero(zero) } else { Grid::Own(uo) }; + v_grid = if vo.is_empty() { Grid::Zero(zero) } else { Grid::Own(vo) }; + mu_chroma = true; + } else { if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } @@ -29602,6 +29952,7 @@ fn decode_inter_block( None, smooth_neighbor_uv, fctx, )?; + } } } // lane-comppin r9: end-of-block checkpoint -- everything between @@ -29634,11 +29985,20 @@ fn decode_inter_block( // units are collected here and re-stamped after that record, in mu-chunk // order so a later unit still wins over an earlier one. let mu_chroma_units: Vec<((usize, usize), usize, Grid)> = if mu_chroma { - let cu = 32usize; + // lane-lossless2: the unit is TX_32X32 (one per 64x64 mu chunk) + // normally and TX_4X4 on a lossless frame, where the whole chroma + // plane block is a raster of them. + let cu = if lossless(fctx) { 4usize } else { 32usize }; + let span = cu * 2; + let (rows, cols) = if lossless(fctx) { + ((write_h / 2).div_ceil(cu), (write_w / 2).div_ceil(cu)) + } else { + ((write_h / 64).max(1), (write_w / 64).max(1)) + }; let mut units = Vec::new(); - for cr in 0..(write_h / 64).max(1) { - for cc in 0..(write_w / 64).max(1) { - let cu_mi = (at.0 + cr * 16, at.1 + cc * 16); + for cr in 0..rows { + for cc in 0..cols { + let cu_mi = (at.0 + cr * (span / MI), at.1 + cc * (span / MI)); for (plane, grid) in [(1usize, &u_grid), (2usize, &v_grid)] { let mut unit = Vec::with_capacity(cu * cu); for rr in 0..cu { @@ -29782,8 +30142,9 @@ fn decode_inter_block( neighbours.record_uv_mode_mi(s.pair_mi.0, s.pair_mi.1, pw / MI, ph / MI, uv_predict_mode); hit!(INTER16_CHROMA_PAIR_HITS); } + let mu_span = if lossless(fctx) { 8 } else { 64 }; for (cu_mi, plane, unit) in &mu_chroma_units { - neighbours.record_mi_chroma(*cu_mi, 64, 64, *plane, unit); + neighbours.record_mi_chroma(*cu_mi, mu_span, mu_span, *plane, unit); } neighbours.record_inter_rect_mi( at, @@ -31201,6 +31562,16 @@ fn decode_inter_sub8_rect2( 0, &mut leaves, ); + } else if lossless(fctx) && !skip { + // lane-lossless2: `read_block_tx_size` returns TX_4X4 before it + // ever looks at `max_txsize_rect_lookup`, so an 8x4/4x8 leaf is + // TWO 4x4 units, not one rect one. + for row in 0..bh / MI { + for col in 0..bw / MI { + leaves.push((row, col, MI, MI)); + } + } + set_txfm_ctxs(neighbours, lmi, MI, w_mi, h_mi, skip); } else { leaves.push((0, 0, bw, bh)); set_txfm_ctxs(neighbours, lmi, bw.max(bh), w_mi, h_mi, skip); diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index f2b82553..85b28776 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -57,15 +57,14 @@ const REFUSALS: &[&str] = &[ "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)", "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)", "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)", - // lane-lossless: the KEY/intra-only half of a lossless frame (base_q_idx - // 0) now decodes sample-exact -- TX_4X4 with the Walsh-Hadamard transform + // lane-lossless/lane-lossless2: a lossless frame (base_q_idx 0) decodes + // sample-exact, KEY and INTER -- TX_4X4 with the Walsh-Hadamard transform // on every plane, no `tx_type` symbol, `is_cfl_allowed` narrowed to a - // BLOCK_4X4 chroma plane block. What is left is the INTER chroma walk: an - // inter block's chroma plane is still read as ONE transform per block - // here, so a lossless inter frame is refused by name (gate - // `a_lossless_inter_frame_is_refused_by_name`). A frame whose segments - // disagree is refused separately: every lossless rule is per segment. - "a lossless INTER frame (its chroma plane is still coded as one transform per block here)", + // BLOCK_4X4 chroma plane block, and the chroma plane walked as 4x4 units + // plane-major inside each mu chunk (gates + // `a_lossless_libaom_key_frame_decodes_sample_exact` / + // `a_lossless_libaom_inter_frame_decodes_sample_exact`). A frame whose + // segments disagree is still refused: every lossless rule is per segment. "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)", "a frame OBU with no tile group", "a frame naming primary_ref_frame at a reference slot with no saved CDF state", @@ -285,10 +284,6 @@ const PROVEN: &[(&str, &str)] = &[ "an inter frame with no key frame before it", "an_inter_frame_opening_a_stream_is_refused_by_name", ), - ( - "a lossless INTER frame (its chroma plane is still coded as one transform per block here)", - "a_lossless_inter_frame_is_refused_by_name", - ), // lane-t900 r25, enumeration: a motion_mode/obmc symbol is read only under // `is_motion_variation_allowed_bsize` (min side >= 8), and each of the 17 // `BLOCK_SIZES_ALL` footprints that clause admits maps to a distinct row of diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 1d9343b4..63f4d801 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -1617,19 +1617,10 @@ fn decode_frame( "a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)", )); } - // lane-lossless r1 ships the KEY/intra-only half: an inter block's chroma - // plane is still read as ONE transform per block here, where a lossless - // frame codes it as 4x4 units like everything else (libaom - // `read_block_tx_size` returns TX_4X4 for every plane). The luma side of - // the inter path is already converted (`read_block_tx_size`'s synthesized - // leaves); the chroma walk and its mu-chunk order are the remaining work, - // so refuse by name rather than return silently wrong pixels. - if coded_lossless && header.frame_type == FrameType::Inter { - return Err(Error::unsupported( - "AV1 decode_stream", - "a lossless INTER frame (its chroma plane is still coded as one transform per block here)", - )); - } + // lane-lossless2: an INTER frame's chroma plane is now walked as 4x4 + // transform units too (`decode::read_inter_chroma_lossless`), so the + // named refusal that stood here is gone -- the gate that replaced it is + // `a_lossless_libaom_inter_frame_decodes_sample_exact`. crate::decode::set_lossless(coded_lossless, fctx); crate::decode::set_bit_depth(bit_depth, fctx); // spec 7.16: this frame's superres state, for the filter chain -- @@ -4033,7 +4024,20 @@ pub(crate) mod tests { raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8); } } - raw.extend(std::iter::repeat_n(128u8, w * h / 2)); + // lane-lossless2: TEXTURED chroma. A flat chroma plane codes one + // `txb_skip` symbol per 4x4 unit with every context at 0, which + // is blind to both the unit ORDER and the per-unit contexts + // (class `gate-blind-to-feature`). + for row in 0..h / 2 { + for col in 0..w / 2 { + raw.push((((col + f) * 11 + row * 5) % 251) as u8); + } + } + for row in 0..h / 2 { + for col in 0..w / 2 { + raw.push(((col * 3 + (row + f) * 17) % 251) as u8); + } + } } // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. let src = std::env::temp_dir().join(format!("ec-av1-lossless-{}.yuv", std::process::id())); @@ -4092,51 +4096,157 @@ pub(crate) mod tests { } } - /// The other half of lane-lossless r1: a lossless INTER frame is refused BY - /// NAME (its chroma plane is still one transform per block here), never - /// decoded into silently wrong pixels -- the refusal this gate pins is the - /// one `refusal_inventory` carries. + /// lane-lossless2: the refusal `a_lossless_inter_frame_is_refused_by_name` + /// pinned became an implementation, so its gate became a DECODE-EXACT one + /// (class `refusal-lifted-without-a-gate`). A lossless INTER frame codes + /// its chroma plane as 4x4 transform units, plane-major inside each 64x64 + /// mu chunk (libaom `read_tx_size` returns TX_4X4 for every plane under + /// `xd->lossless[..]`, and `decode_token_recon_block` walks + /// `for (plane..) for (blk_row..) for (blk_col..)`), which is what + /// `decode::read_inter_chroma_lossless` reads. The source carries TEXTURED + /// CHROMA and real motion on purpose: a flat-chroma source codes one + /// `txb_skip` symbol per unit and is blind to both the unit order and the + /// per-unit contexts (class `gate-blind-to-feature`). #[test] - fn a_lossless_inter_frame_is_refused_by_name() { - const NAME: &str = "a_lossless_inter_frame_is_refused_by_name"; + fn a_lossless_libaom_inter_frame_decodes_sample_exact() { + const NAME: &str = "a_lossless_libaom_inter_frame_decodes_sample_exact"; if !have_ffmpeg() { eprintln!("SKIP {NAME}: no ffmpeg"); return; } - let (w, h, frames) = (128usize, 64usize, 4usize); - let mut raw = Vec::with_capacity(frames * w * h * 3 / 2); - for f in 0..frames { - for row in 0..h { - for col in 0..w { - raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8); + // (w, h, frames, gop, bit depth, 128-superblock, screen content) + // lane-lossless2: the SCREEN rows carry palette blocks, which is what + // caught the whole-block palette prediction being handed to a 4x4 + // chroma unit; they are KEY-only, see the lane report's deferred + // screen-inter desync. + let cases: [(usize, usize, usize, &str, u32, bool, bool); 6] = [ + (256, 128, 8, "4", 8, false, false), + (192, 96, 6, "3", 10, false, false), + (320, 192, 6, "3", 8, false, false), + (256, 256, 4, "2", 8, true, false), + (320, 192, 2, "1", 8, false, true), + (640, 384, 2, "1", 8, false, true), + ]; + for &(w, h, frames, gop, depth, sb128, screen) in &cases { + let tag = format!( + "{w}x{h} {depth}-bit gop {gop}{}{}", + if sb128 { " sb128" } else { "" }, + if screen { " screen" } else { "" } + ); + let mut raw: Vec = Vec::new(); + let put = |v: u32, raw: &mut Vec| { + if depth == 10 { + raw.extend_from_slice(&((v * 4) as u16).to_le_bytes()); + } else { + raw.push(v as u8); + } + }; + // A screen source is a few flat colours in 16x16 tiles plus + // 1-px text-like rows -- what makes libaom code palette blocks. + const PAL: [u32; 8] = [16, 60, 110, 145, 180, 210, 235, 128]; + for f in 0..frames { + for row in 0..h { + for col in 0..w { + let v = if screen { + if row % 7 == 0 && col % 3 == 0 { + if (col / 3 + row + f) % 2 == 1 { 16 } else { 235 } + } else { + PAL[((col + 4 * f) / 16 + row / 16) % PAL.len()] + } + } else { + (((col + 2 * f) * 7 + row * 13) % 251) as u32 + }; + put(v, &mut raw); + } + } + for plane in 0..2usize { + for row in 0..h / 2 { + for col in 0..w / 2 { + let v = if screen { + PAL[((col + 2 * f) / 8 + row / 8 + plane) % PAL.len()] + } else if plane == 0 { + (((col + f) * 11 + row * 5) % 251) as u32 + } else { + ((col * 3 + (row + f) * 17) % 251) as u32 + }; + put(v, &mut raw); + } + } + } + } + let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" }; + // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. + let src = std::env::temp_dir() + .join(format!("ec-av1-lossless2-{}-{w}x{h}-{depth}.yuv", std::process::id())); + std::fs::write(&src, &raw).expect("raw source"); + let mut cmd = Command::new("ffmpeg"); + cmd.args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", pix]) + .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) + .arg(&src) + .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"]) + .args(["-pix_fmt", pix, "-cpu-used", "6", "-b:v", "0", "-crf", "0"]); + if sb128 { + cmd.args(["-aom-params", "sb-size=128"]); + } + if screen { + cmd.args(["-aom-params", "tune-content=screen"]); + } + let out = cmd + .args(["-f", "obu", "-"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + let _ = std::fs::remove_file(&src); + if !out.status.success() { + eprintln!( + "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})", + String::from_utf8_lossy(&out.stderr) + ); + return; + } + let stream = out.stdout; + // The stream must really be lossless AND really carry inter frames + // (class `gate-blind-to-feature`). + let mut parser = Av1Parser::new(); + let (mut pos, mut lossless, mut inters) = (0usize, 0usize, 0usize); + while pos < stream.len() { + let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses"); + pos += obu.total_size.max(1); + let header = match &obu.kind { + ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h, + _ => continue, + }; + if header.lossless.iter().all(|&l| l) { + lossless += 1; + } + if header.frame_type == FrameType::Inter { + inters += 1; + } + } + assert!(lossless >= frames, "{NAME} [{tag}] went blind: {lossless} lossless frames"); + assert!( + screen || inters > 0, + "{NAME} [{tag}] went blind: no inter frame at gop {gop}" + ); + let ours = decode_stream(&stream) + .unwrap_or_else(|e| panic!("{NAME} [{tag}]: a lossless inter stream decodes: {e}")); + let refs = if depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, w, h, frames) + } else { + ffmpeg_decode_sequence(&stream, w, h, frames) + }; + assert_eq!(ours.len(), frames, "{NAME} [{tag}]: frame count"); + for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() { + for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)] + .iter() + .enumerate() + { + let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count(); + assert_eq!(bad, 0, "{NAME} [{tag}]: frame {i} plane {plane}: {bad} samples differ"); } } - raw.extend(std::iter::repeat_n(128u8, w * h / 2)); - } - let src = std::env::temp_dir().join(format!("ec-av1-lossless-i-{}.yuv", std::process::id())); - std::fs::write(&src, &raw).expect("raw source"); - let out = Command::new("ffmpeg") - .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) - .arg(&src) - .args(["-an", "-threads", "1", "-g", "4", "-c:v", "libaom-av1"]) - .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .expect("ffmpeg failed to run"); - let _ = std::fs::remove_file(&src); - if !out.status.success() { - eprintln!("SKIP {NAME}: ffmpeg has no libaom-av1 encoder"); - return; - } - match decode_stream(&out.stdout) { - Ok(_) => panic!("{NAME}: a lossless inter stream decoded instead of being refused"), - Err(e) => assert!( - format!("{e}").contains("a lossless INTER frame"), - "{NAME}: refused for the wrong reason: {e}" - ), } } diff --git a/lanes/lossless2.report.md b/lanes/lossless2.report.md new file mode 100644 index 00000000..baf3dcd7 --- /dev/null +++ b/lanes/lossless2.report.md @@ -0,0 +1,81 @@ +# lane-lossless2 — AV1 lossless INTER decode + +Branch `lane-lossless2`, base `99823eef`. Head `f4c75f48`. + +The refusal `"a lossless INTER frame (its chroma plane is still coded as one +transform per block here)"` is gone from `stream.rs` and from +`refusal_inventory.rs` (both the list and the refusal->gate table); its gate +`a_lossless_inter_frame_is_refused_by_name` is retired and replaced by the +decode-exact gate below (class `refusal-lifted-without-a-gate`). + +## Rules ported (each with its libaom reference) +| rule | libaom | where | +|---|---|---| +| chroma of an INTER block is a raster of TX_4X4 units | `read_tx_size` (`av1/decoder/decodeframe.c`): `if (xd->lossless[..]) return TX_4X4;` for every plane | `decode::read_inter_chroma_lossless`, called from the whole-block chroma site and the 128 mu-chunk site of BOTH `decode_inter_block` arms (compound + single ref) | +| same for an INTRA block inside an inter frame | same | `decode::read_intra_chroma_lossless`, called from the intra tail's whole-block and mu-chunk chroma sites | +| unit order is PLANE-MAJOR inside each 64x64 mu chunk | `decode_token_recon_block`: `for (row..) for (col..) for (plane..) for (blk_row..) for (blk_col..)` | both helpers; `decode_block`'s multi-unit chroma loop was interleaved U,V per unit and is now plane-major (identical symbol order at one unit per plane per chunk, i.e. every non-lossless case) | +| `txb_skip` chroma context offset | `get_txb_ctx` (`av1/common/txb_common.h`): `ctx_offset = num_pels(plane_bsize) > num_pels(tx) ? 10 : 7`; our chroma tables carry the offset-10 rows at `+3` | `offset = (blk_w > 4 \|\| blk_h > 4).then_some(3)` in both helpers | +| per-unit entropy context, stamped as the unit is read | `av1_set_entropy_contexts` per transform block | `record_mi_chroma(cu_mi, 8, 8, plane, grid)` per unit; the block-level re-stamp is suppressed (`mu_chroma`) and `mu_chroma_units` now rebuilds 4x4 units with an 8 px span on a lossless frame | +| an 8x4/4x8 inter leaf is TWO 4x4 units | `read_block_tx_size`'s lossless early return | `decode_inter_sub8_rect2` leaf list | +| no `tx_type` symbol, DCT_DCT, WHT, TX_4X4 luma | (lane-lossless) | unchanged | +| deblock/CDEF/LR off | `coded_lossless`/`all_lossless` in the frame header parser | verified unchanged: `read_cdef_params` forces `bits = 0`, the lf levels and LR are header-gated; no decoder-side change was needed | +| a frame mixing lossless and lossy SEGMENTS | every rule above is per segment (`xd->lossless[segment_id]`) | still refused by name — see Deferred | + +## Defects this lane found (all invisible to the previous lane's gate) +The lane-lossless gate's source had a FLAT chroma plane: every chroma unit +coded one `txb_skip` symbol against all-zero contexts, so the gate was blind +to unit order and to per-unit contexts (class `gate-blind-to-feature`). With +textured chroma the KEY gate fails at `99823eef`. Three root causes: + +1. `decode_block` read chroma units interleaved U,V; libaom is plane-major. +2. `decode_rect_split`'s lossless chroma branch stamped each unit's context + and then let `record_split_luma_rect_mi` overwrite all of them with the + LAST unit's state — the next block read `dc_sign_ctx` 1 where libaom reads + 0 (class `override-slot-on-one-arm`). Localised with the aomdec oracle: + `EC_TRACE_COEFF` on both sides, first divergence at chroma unit 717 of a + 256x128 `-crf 0` key frame, `dcctx=1` vs `dcctx=0`. +3. `decode_inter_sub8_rect2` kept ONE 8x4/4x8 luma transform on a lossless + frame, feeding a rect grid to the 4x4 Walsh-Hadamard (panic, not garbage). + +Our `EC_COEFF_STEP tag=all_zero` trace now prints `dcctx=` so it lines up with +aomdec's field. + +## Fixtures and results +`ffmpeg -c:v libaom-av1 -crf 0 -b:v 0 -cpu-used 6`, synthetic source with +TEXTURED luma AND chroma and per-frame motion. + +| fixture | gate | result | +|---|---|---| +| 256x128, 2 key frames, 8-bit | `a_lossless_libaom_key_frame_decodes_sample_exact` (source now textured chroma) | EXACT | +| 256x128, 8 frames `-g 4`, 8-bit | `a_lossless_libaom_inter_frame_decodes_sample_exact` | EXACT | +| 192x96, 6 frames `-g 3`, 10-bit | same gate | EXACT | +| 320x192, 6 frames `-g 3`, 8-bit | same gate | EXACT | +| 256x256, 4 frames `-g 2`, `-aom-params sb-size=128` | same gate | EXACT | +| 320x192, 2 key frames, `tune-content=screen` (palette) | same gate | EXACT | +| 640x384, 2 key frames, `tune-content=screen` (palette) | same gate | EXACT | + +## Screen content (palette) — three more defects, found by a `tune-content=screen` stream +| defect | libaom | fix | +|---|---|---| +| a 4x4 chroma unit got the WHOLE-BLOCK palette prediction buffer and read it at its own stride, so every unit reconstructed the block's top-left corner | the luma split-transform paths already windowed; `predict_and_reconstruct_intra_block` predicts per unit | `decode::palette_window`, shared by `decode_block`, `decode_rect_split` and `read_intra_chroma_lossless`. 320x192 screen key frame: 9600/15360 chroma samples wrong -> 0 | +| the two-cell neighbour read ran past the band for a unit whose block hangs off the frame edge (libaom still codes that unit: `max_blocks_high` clips in LUMA mi and then ROUNDS UP for chroma) | `get_txb_ctx` reads exactly ONE chroma entropy entry for TX_4X4 (`a[0]`/`l[0]`) | both helpers read one cell (`around_mi(cu_mi, MI)`) -- our bands carry that entry replicated over the unit's two luma-mi cells, so it is the same answer and never runs off | +| a unit whose ORIGIN is past the frame edge was still read | `max_blocks_wide/high` | origin clip in both helpers | + +`tune-content=screen -crf 0` KEY frames at 320x192 and 640x384: sample-exact +(`dump_yuv` vs `ffmpeg -pix_fmt yuv420p10le`, 0/122880 and 0/368640). + +## Gate results +- `a_lossless_libaom_key_frame_decodes_sample_exact` + `a_lossless_libaom_inter_frame_decodes_sample_exact`: PASS (2 passed). +- `cargo check --workspace --all-targets -j4`: RC=0, 0 errors, 0 ec-av1 warnings (the 21 warnings are pre-existing `ec-opus`). +- crate suite `cargo test -p ec-av1 --release --lib -- --test-threads=1`: **557 passed / 0 failed / 44 ignored** (959.9 s), pins green (`the_encoders_own_streams_are_byte_identical_to_their_pins`). That run predates the two screen KEY rows added to the inter gate afterwards; those two were run on their own (2 passed). +- The screen rows really do code palette: the same recipe at 320x192 decoded 9600/15360 chroma samples wrong before `palette_window` and 0 after. +- DECIDING GATE `bd_rate_screen_native`: **RED**, one reference point: + `LADDER DECODE FAILURE: libaom-av1 ["-cpu-used","6","-b:v","0","-crf","5"] frame 0 plane Y sample 625: our decoder decoded 41, ffmpeg 40`. + That point used to be refused; it now decodes, and frame 0 (a KEY frame) is + wrong in ONE luma sample at (col 625, row 0) of 1920x1024. The BD row itself + computed: +33.4% vs libaom, -23.8% vs rav1e. + +## Deferred +- `deferred: the bd_rate_screen_native crf-5 screen point — ONE luma sample (625, row 0) of frame 0, a lossless KEY frame, decodes 41 where ffmpeg decodes 40; every other sample of every other point is exact. Not reproduced by a synthetic 1920x1024 tune-content=screen -crf 5 key frame (0 samples differ), so it needs the gate's own stream — unblocks: dump the ladder stream (EC_ENC_OUT / the external_ladder recipe) and diff EC_TRACE_COEFF against aomdec around that block.` +- `deferred: lossless INTER frames of SCREEN content desync — reproduced at 640x384 tune-content=screen -crf 0 -g 3: key frames 0 and 3 are sample-exact, inter frames 1/2/4/5 are not. Localised with the aomdec oracle to all_zero unit #23422 of the stream: the first LUMA unit of a block right after a sub-8x8 group reads txb_skip_ctx 3 where libaom reads 1 (one neighbour magnitude > 3 where libaom sees 0) — unblocks: that one block's above-band luma level; the synthetic non-screen inter fixtures in the gate are all exact, so it is screen/sub-8x8 specific.` +- `deferred: a frame mixing lossless and lossy segments — still refused by name ("a frame mixing lossless and lossy segments (the TX_4X4/WHT rules are per segment there)"): every rule above keys off a frame-wide `lossless_flag`, so per-segment support means threading `segment_id` through `lossless()`, `lossless_tx()`, the WHT switch and the filter gates — unblocks: a libaom recipe that emits one. Four tried this round at -crf 0 (aom-params aq-mode=1, aq-mode=2, aq-mode=3, deltaq-mode=1): none produced a frame whose segments disagree — the refusal never fired, i.e. every segment stayed at qindex 0.`