Merge branch 'main' into lane-av1comp2
Browse files at this commit4 changed files +942 -12
- crates/ec-av1/src/decode.rs +27 -7
- crates/ec-av1/src/encode.rs +518 -1
- crates/ec-av1/src/stream.rs +6 -1
- crates/ec-av1/src/tile.rs +391 -3
crates/ec-av1/src/decode.rsmodified+27 -7
| @@ -8334,7 +8334,7 @@ fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> { | |||
| 8334 | /// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize] | 8334 | /// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize] |
| 8335 | /// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past | 8335 | /// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past |
| 8336 | /// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise. | 8336 | /// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise. |
| 8337 | -fn palette_bsize_ctx(side: usize) -> Option<usize> { | 8337 | +pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> { |
| 8338 | palette_bsize_ctx_wh(side, side) | 8338 | palette_bsize_ctx_wh(side, side) |
| 8339 | } | 8339 | } |
| 8340 | 8340 | ||
| @@ -8385,7 +8385,7 @@ struct PaletteUv { | |||
| 8385 | /// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s | 8385 | /// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s |
| 8386 | /// `get_unsigned_bits`, which is the same formula): smallest `n` with | 8386 | /// `get_unsigned_bits`, which is the same formula): smallest `n` with |
| 8387 | /// `2^n >= x`, `0` for `x <= 1`. | 8387 | /// `2^n >= x`, `0` for `x <= 1`. |
| 8388 | -fn ceil_log2(x: u32) -> u32 { | 8388 | +pub(crate) fn ceil_log2(x: u32) -> u32 { |
| 8389 | if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() } | 8389 | if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() } |
| 8390 | } | 8390 | } |
| 8391 | 8391 | ||
| @@ -8559,7 +8559,7 @@ const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2 | |||
| 8559 | /// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s | 8559 | /// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s |
| 8560 | /// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the | 8560 | /// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the |
| 8561 | /// actual colour index to store. | 8561 | /// actual colour index to store. |
| 8562 | -fn palette_color_index_context( | 8562 | +pub(crate) fn palette_color_index_context( |
| 8563 | map: &[u8], | 8563 | map: &[u8], |
| 8564 | side: usize, | 8564 | side: usize, |
| 8565 | row: usize, | 8565 | row: usize, |
| @@ -32941,7 +32941,7 @@ pub(crate) fn decode_inter_frame_tile( | |||
| 32941 | data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef, | 32941 | data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef, |
| 32942 | loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, | 32942 | loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, |
| 32943 | enable_dual_filter, reference_select, tx_select, | 32943 | enable_dual_filter, reference_select, tx_select, |
| 32944 | - &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, fctx, | 32944 | + &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false, fctx, |
| 32945 | ) | 32945 | ) |
| 32946 | } | 32946 | } |
| 32947 | 32947 | ||
| @@ -32976,6 +32976,12 @@ pub(crate) fn decode_inter_frame_tile_lr( | |||
| 32976 | // as `tx_select`/`initial_cdfs` above: a header-derived value a raw tile | 32976 | // as `tx_select`/`initial_cdfs` above: a header-derived value a raw tile |
| 32977 | // decode has to be told. | 32977 | // decode has to be told. |
| 32978 | sign_bias: crate::mvstack::SignBiasTable, | 32978 | sign_bias: crate::mvstack::SignBiasTable, |
| 32979 | + // This frame header's own `allow_screen_content_tools`: its intra blocks | ||
| 32980 | + // then carry the palette syntax (spec 5.11.46), which a raw tile decode | ||
| 32981 | + // that guessed `false` reads one symbol short of. Placed after | ||
| 32982 | + // `sign_bias` rather than beside the other bools on purpose (the | ||
| 32983 | + // `adjacent-same-typed-args` class). | ||
| 32984 | + allow_screen_content_tools: bool, | ||
| 32979 | fctx: &crate::decode::FrameCtx, | 32985 | fctx: &crate::decode::FrameCtx, |
| 32980 | ) -> Result<Picture> { | 32986 | ) -> Result<Picture> { |
| 32981 | let single_tile = TileInfo { | 32987 | let single_tile = TileInfo { |
| @@ -33003,6 +33009,7 @@ pub(crate) fn decode_inter_frame_tile_lr( | |||
| 33003 | lr, | 33009 | lr, |
| 33004 | initial_cdfs, | 33010 | initial_cdfs, |
| 33005 | sign_bias, | 33011 | sign_bias, |
| 33012 | + allow_screen_content_tools, | ||
| 33006 | fctx, | 33013 | fctx, |
| 33007 | ) | 33014 | ) |
| 33008 | } | 33015 | } |
| @@ -33030,6 +33037,9 @@ pub(crate) fn decode_inter_frame_tiles_lr( | |||
| 33030 | lr: &LoopRestorationParams, | 33037 | lr: &LoopRestorationParams, |
| 33031 | initial_cdfs: Option<Cdfs>, | 33038 | initial_cdfs: Option<Cdfs>, |
| 33032 | sign_bias: crate::mvstack::SignBiasTable, | 33039 | sign_bias: crate::mvstack::SignBiasTable, |
| 33040 | + // This frame header's own `allow_screen_content_tools` (see the | ||
| 33041 | + // single-tile wrapper): the palette syntax its intra blocks carry. | ||
| 33042 | + allow_screen_content_tools: bool, | ||
| 33033 | fctx: &crate::decode::FrameCtx, | 33043 | fctx: &crate::decode::FrameCtx, |
| 33034 | ) -> Result<Picture> { | 33044 | ) -> Result<Picture> { |
| 33035 | decode_inter_frame_tile_with_cdfs( | 33045 | decode_inter_frame_tile_with_cdfs( |
| @@ -33066,7 +33076,7 @@ pub(crate) fn decode_inter_frame_tiles_lr( | |||
| 33066 | tx_select, | 33076 | tx_select, |
| 33067 | false, | 33077 | false, |
| 33068 | false, | 33078 | false, |
| 33069 | - false, | 33079 | + allow_screen_content_tools, |
| 33070 | DeltaParams::default(), | 33080 | DeltaParams::default(), |
| 33071 | // `enable_filter_intra`: this crate's own encoder never writes the | 33081 | // `enable_filter_intra`: this crate's own encoder never writes the |
| 33072 | // sequence bit (`encode.rs`), so no intra-in-inter block of a stream | 33082 | // sequence bit (`encode.rs`), so no intra-in-inter block of a stream |
| @@ -37563,7 +37573,9 @@ mod tests { | |||
| 37563 | &key.loop_filter, | 37573 | &key.loop_filter, |
| 37564 | key.tx_select, | 37574 | key.tx_select, |
| 37565 | true, | 37575 | true, |
| 37566 | - false, | 37576 | + // This key frame's own `allow_screen_content_tools`: its intra |
| 37577 | + // blocks carry the palette syntax under it (stale-header class). | ||
| 37578 | + key.screen, | ||
| 37567 | false, | 37579 | false, |
| 37568 | &key.loop_restoration, fctx, | 37580 | &key.loop_restoration, fctx, |
| 37569 | ) | 37581 | ) |
| @@ -37610,6 +37622,9 @@ mod tests { | |||
| 37610 | &frame.loop_restoration, | 37622 | &frame.loop_restoration, |
| 37611 | Some(frame.start_cdfs.0.clone()), | 37623 | Some(frame.start_cdfs.0.clone()), |
| 37612 | NO_SIGN_BIAS, | 37624 | NO_SIGN_BIAS, |
| 37625 | + // This frame's own `allow_screen_content_tools`, off the | ||
| 37626 | + // `Encoded` the encoder handed back (stale-header class). | ||
| 37627 | + frame.screen, | ||
| 37613 | fctx, | 37628 | fctx, |
| 37614 | ) | 37629 | ) |
| 37615 | .unwrap(); | 37630 | .unwrap(); |
| @@ -37898,7 +37913,9 @@ mod tests { | |||
| 37898 | &key.loop_filter, | 37913 | &key.loop_filter, |
| 37899 | key.tx_select, | 37914 | key.tx_select, |
| 37900 | true, | 37915 | true, |
| 37901 | - false, | 37916 | + // This key frame's own `allow_screen_content_tools`: its intra |
| 37917 | + // blocks carry the palette syntax under it (stale-header class). | ||
| 37918 | + key.screen, | ||
| 37902 | false, | 37919 | false, |
| 37903 | &key.loop_restoration, fctx, | 37920 | &key.loop_restoration, fctx, |
| 37904 | ) | 37921 | ) |
| @@ -37934,6 +37951,9 @@ mod tests { | |||
| 37934 | &frame.loop_restoration, | 37951 | &frame.loop_restoration, |
| 37935 | Some(frame.start_cdfs.0.clone()), | 37952 | Some(frame.start_cdfs.0.clone()), |
| 37936 | NO_SIGN_BIAS, | 37953 | NO_SIGN_BIAS, |
| 37954 | + // This frame's own `allow_screen_content_tools`, off the | ||
| 37955 | + // `Encoded` the encoder handed back (stale-header class). | ||
| 37956 | + frame.screen, | ||
| 37937 | fctx, | 37957 | fctx, |
| 37938 | ) | 37958 | ) |
| 37939 | .unwrap(); | 37959 | .unwrap(); |
crates/ec-av1/src/encode.rsmodified+518 -1
| @@ -625,6 +625,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En | |||
| 625 | mi_rows: encoded.mi_rows, | 625 | mi_rows: encoded.mi_rows, |
| 626 | base_q_idx: encoded.base_q_idx, | 626 | base_q_idx: encoded.base_q_idx, |
| 627 | tx_select: encoded.tx_select, | 627 | tx_select: encoded.tx_select, |
| 628 | + screen: encoded.screen, | ||
| 628 | start_cdfs: encoded.start_cdfs.clone(), | 629 | start_cdfs: encoded.start_cdfs.clone(), |
| 629 | next_cdfs: encoded.next_cdfs.clone(), | 630 | next_cdfs: encoded.next_cdfs.clone(), |
| 630 | loop_filter: encoded.loop_filter, | 631 | loop_filter: encoded.loop_filter, |
| @@ -698,6 +699,11 @@ pub struct Encoded { | |||
| 698 | /// This frame header's chosen CDEF parameters, threaded for the same | 699 | /// This frame header's chosen CDEF parameters, threaded for the same |
| 699 | /// reason as `loop_filter`. | 700 | /// reason as `loop_filter`. |
| 700 | pub(crate) cdef: CdefParams, | 701 | pub(crate) cdef: CdefParams, |
| 702 | + /// This frame header's `allow_screen_content_tools` | ||
| 703 | + /// ([`screen_content`]) -- every intra block of the tile carries the two | ||
| 704 | + /// palette-mode symbols under it, so a raw tile decode that guessed | ||
| 705 | + /// `false` would desync at the first block (same class as `tx_select`). | ||
| 706 | + pub(crate) screen: bool, | ||
| 701 | /// This frame header's chosen loop restoration parameters, threaded for | 707 | /// This frame header's chosen loop restoration parameters, threaded for |
| 702 | /// the same reason as `loop_filter` -- and doubly so: the per-unit | 708 | /// the same reason as `loop_filter` -- and doubly so: the per-unit |
| 703 | /// filters themselves are coded in `tile`, so a decode of it under a | 709 | /// filters themselves are coded in `tile`, so a decode of it under a |
| @@ -705,6 +711,121 @@ pub struct Encoded { | |||
| 705 | pub(crate) loop_restoration: LoopRestorationParams, | 711 | pub(crate) loop_restoration: LoopRestorationParams, |
| 706 | } | 712 | } |
| 707 | 713 | ||
| 714 | +thread_local! { | ||
| 715 | + /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence | ||
| 716 | + /// header offers the per-frame `allow_screen_content_tools` bit at all. | ||
| 717 | + /// Armed once by the key frame ([`encode_key_frame_inner`], from | ||
| 718 | + /// [`screen_content`]) and read by every header builder after it, so that | ||
| 719 | + /// the inter frames of a screen sequence lay their headers out the same | ||
| 720 | + /// way the sequence header the key frame wrote says they do -- a per-call | ||
| 721 | + /// parameter would have to thread through `inter_frame_headers`' four | ||
| 722 | + /// public entry points and every hand-built-stream test that calls them. | ||
| 723 | + /// A sequence with no screen content leaves this false and writes exactly | ||
| 724 | + /// the bits it wrote before this lane. | ||
| 725 | + static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; | ||
| 726 | +} | ||
| 727 | + | ||
| 728 | +thread_local! { | ||
| 729 | + /// Overrides [`screen_content`] for the calling thread, which is what the | ||
| 730 | + /// intra-MODE ablations use: on a two-colour synthetic picture the palette | ||
| 731 | + /// codes every block losslessly, so both arms of a mode ablation reach | ||
| 732 | + /// infinite PSNR and the ablation measures nothing at all (the | ||
| 733 | + /// `fixture-proves-the-symbol-not-the-signal` class). An environment | ||
| 734 | + /// variable cannot do this -- the tests run in one process, in parallel. | ||
| 735 | + static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; | ||
| 736 | +} | ||
| 737 | + | ||
| 738 | +#[cfg(test)] | ||
| 739 | +pub(crate) fn force_screen(value: Option<bool>) { | ||
| 740 | + SCREEN_FORCE.with(|c| c.set(value)); | ||
| 741 | +} | ||
| 742 | + | ||
| 743 | +pub(crate) fn arm_seq_screen(on: bool) { | ||
| 744 | + SEQ_SCREEN.with(|c| c.set(on)); | ||
| 745 | +} | ||
| 746 | + | ||
| 747 | +fn seq_screen() -> bool { | ||
| 748 | + SEQ_SCREEN.with(std::cell::Cell::get) | ||
| 749 | +} | ||
| 750 | + | ||
| 751 | +/// How many distinct colours a 16x16 luma block may hold and still count as | ||
| 752 | +/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own | ||
| 753 | +/// `av1_set_screen_content_options` bound is 4, which separates NOTHING on a | ||
| 754 | +/// real (lossily coded, so noisy) desktop capture: `probe_screen_detect` | ||
| 755 | +/// measures the share of 16x16 blocks under each bound on the gate's own | ||
| 756 | +/// three clips, and only at 32 do the populations part -- film 20.3..21.9%, | ||
| 757 | +/// his OBS capture 51.1..51.5%. | ||
| 758 | +fn screen_colors() -> usize { | ||
| 759 | + static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); | ||
| 760 | + *N.get_or_init(|| { | ||
| 761 | + std::env::var("EC_AV1_SCREEN_COLORS") | ||
| 762 | + .ok() | ||
| 763 | + .and_then(|v| v.parse().ok()) | ||
| 764 | + .unwrap_or(32) | ||
| 765 | + }) | ||
| 766 | +} | ||
| 767 | + | ||
| 768 | +/// The reciprocal of the frame area those blocks must cover, in tenths -- | ||
| 769 | +/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is 10 (one | ||
| 770 | +/// tenth). 3 (a third) is the midpoint of the two populations | ||
| 771 | +/// `probe_screen_detect` measured at the colour bound above. | ||
| 772 | +/// `EC_AV1_SCREEN_PCT`. | ||
| 773 | +fn screen_pct() -> usize { | ||
| 774 | + static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); | ||
| 775 | + *N.get_or_init(|| { | ||
| 776 | + std::env::var("EC_AV1_SCREEN_PCT") | ||
| 777 | + .ok() | ||
| 778 | + .and_then(|v| v.parse().ok()) | ||
| 779 | + .unwrap_or(3) | ||
| 780 | + }) | ||
| 781 | +} | ||
| 782 | + | ||
| 783 | +/// How many frames [`screen_content`] said yes/no to, so a gate can print | ||
| 784 | +/// whether the detector fired at all (class `gate-blind-to-feature`). | ||
| 785 | +pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] = | ||
| 786 | + [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; | ||
| 787 | + | ||
| 788 | +/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count | ||
| 789 | +/// the distinct colours of every 16x16 block and turn the screen-content | ||
| 790 | +/// tools on when the blocks holding between 2 and [`screen_colors`] of them | ||
| 791 | +/// cover more than a [`screen_pct`]th of the frame. `width` is the plane's | ||
| 792 | +/// stride, `true_*` the frame's real (decodable) extent. | ||
| 793 | +fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool { | ||
| 794 | + if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) { | ||
| 795 | + SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 796 | + return forced; | ||
| 797 | + } | ||
| 798 | + if let Ok(v) = std::env::var("EC_AV1_SCREEN") { | ||
| 799 | + let on = v != "0"; | ||
| 800 | + SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 801 | + return on; | ||
| 802 | + } | ||
| 803 | + let (blk, limit) = (16usize, screen_colors()); | ||
| 804 | + let mut counted = 0usize; | ||
| 805 | + for by in (0..true_height).step_by(blk) { | ||
| 806 | + for bx in (0..true_width).step_by(blk) { | ||
| 807 | + let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk)); | ||
| 808 | + let mut seen = [false; 256]; | ||
| 809 | + let mut colors = 0usize; | ||
| 810 | + for row in 0..h { | ||
| 811 | + for col in 0..w { | ||
| 812 | + let v = usize::from(y[(by + row) * width + bx + col]); | ||
| 813 | + if !seen[v] { | ||
| 814 | + seen[v] = true; | ||
| 815 | + colors += 1; | ||
| 816 | + } | ||
| 817 | + } | ||
| 818 | + } | ||
| 819 | + if colors > 1 && colors <= limit { | ||
| 820 | + counted += 1; | ||
| 821 | + } | ||
| 822 | + } | ||
| 823 | + } | ||
| 824 | + let on = counted * blk * blk * screen_pct() > true_width * true_height; | ||
| 825 | + SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 826 | + on | ||
| 827 | +} | ||
| 828 | + | ||
| 708 | /// The sequence and frame headers a picture of this size is coded under: one | 829 | /// The sequence and frame headers a picture of this size is coded under: one |
| 709 | /// tile, one transform size per block, no in-loop filter parameters yet | 830 | /// tile, one transform size per block, no in-loop filter parameters yet |
| 710 | /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and | 831 | /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and |
| @@ -788,7 +909,17 @@ pub(crate) fn key_frame_headers_colour( | |||
| 788 | // CDEF simply carries zero strengths. | 909 | // CDEF simply carries zero strengths. |
| 789 | enable_cdef: true, | 910 | enable_cdef: true, |
| 790 | enable_restoration: true, | 911 | enable_restoration: true, |
| 791 | - seq_force_screen_content_tools: 0, | 912 | + // SELECT (2) when this sequence's key frame detected screen content |
| 913 | + // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit | ||
| 914 | + // is then coded in every frame header, and only the frames that want | ||
| 915 | + // the palette syntax set it. 0 -- the forced-off form, no bit at all | ||
| 916 | + // -- otherwise, which is what every non-screen stream this encoder | ||
| 917 | + // writes still carries. | ||
| 918 | + seq_force_screen_content_tools: if seq_screen() { | ||
| 919 | + ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS | ||
| 920 | + } else { | ||
| 921 | + 0 | ||
| 922 | + }, | ||
| 792 | seq_force_integer_mv: 0, | 923 | seq_force_integer_mv: 0, |
| 793 | color_config, | 924 | color_config, |
| 794 | still_picture: false, | 925 | still_picture: false, |
| @@ -2204,6 +2335,105 @@ fn commit_inter_luma( | |||
| 2204 | (flat.levels.clone(), 0, 0.0) | 2335 | (flat.levels.clone(), 0, 0.0) |
| 2205 | } | 2336 | } |
| 2206 | 2337 | ||
| 2338 | +/// The largest distinct-colour count a block may hold and still be offered a | ||
| 2339 | +/// palette candidate at all: past it the k-means quantisation costs more | ||
| 2340 | +/// error than the map saves rate, and every trial is wasted wall. | ||
| 2341 | +/// `EC_AV1_PAL_MAXCOLORS`. | ||
| 2342 | +fn palette_max_colors() -> usize { | ||
| 2343 | + static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); | ||
| 2344 | + *N.get_or_init(|| { | ||
| 2345 | + std::env::var("EC_AV1_PAL_MAXCOLORS") | ||
| 2346 | + .ok() | ||
| 2347 | + .and_then(|v| v.parse().ok()) | ||
| 2348 | + .unwrap_or(32) | ||
| 2349 | + }) | ||
| 2350 | +} | ||
| 2351 | + | ||
| 2352 | +/// The palettes worth trying for one block's luma, in the shape libaom's | ||
| 2353 | +/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE` | ||
| 2354 | +/// distinct colours takes them ALL (the prediction is then exact and the | ||
| 2355 | +/// residual empty), and a busier one is quantised to 8 and to 4 colours by a | ||
| 2356 | +/// one-dimensional Lloyd iteration seeded evenly across its range -- both | ||
| 2357 | +/// offered, because which wins is an RD question the caller answers. | ||
| 2358 | +/// `block` is `side*side` source samples, row-major. | ||
| 2359 | +fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> { | ||
| 2360 | + let mut histogram = [0u32; 256]; | ||
| 2361 | + for &v in block { | ||
| 2362 | + histogram[usize::from(v)] += 1; | ||
| 2363 | + } | ||
| 2364 | + let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect(); | ||
| 2365 | + if present.len() < 2 { | ||
| 2366 | + return Vec::new(); | ||
| 2367 | + } | ||
| 2368 | + let exact = |colors: &[u16]| -> crate::tile::PaletteY { | ||
| 2369 | + let mut base = [0u16; 8]; | ||
| 2370 | + base[..colors.len()].copy_from_slice(colors); | ||
| 2371 | + let map = block | ||
| 2372 | + .iter() | ||
| 2373 | + .map(|&v| { | ||
| 2374 | + colors | ||
| 2375 | + .iter() | ||
| 2376 | + .enumerate() | ||
| 2377 | + .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs()) | ||
| 2378 | + .map(|(i, _)| i as u8) | ||
| 2379 | + .expect("a palette holds at least two colours") | ||
| 2380 | + }) | ||
| 2381 | + .collect(); | ||
| 2382 | + crate::tile::PaletteY { size: colors.len() as u8, colors: base, map } | ||
| 2383 | + }; | ||
| 2384 | + if present.len() <= 8 { | ||
| 2385 | + return vec![exact(&present)]; | ||
| 2386 | + } | ||
| 2387 | + if present.len() > palette_max_colors() { | ||
| 2388 | + return Vec::new(); | ||
| 2389 | + } | ||
| 2390 | + let (lo, hi) = ( | ||
| 2391 | + i32::from(present[0]), | ||
| 2392 | + i32::from(present[present.len() - 1]), | ||
| 2393 | + ); | ||
| 2394 | + let mut out = Vec::with_capacity(2); | ||
| 2395 | + for n in [8usize, 4] { | ||
| 2396 | + // Even seeding across the block's own range, then four Lloyd passes | ||
| 2397 | + // over the histogram (256 bins, not `side*side` pixels). | ||
| 2398 | + let mut centres: Vec<f64> = (0..n) | ||
| 2399 | + .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64) | ||
| 2400 | + .collect(); | ||
| 2401 | + for _ in 0..4 { | ||
| 2402 | + let mut sums = vec![0f64; n]; | ||
| 2403 | + let mut counts = vec![0u32; n]; | ||
| 2404 | + for (v, &count) in histogram.iter().enumerate() { | ||
| 2405 | + if count == 0 { | ||
| 2406 | + continue; | ||
| 2407 | + } | ||
| 2408 | + let k = (0..n) | ||
| 2409 | + .min_by(|&a, &b| { | ||
| 2410 | + (centres[a] - v as f64) | ||
| 2411 | + .abs() | ||
| 2412 | + .total_cmp(&(centres[b] - v as f64).abs()) | ||
| 2413 | + }) | ||
| 2414 | + .expect("n >= 2"); | ||
| 2415 | + sums[k] += (v as u32 * count) as f64; | ||
| 2416 | + counts[k] += count; | ||
| 2417 | + } | ||
| 2418 | + for k in 0..n { | ||
| 2419 | + if counts[k] > 0 { | ||
| 2420 | + centres[k] = sums[k] / f64::from(counts[k]); | ||
| 2421 | + } | ||
| 2422 | + } | ||
| 2423 | + } | ||
| 2424 | + let mut colors: Vec<u16> = centres | ||
| 2425 | + .iter() | ||
| 2426 | + .map(|&c| c.round().clamp(0.0, 255.0) as u16) | ||
| 2427 | + .collect(); | ||
| 2428 | + colors.sort_unstable(); | ||
| 2429 | + colors.dedup(); | ||
| 2430 | + if colors.len() >= 2 { | ||
| 2431 | + out.push(exact(&colors)); | ||
| 2432 | + } | ||
| 2433 | + } | ||
| 2434 | + out | ||
| 2435 | +} | ||
| 2436 | + | ||
| 2207 | #[allow(clippy::too_many_arguments)] | 2437 | #[allow(clippy::too_many_arguments)] |
| 2208 | fn code_square( | 2438 | fn code_square( |
| 2209 | luma: &mut Plane, | 2439 | luma: &mut Plane, |
| @@ -2265,6 +2495,55 @@ fn code_square( | |||
| 2265 | luma_coeffs = best.3; | 2495 | luma_coeffs = best.3; |
| 2266 | TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | 2496 | TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2267 | } | 2497 | } |
| 2498 | + // The palette candidate is priced against the mode the luma search (and | ||
| 2499 | + // its transform-depth search) already settled on, so a block only takes | ||
| 2500 | + // one when it beats the best ordinary intra coding of the same pixels. | ||
| 2501 | + // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its | ||
| 2502 | + // prediction is the colour map, not the DC of its neighbours. | ||
| 2503 | + let mut mode = mode; | ||
| 2504 | + let mut palette = None; | ||
| 2505 | + if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { | ||
| 2506 | + let source: Vec<u8> = (y..y + side) | ||
| 2507 | + .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec()) | ||
| 2508 | + .collect(); | ||
| 2509 | + let kept = luma.snapshot(x, y, side); | ||
| 2510 | + for pal in palette_candidates(&source) { | ||
| 2511 | + let n = usize::from(pal.size); | ||
| 2512 | + let prediction: Vec<u8> = pal | ||
| 2513 | + .map | ||
| 2514 | + .iter() | ||
| 2515 | + .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8) | ||
| 2516 | + .collect(); | ||
| 2517 | + let trial = luma.code_from_prediction( | ||
| 2518 | + x, | ||
| 2519 | + y, | ||
| 2520 | + side, | ||
| 2521 | + &prediction, | ||
| 2522 | + false, | ||
| 2523 | + search.base_q_idx, | ||
| 2524 | + search.deadzone, | ||
| 2525 | + luma_set, | ||
| 2526 | + ); | ||
| 2527 | + let cost_p = trial.sse | ||
| 2528 | + + search.lambda | ||
| 2529 | + * (trial.bits | ||
| 2530 | + + mode_bits[DC_PRED as usize] | ||
| 2531 | + + crate::tile::palette_bits(&pal, side) | ||
| 2532 | + + if tx_select { tx_depth_bits(side, 0) } else { 0.0 }); | ||
| 2533 | + if cost_p < cost { | ||
| 2534 | + cost = cost_p; | ||
| 2535 | + mode = DC_PRED as u8; | ||
| 2536 | + tx_depth = 0; | ||
| 2537 | + luma_coeffs = coeffs(&trial.levels, side); | ||
| 2538 | + luma.commit(x, y, side, &trial); | ||
| 2539 | + palette = Some(pal); | ||
| 2540 | + } | ||
| 2541 | + } | ||
| 2542 | + if palette.is_none() { | ||
| 2543 | + luma.restore(x, y, side, &kept); | ||
| 2544 | + } | ||
| 2545 | + } | ||
| 2546 | + | ||
| 2268 | // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both | 2547 | // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both |
| 2269 | // planes; what it costs still counts towards the partition decision. | 2548 | // planes; what it costs still counts towards the partition decision. |
| 2270 | let ([u, v], uv_mode, chroma_cost) = | 2549 | let ([u, v], uv_mode, chroma_cost) = |
| @@ -2278,6 +2557,7 @@ fn code_square( | |||
| 2278 | mode, | 2557 | mode, |
| 2279 | uv_mode, | 2558 | uv_mode, |
| 2280 | tx_depth, | 2559 | tx_depth, |
| 2560 | + palette, | ||
| 2281 | ..BlockCoeffs::default() | 2561 | ..BlockCoeffs::default() |
| 2282 | }, | 2562 | }, |
| 2283 | cost, | 2563 | cost, |
| @@ -2674,6 +2954,7 @@ fn code_square_inter( | |||
| 2674 | uv_mode: DC_PRED, | 2954 | uv_mode: DC_PRED, |
| 2675 | skip: skip_new, | 2955 | skip: skip_new, |
| 2676 | eight: None, | 2956 | eight: None, |
| 2957 | + palette: None, | ||
| 2677 | tx_depth, | 2958 | tx_depth, |
| 2678 | inter: Some(InterInfo { | 2959 | inter: Some(InterInfo { |
| 2679 | ref1: None, | 2960 | ref1: None, |
| @@ -2710,6 +2991,7 @@ fn code_square_inter( | |||
| 2710 | uv_mode: DC_PRED, | 2991 | uv_mode: DC_PRED, |
| 2711 | skip, | 2992 | skip, |
| 2712 | eight: None, | 2993 | eight: None, |
| 2994 | + palette: None, | ||
| 2713 | tx_depth, | 2995 | tx_depth, |
| 2714 | inter: Some(InterInfo { | 2996 | inter: Some(InterInfo { |
| 2715 | ref1: None, | 2997 | ref1: None, |
| @@ -2841,6 +3123,9 @@ fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { | |||
| 2841 | 3123 | ||
| 2842 | /// What the luma mode search picks between, and under what terms. | 3124 | /// What the luma mode search picks between, and under what terms. |
| 2843 | struct Search<'a> { | 3125 | struct Search<'a> { |
| 3126 | + /// This frame's `allow_screen_content_tools` ([`screen_content`]): the | ||
| 3127 | + /// luma search then offers a palette candidate beside the intra modes. | ||
| 3128 | + screen: bool, | ||
| 2844 | base_q_idx: u8, | 3129 | base_q_idx: u8, |
| 2845 | deadzone: f64, | 3130 | deadzone: f64, |
| 2846 | lambda: f64, | 3131 | lambda: f64, |
| @@ -3241,7 +3526,19 @@ pub(crate) fn encode_key_frame_inner( | |||
| 3241 | // `render_and_frame_size_different` is false and no render_size bits are | 3526 | // `render_and_frame_size_different` is false and no render_size bits are |
| 3242 | // written, mirroring libaom/rav1e: the padded `picture` below is only the | 3527 | // written, mirroring libaom/rav1e: the padded `picture` below is only the |
| 3243 | // internal coding surface, never what the header names. | 3528 | // internal coding surface, never what the header names. |
| 3529 | + // Screen-content detection runs on the SOURCE luma, before any header is | ||
| 3530 | + // built: it decides this sequence's `seq_force_screen_content_tools` (and | ||
| 3531 | + // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as | ||
| 3532 | + // this frame's own `allow_screen_content_tools`. | ||
| 3533 | + let screen = screen_content( | ||
| 3534 | + &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(), | ||
| 3535 | + picture.width, | ||
| 3536 | + (picture.width).min(render.0), | ||
| 3537 | + (picture.height).min(render.1), | ||
| 3538 | + ); | ||
| 3539 | + arm_seq_screen(screen); | ||
| 3244 | let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; | 3540 | let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; |
| 3541 | + header.allow_screen_content_tools = screen; | ||
| 3245 | header.render_width = render.0 as u32; | 3542 | header.render_width = render.0 as u32; |
| 3246 | header.render_height = render.1 as u32; | 3543 | header.render_height = render.1 as u32; |
| 3247 | // `TxMode::Select`: every block codes a `tx_depth` symbol and may split | 3544 | // `TxMode::Select`: every block codes a `tx_depth` symbol and may split |
| @@ -3313,6 +3610,7 @@ pub(crate) fn encode_key_frame_inner( | |||
| 3313 | lambda: lambda_scale() * step * step, | 3610 | lambda: lambda_scale() * step * step, |
| 3314 | modes, | 3611 | modes, |
| 3315 | top_k: prune_top_k(), | 3612 | top_k: prune_top_k(), |
| 3613 | + screen, | ||
| 3316 | }; | 3614 | }; |
| 3317 | 3615 | ||
| 3318 | // The block grid this frame is coded over: [`crate::tile::block_grid`]'s | 3616 | // The block grid this frame is coded over: [`crate::tile::block_grid`]'s |
| @@ -3566,6 +3864,7 @@ pub(crate) fn encode_key_frame_inner( | |||
| 3566 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); | 3864 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); |
| 3567 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); | 3865 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 3568 | let mut cdfs = start_cdfs.0.clone(); | 3866 | let mut cdfs = start_cdfs.0.clone(); |
| 3867 | + crate::tile::arm_screen(screen); | ||
| 3569 | let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( | 3868 | let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( |
| 3570 | mi_cols, | 3869 | mi_cols, |
| 3571 | mi_rows, | 3870 | mi_rows, |
| @@ -3645,6 +3944,7 @@ pub(crate) fn encode_key_frame_inner( | |||
| 3645 | mi_rows: header.mi_rows, | 3944 | mi_rows: header.mi_rows, |
| 3646 | base_q_idx, | 3945 | base_q_idx, |
| 3647 | tx_select, | 3946 | tx_select, |
| 3947 | + screen, | ||
| 3648 | next_cdfs: start_cdfs.clone(), | 3948 | next_cdfs: start_cdfs.clone(), |
| 3649 | start_cdfs, | 3949 | start_cdfs, |
| 3650 | loop_filter: header.loop_filter, | 3950 | loop_filter: header.loop_filter, |
| @@ -4836,6 +5136,7 @@ fn search_inter_block( | |||
| 4836 | skip: best.skip, | 5136 | skip: best.skip, |
| 4837 | inter: best.inter, | 5137 | inter: best.inter, |
| 4838 | eight: None, | 5138 | eight: None, |
| 5139 | + palette: None, | ||
| 4839 | tx_depth: 0, | 5140 | tx_depth: 0, |
| 4840 | }, | 5141 | }, |
| 4841 | best.cost, | 5142 | best.cost, |
| @@ -4994,6 +5295,14 @@ pub(crate) fn encode_inter_frame( | |||
| 4994 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); | 5295 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 4995 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); | 5296 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 4996 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); | 5297 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 5298 | + // This frame's own `allow_screen_content_tools`. It can only be set when | ||
| 5299 | + // the SEQUENCE offers the bit at all, which is the key frame's decision | ||
| 5300 | + // ([`SEQ_SCREEN`]): a frame header that contradicts | ||
| 5301 | + // `seq_force_screen_content_tools` is a corrupt stream, not a tighter | ||
| 5302 | + // encode. | ||
| 5303 | + let screen = seq_screen() | ||
| 5304 | + && screen_content(&picture_y8, picture.width, true_width, true_height); | ||
| 5305 | + header.allow_screen_content_tools = screen; | ||
| 4997 | let mut luma = Plane { | 5306 | let mut luma = Plane { |
| 4998 | source: &picture_y8, | 5307 | source: &picture_y8, |
| 4999 | reconstruction: vec![128; picture_y8.len()], | 5308 | reconstruction: vec![128; picture_y8.len()], |
| @@ -5040,6 +5349,7 @@ pub(crate) fn encode_inter_frame( | |||
| 5040 | lambda: lambda_scale() * step * step, | 5349 | lambda: lambda_scale() * step * step, |
| 5041 | modes: &KEY_FRAME_MODES, | 5350 | modes: &KEY_FRAME_MODES, |
| 5042 | top_k: prune_top_k_inter(), | 5351 | top_k: prune_top_k_inter(), |
| 5352 | + screen, | ||
| 5043 | }; | 5353 | }; |
| 5044 | let mode_bits_table = inter_mode_bits(); | 5354 | let mode_bits_table = inter_mode_bits(); |
| 5045 | 5355 | ||
| @@ -5533,6 +5843,7 @@ pub(crate) fn encode_inter_frame( | |||
| 5533 | // Thread-locals: every tile job arms its own worker. | 5843 | // Thread-locals: every tile job arms its own worker. |
| 5534 | crate::tile::arm_reference_select(reference_select_bit); | 5844 | crate::tile::arm_reference_select(reference_select_bit); |
| 5535 | crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); | 5845 | crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); |
| 5846 | + crate::tile::arm_screen(screen); | ||
| 5536 | let mut cdfs = start_cdfs.0.clone(); | 5847 | let mut cdfs = start_cdfs.0.clone(); |
| 5537 | // Each tile's own MV grid: a candidate scan never reaches past | 5848 | // Each tile's own MV grid: a candidate scan never reaches past |
| 5538 | // the tile's bounds, so a grid holding only this tile's own | 5849 | // the tile's bounds, so a grid holding only this tile's own |
| @@ -5655,6 +5966,7 @@ pub(crate) fn encode_inter_frame( | |||
| 5655 | // frame's `start_cdfs`), not from the defaults. | 5966 | // frame's `start_cdfs`), not from the defaults. |
| 5656 | Some(start_cdfs.0.clone()), | 5967 | Some(start_cdfs.0.clone()), |
| 5657 | sign_bias, | 5968 | sign_bias, |
| 5969 | + h.allow_screen_content_tools, | ||
| 5658 | fctx, | 5970 | fctx, |
| 5659 | ) | 5971 | ) |
| 5660 | }, | 5972 | }, |
| @@ -5687,6 +5999,7 @@ pub(crate) fn encode_inter_frame( | |||
| 5687 | mi_rows: header.mi_rows, | 5999 | mi_rows: header.mi_rows, |
| 5688 | base_q_idx, | 6000 | base_q_idx, |
| 5689 | tx_select, | 6001 | tx_select, |
| 6002 | + screen, | ||
| 5690 | start_cdfs, | 6003 | start_cdfs, |
| 5691 | next_cdfs, | 6004 | next_cdfs, |
| 5692 | loop_filter: header.loop_filter, | 6005 | loop_filter: header.loop_filter, |
| @@ -6159,6 +6472,116 @@ mod tests { | |||
| 6159 | ); | 6472 | ); |
| 6160 | } | 6473 | } |
| 6161 | 6474 | ||
| 6475 | + /// A synthetic screen-content picture -- a few flat colours in a grid of | ||
| 6476 | + /// boxes with hard edges and text-like bars, the shape a desktop capture | ||
| 6477 | + /// has -- so the palette path is exercised on content it is for. | ||
| 6478 | + #[cfg(test)] | ||
| 6479 | + fn screen_card(width: usize, height: usize) -> Picture { | ||
| 6480 | + const INK: [u16; 4] = [16, 90, 180, 235]; | ||
| 6481 | + let mut picture = Picture::grey(width, height); | ||
| 6482 | + for y in 0..height { | ||
| 6483 | + for x in 0..width { | ||
| 6484 | + let cell = (x / 24 + y / 24) % 2; | ||
| 6485 | + let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20); | ||
| 6486 | + picture.y[y * width + x] = INK[cell * 2 + bar]; | ||
| 6487 | + } | ||
| 6488 | + } | ||
| 6489 | + for y in 0..height / 2 { | ||
| 6490 | + for x in 0..width / 2 { | ||
| 6491 | + let cell = (x / 12 + y / 12) % 2; | ||
| 6492 | + picture.u[y * (width / 2) + x] = if cell == 0 { 110 } else { 145 }; | ||
| 6493 | + picture.v[y * (width / 2) + x] = if cell == 0 { 140 } else { 108 }; | ||
| 6494 | + } | ||
| 6495 | + } | ||
| 6496 | + picture | ||
| 6497 | + } | ||
| 6498 | + | ||
| 6499 | + /// The lane's own end-to-end check: on screen content the detector fires, | ||
| 6500 | + /// blocks really take a palette (fire count, class | ||
| 6501 | + /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every | ||
| 6502 | + /// symbol this lane writes -- reconstructs exactly what the encoder did. | ||
| 6503 | + /// The film-shaped `test_card` must NOT trip the detector, which is what | ||
| 6504 | + /// keeps every non-screen stream byte-identical. | ||
| 6505 | + #[test] | ||
| 6506 | + fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() { | ||
| 6507 | + let fctx = &crate::decode::FrameCtx::new(); | ||
| 6508 | + let (width, height) = (192usize, 96usize); | ||
| 6509 | + let _ = crate::tile::take_palette_hits(); | ||
| 6510 | + let picture = screen_card(width, height); | ||
| 6511 | + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); | ||
| 6512 | + assert!( | ||
| 6513 | + encoded.screen, | ||
| 6514 | + "the detector did not fire on screen content -- no palette syntax was coded at all" | ||
| 6515 | + ); | ||
| 6516 | + let hits = crate::tile::take_palette_hits(); | ||
| 6517 | + assert!(hits[0] > 0, "no block took a palette: {hits:?}"); | ||
| 6518 | + eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]); | ||
| 6519 | + let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); | ||
| 6520 | + assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); | ||
| 6521 | + assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); | ||
| 6522 | + assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); | ||
| 6523 | + if !have_ffmpeg() { | ||
| 6524 | + eprintln!("SKIP the ffmpeg half: no ffmpeg"); | ||
| 6525 | + return; | ||
| 6526 | + } | ||
| 6527 | + let decoded = ffmpeg_decode(&encoded.stream, width, height); | ||
| 6528 | + assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); | ||
| 6529 | + assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); | ||
| 6530 | + assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); | ||
| 6531 | + // A whole GOP: the inter frames' own intra blocks carry the palette | ||
| 6532 | + // syntax too (the three intra arms of the inter writers), which only | ||
| 6533 | + // ffmpeg reading the frames back can prove. | ||
| 6534 | + let moved: Vec<Picture> = (0..4) | ||
| 6535 | + .map(|f| { | ||
| 6536 | + let base = screen_card(width, height); | ||
| 6537 | + let mut out = Picture::grey(width, height); | ||
| 6538 | + for y in 0..height { | ||
| 6539 | + for x in 0..width { | ||
| 6540 | + let sx = (x + f * 7) % width; | ||
| 6541 | + out.y[y * width + x] = base.y[y * width + sx]; | ||
| 6542 | + } | ||
| 6543 | + } | ||
| 6544 | + for y in 0..height / 2 { | ||
| 6545 | + for x in 0..width / 2 { | ||
| 6546 | + let sx = (x + f * 3) % (width / 2); | ||
| 6547 | + out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx]; | ||
| 6548 | + out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx]; | ||
| 6549 | + } | ||
| 6550 | + } | ||
| 6551 | + out | ||
| 6552 | + }) | ||
| 6553 | + .collect(); | ||
| 6554 | + let _ = crate::tile::take_palette_hits(); | ||
| 6555 | + let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); | ||
| 6556 | + let gop_hits = crate::tile::take_palette_hits(); | ||
| 6557 | + let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count(); | ||
| 6558 | + eprintln!( | ||
| 6559 | + "GOP: {} frames with screen tools after the key frame, {} palette blocks", | ||
| 6560 | + inter_screen, gop_hits[0] | ||
| 6561 | + ); | ||
| 6562 | + assert!( | ||
| 6563 | + inter_screen > 0, | ||
| 6564 | + "no inter frame set allow_screen_content_tools" | ||
| 6565 | + ); | ||
| 6566 | + let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap(); | ||
| 6567 | + for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() { | ||
| 6568 | + assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma"); | ||
| 6569 | + } | ||
| 6570 | + if have_ffmpeg() { | ||
| 6571 | + let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len()); | ||
| 6572 | + for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() { | ||
| 6573 | + assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma"); | ||
| 6574 | + assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U"); | ||
| 6575 | + assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V"); | ||
| 6576 | + } | ||
| 6577 | + } | ||
| 6578 | + | ||
| 6579 | + // The other half of the keep rule: film-shaped content leaves the | ||
| 6580 | + // detector (and so the whole sequence header) alone. | ||
| 6581 | + let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap(); | ||
| 6582 | + assert!(!film.screen, "the detector fired on the film-shaped test card"); | ||
| 6583 | + } | ||
| 6584 | + | ||
| 6162 | /// The minimal repro that isolated the inter-residual desync: a key frame | 6585 | /// The minimal repro that isolated the inter-residual desync: a key frame |
| 6163 | /// followed by one inter frame whose single superblock carries one | 6586 | /// followed by one inter frame whose single superblock carries one |
| 6164 | /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma | 6587 | /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma |
| @@ -6195,6 +6618,7 @@ mod tests { | |||
| 6195 | uv_mode: 0, | 6618 | uv_mode: 0, |
| 6196 | skip: false, | 6619 | skip: false, |
| 6197 | eight: None, | 6620 | eight: None, |
| 6621 | + palette: None, | ||
| 6198 | tx_depth: 0, | 6622 | tx_depth: 0, |
| 6199 | inter: Some(InterInfo { | 6623 | inter: Some(InterInfo { |
| 6200 | ref1: None, | 6624 | ref1: None, |
| @@ -7060,6 +7484,10 @@ mod tests { | |||
| 7060 | /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by | 7484 | /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by |
| 7061 | /// fidelity. | 7485 | /// fidelity. |
| 7062 | fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> { | 7486 | fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> { |
| 7487 | + // A mode ablation measures the MODE search: the palette would code | ||
| 7488 | + // these synthetic two-colour pictures losslessly under every arm and | ||
| 7489 | + // leave nothing to compare (see [`force_screen`]). | ||
| 7490 | + force_screen(Some(false)); | ||
| 7063 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] | 7491 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 7064 | .iter() | 7492 | .iter() |
| 7065 | .map(|&q| { | 7493 | .map(|&q| { |
| @@ -7172,6 +7600,10 @@ mod tests { | |||
| 7172 | /// The mode picked by the most blocks of a picture, ignoring the first | 7600 | /// The mode picked by the most blocks of a picture, ignoring the first |
| 7173 | /// block, which has no neighbours to tell the modes apart with. | 7601 | /// block, which has no neighbours to tell the modes apart with. |
| 7174 | fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) { | 7602 | fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) { |
| 7603 | + // A mode ablation measures the MODE search: the palette would code | ||
| 7604 | + // these synthetic two-colour pictures losslessly under every arm and | ||
| 7605 | + // leave nothing to compare (see [`force_screen`]). | ||
| 7606 | + force_screen(Some(false)); | ||
| 7175 | let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap(); | 7607 | let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap(); |
| 7176 | let blocks = &encoded.modes[1..]; | 7608 | let blocks = &encoded.modes[1..]; |
| 7177 | let mut counts = [0usize; 13]; | 7609 | let mut counts = [0usize; 13]; |
| @@ -8655,6 +9087,71 @@ mod tests { | |||
| 8655 | } | 9087 | } |
| 8656 | } | 9088 | } |
| 8657 | 9089 | ||
| 9090 | + /// The sweep behind [`screen_content`]'s two constants | ||
| 9091 | + /// (`unswept-decision-constants`): the share of 16x16 luma blocks with at | ||
| 9092 | + /// most N distinct colours, per gate clip, at the size the gate codes. | ||
| 9093 | + /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture` | ||
| 9094 | + #[test] | ||
| 9095 | + #[ignore = "reads the real library"] | ||
| 9096 | + fn probe_screen_detect() { | ||
| 9097 | + let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); | ||
| 9098 | + let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); | ||
| 9099 | + for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] { | ||
| 9100 | + let path = fixtures.join("video").join(name); | ||
| 9101 | + if path.exists() { | ||
| 9102 | + clips.push((name.to_string(), path)); | ||
| 9103 | + } | ||
| 9104 | + } | ||
| 9105 | + if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) | ||
| 9106 | + && let Some(p) = manifest | ||
| 9107 | + .lines() | ||
| 9108 | + .skip(1) | ||
| 9109 | + .filter_map(|l| l.split('\t').next()) | ||
| 9110 | + .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) | ||
| 9111 | + { | ||
| 9112 | + clips.push(("screen".to_string(), std::path::PathBuf::from(p))); | ||
| 9113 | + } | ||
| 9114 | + let (width, height) = (640usize, 384usize); | ||
| 9115 | + for (name, path) in &clips { | ||
| 9116 | + let frames = clip_frames(path.to_str().unwrap(), "0", width, height, 4); | ||
| 9117 | + for (f, picture) in frames.iter().enumerate() { | ||
| 9118 | + let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); | ||
| 9119 | + let mut hist = [0usize; 257]; | ||
| 9120 | + let mut blocks = 0usize; | ||
| 9121 | + for by in (0..height).step_by(16) { | ||
| 9122 | + for bx in (0..width).step_by(16) { | ||
| 9123 | + let mut seen = [false; 256]; | ||
| 9124 | + let mut colors = 0usize; | ||
| 9125 | + for row in 0..16 { | ||
| 9126 | + for col in 0..16 { | ||
| 9127 | + let v = usize::from(y[(by + row) * width + bx + col]); | ||
| 9128 | + if !seen[v] { | ||
| 9129 | + seen[v] = true; | ||
| 9130 | + colors += 1; | ||
| 9131 | + } | ||
| 9132 | + } | ||
| 9133 | + } | ||
| 9134 | + hist[colors] += 1; | ||
| 9135 | + blocks += 1; | ||
| 9136 | + } | ||
| 9137 | + } | ||
| 9138 | + let share = |limit: usize| { | ||
| 9139 | + 100.0 * hist[2..=limit.min(256)].iter().sum::<usize>() as f64 | ||
| 9140 | + / blocks.max(1) as f64 | ||
| 9141 | + }; | ||
| 9142 | + eprintln!( | ||
| 9143 | + "{name} frame {f}: <=4 {:.1}% <=8 {:.1}% <=16 {:.1}% <=32 {:.1}% <=64 {:.1}% <=128 {:.1}%", | ||
| 9144 | + share(4), | ||
| 9145 | + share(8), | ||
| 9146 | + share(16), | ||
| 9147 | + share(32), | ||
| 9148 | + share(64), | ||
| 9149 | + share(128), | ||
| 9150 | + ); | ||
| 9151 | + } | ||
| 9152 | + } | ||
| 9153 | + } | ||
| 9154 | + | ||
| 8658 | /// The missing instrument: what this encoder costs against libaom and | 9155 | /// The missing instrument: what this encoder costs against libaom and |
| 8659 | /// rav1e at matched fidelity, and how long it takes to get there. | 9156 | /// rav1e at matched fidelity, and how long it takes to get there. |
| 8660 | /// | 9157 | /// |
| @@ -8793,6 +9290,10 @@ mod tests { | |||
| 8793 | let fctx = &crate::decode::FrameCtx::new(); | 9290 | let fctx = &crate::decode::FrameCtx::new(); |
| 8794 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); | 9291 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 8795 | let _ = take_partition_hits(); | 9292 | let _ = take_partition_hits(); |
| 9293 | + let _ = crate::tile::take_palette_hits(); | ||
| 9294 | + SCREEN_FRAMES.iter().for_each(|c| { | ||
| 9295 | + c.store(0, std::sync::atomic::Ordering::Relaxed); | ||
| 9296 | + }); | ||
| 8796 | let _ = take_uv_mode_hits(); | 9297 | let _ = take_uv_mode_hits(); |
| 8797 | let _ = crate::tile::take_inter_mode_hits(); | 9298 | let _ = crate::tile::take_inter_mode_hits(); |
| 8798 | let _ = crate::tile::take_drl_hits(); | 9299 | let _ = crate::tile::take_drl_hits(); |
| @@ -8931,6 +9432,22 @@ mod tests { | |||
| 8931 | // Which chroma modes the search actually wins with, against the | 9432 | // Which chroma modes the search actually wins with, against the |
| 8932 | // unconditional DC_PRED that was the only outcome before | 9433 | // unconditional DC_PRED that was the only outcome before |
| 8933 | // (gate-blind-to-feature). | 9434 | // (gate-blind-to-feature). |
| 9435 | + // Screen-content detection and the palette it turns on | ||
| 9436 | + // (gate-blind-to-feature): how many frames set | ||
| 9437 | + // `allow_screen_content_tools`, how many blocks took a palette, | ||
| 9438 | + // and of what size. A film clip must print `screen frames on=0`. | ||
| 9439 | + let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); | ||
| 9440 | + let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); | ||
| 9441 | + let palette = crate::tile::take_palette_hits(); | ||
| 9442 | + eprintln!( | ||
| 9443 | + "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}", | ||
| 9444 | + palette[0], | ||
| 9445 | + (2..=8) | ||
| 9446 | + .filter(|&n| palette[n] > 0) | ||
| 9447 | + .map(|n| format!("{n}={}", palette[n])) | ||
| 9448 | + .collect::<Vec<_>>() | ||
| 9449 | + .join(" ") | ||
| 9450 | + ); | ||
| 8934 | let uv = take_uv_mode_hits(); | 9451 | let uv = take_uv_mode_hits(); |
| 8935 | let uv_total: usize = uv.iter().sum(); | 9452 | let uv_total: usize = uv.iter().sum(); |
| 8936 | eprintln!( | 9453 | eprintln!( |
crates/ec-av1/src/stream.rsmodified+6 -1
| @@ -2999,7 +2999,12 @@ pub(crate) mod tests { | |||
| 2999 | encoded.tx_select, | 2999 | encoded.tx_select, |
| 3000 | // Our own encoder always writes `reduced_tx_set: true`. | 3000 | // Our own encoder always writes `reduced_tx_set: true`. |
| 3001 | true, | 3001 | true, |
| 3002 | - false, | 3002 | + // `allow_screen_content_tools` off the frame the encoder |
| 3003 | + // actually wrote: a screen-content picture codes two palette | ||
| 3004 | + // symbols per intra block, and a raw tile decode that guessed | ||
| 3005 | + // `false` desyncs at the first one (class: test asserts | ||
| 3006 | + // against a stale header). | ||
| 3007 | + encoded.screen, | ||
| 3003 | false, | 3008 | false, |
| 3004 | &encoded.loop_restoration, fctx, | 3009 | &encoded.loop_restoration, fctx, |
| 3005 | ) | 3010 | ) |
crates/ec-av1/src/tile.rsmodified+391 -3
| @@ -304,6 +304,25 @@ pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) { | |||
| 304 | SIGN_BIAS.with(|c| c.set(sign_bias)); | 304 | SIGN_BIAS.with(|c| c.set(sign_bias)); |
| 305 | } | 305 | } |
| 306 | 306 | ||
| 307 | +thread_local! { | ||
| 308 | + static SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; | ||
| 309 | +} | ||
| 310 | + | ||
| 311 | +/// Arms the next tile write with this frame's `allow_screen_content_tools` | ||
| 312 | +/// (spec 5.9.2), which is what makes every intra block carry the | ||
| 313 | +/// `palette_y_mode`/`palette_uv_mode` symbols spec 5.11.46 | ||
| 314 | +/// `read_palette_mode_info` reads. Armed the same way [`arm_cdef_idx`]/ | ||
| 315 | +/// [`arm_sign_bias`] are -- and disarmed by the same guard -- so a frame that | ||
| 316 | +/// never detected screen content writes exactly the stream it wrote before | ||
| 317 | +/// this lane. | ||
| 318 | +pub(crate) fn arm_screen(on: bool) { | ||
| 319 | + SCREEN.with(|c| c.set(on)); | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +fn screen_armed() -> bool { | ||
| 323 | + SCREEN.with(std::cell::Cell::get) | ||
| 324 | +} | ||
| 325 | + | ||
| 307 | thread_local! { | 326 | thread_local! { |
| 308 | /// This frame header's own `reference_select` bit (spec 5.9.22), armed | 327 | /// This frame header's own `reference_select` bit (spec 5.9.22), armed |
| 309 | /// the same way `arm_sign_bias` arms the sign-bias table rather than | 328 | /// the same way `arm_sign_bias` arms the sign-bias table rather than |
| @@ -661,6 +680,7 @@ impl Drop for CdefIdxGuard { | |||
| 661 | CDEF_IDX.with(|c| *c.borrow_mut() = None); | 680 | CDEF_IDX.with(|c| *c.borrow_mut() = None); |
| 662 | LR_PLAN.with(|c| *c.borrow_mut() = None); | 681 | LR_PLAN.with(|c| *c.borrow_mut() = None); |
| 663 | SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS)); | 682 | SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS)); |
| 683 | + SCREEN.with(|c| c.set(false)); | ||
| 664 | REFERENCE_SELECT.with(|c| c.set(false)); | 684 | REFERENCE_SELECT.with(|c| c.set(false)); |
| 665 | ORDER_HINTS.with(|c| c.set((7, 0, [0; 7]))); | 685 | ORDER_HINTS.with(|c| c.set((7, 0, [0; 7]))); |
| 666 | } | 686 | } |
| @@ -1148,6 +1168,13 @@ pub struct BlockCoeffs { | |||
| 1148 | /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s | 1168 | /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s |
| 1149 | /// per-quadrant fields are unused. | 1169 | /// per-quadrant fields are unused. |
| 1150 | pub eight: Option<Vec<BlockCoeffs>>, | 1170 | pub eight: Option<Vec<BlockCoeffs>>, |
| 1171 | + /// The luma palette this block is predicted with (spec 5.11.46 | ||
| 1172 | + /// `palette_mode_info`), or `None` for an ordinary intra block. Only a | ||
| 1173 | + /// `DC_PRED` block on a frame whose header set | ||
| 1174 | + /// `allow_screen_content_tools` may carry one, and it forces | ||
| 1175 | + /// `tx_depth` to zero (the whole block is one transform over the | ||
| 1176 | + /// palette's own prediction). | ||
| 1177 | + pub palette: Option<PaletteY>, | ||
| 1151 | /// How many times this block's luma transform is halved under | 1178 | /// How many times this block's luma transform is halved under |
| 1152 | /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole | 1179 | /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole |
| 1153 | /// block). Read only by the writers a `tx_select` frame calls; a | 1180 | /// block). Read only by the writers a `tx_select` frame calls; a |
| @@ -1157,6 +1184,20 @@ pub struct BlockCoeffs { | |||
| 1157 | pub tx_depth: u8, | 1184 | pub tx_depth: u8, |
| 1158 | } | 1185 | } |
| 1159 | 1186 | ||
| 1187 | +/// A block's luma palette: its base colours (ascending, only the first | ||
| 1188 | +/// `size` entries are real) and the per-pixel colour-index map, `side*side` | ||
| 1189 | +/// row-major -- exactly what [`crate::decode`]'s own `PaletteY` carries back | ||
| 1190 | +/// out of the stream. | ||
| 1191 | +#[derive(Clone, Debug, Default, PartialEq, Eq)] | ||
| 1192 | +pub struct PaletteY { | ||
| 1193 | + /// How many base colours, 2..=8 (spec `PaletteSizeY`). | ||
| 1194 | + pub size: u8, | ||
| 1195 | + /// The base colours, ascending. | ||
| 1196 | + pub colors: [u16; 8], | ||
| 1197 | + /// Which colour each pixel takes, row-major over the block's own side. | ||
| 1198 | + pub map: Vec<u8>, | ||
| 1199 | +} | ||
| 1200 | + | ||
| 1160 | /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole | 1201 | /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole |
| 1161 | /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by | 1202 | /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by |
| 1162 | /// [`write_inter_mode`] with the decoder's own contexts. | 1203 | /// [`write_inter_mode`] with the decoder's own contexts. |
| @@ -1404,6 +1445,27 @@ struct Neighbours { | |||
| 1404 | above_txfm: Vec<u8>, | 1445 | above_txfm: Vec<u8>, |
| 1405 | /// The same, down the left edge (transform HEIGHT). | 1446 | /// The same, down the left edge (transform HEIGHT). |
| 1406 | left_txfm: Vec<u8>, | 1447 | left_txfm: Vec<u8>, |
| 1448 | + /// The palette size each 4x4 mode-info column last left behind, and its | ||
| 1449 | + /// base colours -- `av1_get_palette_mode_ctx`'s neighbour lookup and | ||
| 1450 | + /// `av1_get_palette_cache`'s colour source, mirrored from the decoder's | ||
| 1451 | + /// own `above_palette_size`/`above_palette_colors` bands (decode.rs | ||
| 1452 | + /// `palette_ctx_and_cache_mi`). Every intra block of a screen-content | ||
| 1453 | + /// frame writes them, `0` when it took no palette, so a stale size never | ||
| 1454 | + /// survives into the next block's context. | ||
| 1455 | + above_palette_size: Vec<u8>, | ||
| 1456 | + /// The same, down the left edge. | ||
| 1457 | + left_palette_size: Vec<u8>, | ||
| 1458 | + /// What the block being written right now will leave in the two palette | ||
| 1459 | + /// bands, published by [`Self::record_mi_planes`] -- the one point EVERY | ||
| 1460 | + /// block of either frame type passes through, so an inter block (or an | ||
| 1461 | + /// intra block that took no palette) clears the bands rather than letting | ||
| 1462 | + /// an earlier palette block's size stand (the neighbour-band hazard | ||
| 1463 | + /// lane-t900 r23 hit on the decoder side). | ||
| 1464 | + pending_palette: Option<(u8, [u16; 8])>, | ||
| 1465 | + /// The colours beside [`Self::above_palette_size`]. | ||
| 1466 | + above_palette_colors: Vec<[u16; 8]>, | ||
| 1467 | + /// The same, down the left edge. | ||
| 1468 | + left_palette_colors: Vec<[u16; 8]>, | ||
| 1407 | /// Whether the neighbour was coded inter, for the `is_inter` context. | 1469 | /// Whether the neighbour was coded inter, for the `is_inter` context. |
| 1408 | /// Unused by the key frame writers. | 1470 | /// Unused by the key frame writers. |
| 1409 | above_inter: Vec<bool>, | 1471 | above_inter: Vec<bool>, |
| @@ -1489,6 +1551,11 @@ impl Neighbours { | |||
| 1489 | left_tx: vec![0; rows * (SUB / MI)], | 1551 | left_tx: vec![0; rows * (SUB / MI)], |
| 1490 | above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], | 1552 | above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], |
| 1491 | left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)], | 1553 | left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)], |
| 1554 | + above_palette_size: vec![0; cols * (SUB / MI)], | ||
| 1555 | + left_palette_size: vec![0; rows * (SUB / MI)], | ||
| 1556 | + pending_palette: None, | ||
| 1557 | + above_palette_colors: vec![[0; 8]; cols * (SUB / MI)], | ||
| 1558 | + left_palette_colors: vec![[0; 8]; rows * (SUB / MI)], | ||
| 1492 | mi_cols, | 1559 | mi_cols, |
| 1493 | mi_rows, | 1560 | mi_rows, |
| 1494 | } | 1561 | } |
| @@ -1525,6 +1592,82 @@ impl Neighbours { | |||
| 1525 | self.left_compound_idx.iter_mut().for_each(|r| *r = 0); | 1592 | self.left_compound_idx.iter_mut().for_each(|r| *r = 0); |
| 1526 | self.left_tx.iter_mut().for_each(|t| *t = 0); | 1593 | self.left_tx.iter_mut().for_each(|t| *t = 0); |
| 1527 | self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); | 1594 | self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); |
| 1595 | + self.left_palette_size.iter_mut().for_each(|s| *s = 0); | ||
| 1596 | + } | ||
| 1597 | + | ||
| 1598 | + /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from | ||
| 1599 | + /// the decoder's [`crate::decode`] `palette_ctx_and_cache_mi`: the | ||
| 1600 | + /// `palette_y_mode` context (how many of the two neighbours took a | ||
| 1601 | + /// palette) and the ascending, deduplicated colour cache the neighbours | ||
| 1602 | + /// offer. `mi` is the block's own position in 4x4 units; this writer | ||
| 1603 | + /// codes one tile starting at (0, 0), which is what the `r > 0`/`c > 0` | ||
| 1604 | + /// availability terms read against. | ||
| 1605 | + fn palette_ctx_and_cache(&self, (r, c): (usize, usize)) -> (usize, Vec<u16>) { | ||
| 1606 | + // `av1_get_palette_cache` drops the above neighbour on a 64-px | ||
| 1607 | + // superblock boundary (pred_common.c:76) -- but the mode CONTEXT does | ||
| 1608 | + // not, which is why the two terms below are asked separately. | ||
| 1609 | + let above_ok = r % 16 != 0; | ||
| 1610 | + let above_is_palette = r > 0 && self.above_palette_size[c] > 0; | ||
| 1611 | + let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 { | ||
| 1612 | + (usize::from(self.above_palette_size[c]), self.above_palette_colors[c]) | ||
| 1613 | + } else { | ||
| 1614 | + (0, [0u16; 8]) | ||
| 1615 | + }; | ||
| 1616 | + let (left_n, left_colors) = if c > 0 && self.left_palette_size[r] > 0 { | ||
| 1617 | + (usize::from(self.left_palette_size[r]), self.left_palette_colors[r]) | ||
| 1618 | + } else { | ||
| 1619 | + (0, [0u16; 8]) | ||
| 1620 | + }; | ||
| 1621 | + let ctx = usize::from(above_is_palette) + usize::from(left_n > 0); | ||
| 1622 | + let mut cache = Vec::with_capacity(16); | ||
| 1623 | + let push_dedup = |cache: &mut Vec<u16>, v: u16| { | ||
| 1624 | + if cache.last() != Some(&v) { | ||
| 1625 | + cache.push(v); | ||
| 1626 | + } | ||
| 1627 | + }; | ||
| 1628 | + let (mut ai, mut li) = (0usize, 0usize); | ||
| 1629 | + while ai < above_n && li < left_n { | ||
| 1630 | + let (va, vl) = (above_colors[ai], left_colors[li]); | ||
| 1631 | + if vl < va { | ||
| 1632 | + push_dedup(&mut cache, vl); | ||
| 1633 | + li += 1; | ||
| 1634 | + } else { | ||
| 1635 | + push_dedup(&mut cache, va); | ||
| 1636 | + ai += 1; | ||
| 1637 | + if vl == va { | ||
| 1638 | + li += 1; | ||
| 1639 | + } | ||
| 1640 | + } | ||
| 1641 | + } | ||
| 1642 | + while ai < above_n { | ||
| 1643 | + push_dedup(&mut cache, above_colors[ai]); | ||
| 1644 | + ai += 1; | ||
| 1645 | + } | ||
| 1646 | + while li < left_n { | ||
| 1647 | + push_dedup(&mut cache, left_colors[li]); | ||
| 1648 | + li += 1; | ||
| 1649 | + } | ||
| 1650 | + (ctx, cache) | ||
| 1651 | + } | ||
| 1652 | + | ||
| 1653 | + /// What a just-written block leaves in the palette bands (decode.rs | ||
| 1654 | + /// `record_palette_y_rect`): its size and colours over every 4x4 unit it | ||
| 1655 | + /// spans, `0` for a block that took no palette. | ||
| 1656 | + fn record_palette_y(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) { | ||
| 1657 | + for cell in 0..(side / MI).max(1) { | ||
| 1658 | + if let Some(e) = self.above_palette_size.get_mut(c + cell) { | ||
| 1659 | + *e = size; | ||
| 1660 | + if size > 0 { | ||
| 1661 | + self.above_palette_colors[c + cell] = colors; | ||
| 1662 | + } | ||
| 1663 | + } | ||
| 1664 | + if let Some(e) = self.left_palette_size.get_mut(r + cell) { | ||
| 1665 | + *e = size; | ||
| 1666 | + if size > 0 { | ||
| 1667 | + self.left_palette_colors[r + cell] = colors; | ||
| 1668 | + } | ||
| 1669 | + } | ||
| 1670 | + } | ||
| 1528 | } | 1671 | } |
| 1529 | 1672 | ||
| 1530 | /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block | 1673 | /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block |
| @@ -1672,6 +1815,10 @@ impl Neighbours { | |||
| 1672 | luma: bool, | 1815 | luma: bool, |
| 1673 | ) { | 1816 | ) { |
| 1674 | let (mi_r, mi_c) = at_mi; | 1817 | let (mi_r, mi_c) = at_mi; |
| 1818 | + if screen_armed() { | ||
| 1819 | + let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8])); | ||
| 1820 | + self.record_palette_y(at_mi, side, size, colors); | ||
| 1821 | + } | ||
| 1675 | let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); | 1822 | let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); |
| 1676 | let side_mi = side / MI; | 1823 | let side_mi = side / MI; |
| 1677 | for cell in 0..side_mi { | 1824 | for cell in 0..side_mi { |
| @@ -2368,6 +2515,130 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( | |||
| 2368 | Ok(enc.finish()) | 2515 | Ok(enc.finish()) |
| 2369 | } | 2516 | } |
| 2370 | 2517 | ||
| 2518 | +/// `av1_write_uniform` -- the inverse of [`crate::decode`]'s `read_uniform`, | ||
| 2519 | +/// which the palette colour-index map's first (context-free) symbol is coded | ||
| 2520 | +/// with. | ||
| 2521 | +fn write_uniform(enc: &mut SymbolEncoder, value: usize, n: usize) { | ||
| 2522 | + let l = crate::decode::ceil_log2(n as u32); | ||
| 2523 | + let m = (1usize << l) - n; | ||
| 2524 | + if value < m { | ||
| 2525 | + enc.literal(value as u32, l - 1); | ||
| 2526 | + } else { | ||
| 2527 | + enc.literal(((value + m) >> 1) as u32, l - 1); | ||
| 2528 | + enc.literal(((value + m) & 1) as u32, 1); | ||
| 2529 | + } | ||
| 2530 | +} | ||
| 2531 | + | ||
| 2532 | +/// `write_palette_colors_y` (bitstream.c:1178), the write side of | ||
| 2533 | +/// [`crate::decode`]'s `read_palette_colors_y` at 8 bits: one flag per cache | ||
| 2534 | +/// entry (taken when this palette holds that colour, in cache order, stopping | ||
| 2535 | +/// once `n` are cached), then the colours the cache did not supply -- the | ||
| 2536 | +/// first raw, the rest as deltas off a bit width that shrinks with the range | ||
| 2537 | +/// left. `colors` is ascending and distinct, so the decoder's `merge_colors` | ||
| 2538 | +/// of the two ascending lists puts it back exactly. | ||
| 2539 | +fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]) { | ||
| 2540 | + let n = colors.len(); | ||
| 2541 | + let mut cached: Vec<u16> = Vec::with_capacity(n); | ||
| 2542 | + for &c in cache { | ||
| 2543 | + if cached.len() >= n { | ||
| 2544 | + break; | ||
| 2545 | + } | ||
| 2546 | + let take = colors.contains(&c); | ||
| 2547 | + enc.literal(u32::from(take), 1); | ||
| 2548 | + if take { | ||
| 2549 | + cached.push(c); | ||
| 2550 | + } | ||
| 2551 | + } | ||
| 2552 | + let transmitted: Vec<u16> = colors | ||
| 2553 | + .iter() | ||
| 2554 | + .copied() | ||
| 2555 | + .filter(|c| !cached.contains(c)) | ||
| 2556 | + .collect(); | ||
| 2557 | + if transmitted.is_empty() { | ||
| 2558 | + return; | ||
| 2559 | + } | ||
| 2560 | + enc.literal(u32::from(transmitted[0]), 8); | ||
| 2561 | + if transmitted.len() == 1 { | ||
| 2562 | + return; | ||
| 2563 | + } | ||
| 2564 | + // The 2-bit `extra` the decoder adds to `bit_depth - 3`: the smallest one | ||
| 2565 | + // under which every delta still fits its (shrinking) width. `extra == 3` | ||
| 2566 | + // always works -- a delta can never exceed the range left -- so the | ||
| 2567 | + // search below always finds one. | ||
| 2568 | + let fits = |extra: u32| -> bool { | ||
| 2569 | + let mut bits = 5 + extra; | ||
| 2570 | + let mut range = 255i32 - i32::from(transmitted[0]); | ||
| 2571 | + for w in transmitted.windows(2) { | ||
| 2572 | + let delta = i32::from(w[1]) - i32::from(w[0]); | ||
| 2573 | + if delta - 1 >= (1i32 << bits) { | ||
| 2574 | + return false; | ||
| 2575 | + } | ||
| 2576 | + range -= delta; | ||
| 2577 | + bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); | ||
| 2578 | + } | ||
| 2579 | + true | ||
| 2580 | + }; | ||
| 2581 | + let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3); | ||
| 2582 | + enc.literal(extra, 2); | ||
| 2583 | + let mut bits = 5 + extra; | ||
| 2584 | + let mut range = 255i32 - i32::from(transmitted[0]); | ||
| 2585 | + for w in transmitted.windows(2) { | ||
| 2586 | + let delta = i32::from(w[1]) - i32::from(w[0]); | ||
| 2587 | + enc.literal((delta - 1) as u32, bits); | ||
| 2588 | + range -= delta; | ||
| 2589 | + bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); | ||
| 2590 | + } | ||
| 2591 | +} | ||
| 2592 | + | ||
| 2593 | +/// `write_palette_color_map` (bitstream.c), the write side of | ||
| 2594 | +/// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal, | ||
| 2595 | +/// each symbol written as the position its colour takes in the neighbour | ||
| 2596 | +/// ordering `av1_get_palette_color_index_context` hands back. | ||
| 2597 | +fn write_color_index_map( | ||
| 2598 | + enc: &mut SymbolEncoder, | ||
| 2599 | + idx_cdfs: &mut [[u16; 9]; 5], | ||
| 2600 | + map: &[u8], | ||
| 2601 | + side: usize, | ||
| 2602 | + n: usize, | ||
| 2603 | +) { | ||
| 2604 | + write_uniform(enc, usize::from(map[0]), n); | ||
| 2605 | + for i in 1..(2 * side - 1) { | ||
| 2606 | + for j in (i.saturating_sub(side - 1)..=i.min(side - 1)).rev() { | ||
| 2607 | + let (row, col) = (i - j, j); | ||
| 2608 | + let (ctx, color_order) = | ||
| 2609 | + crate::decode::palette_color_index_context(map, side, row, col, n); | ||
| 2610 | + let want = map[row * side + col]; | ||
| 2611 | + let symbol = color_order[..n] | ||
| 2612 | + .iter() | ||
| 2613 | + .position(|&c| c == want) | ||
| 2614 | + .expect("every colour index is in the block\'s own palette"); | ||
| 2615 | + enc.symbol(symbol, &mut idx_cdfs[ctx][..=n]); | ||
| 2616 | + } | ||
| 2617 | + } | ||
| 2618 | +} | ||
| 2619 | + | ||
| 2620 | +/// What one block's palette syntax costs, in bits: the `palette_y_mode` flag, | ||
| 2621 | +/// the size symbol, the colours and the whole colour-index map, priced | ||
| 2622 | +/// through the very writers above on a [`SymbolEncoder::pricer`] -- so the | ||
| 2623 | +/// search reads the rate the tile will really spend, not an estimate of it. | ||
| 2624 | +/// The neighbour cache is taken as empty (the search runs before the tile | ||
| 2625 | +/// knows what its neighbours will be), which only ever over-prices. | ||
| 2626 | +pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 { | ||
| 2627 | + let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else { | ||
| 2628 | + return f64::INFINITY; | ||
| 2629 | + }; | ||
| 2630 | + let n = usize::from(pal.size); | ||
| 2631 | + let mut enc = SymbolEncoder::pricer(); | ||
| 2632 | + let mut mode_cdf = cdf::PALETTE_Y_MODE[bsize_ctx][0]; | ||
| 2633 | + enc.symbol(1, &mut mode_cdf); | ||
| 2634 | + let mut size_cdf = cdf::PALETTE_Y_SIZE[bsize_ctx]; | ||
| 2635 | + enc.symbol(n - 2, &mut size_cdf); | ||
| 2636 | + write_palette_colors_y(&mut enc, &pal.colors[..n], &[]); | ||
| 2637 | + let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2]; | ||
| 2638 | + write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n); | ||
| 2639 | + enc.bits() | ||
| 2640 | +} | ||
| 2641 | + | ||
| 2371 | /// Writes everything a key frame's block carries before its coefficients: the | 2642 | /// Writes everything a key frame's block carries before its coefficients: the |
| 2372 | /// skip flag, its luma intra mode against the CDF its neighbours' modes pick, | 2643 | /// skip flag, its luma intra mode against the CDF its neighbours' modes pick, |
| 2373 | /// the angle a directional mode is steered by, and its chroma mode. Hands back | 2644 | /// the angle a directional mode is steered by, and its chroma mode. Hands back |
| @@ -2375,6 +2646,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( | |||
| 2375 | fn write_intra_mode( | 2646 | fn write_intra_mode( |
| 2376 | enc: &mut SymbolEncoder, | 2647 | enc: &mut SymbolEncoder, |
| 2377 | cdfs: &mut Cdfs, | 2648 | cdfs: &mut Cdfs, |
| 2649 | + neighbours: &mut Neighbours, | ||
| 2378 | block: &BlockCoeffs, | 2650 | block: &BlockCoeffs, |
| 2379 | above_mode: usize, | 2651 | above_mode: usize, |
| 2380 | left_mode: usize, | 2652 | left_mode: usize, |
| @@ -2382,6 +2654,9 @@ fn write_intra_mode( | |||
| 2382 | // This block's own position in 4x4 mode-info units, for the `cdef_idx` | 2654 | // This block's own position in 4x4 mode-info units, for the `cdef_idx` |
| 2383 | // literal that follows the `skip` symbol (see [`write_cdef_idx`]). | 2655 | // literal that follows the `skip` symbol (see [`write_cdef_idx`]). |
| 2384 | mi: (usize, usize), | 2656 | mi: (usize, usize), |
| 2657 | + // The block's side in samples, which gates the palette syntax below | ||
| 2658 | + // (`av1_allow_palette`, [`crate::decode::palette_bsize_ctx`]). | ||
| 2659 | + side: usize, | ||
| 2385 | ) -> usize { | 2660 | ) -> usize { |
| 2386 | let mode = usize::from(block.mode); | 2661 | let mode = usize::from(block.mode); |
| 2387 | enc.symbol(0, &mut cdfs.skip[0]); | 2662 | enc.symbol(0, &mut cdfs.skip[0]); |
| @@ -2407,9 +2682,89 @@ fn write_intra_mode( | |||
| 2407 | if (V_PRED..=D67_PRED).contains(&uv_mode) { | 2682 | if (V_PRED..=D67_PRED).contains(&uv_mode) { |
| 2408 | enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); | 2683 | enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); |
| 2409 | } | 2684 | } |
| 2685 | + // `read_palette_mode_info` (spec 5.11.46), mirrored symbol for symbol from | ||
| 2686 | + // the decoder's own read in `read_intra_mode`: on a frame whose header set | ||
| 2687 | + // `allow_screen_content_tools`, a `DC_PRED` luma block and a `UV_DC_PRED` | ||
| 2688 | + // chroma pair each carry a use-palette flag. Both contexts are 0 here -- | ||
| 2689 | + // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer | ||
| 2690 | + // codes none -- exactly the ctx-0 read the decoder does under the same | ||
| 2691 | + // condition. | ||
| 2692 | + write_palette_syntax(enc, cdfs, neighbours, block.palette.as_ref(), mode, uv_mode, mi, side); | ||
| 2410 | mode | 2693 | mode |
| 2411 | } | 2694 | } |
| 2412 | 2695 | ||
| 2696 | +/// `read_palette_mode_info` (spec 5.11.46) written out, mirrored symbol for | ||
| 2697 | +/// symbol from the decoder's own read in `read_intra_mode`: on a frame whose | ||
| 2698 | +/// header set `allow_screen_content_tools`, a `DC_PRED` luma block and a | ||
| 2699 | +/// `UV_DC_PRED` chroma pair each carry a use-palette flag, and a luma palette | ||
| 2700 | +/// then codes its size, its colours (against the neighbour colour cache) and | ||
| 2701 | +/// -- after the chroma flag, exactly where libaom's `av1_visit_palette` runs | ||
| 2702 | +/// -- its colour-index map. Shared by the key frame's [`write_intra_mode`] and | ||
| 2703 | +/// by the three intra arms of the inter-frame writers, which read the same | ||
| 2704 | +/// syntax back through `decode_inter_block`/`decode_intra_rect_in_inter`. | ||
| 2705 | +/// | ||
| 2706 | +/// The band publication is deferred to [`Neighbours::record_mi_planes`] (the | ||
| 2707 | +/// one point every block passes through), so a block that takes no palette | ||
| 2708 | +/// still clears what the column held. | ||
| 2709 | +#[allow(clippy::too_many_arguments)] | ||
| 2710 | +fn write_palette_syntax( | ||
| 2711 | + enc: &mut SymbolEncoder, | ||
| 2712 | + cdfs: &mut Cdfs, | ||
| 2713 | + neighbours: &mut Neighbours, | ||
| 2714 | + palette: Option<&PaletteY>, | ||
| 2715 | + mode: usize, | ||
| 2716 | + uv_mode: usize, | ||
| 2717 | + mi: (usize, usize), | ||
| 2718 | + side: usize, | ||
| 2719 | +) { | ||
| 2720 | + if !screen_armed() { | ||
| 2721 | + return; | ||
| 2722 | + } | ||
| 2723 | + let palette = palette.filter(|_| mode == DC_PRED); | ||
| 2724 | + if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) { | ||
| 2725 | + let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi); | ||
| 2726 | + if mode == DC_PRED { | ||
| 2727 | + enc.symbol( | ||
| 2728 | + usize::from(palette.is_some()), | ||
| 2729 | + &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx], | ||
| 2730 | + ); | ||
| 2731 | + } | ||
| 2732 | + if let Some(pal) = palette { | ||
| 2733 | + let n = usize::from(pal.size); | ||
| 2734 | + enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]); | ||
| 2735 | + write_palette_colors_y(enc, &pal.colors[..n], &cache); | ||
| 2736 | + } | ||
| 2737 | + if uv_mode == DC_PRED { | ||
| 2738 | + enc.symbol(0, &mut cdfs.palette_uv_mode[usize::from(palette.is_some())]); | ||
| 2739 | + } | ||
| 2740 | + if let Some(pal) = palette { | ||
| 2741 | + let n = usize::from(pal.size); | ||
| 2742 | + write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n); | ||
| 2743 | + note_palette(n); | ||
| 2744 | + } | ||
| 2745 | + } | ||
| 2746 | + neighbours.pending_palette = palette.map(|p| (p.size, p.colors)); | ||
| 2747 | +} | ||
| 2748 | + | ||
| 2749 | +/// How many blocks took a palette, and of what size -- the fire count a gate | ||
| 2750 | +/// prints so that "palette is on" is a measurement rather than a claim | ||
| 2751 | +/// (class `gate-blind-to-feature`). Index 0 is the block count, 2..=8 the | ||
| 2752 | +/// per-size histogram. | ||
| 2753 | +static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] = | ||
| 2754 | + [const { std::sync::atomic::AtomicUsize::new(0) }; 9]; | ||
| 2755 | + | ||
| 2756 | +fn note_palette(n: usize) { | ||
| 2757 | + PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 2758 | + PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 2759 | +} | ||
| 2760 | + | ||
| 2761 | +/// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to | ||
| 2762 | +/// its own encode. | ||
| 2763 | +#[cfg(test)] | ||
| 2764 | +pub(crate) fn take_palette_hits() -> [usize; 9] { | ||
| 2765 | + std::array::from_fn(|i| PALETTE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) | ||
| 2766 | +} | ||
| 2767 | + | ||
| 2413 | /// Writes one coded block: its mode, its three transform blocks, and what it | 2768 | /// Writes one coded block: its mode, its three transform blocks, and what it |
| 2414 | /// leaves behind for the blocks beside it. Its partition symbol is already | 2769 | /// leaves behind for the blocks beside it. Its partition symbol is already |
| 2415 | /// written, because only the caller knows what tree led here. | 2770 | /// written, because only the caller knows what tree led here. |
| @@ -2434,14 +2789,17 @@ fn write_block( | |||
| 2434 | ) -> Result<()> { | 2789 | ) -> Result<()> { |
| 2435 | let (r, c) = at; | 2790 | let (r, c) = at; |
| 2436 | let at_mi = (r * (SUB / MI), c * (SUB / MI)); | 2791 | let at_mi = (r * (SUB / MI), c * (SUB / MI)); |
| 2792 | + let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]); | ||
| 2437 | let mode = write_intra_mode( | 2793 | let mode = write_intra_mode( |
| 2438 | enc, | 2794 | enc, |
| 2439 | cdfs, | 2795 | cdfs, |
| 2796 | + neighbours, | ||
| 2440 | block, | 2797 | block, |
| 2441 | - neighbours.above_mode[c], | 2798 | + above_mode, |
| 2442 | - neighbours.left_mode[r], | 2799 | + left_mode, |
| 2443 | cfl, | 2800 | cfl, |
| 2444 | at_mi, | 2801 | at_mi, |
| 2802 | + side, | ||
| 2445 | ); | 2803 | ); |
| 2446 | let split = if tx_select { | 2804 | let split = if tx_select { |
| 2447 | let tx = write_luma_select( | 2805 | let tx = write_luma_select( |
| @@ -2516,7 +2874,7 @@ fn write_leaf8( | |||
| 2516 | // true first divergence (a differently-sized alphabet under the same | 2874 | // true first divergence (a differently-sized alphabet under the same |
| 2517 | // DC_PRED decision desyncs the coder even though the decoded mode is | 2875 | // DC_PRED decision desyncs the coder even though the decoded mode is |
| 2518 | // unchanged). | 2876 | // unchanged). |
| 2519 | - let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true, leaf_mi); | 2877 | + let mode = write_intra_mode(enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8); |
| 2520 | let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]; | 2878 | let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]; |
| 2521 | let split = if tx_select { | 2879 | let split = if tx_select { |
| 2522 | let tx = write_luma_select( | 2880 | let tx = write_luma_select( |
| @@ -4318,6 +4676,16 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( | |||
| 4318 | // Intra: no vote, but still a coded cell -- mvstack's | 4676 | // Intra: no vote, but still a coded cell -- mvstack's |
| 4319 | // extended-scan coverage must see it (module doc). | 4677 | // extended-scan coverage must see it (module doc). |
| 4320 | let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); | 4678 | let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); |
| 4679 | + write_palette_syntax( | ||
| 4680 | + &mut enc, | ||
| 4681 | + &mut cdfs, | ||
| 4682 | + &mut neighbours, | ||
| 4683 | + block.palette.as_ref(), | ||
| 4684 | + mode, | ||
| 4685 | + uv_mode, | ||
| 4686 | + (mi_row, mi_col), | ||
| 4687 | + BLOCK, | ||
| 4688 | + ); | ||
| 4321 | for dr in 0..8 { | 4689 | for dr in 0..8 { |
| 4322 | for dc in 0..8 { | 4690 | for dc in 0..8 { |
| 4323 | grid.set( | 4691 | grid.set( |
| @@ -4531,6 +4899,16 @@ fn write_inter_frame_leaf( | |||
| 4531 | // Intra: no vote, but still a coded cell -- mvstack's extended-scan | 4899 | // Intra: no vote, but still a coded cell -- mvstack's extended-scan |
| 4532 | // coverage must see it (module doc). | 4900 | // coverage must see it (module doc). |
| 4533 | let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); | 4901 | let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); |
| 4902 | + write_palette_syntax( | ||
| 4903 | + enc, | ||
| 4904 | + cdfs, | ||
| 4905 | + neighbours, | ||
| 4906 | + block.palette.as_ref(), | ||
| 4907 | + mode, | ||
| 4908 | + uv_mode, | ||
| 4909 | + (mi_row, mi_col), | ||
| 4910 | + SUB, | ||
| 4911 | + ); | ||
| 4534 | for dr in 0..SUB_MI as usize { | 4912 | for dr in 0..SUB_MI as usize { |
| 4535 | for dc in 0..SUB_MI as usize { | 4913 | for dc in 0..SUB_MI as usize { |
| 4536 | grid.set( | 4914 | grid.set( |
| @@ -4750,6 +5128,16 @@ fn write_inter_frame_leaf8( | |||
| 4750 | // Intra: no vote, but still a coded cell -- mvstack's extended-scan | 5128 | // Intra: no vote, but still a coded cell -- mvstack's extended-scan |
| 4751 | // coverage must see it (module doc). | 5129 | // coverage must see it (module doc). |
| 4752 | let (mi_row, mi_col) = leaf_mi; | 5130 | let (mi_row, mi_col) = leaf_mi; |
| 5131 | + write_palette_syntax( | ||
| 5132 | + enc, | ||
| 5133 | + cdfs, | ||
| 5134 | + neighbours, | ||
| 5135 | + block.palette.as_ref(), | ||
| 5136 | + mode, | ||
| 5137 | + uv_mode, | ||
| 5138 | + leaf_mi, | ||
| 5139 | + 8, | ||
| 5140 | + ); | ||
| 4753 | for dr in 0..2 { | 5141 | for dr in 0..2 { |
| 4754 | for dc in 0..2 { | 5142 | for dc in 0..2 { |
| 4755 | grid.set( | 5143 | grid.set( |