forge
Explore
Log in

Don't you dare go Hollow

Palette on the intra blocks of inter frames too

Browse files at this commit

17922e66d975f99d06b50b2e240518f19836f4f0Ahmet Kaan GümüşParent: 8fb4a27
  • feat
    • palette on the intra blocks of inter frames too
Show full message
feat(av1): palette on the intra blocks of inter frames too

The three intra arms of the inter-frame writers (32/16/8) now code the same
spec 5.11.46 syntax the key frame's does, through one shared
`write_palette_syntax`; the neighbour bands are published from
`record_mi_planes` -- the single point EVERY block of either frame type
passes through -- so an inter block clears what an earlier palette block left
in its column instead of desyncing the next context (the hazard lane-t900 r23
hit on the decoder side).

The inter frame sets `allow_screen_content_tools` from its own detection,
gated on the sequence having offered the bit at all (the key frame's
decision); `decode_inter_frame_tile_lr` takes the flag rather than assuming
false, and `Encoded::screen` carries it to every raw-tile decode.

The leaf (16/8) intra candidates get the palette RD for free -- they route
through `code_square`. The 32x32 inter search's own intra loop does NOT yet
offer one (corner-cut: its candidates are hand-rolled beside the inter ones).

Check: a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly
now codes a 4-frame GOP as well -- 3 inter frames set the bit, 56 palette
blocks, ffmpeg reconstructs all four frames exactly in all three planes.
crates/ec-av1/src/decode.rsmodified+14 -2
@@ -32897,7 +32897,7 @@ pub(crate) fn decode_inter_frame_tile(
32897 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef,32897 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef,
32898 loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,32898 loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,
32899 enable_dual_filter, reference_select, tx_select,32899 enable_dual_filter, reference_select, tx_select,
32900- &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, fctx,32900+ &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false, fctx,
32901 )32901 )
32902 }32902 }
32903 32903
@@ -32932,6 +32932,12 @@ pub(crate) fn decode_inter_frame_tile_lr(
32932 // as `tx_select`/`initial_cdfs` above: a header-derived value a raw tile32932 // as `tx_select`/`initial_cdfs` above: a header-derived value a raw tile
32933 // decode has to be told.32933 // decode has to be told.
32934 sign_bias: crate::mvstack::SignBiasTable,32934 sign_bias: crate::mvstack::SignBiasTable,
32935+ // This frame header's own `allow_screen_content_tools`: its intra blocks
32936+ // then carry the palette syntax (spec 5.11.46), which a raw tile decode
32937+ // that guessed `false` reads one symbol short of. Placed after
32938+ // `sign_bias` rather than beside the other bools on purpose (the
32939+ // `adjacent-same-typed-args` class).
32940+ allow_screen_content_tools: bool,
32935 fctx: &crate::decode::FrameCtx,32941 fctx: &crate::decode::FrameCtx,
32936 ) -> Result<Picture> {32942 ) -> Result<Picture> {
32937 let single_tile = TileInfo {32943 let single_tile = TileInfo {
@@ -32973,7 +32979,7 @@ pub(crate) fn decode_inter_frame_tile_lr(
32973 tx_select,32979 tx_select,
32974 false,32980 false,
32975 false,32981 false,
32976- false,32982+ allow_screen_content_tools,
32977 DeltaParams::default(),32983 DeltaParams::default(),
32978 // `enable_filter_intra`: this crate's own encoder never writes the32984 // `enable_filter_intra`: this crate's own encoder never writes the
32979 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream32985 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream
@@ -37517,6 +37523,9 @@ mod tests {
37517 &frame.loop_restoration,37523 &frame.loop_restoration,
37518 Some(frame.start_cdfs.0.clone()),37524 Some(frame.start_cdfs.0.clone()),
37519 NO_SIGN_BIAS,37525 NO_SIGN_BIAS,
37526+ // This frame's own `allow_screen_content_tools`, off the
37527+ // `Encoded` the encoder handed back (stale-header class).
37528+ frame.screen,
37520 fctx,37529 fctx,
37521 )37530 )
37522 .unwrap();37531 .unwrap();
@@ -37841,6 +37850,9 @@ mod tests {
37841 &frame.loop_restoration,37850 &frame.loop_restoration,
37842 Some(frame.start_cdfs.0.clone()),37851 Some(frame.start_cdfs.0.clone()),
37843 NO_SIGN_BIAS,37852 NO_SIGN_BIAS,
37853+ // This frame's own `allow_screen_content_tools`, off the
37854+ // `Encoded` the encoder handed back (stale-header class).
37855+ frame.screen,
37844 fctx,37856 fctx,
37845 )37857 )
37846 .unwrap();37858 .unwrap();
crates/ec-av1/src/encode.rsmodified+61 -6
@@ -5011,6 +5011,14 @@ pub(crate) fn encode_inter_frame(
5011 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();5011 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
5012 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();5012 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
5013 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();5013 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
5014+ // This frame's own `allow_screen_content_tools`. It can only be set when
5015+ // the SEQUENCE offers the bit at all, which is the key frame's decision
5016+ // ([`SEQ_SCREEN`]): a frame header that contradicts
5017+ // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
5018+ // encode.
5019+ let screen = seq_screen()
5020+ && screen_content(&picture_y8, picture.width, true_width, true_height);
5021+ header.allow_screen_content_tools = screen;
5014 let mut luma = Plane {5022 let mut luma = Plane {
5015 source: &picture_y8,5023 source: &picture_y8,
5016 reconstruction: vec![128; picture_y8.len()],5024 reconstruction: vec![128; picture_y8.len()],
@@ -5045,9 +5053,7 @@ pub(crate) fn encode_inter_frame(
5045 lambda: lambda_scale() * step * step,5053 lambda: lambda_scale() * step * step,
5046 modes: &KEY_FRAME_MODES,5054 modes: &KEY_FRAME_MODES,
5047 top_k: prune_top_k_inter(),5055 top_k: prune_top_k_inter(),
5048- // An inter frame never sets `allow_screen_content_tools` yet, so its5056+ screen,
5049- // intra blocks code no palette syntax (deferred, see the lane report).
5050- screen: false,
5051 };5057 };
5052 let mode_bits_table = inter_mode_bits();5058 let mode_bits_table = inter_mode_bits();
5053 5059
@@ -5503,6 +5509,7 @@ pub(crate) fn encode_inter_frame(
5503 crate::tile::arm_sign_bias(sign_bias);5509 crate::tile::arm_sign_bias(sign_bias);
5504 crate::tile::arm_reference_select(header.reference_select);5510 crate::tile::arm_reference_select(header.reference_select);
5505 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);5511 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
5512+ crate::tile::arm_screen(screen);
5506 let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(5513 let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5507 mi_cols,5514 mi_cols,
5508 mi_rows,5515 mi_rows,
@@ -5595,6 +5602,7 @@ pub(crate) fn encode_inter_frame(
5595 crate::tile::arm_sign_bias(sign_bias);5602 crate::tile::arm_sign_bias(sign_bias);
5596 crate::tile::arm_reference_select(reference_select());5603 crate::tile::arm_reference_select(reference_select());
5597 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);5604 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
5605+ crate::tile::arm_screen(screen);
5598 let mut cdfs = start_cdfs.0.clone();5606 let mut cdfs = start_cdfs.0.clone();
5599 let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(5607 let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5600 mi_cols,5608 mi_cols,
@@ -5632,6 +5640,7 @@ pub(crate) fn encode_inter_frame(
5632 // frame's `start_cdfs`), not from the defaults.5640 // frame's `start_cdfs`), not from the defaults.
5633 Some(start_cdfs.0.clone()),5641 Some(start_cdfs.0.clone()),
5634 sign_bias,5642 sign_bias,
5643+ h.allow_screen_content_tools,
5635 fctx,5644 fctx,
5636 )5645 )
5637 },5646 },
@@ -5659,9 +5668,7 @@ pub(crate) fn encode_inter_frame(
5659 mi_rows: header.mi_rows,5668 mi_rows: header.mi_rows,
5660 base_q_idx,5669 base_q_idx,
5661 tx_select,5670 tx_select,
5662- // An inter frame of this encoder never sets the bit (its intra blocks5671+ screen,
5663- // code no palette syntax yet -- see the lane report's deferred item).
5664- screen: false,
5665 start_cdfs,5672 start_cdfs,
5666 next_cdfs,5673 next_cdfs,
5667 loop_filter: header.loop_filter,5674 loop_filter: header.loop_filter,
@@ -6190,6 +6197,54 @@ mod tests {
6190 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");6197 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
6191 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");6198 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
6192 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");6199 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
6200+ // A whole GOP: the inter frames' own intra blocks carry the palette
6201+ // syntax too (the three intra arms of the inter writers), which only
6202+ // ffmpeg reading the frames back can prove.
6203+ let moved: Vec<Picture> = (0..4)
6204+ .map(|f| {
6205+ let base = screen_card(width, height);
6206+ let mut out = Picture::grey(width, height);
6207+ for y in 0..height {
6208+ for x in 0..width {
6209+ let sx = (x + f * 7) % width;
6210+ out.y[y * width + x] = base.y[y * width + sx];
6211+ }
6212+ }
6213+ for y in 0..height / 2 {
6214+ for x in 0..width / 2 {
6215+ let sx = (x + f * 3) % (width / 2);
6216+ out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
6217+ out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
6218+ }
6219+ }
6220+ out
6221+ })
6222+ .collect();
6223+ let _ = crate::tile::take_palette_hits();
6224+ let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
6225+ let gop_hits = crate::tile::take_palette_hits();
6226+ let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
6227+ eprintln!(
6228+ "GOP: {} frames with screen tools after the key frame, {} palette blocks",
6229+ inter_screen, gop_hits[0]
6230+ );
6231+ assert!(
6232+ inter_screen > 0,
6233+ "no inter frame set allow_screen_content_tools"
6234+ );
6235+ let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
6236+ for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
6237+ assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
6238+ }
6239+ if have_ffmpeg() {
6240+ let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
6241+ for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
6242+ assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
6243+ assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
6244+ assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
6245+ }
6246+ }
6247+
6193 // The other half of the keep rule: film-shaped content leaves the6248 // The other half of the keep rule: film-shaped content leaves the
6194 // detector (and so the whole sequence header) alone.6249 // detector (and so the whole sequence header) alone.
6195 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();6250 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
crates/ec-av1/src/tile.rsmodified+95 -39
@@ -1235,6 +1235,13 @@ struct Neighbours {
1235 above_palette_size: Vec<u8>,1235 above_palette_size: Vec<u8>,
1236 /// The same, down the left edge.1236 /// The same, down the left edge.
1237 left_palette_size: Vec<u8>,1237 left_palette_size: Vec<u8>,
1238+ /// What the block being written right now will leave in the two palette
1239+ /// bands, published by [`Self::record_mi_planes`] -- the one point EVERY
1240+ /// block of either frame type passes through, so an inter block (or an
1241+ /// intra block that took no palette) clears the bands rather than letting
1242+ /// an earlier palette block's size stand (the neighbour-band hazard
1243+ /// lane-t900 r23 hit on the decoder side).
1244+ pending_palette: Option<(u8, [u16; 8])>,
1238 /// The colours beside [`Self::above_palette_size`].1245 /// The colours beside [`Self::above_palette_size`].
1239 above_palette_colors: Vec<[u16; 8]>,1246 above_palette_colors: Vec<[u16; 8]>,
1240 /// The same, down the left edge.1247 /// The same, down the left edge.
@@ -1324,6 +1331,7 @@ impl Neighbours {
1324 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],1331 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
1325 above_palette_size: vec![0; cols * (SUB / MI)],1332 above_palette_size: vec![0; cols * (SUB / MI)],
1326 left_palette_size: vec![0; rows * (SUB / MI)],1333 left_palette_size: vec![0; rows * (SUB / MI)],
1334+ pending_palette: None,
1327 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],1335 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],
1328 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],1336 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
1329 mi_cols,1337 mi_cols,
@@ -1568,6 +1576,10 @@ impl Neighbours {
1568 luma: bool,1576 luma: bool,
1569 ) {1577 ) {
1570 let (mi_r, mi_c) = at_mi;1578 let (mi_r, mi_c) = at_mi;
1579+ if screen_armed() {
1580+ let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
1581+ self.record_palette_y(at_mi, side, size, colors);
1582+ }
1571 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));1583 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
1572 let side_mi = side / MI;1584 let side_mi = side / MI;
1573 for cell in 0..side_mi {1585 for cell in 0..side_mi {
@@ -2424,47 +2436,61 @@ fn write_intra_mode(
2424 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer2436 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
2425 // codes none -- exactly the ctx-0 read the decoder does under the same2437 // codes none -- exactly the ctx-0 read the decoder does under the same
2426 // condition.2438 // condition.
2427- if screen_armed() {2439+ write_palette_syntax(enc, cdfs, neighbours, block.palette.as_ref(), mode, uv_mode, mi, side);
2428- let palette = block.palette.as_ref().filter(|_| mode == DC_PRED);2440+ mode
2429- if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {2441+}
2430- let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);2442+
2431- if mode == DC_PRED {2443+/// `read_palette_mode_info` (spec 5.11.46) written out, mirrored symbol for
2432- enc.symbol(2444+/// symbol from the decoder's own read in `read_intra_mode`: on a frame whose
2433- usize::from(palette.is_some()),2445+/// header set `allow_screen_content_tools`, a `DC_PRED` luma block and a
2434- &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx],2446+/// `UV_DC_PRED` chroma pair each carry a use-palette flag, and a luma palette
2435- );2447+/// then codes its size, its colours (against the neighbour colour cache) and
2436- }2448+/// -- after the chroma flag, exactly where libaom's `av1_visit_palette` runs
2437- if let Some(pal) = palette {2449+/// -- its colour-index map. Shared by the key frame's [`write_intra_mode`] and
2438- let n = usize::from(pal.size);2450+/// by the three intra arms of the inter-frame writers, which read the same
2439- enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]);2451+/// syntax back through `decode_inter_block`/`decode_intra_rect_in_inter`.
2440- write_palette_colors_y(enc, &pal.colors[..n], &cache);2452+///
2441- }2453+/// The band publication is deferred to [`Neighbours::record_mi_planes`] (the
2442- // `read_palette_mode_info`'s UV half sits between the luma2454+/// one point every block passes through), so a block that takes no palette
2443- // colours and the luma colour-index map: libaom defers both maps2455+/// still clears what the column held.
2444- // to `av1_visit_palette`, after the whole mode info.2456+#[allow(clippy::too_many_arguments)]
2445- if uv_mode == DC_PRED {2457+fn write_palette_syntax(
2446- enc.symbol(0, &mut cdfs.palette_uv_mode[usize::from(palette.is_some())]);2458+ enc: &mut SymbolEncoder,
2447- }2459+ cdfs: &mut Cdfs,
2448- if let Some(pal) = palette {2460+ neighbours: &mut Neighbours,
2449- let n = usize::from(pal.size);2461+ palette: Option<&PaletteY>,
2450- write_color_index_map(2462+ mode: usize,
2451- enc,2463+ uv_mode: usize,
2452- &mut cdfs.palette_y_color_index[n - 2],2464+ mi: (usize, usize),
2453- &pal.map,2465+ side: usize,
2454- side,2466+) {
2455- n,2467+ if !screen_armed() {
2456- );2468+ return;
2457- note_palette(n);2469+ }
2458- }2470+ let palette = palette.filter(|_| mode == DC_PRED);
2471+ if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
2472+ let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
2473+ if mode == DC_PRED {
2474+ enc.symbol(
2475+ usize::from(palette.is_some()),
2476+ &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx],
2477+ );
2478+ }
2479+ if let Some(pal) = palette {
2480+ let n = usize::from(pal.size);
2481+ enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]);
2482+ write_palette_colors_y(enc, &pal.colors[..n], &cache);
2483+ }
2484+ if uv_mode == DC_PRED {
2485+ enc.symbol(0, &mut cdfs.palette_uv_mode[usize::from(palette.is_some())]);
2486+ }
2487+ if let Some(pal) = palette {
2488+ let n = usize::from(pal.size);
2489+ write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n);
2490+ note_palette(n);
2459 }2491 }
2460- // Every block of a screen-content frame publishes its (possibly zero)
2461- // palette state, or a neighbour column keeps an earlier block's size
2462- // and reads a context the decoder does not.
2463- let (size, colors) =
2464- palette.map_or((0, [0u16; 8]), |p| (p.size, p.colors));
2465- neighbours.record_palette_y(mi, side, size, colors);
2466 }2492 }
2467- mode2493+ neighbours.pending_palette = palette.map(|p| (p.size, p.colors));
2468 }2494 }
2469 2495
2470 /// How many blocks took a palette, and of what size -- the fire count a gate2496 /// How many blocks took a palette, and of what size -- the fire count a gate
@@ -4368,6 +4394,16 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
4368 // Intra: no vote, but still a coded cell -- mvstack's4394 // Intra: no vote, but still a coded cell -- mvstack's
4369 // extended-scan coverage must see it (module doc).4395 // extended-scan coverage must see it (module doc).
4370 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);4396 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
4397+ write_palette_syntax(
4398+ &mut enc,
4399+ &mut cdfs,
4400+ &mut neighbours,
4401+ block.palette.as_ref(),
4402+ mode,
4403+ uv_mode,
4404+ (mi_row, mi_col),
4405+ BLOCK,
4406+ );
4371 for dr in 0..8 {4407 for dr in 0..8 {
4372 for dc in 0..8 {4408 for dc in 0..8 {
4373 grid.set(4409 grid.set(
@@ -4581,6 +4617,16 @@ fn write_inter_frame_leaf(
4581 // Intra: no vote, but still a coded cell -- mvstack's extended-scan4617 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
4582 // coverage must see it (module doc).4618 // coverage must see it (module doc).
4583 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);4619 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
4620+ write_palette_syntax(
4621+ enc,
4622+ cdfs,
4623+ neighbours,
4624+ block.palette.as_ref(),
4625+ mode,
4626+ uv_mode,
4627+ (mi_row, mi_col),
4628+ SUB,
4629+ );
4584 for dr in 0..SUB_MI as usize {4630 for dr in 0..SUB_MI as usize {
4585 for dc in 0..SUB_MI as usize {4631 for dc in 0..SUB_MI as usize {
4586 grid.set(4632 grid.set(
@@ -4800,6 +4846,16 @@ fn write_inter_frame_leaf8(
4800 // Intra: no vote, but still a coded cell -- mvstack's extended-scan4846 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
4801 // coverage must see it (module doc).4847 // coverage must see it (module doc).
4802 let (mi_row, mi_col) = leaf_mi;4848 let (mi_row, mi_col) = leaf_mi;
4849+ write_palette_syntax(
4850+ enc,
4851+ cdfs,
4852+ neighbours,
4853+ block.palette.as_ref(),
4854+ mode,
4855+ uv_mode,
4856+ leaf_mi,
4857+ 8,
4858+ );
4803 for dr in 0..2 {4859 for dr in 0..2 {
4804 for dc in 0..2 {4860 for dc in 0..2 {
4805 grid.set(4861 grid.set(