Merge branch 'lane-av1pal2' (be1937b0): chroma palette and a 128-colour palette bound
Browse files at this commit2 changed files +417 -11
- crates/ec-av1/src/encode.rs +137 -9
- crates/ec-av1/src/tile.rs +280 -2
crates/ec-av1/src/encode.rsmodified+137 -9
| @@ -2338,6 +2338,15 @@ fn commit_inter_luma( | ||
| 2338 | 2338 | /// The largest distinct-colour count a block may hold and still be offered a |
| 2339 | 2339 | /// palette candidate at all: past it the k-means quantisation costs more |
| 2340 | 2340 | /// error than the map saves rate, and every trial is wasted wall. |
| 2341 | +/// | |
| 2342 | +/// Swept on the gate's own screen capture (lane-av1pal2, the | |
| 2343 | +/// `unswept-decision-constants` class): 32 (the value this lane inherited) | |
| 2344 | +/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64 | |
| 2345 | +/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores | |
| 2346 | +/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound | |
| 2347 | +/// binds on nothing this content holds. 128 ships: best BD against both | |
| 2348 | +/// references and no wall cost at all (6.1s, the same as at 32, because the | |
| 2349 | +/// blocks it newly admits are ones the RD then keeps). | |
| 2341 | 2350 | /// `EC_AV1_PAL_MAXCOLORS`. |
| 2342 | 2351 | fn palette_max_colors() -> usize { |
| 2343 | 2352 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| @@ -2345,7 +2354,7 @@ fn palette_max_colors() -> usize { | ||
| 2345 | 2354 | std::env::var("EC_AV1_PAL_MAXCOLORS") |
| 2346 | 2355 | .ok() |
| 2347 | 2356 | .and_then(|v| v.parse().ok()) |
| 2348 | - .unwrap_or(32) | |
| 2357 | + .unwrap_or(128) | |
| 2349 | 2358 | }) |
| 2350 | 2359 | } |
| 2351 | 2360 | |
| @@ -2546,7 +2555,7 @@ fn code_square( | ||
| 2546 | 2555 | |
| 2547 | 2556 | // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both |
| 2548 | 2557 | // planes; what it costs still counts towards the partition decision. |
| 2549 | - let ([u, v], uv_mode, chroma_cost) = | |
| 2558 | + let ([u, v], uv_mode, chroma_cost, palette_uv) = | |
| 2550 | 2559 | search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx); |
| 2551 | 2560 | cost += chroma_cost; |
| 2552 | 2561 | ( |
| @@ -2558,6 +2567,7 @@ fn code_square( | ||
| 2558 | 2567 | uv_mode, |
| 2559 | 2568 | tx_depth, |
| 2560 | 2569 | palette, |
| 2570 | + palette_uv, | |
| 2561 | 2571 | ..BlockCoeffs::default() |
| 2562 | 2572 | }, |
| 2563 | 2573 | cost, |
| @@ -2647,7 +2657,7 @@ fn search_chroma( | ||
| 2647 | 2657 | search: &Search, |
| 2648 | 2658 | luma_mode: u8, |
| 2649 | 2659 | fctx: &crate::decode::FrameCtx, |
| 2650 | -) -> ([Vec<Coeff>; 2], u8, f64) { | |
| 2660 | +) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) { | |
| 2651 | 2661 | let at = At { |
| 2652 | 2662 | x: x / 2, |
| 2653 | 2663 | y: y / 2, |
| @@ -2695,7 +2705,79 @@ fn search_chroma( | ||
| 2695 | 2705 | best = Some((cost, mode, u, v)); |
| 2696 | 2706 | } |
| 2697 | 2707 | } |
| 2698 | - let (cost, mode, u, v) = best.expect("CHROMA_MODES is not empty"); | |
| 2708 | + let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty"); | |
| 2709 | + // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over | |
| 2710 | + // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is | |
| 2711 | + // what keeps `u_colors` ascending and distinct the way | |
| 2712 | + // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as | |
| 2713 | + // each cluster's own mean, since the colour-index map is SHARED by the | |
| 2714 | + // two planes. Priced against the best ordinary chroma mode above, so a | |
| 2715 | + // block only takes one when it beats it; a palette block's chroma mode is | |
| 2716 | + // `UV_DC_PRED` by construction. | |
| 2717 | + let mut palette_uv = None; | |
| 2718 | + if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { | |
| 2719 | + debug_assert_eq!(crate::tile::palette_uv_side(side), at.side); | |
| 2720 | + let plane_source = |p: &Plane| -> Vec<u8> { | |
| 2721 | + (at.y..at.y + at.side) | |
| 2722 | + .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec()) | |
| 2723 | + .collect() | |
| 2724 | + }; | |
| 2725 | + let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1])); | |
| 2726 | + for pal in palette_candidates(&u_source) { | |
| 2727 | + let n = usize::from(pal.size); | |
| 2728 | + // V's base colour per cluster: the mean of the samples the shared | |
| 2729 | + // map assigns to it (an empty cluster cannot happen -- every | |
| 2730 | + // colour `palette_candidates` returns is some pixel's nearest). | |
| 2731 | + let mut sums = [0u32; 8]; | |
| 2732 | + let mut counts = [0u32; 8]; | |
| 2733 | + for (&i, &sample) in pal.map.iter().zip(v_source.iter()) { | |
| 2734 | + let k = usize::from(i).min(n - 1); | |
| 2735 | + sums[k] += u32::from(sample); | |
| 2736 | + counts[k] += 1; | |
| 2737 | + } | |
| 2738 | + let mut v_colors = [0u16; 8]; | |
| 2739 | + for k in 0..n { | |
| 2740 | + v_colors[k] = if counts[k] > 0 { | |
| 2741 | + ((sums[k] + counts[k] / 2) / counts[k]) as u16 | |
| 2742 | + } else { | |
| 2743 | + 0 | |
| 2744 | + }; | |
| 2745 | + } | |
| 2746 | + let candidate = crate::tile::PaletteUv { | |
| 2747 | + size: pal.size, | |
| 2748 | + u_colors: pal.colors, | |
| 2749 | + v_colors, | |
| 2750 | + map: pal.map, | |
| 2751 | + }; | |
| 2752 | + let predict = |colors: &[u16; 8]| -> Vec<u8> { | |
| 2753 | + candidate | |
| 2754 | + .map | |
| 2755 | + .iter() | |
| 2756 | + .map(|&i| colors[usize::from(i).min(n - 1)] as u8) | |
| 2757 | + .collect() | |
| 2758 | + }; | |
| 2759 | + let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors)); | |
| 2760 | + let u_trial = chroma[0].code_from_prediction( | |
| 2761 | + at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set, | |
| 2762 | + ); | |
| 2763 | + let v_trial = chroma[1].code_from_prediction( | |
| 2764 | + at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set, | |
| 2765 | + ); | |
| 2766 | + let cost_p = u_trial.sse | |
| 2767 | + + v_trial.sse | |
| 2768 | + + search.lambda | |
| 2769 | + * (u_trial.bits | |
| 2770 | + + v_trial.bits | |
| 2771 | + + crate::tile::palette_uv_bits(&candidate, side)); | |
| 2772 | + if cost_p < cost { | |
| 2773 | + cost = cost_p; | |
| 2774 | + mode = DC_PRED; | |
| 2775 | + u = u_trial; | |
| 2776 | + v = v_trial; | |
| 2777 | + palette_uv = Some(candidate); | |
| 2778 | + } | |
| 2779 | + } | |
| 2780 | + } | |
| 2699 | 2781 | if census_on() { |
| 2700 | 2782 | CHROMA_RANK[sad_rank(&ranking, mode).min(6)] |
| 2701 | 2783 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| @@ -2707,6 +2789,7 @@ fn search_chroma( | ||
| 2707 | 2789 | [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)], |
| 2708 | 2790 | mode, |
| 2709 | 2791 | cost, |
| 2792 | + palette_uv, | |
| 2710 | 2793 | ) |
| 2711 | 2794 | } |
| 2712 | 2795 | |
| @@ -2955,6 +3038,7 @@ fn code_square_inter( | ||
| 2955 | 3038 | skip: skip_new, |
| 2956 | 3039 | eight: None, |
| 2957 | 3040 | palette: None, |
| 3041 | + palette_uv: None, | |
| 2958 | 3042 | tx_depth, |
| 2959 | 3043 | inter: Some(InterInfo { |
| 2960 | 3044 | ref1: None, |
| @@ -2992,6 +3076,7 @@ fn code_square_inter( | ||
| 2992 | 3076 | skip, |
| 2993 | 3077 | eight: None, |
| 2994 | 3078 | palette: None, |
| 3079 | + palette_uv: None, | |
| 2995 | 3080 | tx_depth, |
| 2996 | 3081 | inter: Some(InterInfo { |
| 2997 | 3082 | ref1: None, |
| @@ -5299,6 +5384,7 @@ fn search_inter_block( | ||
| 5299 | 5384 | inter: best.inter, |
| 5300 | 5385 | eight: None, |
| 5301 | 5386 | palette: None, |
| 5387 | + palette_uv: None, | |
| 5302 | 5388 | tx_depth: 0, |
| 5303 | 5389 | }, |
| 5304 | 5390 | best.cost, |
| @@ -6693,11 +6779,18 @@ mod tests { | ||
| 6693 | 6779 | picture.y[y * width + x] = INK[cell * 2 + bar]; |
| 6694 | 6780 | } |
| 6695 | 6781 | } |
| 6782 | + // Four chroma colours, not two: a two-colour chroma block only ever | |
| 6783 | + // codes a `PaletteSizeUV` of 2, which leaves | |
| 6784 | + // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking | |
| 6785 | + // deltas and the neighbour cache flags, exercised only when | |
| 6786 | + // neighbouring blocks share colours) unproven by the ffmpeg oracle. | |
| 6787 | + const CHROMA_U: [u16; 4] = [96, 118, 150, 176]; | |
| 6788 | + const CHROMA_V: [u16; 4] = [148, 126, 104, 92]; | |
| 6696 | 6789 | for y in 0..height / 2 { |
| 6697 | 6790 | for x in 0..width / 2 { |
| 6698 | - let cell = (x / 12 + y / 12) % 2; | |
| 6699 | - picture.u[y * (width / 2) + x] = if cell == 0 { 110 } else { 145 }; | |
| 6700 | - picture.v[y * (width / 2) + x] = if cell == 0 { 140 } else { 108 }; | |
| 6791 | + let cell = (x / 12 + 2 * (y / 12)) % 4; | |
| 6792 | + picture.u[y * (width / 2) + x] = CHROMA_U[cell]; | |
| 6793 | + picture.v[y * (width / 2) + x] = CHROMA_V[cell]; | |
| 6701 | 6794 | } |
| 6702 | 6795 | } |
| 6703 | 6796 | picture |
| @@ -6723,6 +6816,23 @@ mod tests { | ||
| 6723 | 6816 | let hits = crate::tile::take_palette_hits(); |
| 6724 | 6817 | assert!(hits[0] > 0, "no block took a palette: {hits:?}"); |
| 6725 | 6818 | eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]); |
| 6819 | + // The chroma half is a claim about the plane-1 syntax only if some | |
| 6820 | + // block really took a chroma palette (`gate-blind-to-feature`): every | |
| 6821 | + // exactness assert below passes on a stream that codes | |
| 6822 | + // `palette_uv_mode == 0` everywhere. | |
| 6823 | + let uv_hits = crate::tile::take_palette_uv_hits(); | |
| 6824 | + assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}"); | |
| 6825 | + let uv_cached = crate::tile::take_palette_uv_cache_hits(); | |
| 6826 | + eprintln!( | |
| 6827 | + "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache", | |
| 6828 | + uv_hits[0], | |
| 6829 | + &uv_hits[2..] | |
| 6830 | + ); | |
| 6831 | + assert!( | |
| 6832 | + uv_cached > 0, | |
| 6833 | + "no chroma base colour came out of the neighbour cache -- \ | |
| 6834 | + `write_palette_colors_uv`'s cache half is unproven by the oracle below" | |
| 6835 | + ); | |
| 6726 | 6836 | let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 6727 | 6837 | assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); |
| 6728 | 6838 | assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); |
| @@ -6759,12 +6869,19 @@ mod tests { | ||
| 6759 | 6869 | }) |
| 6760 | 6870 | .collect(); |
| 6761 | 6871 | let _ = crate::tile::take_palette_hits(); |
| 6872 | + let _ = crate::tile::take_palette_uv_hits(); | |
| 6762 | 6873 | let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); |
| 6763 | 6874 | let gop_hits = crate::tile::take_palette_hits(); |
| 6875 | + let gop_uv_hits = crate::tile::take_palette_uv_hits(); | |
| 6764 | 6876 | let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count(); |
| 6765 | 6877 | eprintln!( |
| 6766 | - "GOP: {} frames with screen tools after the key frame, {} palette blocks", | |
| 6767 | - inter_screen, gop_hits[0] | |
| 6878 | + "GOP: {} frames with screen tools after the key frame, {} palette blocks, \ | |
| 6879 | + {} chroma palette blocks", | |
| 6880 | + inter_screen, gop_hits[0], gop_uv_hits[0] | |
| 6881 | + ); | |
| 6882 | + assert!( | |
| 6883 | + gop_uv_hits[0] > 0, | |
| 6884 | + "no block of the GOP took a chroma palette: {gop_uv_hits:?}" | |
| 6768 | 6885 | ); |
| 6769 | 6886 | assert!( |
| 6770 | 6887 | inter_screen > 0, |
| @@ -6826,6 +6943,7 @@ mod tests { | ||
| 6826 | 6943 | skip: false, |
| 6827 | 6944 | eight: None, |
| 6828 | 6945 | palette: None, |
| 6946 | + palette_uv: None, | |
| 6829 | 6947 | tx_depth: 0, |
| 6830 | 6948 | inter: Some(InterInfo { |
| 6831 | 6949 | ref1: None, |
| @@ -9655,6 +9773,16 @@ mod tests { | ||
| 9655 | 9773 | .collect::<Vec<_>>() |
| 9656 | 9774 | .join(" ") |
| 9657 | 9775 | ); |
| 9776 | + let palette_uv = crate::tile::take_palette_uv_hits(); | |
| 9777 | + eprintln!( | |
| 9778 | + "{name}: chroma palette blocks {} sizes {}", | |
| 9779 | + palette_uv[0], | |
| 9780 | + (2..=8) | |
| 9781 | + .filter(|&n| palette_uv[n] > 0) | |
| 9782 | + .map(|n| format!("{n}={}", palette_uv[n])) | |
| 9783 | + .collect::<Vec<_>>() | |
| 9784 | + .join(" ") | |
| 9785 | + ); | |
| 9658 | 9786 | let uv = take_uv_mode_hits(); |
| 9659 | 9787 | let uv_total: usize = uv.iter().sum(); |
| 9660 | 9788 | eprintln!( |
crates/ec-av1/src/tile.rsmodified+280 -2
| @@ -1166,6 +1166,11 @@ pub struct BlockCoeffs { | ||
| 1166 | 1166 | /// `tx_depth` to zero (the whole block is one transform over the |
| 1167 | 1167 | /// palette's own prediction). |
| 1168 | 1168 | pub palette: Option<PaletteY>, |
| 1169 | + /// The chroma palette this block's two chroma planes are predicted with | |
| 1170 | + /// (spec 5.11.46 `palette_mode_info`'s plane-1 half), or `None`. Only a | |
| 1171 | + /// `UV_DC_PRED` block of an `allow_screen_content_tools` frame may carry | |
| 1172 | + /// one; it is independent of [`Self::palette`] (either, both or neither). | |
| 1173 | + pub palette_uv: Option<PaletteUv>, | |
| 1169 | 1174 | /// How many times this block's luma transform is halved under |
| 1170 | 1175 | /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole |
| 1171 | 1176 | /// block). Read only by the writers a `tx_select` frame calls; a |
| @@ -1189,6 +1194,27 @@ pub struct PaletteY { | ||
| 1189 | 1194 | pub map: Vec<u8>, |
| 1190 | 1195 | } |
| 1191 | 1196 | |
| 1197 | +/// As [`PaletteY`], for a block's chroma palette -- one colour-index map | |
| 1198 | +/// SHARED by U and V (spec `av1_visit_palette`'s plane-1 pass; the two planes | |
| 1199 | +/// are co-located after 4:2:0 subsampling) plus each plane's own base | |
| 1200 | +/// colours, exactly what [`crate::decode`]'s own `PaletteUv` carries out of | |
| 1201 | +/// the stream. | |
| 1202 | +#[derive(Clone, Debug, Default, PartialEq, Eq)] | |
| 1203 | +pub struct PaletteUv { | |
| 1204 | + /// How many base colours, 2..=8 (spec `PaletteSizeUV`). | |
| 1205 | + pub size: u8, | |
| 1206 | + /// U's base colours, ASCENDING and distinct -- `read_palette_colors_uv` | |
| 1207 | + /// merges the cached and transmitted lists as two ascending runs, and its | |
| 1208 | + /// delta form only ever steps upwards. | |
| 1209 | + pub u_colors: [u16; 8], | |
| 1210 | + /// V's base colours, in the same cluster order as [`Self::u_colors`] -- | |
| 1211 | + /// the shared map indexes both, and V's own coding needs no ordering. | |
| 1212 | + pub v_colors: [u16; 8], | |
| 1213 | + /// Which colour each chroma pixel takes, row-major over the subsampled | |
| 1214 | + /// block's own `(side / 2).max(4)` side. | |
| 1215 | + pub map: Vec<u8>, | |
| 1216 | +} | |
| 1217 | + | |
| 1192 | 1218 | /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole |
| 1193 | 1219 | /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by |
| 1194 | 1220 | /// [`write_inter_mode`] with the decoder's own contexts. |
| @@ -1455,6 +1481,15 @@ struct Neighbours { | ||
| 1455 | 1481 | pending_palette: Option<(u8, [u16; 8])>, |
| 1456 | 1482 | /// The colours beside [`Self::above_palette_size`]. |
| 1457 | 1483 | above_palette_colors: Vec<[u16; 8]>, |
| 1484 | + /// The chroma (U-channel) halves of the three bands above -- | |
| 1485 | + /// `av1_get_palette_cache(xd, 1, cache)`'s source, mirrored from the | |
| 1486 | + /// decoder's own `above_palette_uv_*`/`left_palette_uv_*`. | |
| 1487 | + above_palette_uv_size: Vec<u8>, | |
| 1488 | + left_palette_uv_size: Vec<u8>, | |
| 1489 | + above_palette_uv_colors: Vec<[u16; 8]>, | |
| 1490 | + left_palette_uv_colors: Vec<[u16; 8]>, | |
| 1491 | + /// [`Self::pending_palette`] for the chroma palette. | |
| 1492 | + pending_palette_uv: Option<(u8, [u16; 8])>, | |
| 1458 | 1493 | /// The same, down the left edge. |
| 1459 | 1494 | left_palette_colors: Vec<[u16; 8]>, |
| 1460 | 1495 | /// Whether the neighbour was coded inter, for the `is_inter` context. |
| @@ -1546,6 +1581,11 @@ impl Neighbours { | ||
| 1546 | 1581 | left_palette_size: vec![0; rows * (SUB / MI)], |
| 1547 | 1582 | pending_palette: None, |
| 1548 | 1583 | above_palette_colors: vec![[0; 8]; cols * (SUB / MI)], |
| 1584 | + above_palette_uv_size: vec![0; cols * (SUB / MI)], | |
| 1585 | + left_palette_uv_size: vec![0; rows * (SUB / MI)], | |
| 1586 | + above_palette_uv_colors: vec![[0; 8]; cols * (SUB / MI)], | |
| 1587 | + left_palette_uv_colors: vec![[0; 8]; rows * (SUB / MI)], | |
| 1588 | + pending_palette_uv: None, | |
| 1549 | 1589 | left_palette_colors: vec![[0; 8]; rows * (SUB / MI)], |
| 1550 | 1590 | mi_cols, |
| 1551 | 1591 | mi_rows, |
| @@ -1584,6 +1624,8 @@ impl Neighbours { | ||
| 1584 | 1624 | self.left_tx.iter_mut().for_each(|t| *t = 0); |
| 1585 | 1625 | self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); |
| 1586 | 1626 | self.left_palette_size.iter_mut().for_each(|s| *s = 0); |
| 1627 | + self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0); | |
| 1628 | + self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]); | |
| 1587 | 1629 | } |
| 1588 | 1630 | |
| 1589 | 1631 | /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from |
| @@ -1641,6 +1683,80 @@ impl Neighbours { | ||
| 1641 | 1683 | (ctx, cache) |
| 1642 | 1684 | } |
| 1643 | 1685 | |
| 1686 | + /// [`Self::palette_ctx_and_cache`]'s cache half for the U channel | |
| 1687 | + /// (`av1_get_palette_cache(xd, 1, cache)`), mirrored from the decoder's | |
| 1688 | + /// `palette_uv_cache_mi`: the `palette_uv_mode` context needs no | |
| 1689 | + /// neighbour lookup at all (it is this block's own just-decided Y palette | |
| 1690 | + /// use), so only the cache is wanted here. | |
| 1691 | + fn palette_uv_cache(&self, (r, c): (usize, usize)) -> Vec<u16> { | |
| 1692 | + let above_ok = r % 16 != 0; | |
| 1693 | + let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 { | |
| 1694 | + ( | |
| 1695 | + usize::from(self.above_palette_uv_size[c]), | |
| 1696 | + self.above_palette_uv_colors[c], | |
| 1697 | + ) | |
| 1698 | + } else { | |
| 1699 | + (0, [0u16; 8]) | |
| 1700 | + }; | |
| 1701 | + let (left_n, left_colors) = if c > 0 && self.left_palette_uv_size[r] > 0 { | |
| 1702 | + ( | |
| 1703 | + usize::from(self.left_palette_uv_size[r]), | |
| 1704 | + self.left_palette_uv_colors[r], | |
| 1705 | + ) | |
| 1706 | + } else { | |
| 1707 | + (0, [0u16; 8]) | |
| 1708 | + }; | |
| 1709 | + let mut cache = Vec::with_capacity(16); | |
| 1710 | + let push_dedup = |cache: &mut Vec<u16>, v: u16| { | |
| 1711 | + if cache.last() != Some(&v) { | |
| 1712 | + cache.push(v); | |
| 1713 | + } | |
| 1714 | + }; | |
| 1715 | + let (mut ai, mut li) = (0usize, 0usize); | |
| 1716 | + while ai < above_n && li < left_n { | |
| 1717 | + let (va, vl) = (above_colors[ai], left_colors[li]); | |
| 1718 | + if vl < va { | |
| 1719 | + push_dedup(&mut cache, vl); | |
| 1720 | + li += 1; | |
| 1721 | + } else { | |
| 1722 | + push_dedup(&mut cache, va); | |
| 1723 | + ai += 1; | |
| 1724 | + if vl == va { | |
| 1725 | + li += 1; | |
| 1726 | + } | |
| 1727 | + } | |
| 1728 | + } | |
| 1729 | + while ai < above_n { | |
| 1730 | + push_dedup(&mut cache, above_colors[ai]); | |
| 1731 | + ai += 1; | |
| 1732 | + } | |
| 1733 | + while li < left_n { | |
| 1734 | + push_dedup(&mut cache, left_colors[li]); | |
| 1735 | + li += 1; | |
| 1736 | + } | |
| 1737 | + cache | |
| 1738 | + } | |
| 1739 | + | |
| 1740 | + /// [`Self::record_palette_y`] for the chroma bands (decode.rs | |
| 1741 | + /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same | |
| 1742 | + /// way, and the span is in LUMA pixels for both planes' bands alike. | |
| 1743 | + fn record_palette_uv(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) { | |
| 1744 | + for cell in 0..(side / MI).max(1) { | |
| 1745 | + if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) { | |
| 1746 | + *e = size; | |
| 1747 | + if size > 0 { | |
| 1748 | + self.above_palette_uv_colors[c + cell] = colors; | |
| 1749 | + } | |
| 1750 | + } | |
| 1751 | + if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) { | |
| 1752 | + *e = size; | |
| 1753 | + if size > 0 { | |
| 1754 | + self.left_palette_uv_colors[r + cell] = colors; | |
| 1755 | + } | |
| 1756 | + } | |
| 1757 | + } | |
| 1758 | + } | |
| 1759 | + | |
| 1644 | 1760 | /// What a just-written block leaves in the palette bands (decode.rs |
| 1645 | 1761 | /// `record_palette_y_rect`): its size and colours over every 4x4 unit it |
| 1646 | 1762 | /// spans, `0` for a block that took no palette. |
| @@ -1809,6 +1925,8 @@ impl Neighbours { | ||
| 1809 | 1925 | if screen_armed() { |
| 1810 | 1926 | let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8])); |
| 1811 | 1927 | self.record_palette_y(at_mi, side, size, colors); |
| 1928 | + let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8])); | |
| 1929 | + self.record_palette_uv(at_mi, side, uv_size, uv_colors); | |
| 1812 | 1930 | } |
| 1813 | 1931 | let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); |
| 1814 | 1932 | let side_mi = side / MI; |
| @@ -2581,6 +2699,72 @@ fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16] | ||
| 2581 | 2699 | } |
| 2582 | 2700 | } |
| 2583 | 2701 | |
| 2702 | +/// `write_palette_colors_uv` (bitstream.c:1236), the write side of | |
| 2703 | +/// [`crate::decode`]'s `read_palette_colors_uv` at 8 bits. U is | |
| 2704 | +/// [`write_palette_colors_y`]'s cache/delta scheme with the reader's two | |
| 2705 | +/// documented differences -- the shrinking range starts at `256 - first` | |
| 2706 | +/// (not `255 - first`) and each delta is written unbiased (no `-1`). | |
| 2707 | +/// | |
| 2708 | +/// corner-cut: V takes the reader's RAW form (the leading bit 0, then `n` | |
| 2709 | +/// 8-bit literals) rather than its first-value-plus-signed-deltas form. | |
| 2710 | +/// Ceiling: about `n` bits per chroma-palette block more than the delta form | |
| 2711 | +/// would spend (8n against roughly 10 + (n-1)*(5..8)), which the RD pricer | |
| 2712 | +/// below sees, so it only ever makes the encoder take FEWER chroma palettes | |
| 2713 | +/// than it should -- never a wrong stream. Upgrade path: price both forms | |
| 2714 | +/// here and write the cheaper one under its own leading bit. | |
| 2715 | +fn write_palette_colors_uv(enc: &mut SymbolEncoder, u_colors: &[u16], v_colors: &[u16], cache: &[u16]) { | |
| 2716 | + let n = u_colors.len(); | |
| 2717 | + let mut cached: Vec<u16> = Vec::with_capacity(n); | |
| 2718 | + for &c in cache { | |
| 2719 | + if cached.len() >= n { | |
| 2720 | + break; | |
| 2721 | + } | |
| 2722 | + let take = u_colors.contains(&c); | |
| 2723 | + enc.literal(u32::from(take), 1); | |
| 2724 | + if take { | |
| 2725 | + PALETTE_UV_CACHE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | |
| 2726 | + cached.push(c); | |
| 2727 | + } | |
| 2728 | + } | |
| 2729 | + let transmitted: Vec<u16> = u_colors | |
| 2730 | + .iter() | |
| 2731 | + .copied() | |
| 2732 | + .filter(|c| !cached.contains(c)) | |
| 2733 | + .collect(); | |
| 2734 | + if !transmitted.is_empty() { | |
| 2735 | + enc.literal(u32::from(transmitted[0]), 8); | |
| 2736 | + if transmitted.len() > 1 { | |
| 2737 | + let fits = |extra: u32| -> bool { | |
| 2738 | + let mut bits = 5 + extra; | |
| 2739 | + let mut range = 256i32 - i32::from(transmitted[0]); | |
| 2740 | + for w in transmitted.windows(2) { | |
| 2741 | + let delta = i32::from(w[1]) - i32::from(w[0]); | |
| 2742 | + if delta >= (1i32 << bits) { | |
| 2743 | + return false; | |
| 2744 | + } | |
| 2745 | + range -= delta; | |
| 2746 | + bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); | |
| 2747 | + } | |
| 2748 | + true | |
| 2749 | + }; | |
| 2750 | + let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3); | |
| 2751 | + enc.literal(extra, 2); | |
| 2752 | + let mut bits = 5 + extra; | |
| 2753 | + let mut range = 256i32 - i32::from(transmitted[0]); | |
| 2754 | + for w in transmitted.windows(2) { | |
| 2755 | + let delta = i32::from(w[1]) - i32::from(w[0]); | |
| 2756 | + enc.literal(delta as u32, bits); | |
| 2757 | + range -= delta; | |
| 2758 | + bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); | |
| 2759 | + } | |
| 2760 | + } | |
| 2761 | + } | |
| 2762 | + enc.literal(0, 1); | |
| 2763 | + for &v in v_colors { | |
| 2764 | + enc.literal(u32::from(v), 8); | |
| 2765 | + } | |
| 2766 | +} | |
| 2767 | + | |
| 2584 | 2768 | /// `write_palette_color_map` (bitstream.c), the write side of |
| 2585 | 2769 | /// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal, |
| 2586 | 2770 | /// each symbol written as the position its colour takes in the neighbour |
| @@ -2630,6 +2814,25 @@ pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 { | ||
| 2630 | 2814 | enc.bits() |
| 2631 | 2815 | } |
| 2632 | 2816 | |
| 2817 | +/// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the | |
| 2818 | +/// size symbol, both colour lists and the shared colour-index map, priced | |
| 2819 | +/// through the very writers above (empty cache, which only over-prices). | |
| 2820 | +pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 { | |
| 2821 | + let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else { | |
| 2822 | + return f64::INFINITY; | |
| 2823 | + }; | |
| 2824 | + let n = usize::from(pal.size); | |
| 2825 | + let mut enc = SymbolEncoder::pricer(); | |
| 2826 | + let mut mode_cdf = cdf::PALETTE_UV_MODE[0]; | |
| 2827 | + enc.symbol(1, &mut mode_cdf); | |
| 2828 | + let mut size_cdf = cdf::PALETTE_UV_SIZE[bsize_ctx]; | |
| 2829 | + enc.symbol(n - 2, &mut size_cdf); | |
| 2830 | + write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]); | |
| 2831 | + let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2]; | |
| 2832 | + write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n); | |
| 2833 | + enc.bits() | |
| 2834 | +} | |
| 2835 | + | |
| 2633 | 2836 | /// Writes everything a key frame's block carries before its coefficients: the |
| 2634 | 2837 | /// skip flag, its luma intra mode against the CDF its neighbours' modes pick, |
| 2635 | 2838 | /// the angle a directional mode is steered by, and its chroma mode. Hands back |
| @@ -2680,7 +2883,17 @@ fn write_intra_mode( | ||
| 2680 | 2883 | // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer |
| 2681 | 2884 | // codes none -- exactly the ctx-0 read the decoder does under the same |
| 2682 | 2885 | // condition. |
| 2683 | - write_palette_syntax(enc, cdfs, neighbours, block.palette.as_ref(), mode, uv_mode, mi, side); | |
| 2886 | + write_palette_syntax( | |
| 2887 | + enc, | |
| 2888 | + cdfs, | |
| 2889 | + neighbours, | |
| 2890 | + block.palette.as_ref(), | |
| 2891 | + block.palette_uv.as_ref(), | |
| 2892 | + mode, | |
| 2893 | + uv_mode, | |
| 2894 | + mi, | |
| 2895 | + side, | |
| 2896 | + ); | |
| 2684 | 2897 | mode |
| 2685 | 2898 | } |
| 2686 | 2899 | |
| @@ -2703,6 +2916,7 @@ fn write_palette_syntax( | ||
| 2703 | 2916 | cdfs: &mut Cdfs, |
| 2704 | 2917 | neighbours: &mut Neighbours, |
| 2705 | 2918 | palette: Option<&PaletteY>, |
| 2919 | + palette_uv: Option<&PaletteUv>, | |
| 2706 | 2920 | mode: usize, |
| 2707 | 2921 | uv_mode: usize, |
| 2708 | 2922 | mi: (usize, usize), |
| @@ -2712,8 +2926,10 @@ fn write_palette_syntax( | ||
| 2712 | 2926 | return; |
| 2713 | 2927 | } |
| 2714 | 2928 | let palette = palette.filter(|_| mode == DC_PRED); |
| 2929 | + let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED); | |
| 2715 | 2930 | if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) { |
| 2716 | 2931 | let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi); |
| 2932 | + let uv_cache = neighbours.palette_uv_cache(mi); | |
| 2717 | 2933 | if mode == DC_PRED { |
| 2718 | 2934 | enc.symbol( |
| 2719 | 2935 | usize::from(palette.is_some()), |
| @@ -2726,15 +2942,45 @@ fn write_palette_syntax( | ||
| 2726 | 2942 | write_palette_colors_y(enc, &pal.colors[..n], &cache); |
| 2727 | 2943 | } |
| 2728 | 2944 | if uv_mode == DC_PRED { |
| 2729 | - enc.symbol(0, &mut cdfs.palette_uv_mode[usize::from(palette.is_some())]); | |
| 2945 | + enc.symbol( | |
| 2946 | + usize::from(palette_uv.is_some()), | |
| 2947 | + &mut cdfs.palette_uv_mode[usize::from(palette.is_some())], | |
| 2948 | + ); | |
| 2949 | + } | |
| 2950 | + if let Some(pal) = palette_uv { | |
| 2951 | + let n = usize::from(pal.size); | |
| 2952 | + enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]); | |
| 2953 | + write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache); | |
| 2730 | 2954 | } |
| 2955 | + // Both colour-index maps come after BOTH colour lists, in plane order | |
| 2956 | + // (`av1_visit_palette` runs from the caller, past `filter_intra`). | |
| 2731 | 2957 | if let Some(pal) = palette { |
| 2732 | 2958 | let n = usize::from(pal.size); |
| 2733 | 2959 | write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n); |
| 2734 | 2960 | note_palette(n); |
| 2735 | 2961 | } |
| 2962 | + if let Some(pal) = palette_uv { | |
| 2963 | + let n = usize::from(pal.size); | |
| 2964 | + write_color_index_map( | |
| 2965 | + enc, | |
| 2966 | + &mut cdfs.palette_uv_color_index[n - 2], | |
| 2967 | + &pal.map, | |
| 2968 | + palette_uv_side(side), | |
| 2969 | + n, | |
| 2970 | + ); | |
| 2971 | + note_palette_uv(n); | |
| 2972 | + } | |
| 2736 | 2973 | } |
| 2737 | 2974 | neighbours.pending_palette = palette.map(|p| (p.size, p.colors)); |
| 2975 | + neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors)); | |
| 2976 | +} | |
| 2977 | + | |
| 2978 | +/// The side of a chroma palette's shared colour-index map for a square luma | |
| 2979 | +/// block of `side` samples: `av1_get_plane_block_size(bsize, 1, 1)` floored at | |
| 2980 | +/// the 4-px transform, NOT a plain halving (decode.rs reads the map at | |
| 2981 | +/// exactly this size). | |
| 2982 | +pub(crate) fn palette_uv_side(side: usize) -> usize { | |
| 2983 | + (side / 2).max(4) | |
| 2738 | 2984 | } |
| 2739 | 2985 | |
| 2740 | 2986 | /// How many blocks took a palette, and of what size -- the fire count a gate |
| @@ -2749,6 +2995,35 @@ fn note_palette(n: usize) { | ||
| 2749 | 2995 | PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2750 | 2996 | } |
| 2751 | 2997 | |
| 2998 | +/// [`PALETTE_HITS`] for the chroma palette -- the same shape, so a gate can | |
| 2999 | +/// print the share of each plane's palette separately. | |
| 3000 | +static PALETTE_UV_HITS: [std::sync::atomic::AtomicUsize; 9] = | |
| 3001 | + [const { std::sync::atomic::AtomicUsize::new(0) }; 9]; | |
| 3002 | + | |
| 3003 | +fn note_palette_uv(n: usize) { | |
| 3004 | + PALETTE_UV_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | |
| 3005 | + PALETTE_UV_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | |
| 3006 | +} | |
| 3007 | + | |
| 3008 | +/// How many chroma base colours came out of the NEIGHBOUR CACHE rather than | |
| 3009 | +/// the stream -- the half of `write_palette_colors_uv` a test cannot see from | |
| 3010 | +/// the block counts alone, and the one that desyncs the tile if this writer's | |
| 3011 | +/// cache ever disagrees with the decoder's (`gate-blind-to-feature`). | |
| 3012 | +static PALETTE_UV_CACHE_HITS: std::sync::atomic::AtomicUsize = | |
| 3013 | + std::sync::atomic::AtomicUsize::new(0); | |
| 3014 | + | |
| 3015 | +/// Reads [`PALETTE_UV_CACHE_HITS`] and zeroes it. | |
| 3016 | +#[cfg(test)] | |
| 3017 | +pub(crate) fn take_palette_uv_cache_hits() -> usize { | |
| 3018 | + PALETTE_UV_CACHE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) | |
| 3019 | +} | |
| 3020 | + | |
| 3021 | +/// [`take_palette_hits`] for the chroma palette. | |
| 3022 | +#[cfg(test)] | |
| 3023 | +pub(crate) fn take_palette_uv_hits() -> [usize; 9] { | |
| 3024 | + std::array::from_fn(|i| PALETTE_UV_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) | |
| 3025 | +} | |
| 3026 | + | |
| 2752 | 3027 | /// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to |
| 2753 | 3028 | /// its own encode. |
| 2754 | 3029 | #[cfg(test)] |
| @@ -4672,6 +4947,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( | ||
| 4672 | 4947 | &mut cdfs, |
| 4673 | 4948 | &mut neighbours, |
| 4674 | 4949 | block.palette.as_ref(), |
| 4950 | + block.palette_uv.as_ref(), | |
| 4675 | 4951 | mode, |
| 4676 | 4952 | uv_mode, |
| 4677 | 4953 | (mi_row, mi_col), |
| @@ -4895,6 +5171,7 @@ fn write_inter_frame_leaf( | ||
| 4895 | 5171 | cdfs, |
| 4896 | 5172 | neighbours, |
| 4897 | 5173 | block.palette.as_ref(), |
| 5174 | + block.palette_uv.as_ref(), | |
| 4898 | 5175 | mode, |
| 4899 | 5176 | uv_mode, |
| 4900 | 5177 | (mi_row, mi_col), |
| @@ -5124,6 +5401,7 @@ fn write_inter_frame_leaf8( | ||
| 5124 | 5401 | cdfs, |
| 5125 | 5402 | neighbours, |
| 5126 | 5403 | block.palette.as_ref(), |
| 5404 | + block.palette_uv.as_ref(), | |
| 5127 | 5405 | mode, |
| 5128 | 5406 | uv_mode, |
| 5129 | 5407 | leaf_mi, |