diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 00000000..ad84c55b --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,7 @@ +[target.x86_64-unknown-linux-gnu] +# Wrap every test/bin run in scripts/memguard-runner.sh so a runaway +# allocation gets killed inside its own cgroup instead of OOM-killing the +# machine. Located via `git rev-parse --show-toplevel` from the invoker's cwd +# (cargo does not resolve runner paths relative to this file, and an absolute +# path would break other worktree checkouts of this repo). +runner = ["bash", "-c", "root=$(git rev-parse --show-toplevel) && exec \"$root/scripts/memguard-runner.sh\" \"$@\"", "--"] diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index e9a66bad..c6841476 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -957,3 +957,239 @@ pub const INTRA_TX_TYPE_SET2_16: [[u16; 6]; 13] = [ [83, 5615, 12001, 17228, 32768, 0], [1968, 5556, 12023, 18547, 32768, 0], ]; + +// The inter-frame tables below (spec 9.4) support the syntax an inter block +// needs: whether it is coded as intra at all, which reference frame and +// motion vector it takes when it is not. Compound reference and compound +// prediction are not among them -- this encoder never sets +// `reference_select`, so their CDFs are never read. + +/// `Default_Intra_Inter_Cdf` (spec 9.4): whether an inter frame's block is +/// coded as intra, indexed by whether the block above and left are inter. +pub const INTRA_INTER: [[u16; 3]; 4] = [ + [806, 32768, 0], + [16662, 32768, 0], + [20186, 32768, 0], + [26538, 32768, 0], +]; + +/// `Default_Single_Ref_Cdf` (spec 9.4): the six binary decisions that narrow +/// an inter block's single reference frame down from the seven it can name, +/// indexed by the reference context of the blocks around it. +pub const SINGLE_REF: [[[u16; 3]; 6]; 3] = [ + [ + [4897, 32768, 0], + [1555, 32768, 0], + [4236, 32768, 0], + [8650, 32768, 0], + [904, 32768, 0], + [1444, 32768, 0], + ], + [ + [16973, 32768, 0], + [16751, 32768, 0], + [19647, 32768, 0], + [24773, 32768, 0], + [11014, 32768, 0], + [15087, 32768, 0], + ], + [ + [29744, 32768, 0], + [30279, 32768, 0], + [31194, 32768, 0], + [31895, 32768, 0], + [26875, 32768, 0], + [30304, 32768, 0], + ], +]; + +/// `Default_Y_Mode_Cdf` (spec 9.4): the thirteen luma intra modes of an inter +/// frame's intra block, indexed by the block's size group -- unlike a key +/// frame's [`KF_Y_MODE`], which is indexed by the neighbours' modes instead. +pub const Y_MODE: [[u16; 14]; 4] = [ + [ + 22801, 23489, 24293, 24756, 25601, 26123, 26606, 27418, 27945, 29228, 29685, 30349, 32768, + 0, + ], + [ + 18673, 19845, 22631, 23318, 23950, 24649, 25527, 27364, 28152, 29701, 29984, 30852, 32768, + 0, + ], + [ + 19770, 20979, 23396, 23939, 24241, 24654, 25136, 27073, 27830, 29360, 29730, 30659, 32768, + 0, + ], + [ + 20155, 21301, 22838, 23178, 23261, 23533, 23703, 24804, 25352, 26575, 27016, 28049, 32768, + 0, + ], +]; + +/// `Default_New_Mv_Cdf` (spec 9.4): whether an inter block's motion vector is +/// coded explicitly rather than taken from a neighbour, indexed by how many +/// neighbours already chose a new vector. +pub const NEW_MV: [[u16; 3]; 6] = [ + [24035, 32768, 0], + [16630, 32768, 0], + [15339, 32768, 0], + [8386, 32768, 0], + [12222, 32768, 0], + [4676, 32768, 0], +]; + +/// `Default_Zero_Mv_Cdf` (spec 9.4): whether an inter block's motion vector is +/// the zero vector, indexed by whether the block's global motion type is +/// identity. +pub const ZERO_MV: [[u16; 3]; 2] = [[2175, 32768, 0], [1054, 32768, 0]]; + +/// `Default_Ref_Mv_Cdf` (spec 9.4): which of the block's reference motion +/// vector candidates it takes, indexed by how many candidates are available. +pub const REF_MV: [[u16; 3]; 6] = [ + [23974, 32768, 0], + [24188, 32768, 0], + [17848, 32768, 0], + [28622, 32768, 0], + [24312, 32768, 0], + [19923, 32768, 0], +]; + +/// `Default_Drl_Mode_Cdf` (spec 9.4): the dynamic reference list index a +/// block's motion vector prediction is drawn from, indexed by the list's +/// context. +pub const DRL_MODE: [[u16; 3]; 3] = [[13104, 32768, 0], [24560, 32768, 0], [18945, 32768, 0]]; + +// The motion vector tables below (spec 9.4's `Default_Mv_*`) are the shared +// defaults for both components of a vector: [`crate::cdf_state::Cdfs`] holds +// one owned copy of each per component, seeded from the same constant here, +// since the spec's default state does not distinguish them -- only adaptation +// does, once a tile has coded a few vectors. + +/// `Default_Mv_Joint_Cdf` (spec 9.4): which of a motion vector's two +/// components change at all. +pub const MV_JOINT: [u16; 5] = [4096, 11264, 19328, 32768, 0]; + +/// `Default_Mv_Class_Cdf` (spec 9.4): the magnitude class of one motion +/// vector component. +pub const MV_CLASS: [u16; 12] = [ + 28672, 30976, 31858, 32320, 32551, 32656, 32740, 32757, 32762, 32767, 32768, 0, +]; + +/// `Default_Mv_Class0_Bit_Cdf` (spec 9.4): the integer bit of a small-class +/// motion vector's magnitude. +pub const MV_CLASS0_BIT: [u16; 3] = [27648, 32768, 0]; + +/// `Default_Mv_Class0_Fr_Cdf` (spec 9.4): the fractional part of a +/// small-class motion vector's magnitude, indexed by its integer bit. +pub const MV_CLASS0_FR: [[u16; 5]; 2] = [ + [16384, 24576, 26624, 32768, 0], + [12288, 21248, 24128, 32768, 0], +]; + +/// `Default_Mv_Class0_Hp_Cdf` (spec 9.4): the half-pel bit of a small-class +/// motion vector's magnitude. +pub const MV_CLASS0_HP: [u16; 3] = [20480, 32768, 0]; + +/// `Default_Mv_Bit_Cdf` (spec 9.4): one bit of a motion vector's integer +/// magnitude above the small-class range, indexed by the bit's position. +pub const MV_BIT: [[u16; 3]; 10] = [ + [17408, 32768, 0], + [17920, 32768, 0], + [18944, 32768, 0], + [20480, 32768, 0], + [22528, 32768, 0], + [24576, 32768, 0], + [28672, 32768, 0], + [29952, 32768, 0], + [29952, 32768, 0], + [30720, 32768, 0], +]; + +/// `Default_Mv_Fr_Cdf` (spec 9.4): the fractional part of a motion vector's +/// magnitude, outside the small-class range. +pub const MV_FR: [u16; 5] = [8192, 17408, 21248, 32768, 0]; + +/// `Default_Mv_Hp_Cdf` (spec 9.4): the half-pel bit of a motion vector's +/// magnitude, outside the small-class range. +pub const MV_HP: [u16; 3] = [16384, 32768, 0]; + +/// `Default_Mv_Sign_Cdf` (spec 9.4): the sign of a motion vector component. +pub const MV_SIGN: [u16; 3] = [16384, 32768, 0]; + +#[cfg(test)] +mod tests { + use super::*; + + /// Every row of a CDF table is non-decreasing and ends with the + /// alphabet's total (`32768`) followed by the adaptation counter (`0`), + /// which is the shape [`crate::msac`] expects to read. + fn assert_row_shape(row: &[u16]) { + assert_eq!(row[row.len() - 2], 32768, "row does not total 32768"); + assert_eq!(row[row.len() - 1], 0, "row's adaptation counter is not 0"); + for w in row[..row.len() - 1].windows(2) { + assert!(w[0] <= w[1], "row is not non-decreasing: {row:?}"); + } + } + + #[test] + fn inter_frame_tables_are_well_formed_cdfs() { + for row in INTRA_INTER { + assert_row_shape(&row); + } + for ctx in SINGLE_REF { + for row in ctx { + assert_row_shape(&row); + } + } + for row in Y_MODE { + assert_row_shape(&row); + } + for row in NEW_MV { + assert_row_shape(&row); + } + for row in ZERO_MV { + assert_row_shape(&row); + } + for row in REF_MV { + assert_row_shape(&row); + } + for row in DRL_MODE { + assert_row_shape(&row); + } + assert_row_shape(&MV_JOINT); + assert_row_shape(&MV_CLASS); + assert_row_shape(&MV_CLASS0_BIT); + for row in MV_CLASS0_FR { + assert_row_shape(&row); + } + assert_row_shape(&MV_CLASS0_HP); + for row in MV_BIT { + assert_row_shape(&row); + } + assert_row_shape(&MV_FR); + assert_row_shape(&MV_HP); + assert_row_shape(&MV_SIGN); + } + + /// Each table's row length matches the spec's symbol count for that + /// syntax element: two entries (total, counter) plus one fewer than the + /// alphabet. + #[test] + fn inter_frame_tables_have_the_spec_alphabet_size() { + assert_eq!(INTRA_INTER[0].len(), 2 + 1); // binary + assert_eq!(SINGLE_REF[0][0].len(), 2 + 1); // binary + assert_eq!(Y_MODE[0].len(), 2 + 13 - 1); // 13 luma intra modes + assert_eq!(NEW_MV[0].len(), 2 + 1); + assert_eq!(ZERO_MV[0].len(), 2 + 1); + assert_eq!(REF_MV[0].len(), 2 + 1); + assert_eq!(DRL_MODE[0].len(), 2 + 1); + assert_eq!(MV_JOINT.len(), 2 + 3); // MV_JOINTS = 4 + assert_eq!(MV_CLASS.len(), 2 + 10); // MV_CLASSES = 11 + assert_eq!(MV_CLASS0_BIT.len(), 2 + 1); + assert_eq!(MV_CLASS0_FR[0].len(), 2 + 3); // 4-way fraction + assert_eq!(MV_CLASS0_HP.len(), 2 + 1); + assert_eq!(MV_BIT[0].len(), 2 + 1); + assert_eq!(MV_FR.len(), 2 + 3); + assert_eq!(MV_HP.len(), 2 + 1); + assert_eq!(MV_SIGN.len(), 2 + 1); + } +} diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index bc78a083..171de5bb 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -146,6 +146,63 @@ pub(crate) struct Cdfs { pub intra_tx_type_16: [[u16; 6]; 13], /// The DC sign of a chroma coefficient, shared by both chroma sets. pub dc_sign_chroma: [[u16; 3]; 3], + /// Whether an inter frame's block is coded as intra. + pub intra_inter: [[u16; 3]; 4], + /// The six binary decisions of an inter block's single reference frame. + pub single_ref: [[[u16; 3]; 6]; 3], + /// The luma mode of an inter frame's intra block, by its size group. + pub y_mode: [[u16; 14]; 4], + /// Whether an inter block codes its motion vector explicitly. + pub new_mv: [[u16; 3]; 6], + /// Whether an inter block's motion vector is the zero vector. + pub zero_mv: [[u16; 3]; 2], + /// Which reference motion vector candidate an inter block takes. + pub ref_mv: [[u16; 3]; 6], + /// The dynamic reference list index of a motion vector prediction. + pub drl_mode: [[u16; 3]; 3], + /// A motion vector's joint (which components change), shared by both + /// components since it is read once per vector, not once per component. + pub mv_joint: [u16; 5], + /// The two motion vector components' own tables: separate owned state, + /// since spec 8.3.2 adapts one component without touching the other. + pub mv_comp: [MvComponentCdfs; 2], +} + +/// One motion vector component's adapting state (spec 9.4's `Default_Mv_*`, +/// held once per component so that adapting one leaves the other alone). +#[derive(Clone)] +pub(crate) struct MvComponentCdfs { + /// The magnitude class. + pub class: [u16; 12], + /// The integer bit of a small-class magnitude. + pub class0_bit: [u16; 3], + /// The fractional part of a small-class magnitude, by its integer bit. + pub class0_fr: [[u16; 5]; 2], + /// The half-pel bit of a small-class magnitude. + pub class0_hp: [u16; 3], + /// One bit of an above-small-class magnitude, by its position. + pub bit: [[u16; 3]; 10], + /// The fractional part of an above-small-class magnitude. + pub fr: [u16; 5], + /// The half-pel bit of an above-small-class magnitude. + pub hp: [u16; 3], + /// The component's sign. + pub sign: [u16; 3], +} + +impl MvComponentCdfs { + fn new() -> MvComponentCdfs { + MvComponentCdfs { + class: cdf::MV_CLASS, + class0_bit: cdf::MV_CLASS0_BIT, + class0_fr: cdf::MV_CLASS0_FR, + class0_hp: cdf::MV_CLASS0_HP, + bit: cdf::MV_BIT, + fr: cdf::MV_FR, + hp: cdf::MV_HP, + sign: cdf::MV_SIGN, + } + } } impl Cdfs { @@ -199,6 +256,15 @@ impl Cdfs { dc_sign_luma: cdf::DC_SIGN_LUMA, intra_tx_type_16: cdf::INTRA_TX_TYPE_SET2_16, dc_sign_chroma: cdf::DC_SIGN_CHROMA, + intra_inter: cdf::INTRA_INTER, + single_ref: cdf::SINGLE_REF, + y_mode: cdf::Y_MODE, + new_mv: cdf::NEW_MV, + zero_mv: cdf::ZERO_MV, + ref_mv: cdf::REF_MV, + drl_mode: cdf::DRL_MODE, + mv_joint: cdf::MV_JOINT, + mv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()], } } @@ -328,5 +394,29 @@ mod tests { cdf::EOB_EXTRA_CHROMA_16[2] ); assert_eq!(cdfs.partition_w64[2], cdf::PARTITION_W64[2]); + assert_eq!(cdfs.intra_inter, cdf::INTRA_INTER); + assert_eq!(cdfs.single_ref, cdf::SINGLE_REF); + assert_eq!(cdfs.y_mode, cdf::Y_MODE); + assert_eq!(cdfs.new_mv, cdf::NEW_MV); + assert_eq!(cdfs.zero_mv, cdf::ZERO_MV); + assert_eq!(cdfs.ref_mv, cdf::REF_MV); + assert_eq!(cdfs.drl_mode, cdf::DRL_MODE); + assert_eq!(cdfs.mv_joint, cdf::MV_JOINT); + assert_eq!(cdfs.mv_comp[0].class, cdf::MV_CLASS); + assert_eq!(cdfs.mv_comp[1].sign, cdf::MV_SIGN); + } + + /// A motion vector's two components are separate owned tables: adapting + /// one component's CDFs must not be visible through the other, the same + /// hazard the coefficient sets guard against above. + #[test] + fn the_mv_components_are_separate_and_do_not_share_adaptation() { + let mut cdfs = Cdfs::new(); + cdfs.mv_comp[0].class[0] = 1; + cdfs.mv_comp[0].bit[3][0] = 2; + assert_ne!(cdfs.mv_comp[1].class[0], 1); + assert_ne!(cdfs.mv_comp[1].bit[3][0], 2); + assert_eq!(cdfs.mv_comp[1].class[0], cdf::MV_CLASS[0]); + assert_eq!(cdfs.mv_comp[1].bit[3][0], cdf::MV_BIT[3][0]); } } diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 7361177a..e5e5371a 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -256,6 +256,43 @@ pub fn key_frame_headers( Ok((seq, header)) } +/// The frame header for a shown inter frame that predicts from the single +/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that +/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s, +/// reused verbatim: an inter frame never changes the sequence. +/// +/// # Errors +/// Returns an error under the same conditions as [`key_frame_headers`]. +pub fn inter_frame_headers( + width: usize, + height: usize, + base_q_idx: u8, + order_hint: u32, + last_slot: u8, +) -> Result<(SequenceHeader, FrameHeader)> { + let (seq, key) = key_frame_headers(width, height, base_q_idx)?; + let header = FrameHeader { + frame_type: FrameType::Inter, + frame_is_intra: false, + show_frame: true, + error_resilient_mode: false, + disable_cdf_update: false, + disable_frame_end_update_cdf: true, + force_integer_mv: false, + order_hint, + primary_ref_frame: 0, + refresh_frame_flags: 1 << last_slot, + ref_frame_idx: [last_slot; ec_av1_syntax::REFS_PER_FRAME], + allow_high_precision_mv: false, + interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap, + is_motion_mode_switchable: false, + use_ref_frame_mvs: false, + reduced_tx_set: false, + ..key + }; + Ok((seq, header)) +} + fn too_large() -> Error { Error::unsupported( "AV1 encode", diff --git a/crates/ec-av1/src/frame.rs b/crates/ec-av1/src/frame.rs index 997e5c64..4b56b1c8 100644 --- a/crates/ec-av1/src/frame.rs +++ b/crates/ec-av1/src/frame.rs @@ -1,18 +1,21 @@ -//! The frame header OBU (spec 5.9), for shown key frames. +//! The frame header OBU (spec 5.9), for shown key and inter frames. //! //! Every writer here is the bit-exact inverse of the matching reader in //! [`ec_av1_syntax::frame`], and the tests prove it by parsing back what they -//! wrote. The subset is the one a stateless hardware encoder needs: a key frame -//! that is shown, in a sequence with no decoder model, no frame ids and no -//! still-picture shortcut. Everything outside it is refused by name rather than -//! written wrong — superres with a denominator other than 8, film grain -//! synthesis, non-uniform tile spacing, and every non-key or hidden frame. +//! wrote. The subset is the one a stateless hardware encoder needs: a key or +//! inter frame that is shown, in a sequence with no decoder model, no frame +//! ids and no still-picture shortcut. Everything outside it is refused by name +//! rather than written wrong — superres with a denominator other than 8, film +//! grain synthesis, non-uniform tile spacing, every hidden frame, short +//! reference signalling, non-identity global motion, and compound reference +//! selection (with the skip mode and warped motion it would gate). use ec_av1_syntax::obu::{ObuHeader, ObuType, tile_log2}; use ec_av1_syntax::sequence::{SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS, SequenceHeader}; use ec_av1_syntax::{ - FrameHeader, FrameType, MAX_SEGMENTS, MAX_TILE_AREA, MAX_TILE_COLS, MAX_TILE_ROWS, - MAX_TILE_WIDTH, PRIMARY_REF_NONE, RestorationType, SEG_LVL_MAX, TOTAL_REFS_PER_FRAME, TxMode, + FrameHeader, FrameType, InterpolationFilter, MAX_SEGMENTS, MAX_TILE_AREA, MAX_TILE_COLS, + MAX_TILE_ROWS, MAX_TILE_WIDTH, PRIMARY_REF_NONE, REFS_PER_FRAME, RestorationType, SEG_LVL_MAX, + TOTAL_REFS_PER_FRAME, TxMode, WarpModel, }; use ec_core::{BitWriter, Error, Result}; @@ -295,14 +298,47 @@ fn write_lr_params(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader, all } } -/// `uncompressed_header()` (spec 5.9.2) for a shown key frame. +/// `frame_size()` + `render_size()` (spec 5.9.5, 5.9.6), shared by the intra +/// and inter paths: this writer never overrides the size mid-stream +/// (`frame_size_with_refs`, spec 5.9.7, is not written). +fn write_frame_size(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) -> Result<()> { + if h.frame_size_override_flag { + w.write_bits(h.frame_width - 1, seq.frame_width_bits); + w.write_bits(h.frame_height - 1, seq.frame_height_bits); + } + if seq.enable_superres { + w.write_bit(h.use_superres); + } + if h.use_superres || h.superres_denom != 8 { + return Err(Error::unsupported( + "AV1 superres", + "only a superres denominator of 8 (no scaling) is written", + )); + } + let render_differs = h.render_width != h.upscaled_width || h.render_height != h.frame_height; + w.write_bit(render_differs); + if render_differs { + w.write_bits(h.render_width - 1, 16); + w.write_bits(h.render_height - 1, 16); + } + Ok(()) +} + +/// `uncompressed_header()` (spec 5.9.2) for a shown key or inter frame: no +/// decoder model, no frame ids, no still-picture shortcut, and (for an inter +/// frame) short reference signalling, non-identity global motion, compound +/// reference selection and warped motion are all refused rather than written. pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) -> Result<()> { - if h.frame_type != FrameType::Key || !h.show_frame || h.show_existing_frame { + if !matches!(h.frame_type, FrameType::Key | FrameType::Inter) + || !h.show_frame + || h.show_existing_frame + { return Err(Error::unsupported( "AV1 frame header", - "only a shown key frame is written", + "only a shown key or inter frame is written", )); } + let is_key = h.frame_type == FrameType::Key; if seq.reduced_still_picture_header { return Err(Error::unsupported( "AV1 frame header", @@ -323,9 +359,14 @@ pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHead } w.write_bit(false); // show_existing_frame - w.write_bits(0, 2); // frame_type: KEY_FRAME + w.write_bits(if is_key { 0 } else { 1 }, 2); // frame_type w.write_bit(true); // show_frame - // showable_frame and error_resilient_mode are forced for a shown key frame. + // showable_frame is derived by the reader when show_frame is set, and not coded. + if is_key { + // error_resilient_mode is forced true for a shown key frame. + } else { + w.write_bit(h.error_resilient_mode); + } w.write_bit(h.disable_cdf_update); if seq.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS { @@ -342,34 +383,72 @@ pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHead } w.write_bit(h.frame_size_override_flag); w.write_bits(h.order_hint, seq.order_hint_bits); - // primary_ref_frame, buffer_removal_time, refresh_frame_flags and the - // ref_order_hint loop are all forced for a shown key frame. - if h.frame_size_override_flag { - w.write_bits(h.frame_width - 1, seq.frame_width_bits); - w.write_bits(h.frame_height - 1, seq.frame_height_bits); - } - if seq.enable_superres { - w.write_bit(h.use_superres); + if h.frame_is_intra || h.error_resilient_mode { + // primary_ref_frame is forced PRIMARY_REF_NONE and not coded. + } else { + w.write_bits(u32::from(h.primary_ref_frame), 3); } - if h.use_superres || h.superres_denom != 8 { - return Err(Error::unsupported( - "AV1 superres", - "only a superres denominator of 8 (no scaling) is written", - )); + // buffer_removal_time is not coded: decoder_model_info is refused above. + + if is_key { + // refresh_frame_flags is forced to every slot for a shown key frame. + } else { + w.write_bits(u32::from(h.refresh_frame_flags), 8); } - let render_differs = h.render_width != h.upscaled_width || h.render_height != h.frame_height; - w.write_bit(render_differs); - if render_differs { - w.write_bits(h.render_width - 1, 16); - w.write_bits(h.render_height - 1, 16); + if (!h.frame_is_intra || h.refresh_frame_flags != u8::MAX) + && h.error_resilient_mode + && seq.enable_order_hint + { + for hint in h.ref_order_hint { + w.write_bits(hint, seq.order_hint_bits); + } } - if h.allow_screen_content_tools && h.upscaled_width == h.frame_width { - w.write_bit(h.allow_intrabc); + + if h.frame_is_intra { + write_frame_size(w, seq, h)?; + if h.allow_screen_content_tools && h.upscaled_width == h.frame_width { + w.write_bit(h.allow_intrabc); + } + } else { + w.write_bit(h.frame_refs_short_signaling); + if h.frame_refs_short_signaling { + return Err(Error::unsupported( + "AV1 frame header", + "short reference frame signalling is not written", + )); + } + for &idx in &h.ref_frame_idx[..REFS_PER_FRAME] { + w.write_bits(u32::from(idx), 3); + } + if h.frame_size_override_flag && !h.error_resilient_mode { + return Err(Error::unsupported( + "AV1 frame header", + "frame_size_with_refs is not written", + )); + } + write_frame_size(w, seq, h)?; + + w.write_bit(h.allow_high_precision_mv); // force_integer_mv is false here + if h.interpolation_filter == InterpolationFilter::Switchable { + w.write_bit(true); + } else { + w.write_bit(false); + w.write_bits(h.interpolation_filter as u32, 2); + } + w.write_bit(h.is_motion_mode_switchable); + if h.error_resilient_mode || !seq.enable_ref_frame_mvs { + // use_ref_frame_mvs is forced false and not coded. + } else { + w.write_bit(h.use_ref_frame_mvs); + } + // OrderHints and RefFrameSignBias are derived from decoder state, not coded. } + if !h.disable_cdf_update { w.write_bit(h.disable_frame_end_update_cdf); } + // disable_frame_end_update_cdf is forced true when disable_cdf_update is set. write_tile_info(w, seq, h)?; write_quantization_params(w, seq, h); @@ -402,8 +481,35 @@ pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHead } else { w.write_bit(h.tx_mode == TxMode::Select); } - // reference_select, skip mode and warped motion are all forced for intra. + if h.frame_is_intra { + // reference_select is forced false and not coded. + } else if h.reference_select { + return Err(Error::unsupported( + "AV1 frame header", + "reference_select (and the skip mode it gates) is not written", + )); + } else { + w.write_bit(false); + // skip_mode_present is forced false when reference_select is false + // (spec 5.9.22), and not coded. + } + if h.frame_is_intra || h.error_resilient_mode || !seq.enable_warped_motion { + // allow_warped_motion is forced false and not coded. + } else { + w.write_bit(h.allow_warped_motion); + } w.write_bit(h.reduced_tx_set); + if !h.frame_is_intra { + for warp in &h.global_motion[..REFS_PER_FRAME] { + if warp.model != WarpModel::Identity { + return Err(Error::unsupported( + "AV1 global motion", + "only the identity model is written", + )); + } + w.write_bit(false); // is_global + } + } // Global motion is the identity for intra and is not coded. if seq.film_grain_params_present { w.write_bit(h.film_grain.apply_grain); @@ -624,9 +730,13 @@ mod tests { fn unsupported_frames_are_refused_by_name() { let seq = sample_1080p(); - let mut inter = sample_key_frame(); - inter.frame_type = FrameType::Inter; - assert!(frame_obu(&seq, &inter, &[0x00]).is_err()); + let mut intra_only = sample_key_frame(); + intra_only.frame_type = FrameType::IntraOnly; + assert!(frame_obu(&seq, &intra_only, &[0x00]).is_err()); + + let mut switch = sample_key_frame(); + switch.frame_type = FrameType::Switch; + assert!(frame_obu(&seq, &switch, &[0x00]).is_err()); let mut hidden = sample_key_frame(); hidden.show_frame = false; @@ -646,4 +756,55 @@ mod tests { grain_frame.film_grain.apply_grain = true; assert!(frame_obu(&grainy, &grain_frame, &[0x00]).is_err()); } + + /// A key frame followed by two inter frames, all referencing the single + /// slot the key frame filled: every field the parser hands back, parsed + /// through [`ec_av1_syntax::Av1Parser`]'s own `FrameState` threading, must + /// equal what was asked to be written, and the header must consume + /// exactly the bit count the writer produced (a shifted field would still + /// often parse to *some* value, but not to the same bit length). + #[test] + fn key_and_inter_frames_roundtrip() { + let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap(); + let (seq_again, inter1) = crate::encode::inter_frame_headers(64, 64, 100, 1, 0).unwrap(); + assert_eq!( + seq, seq_again, + "an inter frame must reuse the sequence header verbatim" + ); + let (_, inter2) = crate::encode::inter_frame_headers(64, 64, 100, 2, 0).unwrap(); + + let mut stream = sequence_header_obu(&seq).unwrap(); + stream.extend_from_slice(&frame_obu(&seq, &key, &[0xAA]).unwrap()); + stream.extend_from_slice(&frame_obu(&seq, &inter1, &[0xBB]).unwrap()); + stream.extend_from_slice(&frame_obu(&seq, &inter2, &[0xCC]).unwrap()); + + let mut parser = Av1Parser::new(); + let obus = parser.parse_temporal_unit(&stream).unwrap(); + assert_eq!(obus.len(), 4); + + for (obu, expected) in obus[1..].iter().zip([&key, &inter1, &inter2]) { + let ObuKind::Frame(parsed, _tiles) = &obu.kind else { + panic!("expected an OBU_FRAME, got {:?}", obu.kind); + }; + + let mut w = BitWriter::new(); + write_frame_header(&mut w, &seq, expected).unwrap(); + assert_eq!( + parsed.header_bits, + w.bit_len(), + "the header must consume exactly the bits it was written with" + ); + + // showable_frame, OrderHints, RefFrameSignBias and header_bits are + // all derived by the reader (spec 5.9.2, 7.8) rather than coded; + // the writer does not fill them in, so they are taken from the + // parse before the rest of the header is compared field by field. + let mut expected = expected.clone(); + expected.showable_frame = parsed.showable_frame; + expected.order_hints = parsed.order_hints; + expected.ref_frame_sign_bias = parsed.ref_frame_sign_bias; + expected.header_bits = parsed.header_bits; + assert_eq!(**parsed, expected); + } + } } diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 0d8e4e1e..e3eab570 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -18,7 +18,9 @@ mod cdf_state; pub mod encode; pub mod frame; pub mod intra; +pub mod mc; pub mod msac; +pub mod mvstack; pub mod obu; pub mod quant; pub mod sequence; diff --git a/crates/ec-av1/src/mc.rs b/crates/ec-av1/src/mc.rs new file mode 100644 index 00000000..a37630f2 --- /dev/null +++ b/crates/ec-av1/src/mc.rs @@ -0,0 +1,304 @@ +//! Sub-pel motion compensation, spec 7.11.3 ("Motion vector scaling process" +//! through "Block inter predictor process"), the REGULAR (`EIGHTTAP`) filter +//! only, 8-bit samples only. +//! +//! A block's inter prediction is separable: an 8-tap horizontal pass over the +//! reference, rounded down by `InterRound0`, feeds an 8-tap vertical pass +//! over that intermediate, rounded down by `InterRound1`. Both fractions run +//! in 1/16-pel steps -- luma motion vectors are stored at 1/8-pel and always +//! land on an even step; chroma vectors, once scaled for subsampling, can +//! land on any of the 16. + +/// `Round2` (spec 4.7): halves round up. +fn round2(value: i32, shift: u32) -> i32 { + if shift == 0 { + value + } else { + (value + (1 << (shift - 1))) >> shift + } +} + +/// `InterRound0` (spec 7.11.3.2), 8-bit, non-compound: the shift the +/// horizontal pass's sum is brought down by before it is stored as the +/// intermediate. +const INTER_ROUND_0: u32 = 3; +/// `InterRound1` (spec 7.11.3.2), 8-bit, non-compound: the shift the vertical +/// pass's sum is brought down by to land back on an 8-bit sample. Composed +/// with `INTER_ROUND_0` the two shifts are the filter's own gain (each pass +/// sums to 128, `128 * 128 == 1 << 14 == 1 << (INTER_ROUND_0 + INTER_ROUND_1)`) +/// -- so an identity or DC input comes back exactly, by construction of the +/// table rather than by a fitted constant. +const INTER_ROUND_1: u32 = 11; + +/// `Subpel_Filters[EIGHTTAP]` (spec 7.11.3.3): 16 rows, one per 1/16-pel +/// fraction, each an 8-tap kernel centred so tap index 3 lands on the integer +/// sample (fraction 0 is the identity tap `[.., 128, ..]`). +const SUBPEL_FILTERS: [[i32; 8]; 16] = [ + [0, 0, 0, 128, 0, 0, 0, 0], + [0, 2, -6, 126, 8, -2, 0, 0], + [0, 2, -10, 122, 18, -4, 0, 0], + [0, 2, -12, 116, 28, -8, 2, 0], + [0, 2, -14, 110, 38, -10, 2, 0], + [0, 2, -14, 102, 48, -12, 2, 0], + [0, 2, -16, 94, 58, -12, 2, 0], + [0, 2, -14, 84, 66, -12, 2, 0], + [0, 2, -14, 76, 76, -14, 2, 0], + [0, 2, -12, 66, 84, -14, 2, 0], + [0, 2, -12, 58, 94, -16, 2, 0], + [0, 2, -12, 48, 102, -14, 2, 0], + [0, 2, -10, 38, 110, -14, 2, 0], + [0, 2, -8, 28, 116, -12, 2, 0], + [0, 0, -4, 18, 122, -10, 2, 0], + [0, 0, -2, 8, 126, -6, 2, 0], +]; + +/// A reference sample at `(x, y)`, clamped to the plane's bounds (spec +/// 7.11.3.4's `Clip3` against the frame's edges) rather than read out of +/// range -- a motion vector that points past the frame repeats the edge +/// sample instead of panicking. +fn sample(reference: &[u8], ref_width: usize, ref_height: usize, x: i32, y: i32) -> i32 { + let cx = x.clamp(0, ref_width as i32 - 1) as usize; + let cy = y.clamp(0, ref_height as i32 - 1) as usize; + i32::from(reference[cy * ref_width + cx]) +} + +/// Predicts one `block_w * block_h` block into `dst`, row-major, from +/// `reference` (row-major, `ref_width * ref_height`, stride `ref_width`). +/// +/// `x_q4` / `y_q4` are the block's top-left position in the reference, in +/// 1/16-pel units (an integer MV has its low 4 bits zero); this function +/// splits each into its whole-sample part and its 0..16 fraction itself, so +/// the caller need not pre-split a motion vector. +/// +/// # Panics +/// Panics when `dst` is not `block_w * block_h` long, or the reference is +/// empty. +#[allow(clippy::too_many_arguments)] // one reference plane, one position, one block shape +pub fn predict( + reference: &[u8], + ref_width: usize, + ref_height: usize, + x_q4: i32, + y_q4: i32, + block_w: usize, + block_h: usize, + dst: &mut [u8], +) { + assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); + assert!(!reference.is_empty(), "a reference plane has samples"); + + let x0 = x_q4.div_euclid(16); + let xfrac = x_q4.rem_euclid(16) as usize; + let y0 = y_q4.div_euclid(16); + let yfrac = y_q4.rem_euclid(16) as usize; + + let h_filter = &SUBPEL_FILTERS[xfrac]; + let v_filter = &SUBPEL_FILTERS[yfrac]; + + // The vertical pass reads 3 rows above and 4 below the block, so the + // horizontal pass must produce that many extra intermediate rows. + let rows = block_h + 7; + let mut intermediate = vec![0i32; rows * block_w]; + for r in 0..rows { + let y = y0 - 3 + r as i32; + for c in 0..block_w { + let mut sum = 0; + for (t, &tap) in h_filter.iter().enumerate() { + let x = x0 + c as i32 + t as i32 - 3; + sum += tap * sample(reference, ref_width, ref_height, x, y); + } + intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0); + } + } + + for row in 0..block_h { + for col in 0..block_w { + let mut sum = 0; + for (t, &tap) in v_filter.iter().enumerate() { + sum += tap * intermediate[(row + t) * block_w + col]; + } + dst[row * block_w + col] = round2(sum, INTER_ROUND_1).clamp(0, 255) as u8; + } + } +} + +#[cfg(test)] +mod tests { + use super::predict; + + #[test] + fn integer_mv_is_identity() { + let width = 12; + let height = 12; + let reference: Vec = (0..width * height).map(|i| (i * 7 % 251) as u8).collect(); + let mut dst = vec![0u8; 6 * 6]; + predict(&reference, width, height, 3 * 16, 4 * 16, 6, 6, &mut dst); + for row in 0..6 { + for col in 0..6 { + assert_eq!( + dst[row * 6 + col], + reference[(4 + row) * width + 3 + col], + "integer MV must reproduce the reference block byte-for-byte" + ); + } + } + } + + #[test] + fn half_pel_reproduces_the_ramp_midpoint() { + // Step 2 so every half-pel position lands on an exact integer. + let width = 16; + let height = 16; + let reference: Vec = (0..width * height) + .map(|i| (2 * (i % width)) as u8) + .collect(); + let mut dst = vec![0u8; 4 * 4]; + // Half-pel in x only: fraction 8/16, integer part at column 5. + predict( + &reference, + width, + height, + 5 * 16 + 8, + 5 * 16, + 4, + 4, + &mut dst, + ); + for row in 0..4 { + for col in 0..4 { + let midpoint = 2 * (5 + col) + 1; // halfway between col and col+1 + assert_eq!( + dst[row * 4 + col] as i32, + midpoint as i32, + "half-pel MV over a linear ramp must land exactly on the midpoint" + ); + } + } + } + + #[test] + fn constant_plane_has_unit_dc_gain_at_every_subpel_position() { + let width = 20; + let height = 20; + let reference = vec![142u8; width * height]; + for yfrac in 0..16 { + for xfrac in 0..16 { + let mut dst = vec![0u8; 5 * 5]; + predict( + &reference, + width, + height, + 5 * 16 + xfrac, + 5 * 16 + yfrac, + 5, + 5, + &mut dst, + ); + assert!( + dst.iter().all(|&v| v == 142), + "DC gain must be exactly 1 at fraction ({xfrac}, {yfrac}), got {dst:?}" + ); + } + } + } + + #[test] + fn horizontal_and_vertical_only_filtering_differ() { + // A plane linear in both x and y with different, even coefficients so + // each axis's half-pel interpolation lands on an exact integer: this + // pins the actual value each pass produces, not just that the two + // differ, so swapping which pass reads which axis is caught even if + // it happened to produce two merely-different numbers. + let width = 10; + let height = 10; + let reference: Vec = (0..height) + .flat_map(|y| (0..width).map(move |x| (20 * x + 4 * y) as u8)) + .collect(); + + let mut horiz = vec![0u8; 4 * 4]; + predict( + &reference, + width, + height, + 3 * 16 + 8, + 3 * 16, + 4, + 4, + &mut horiz, + ); + let mut vert = vec![0u8; 4 * 4]; + predict( + &reference, + width, + height, + 3 * 16, + 3 * 16 + 8, + 4, + 4, + &mut vert, + ); + + for row in 0..4 { + for col in 0..4 { + // Horizontal half-pel: x interpolates to x0+col+0.5, y stays put. + assert_eq!( + horiz[row * 4 + col] as i32, + 20 * (3 + col as i32) + 10 + 4 * (3 + row as i32), + "horizontal-only MV must interpolate along x only" + ); + // Vertical half-pel: y interpolates to y0+row+0.5, x stays put. + assert_eq!( + vert[row * 4 + col] as i32, + 20 * (3 + col as i32) + 4 * (3 + row as i32) + 2, + "vertical-only MV must interpolate along y only" + ); + } + } + assert_ne!( + horiz, vert, + "horizontal-only and vertical-only sub-pel MVs must give different outputs" + ); + } + + #[test] + fn mv_past_the_edge_clamps_instead_of_panicking() { + let width = 8; + let height = 8; + let reference: Vec = (0..width * height).map(|i| (i * 3 % 200) as u8).collect(); + let mut dst = vec![0u8; 4 * 4]; + // Whole-sample position far above and to the left of the plane, with + // an odd fraction so both filter passes exercise the clamp. + predict( + &reference, + width, + height, + -50 * 16 + 5, + -50 * 16 + 5, + 4, + 4, + &mut dst, + ); + let expected = reference[0]; // the whole plane clamps to the top-left corner + assert!( + dst.iter().all(|&v| v == expected), + "an MV past the top-left edge must clamp to the corner sample, got {dst:?}" + ); + + let mut dst2 = vec![0u8; 4 * 4]; + predict( + &reference, + width, + height, + 50 * 16 + 5, + 50 * 16 + 5, + 4, + 4, + &mut dst2, + ); + let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner + assert!( + dst2.iter().all(|&v| v == expected2), + "an MV past the bottom-right edge must clamp to the corner sample, got {dst2:?}" + ); + } +} diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs new file mode 100644 index 00000000..752e545f --- /dev/null +++ b/crates/ec-av1/src/mvstack.rs @@ -0,0 +1,399 @@ +//! Reference MV list construction (AV1 spec 7.10.2, `find_mv_stack`), +//! reduced to the single-reference, non-compound, `use_ref_frame_mvs = 0` +//! case a key/inter frame without temporal MV projection needs. +//! +//! Implemented from the spec: the row-above scan (7.10.2.2), the col-left +//! scan (7.10.2.3), a single top-right probe (the first of 7.10.2.4's extra +//! positions), weight-based dedupe (7.10.2.5's `add_ref_mv_candidate`), the +//! weight-descending sort (7.10.2.6), and the DRL context derivation from +//! `REF_CAT_LEVEL` (7.10.2.8, the one piece of that section whose constant +//! and shape is unambiguous from the spec text). +//! +//! Deliberately reduced away (see the crate report, not reproduced bit-exact +//! here): compound/multi-reference candidates, the temporal MV projection +//! scan, the `>1` row/col scans at offset 3 and their skip-by-block-size +//! stepping, and the exact `NewMvContext`/`RefMvContext`/`ZeroMvContext` +//! tables — spec 7.10.2.8 derives those through several more match classes +//! than this reduction tracks, and nothing in this crate consumes them yet +//! (no CDF wiring), so the formulas below are a documented, monotonic +//! stand-in rather than a proven port. Also reduced away: clamping +//! `NearestMv`/`NearMv`/`PredMv` to the frame's allowed MV range +//! (7.10.2.14) — the caller gets unclamped values. + +/// One 4x4 `mi` unit's motion state, as the encode loop will have filled it +/// in by the time it asks for a block's MV stack. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MiInfo { + /// Whether this unit was coded inter (as opposed to intra). + pub is_inter: bool, + /// The single reference frame this unit's MV points into. Ignored (and + /// the unit contributes no candidate) when `is_inter` is `false`. + pub ref_frame: i8, + /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units. + pub mv: (i32, i32), +} + +/// The whole frame's `mi` grid, one [`MiInfo`] per 4x4 unit, in raster order. +/// A unit an encode pass hasn't visited yet (or that sits outside the tile) +/// reads as `None` and contributes nothing to any block's MV stack. +#[derive(Clone, Debug)] +pub struct MiGrid { + cols: usize, + rows: usize, + cells: Vec>, +} + +impl MiGrid { + /// A grid of `cols` by `rows` 4x4 units, all initially unset. + pub fn new(cols: usize, rows: usize) -> Self { + Self { + cols, + rows, + cells: vec![None; cols * rows], + } + } + + /// Records the unit at `(row, col)`. Out-of-range coordinates are a + /// no-op — the caller only ever addresses units inside the grid it built. + pub fn set(&mut self, row: usize, col: usize, info: MiInfo) { + if row < self.rows && col < self.cols { + self.cells[row * self.cols + col] = Some(info); + } + } + + /// The unit at `(row, col)`, or `None` when it is outside the grid (the + /// tile) or hasn't been coded. + pub fn get(&self, row: usize, col: usize) -> Option<&MiInfo> { + if row < self.rows && col < self.cols { + self.cells[row * self.cols + col].as_ref() + } else { + None + } + } +} + +/// One entry of the reference MV stack: a candidate motion vector and the +/// total weight the neighbours that agreed on it contributed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StackEntry { + /// The candidate `(row, col)` motion vector. + pub mv: (i32, i32), + /// The summed weight of every neighbour cell that voted for this MV. + pub weight: u32, +} + +/// The result of [`find_mv_stack`]: the sorted candidate list, the two +/// predictors a `NEARESTMV`/`NEARMV` block reads from it, the predictor a +/// `NEWMV` residual is coded against, and the symbol contexts the block's +/// mode and DRL-index syntax elements are coded with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MvStack { + /// The candidates, highest weight first (ties keep scan order: above, + /// then left, then top-right). + pub entries: Vec, + /// `RefStackMv[0]`, or `(0, 0)` when the stack is empty. + pub nearest_mv: (i32, i32), + /// `RefStackMv[1]`, or `(0, 0)` when the stack has fewer than two + /// entries. + pub near_mv: (i32, i32), + /// The predictor a `NEWMV` block's MV difference is coded against: + /// `nearest_mv` when the stack is non-empty, `(0, 0)` otherwise. + pub pred_mv: (i32, i32), + /// Context for the `new_mv` symbol. + pub new_mv_ctx: usize, + /// Context for the `ref_mv` symbol. + pub ref_mv_ctx: usize, + /// Context for the `zero_mv` symbol. + pub zero_mv_ctx: usize, + /// Context for each `drl_mode` symbol between consecutive stack + /// entries, `entries.len().saturating_sub(1)` long. + pub drl_ctx: Vec, +} + +/// Spec 7.10.2.8's threshold a candidate's weight is compared against to +/// pick its DRL context. +const REF_CAT_LEVEL: u32 = 640; + +/// The most candidates a stack keeps (spec `MAX_REF_MV_STACK_SIZE`). +const MAX_STACK_SIZE: usize = 8; + +/// Weight one immediate (row `-1` / col `-1`) neighbour 4x4 unit's vote +/// counts for (spec: `len * 2` with `len = 1` per unit for the reduction +/// this module makes — see the module doc). +const IMMEDIATE_WEIGHT: u32 = 2; + +/// Adds one candidate MV with `weight` to `candidates`, merging it into an +/// existing entry with the same MV rather than duplicating it (spec +/// `add_ref_mv_candidate`, 7.10.2.5). +fn add_candidate(candidates: &mut Vec, mv: (i32, i32), weight: u32) { + if let Some(entry) = candidates.iter_mut().find(|e| e.mv == mv) { + entry.weight += weight; + } else { + candidates.push(StackEntry { mv, weight }); + } +} + +/// The row-above scan (spec 7.10.2.2): every 4x4 unit directly above the +/// block's span. Returns whether any unit voted. +fn scan_row( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bw4: usize, + ref_frame: i8, + candidates: &mut Vec, +) -> bool { + let Some(row) = mi_row.checked_sub(1) else { + return false; + }; + let mut found = false; + for col in mi_col..mi_col + bw4 { + if let Some(info) = grid.get(row, col) + && info.is_inter + && info.ref_frame == ref_frame + { + found = true; + add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT); + } + } + found +} + +/// The col-left scan (spec 7.10.2.3): every 4x4 unit directly left of the +/// block's span. Returns whether any unit voted. +fn scan_col( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bh4: usize, + ref_frame: i8, + candidates: &mut Vec, +) -> bool { + let Some(col) = mi_col.checked_sub(1) else { + return false; + }; + let mut found = false; + for row in mi_row..mi_row + bh4 { + if let Some(info) = grid.get(row, col) + && info.is_inter + && info.ref_frame == ref_frame + { + found = true; + add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT); + } + } + found +} + +/// The single top-right probe this reduction keeps of spec 7.10.2.4's extra +/// scan positions, at the unit diagonally above-right of the block. Its +/// vote is folded into the row scan's candidates (it sits on the same row +/// as the block's neighbours above), which is what makes the row and column +/// scans asymmetric under transposing a grid — spec has no matching +/// bottom-left probe. +fn scan_top_right( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bw4: usize, + ref_frame: i8, + candidates: &mut Vec, +) -> bool { + let Some(row) = mi_row.checked_sub(1) else { + return false; + }; + let col = mi_col + bw4; + if let Some(info) = grid.get(row, col) + && info.is_inter + && info.ref_frame == ref_frame + { + add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT); + return true; + } + false +} + +/// Builds the reference MV stack for the `bw4`-by-`bh4` (in 4x4 units) +/// block at `(mi_row, mi_col)`, predicting against `ref_frame`. +pub fn find_mv_stack( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bw4: usize, + bh4: usize, + ref_frame: i8, +) -> MvStack { + let mut candidates = Vec::new(); + let found_above = scan_row(grid, mi_row, mi_col, bw4, ref_frame, &mut candidates); + let found_left = scan_col(grid, mi_row, mi_col, bh4, ref_frame, &mut candidates); + let found_top_right = scan_top_right(grid, mi_row, mi_col, bw4, ref_frame, &mut candidates); + + // Highest weight first; a stable sort keeps scan order (above, left, + // top-right) among ties, matching spec 7.10.2.6. + candidates.sort_by_key(|e| std::cmp::Reverse(e.weight)); + candidates.truncate(MAX_STACK_SIZE); + + let nearest_mv = candidates.first().map_or((0, 0), |e| e.mv); + let near_mv = candidates.get(1).map_or((0, 0), |e| e.mv); + let pred_mv = if candidates.is_empty() { + (0, 0) + } else { + nearest_mv + }; + + let close_matches = usize::from(found_above) + usize::from(found_left); + let total_matches = close_matches + usize::from(found_top_right); + + // Reduced context tables (see module doc): monotonic in how much + // neighbour agreement was found, not a bit-exact port of 7.10.2.8. + let new_mv_ctx = match (found_above, found_left, candidates.len()) { + (false, false, _) => 0, + (true, false, _) | (false, true, _) => 1, + (true, true, 1) => 2, + (true, true, _) => 3, + }; + let ref_mv_ctx = total_matches.min(5); + let zero_mv_ctx = usize::from(nearest_mv != (0, 0)); + + let drl_ctx = candidates + .windows(2) + .map(|w| { + let (a, b) = (w[0].weight, w[1].weight); + if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL { + 1 + } else if a < REF_CAT_LEVEL && b < REF_CAT_LEVEL { + 2 + } else { + 0 + } + }) + .collect(); + + MvStack { + entries: candidates, + nearest_mv, + near_mv, + pred_mv, + new_mv_ctx, + ref_mv_ctx, + zero_mv_ctx, + drl_ctx, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn inter(mv: (i32, i32)) -> MiInfo { + MiInfo { + is_inter: true, + ref_frame: 1, + mv, + } + } + + #[test] + fn all_same_mv_neighbourhood_dedupes_to_one_entry() { + let mut grid = MiGrid::new(8, 8); + // Block at (2, 2), 2x2 mi units. Above row 1, cols 2..4; left col 1, + // rows 2..4; top-right at (1, 4). All the same MV. + let mv = (4, 4); + grid.set(1, 2, inter(mv)); + grid.set(1, 3, inter(mv)); + grid.set(2, 1, inter(mv)); + grid.set(3, 1, inter(mv)); + grid.set(1, 4, inter(mv)); + + let stack = find_mv_stack(&grid, 2, 2, 2, 2, 1); + + assert_eq!(stack.entries.len(), 1); + assert_eq!(stack.entries[0].mv, mv); + // 2 above cells + 2 left cells + 1 top-right, each weight 2. + assert_eq!(stack.entries[0].weight, 10); + assert_eq!(stack.nearest_mv, mv); + // Documented reduced-context value (see module doc): both sides + // found a match and they collapsed to a single stack entry. + assert_eq!(stack.new_mv_ctx, 2); + } + + #[test] + fn two_distinct_neighbour_mvs_yield_two_entries_in_weight_order() { + let mut grid = MiGrid::new(8, 8); + // Block at (3, 3), bw4=2, bh4=3: above spans 2 cells (weight 4), + // left spans 3 cells (weight 6) — distinct MVs, distinct weights. + let above_mv = (4, 4); + let left_mv = (8, 8); + grid.set(2, 3, inter(above_mv)); + grid.set(2, 4, inter(above_mv)); + grid.set(3, 2, inter(left_mv)); + grid.set(4, 2, inter(left_mv)); + grid.set(5, 2, inter(left_mv)); + + let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1); + + assert_eq!(stack.entries.len(), 2); + assert_eq!( + stack.entries[0], + StackEntry { + mv: left_mv, + weight: 6 + } + ); + assert_eq!( + stack.entries[1], + StackEntry { + mv: above_mv, + weight: 4 + } + ); + assert_eq!(stack.nearest_mv, left_mv); + assert_eq!(stack.near_mv, above_mv); + } + + #[test] + fn transposing_above_and_left_produces_a_different_stack() { + // Grid A: above = (4,4) x2 cells, left = (8,8) x2 cells, top-right + // matches the above MV (so it folds into the above bucket, making + // it heavier than left). + let mut a = MiGrid::new(8, 8); + a.set(1, 2, inter((4, 4))); + a.set(1, 3, inter((4, 4))); + a.set(2, 1, inter((8, 8))); + a.set(3, 1, inter((8, 8))); + a.set(1, 4, inter((4, 4))); + let stack_a = find_mv_stack(&a, 2, 2, 2, 2, 1); + + // Grid B: the naive transpose — swap which MV sits above vs left — + // with the top-right probe again matching whatever now sits above. + let mut b = MiGrid::new(8, 8); + b.set(1, 2, inter((8, 8))); + b.set(1, 3, inter((8, 8))); + b.set(2, 1, inter((4, 4))); + b.set(3, 1, inter((4, 4))); + b.set(1, 4, inter((8, 8))); + let stack_b = find_mv_stack(&b, 2, 2, 2, 2, 1); + + assert_ne!(stack_a, stack_b); + assert_eq!(stack_a.entries[0].mv, (4, 4)); + assert_eq!(stack_b.entries[0].mv, (8, 8)); + } + + #[test] + fn mi_units_outside_the_tile_contribute_nothing() { + let grid = MiGrid::new(4, 4); + // Block at the tile's top-left corner: no row above, no col left, + // and the top-right probe is also off the top edge. + let stack = find_mv_stack(&grid, 0, 0, 2, 2, 1); + + assert!(stack.entries.is_empty()); + assert_eq!(stack.nearest_mv, (0, 0)); + assert_eq!(stack.near_mv, (0, 0)); + assert_eq!(stack.pred_mv, (0, 0)); + assert!(stack.drl_ctx.is_empty()); + + // Out-of-range reads are also inert directly against the grid. + assert!(grid.get(0, 10).is_none()); + assert!(grid.get(10, 0).is_none()); + } +} diff --git a/crates/ec-h265-syntax/src/slice.rs b/crates/ec-h265-syntax/src/slice.rs index e483291b..d0d5a6f3 100644 --- a/crates/ec-h265-syntax/src/slice.rs +++ b/crates/ec-h265-syntax/src/slice.rs @@ -430,6 +430,17 @@ impl SliceHeader { if h.slice_type == SliceType::B { h.num_ref_idx_l1_active_minus1 = r.read_ue()?; } + // 7.4.7.1: both fields are in range 0..=14. Past that is + // a corrupt stream, not a bigger reference list -- and + // pred_weight_table below sizes a Vec from this value, so + // an unchecked ue(v) is a header-declared allocation an + // attacker fully controls (up to 2^32 entries from a + // handful of bits). + if h.num_ref_idx_l0_active_minus1 > 14 || h.num_ref_idx_l1_active_minus1 > 14 { + return Err(Error::corrupt( + "HEVC slice header: num_ref_idx_lX_active_minus1 out of range", + )); + } } let num_pic_total_curr = h.short_term_ref_pic_set.num_used_by_curr + num_long_term; if pps.lists_modification_present && num_pic_total_curr > 1 { diff --git a/crates/ec-image/src/gif.rs b/crates/ec-image/src/gif.rs index ce421755..b0427a00 100644 --- a/crates/ec-image/src/gif.rs +++ b/crates/ec-image/src/gif.rs @@ -14,7 +14,7 @@ //! so a decoder that waits one code longer reads small pictures correctly and //! large ones as noise. -use crate::{AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels}; +use crate::{AllocBudget, AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels}; use ec_core::{Error, Result}; /// GIF interlace: `(start, step)` for each of the four passes. @@ -150,6 +150,13 @@ fn lzw_decode(min_code_size: u8, data: &[u8], expected: usize) -> Result let mut pos = 0; while let Some(code) = lzw.read_code(data, &mut pos) { + if out.len() >= expected { + // Output already satisfies the declared frame size; a bomb-style + // stream can keep growing the dictionary and emitting further + // codes after this point, so stop before decoding any more of + // them rather than let `out` expand unbounded (LZW bomb). + break; + } if code == lzw.clear_code { lzw.reset(); continue; @@ -328,7 +335,13 @@ fn indices_to_rgba(indices: &[u8], palette: &[[u8; 3]], gce: Option<&Gce>) -> Re /// Composite every raw frame onto a full-canvas buffer: blend the frame over /// the canvas, then apply its disposal method to the canvas the next frame /// starts from. -fn composite(frames: Vec, canvas_w: u32, canvas_h: u32) -> Result> { +fn composite( + frames: Vec, + canvas_w: u32, + canvas_h: u32, + limits: &Limits, + budget: &mut AllocBudget, +) -> Result> { let cw = canvas_w as usize; let ch = canvas_h as usize; let n = cw * ch; @@ -337,6 +350,10 @@ fn composite(frames: Vec, canvas_w: u32, canvas_h: u32) -> Result, u32)> = Vec::with_capacity(frames.len()); for frame in frames { + // Every frame clones the whole canvas -- the real multiplier a + // single buffer's own bound never catches -- so it is spent from the + // decode-wide budget just like the frame's own indices were above. + budget.spend(limits, "GIF composited canvas", n * 4)?; let indices = if frame.interlaced { deinterlace(&frame.indices, frame.width as usize, frame.height as usize) } else { @@ -482,6 +499,8 @@ pub fn decode_animation(data: &[u8], limits: Limits) -> Result = None; + let mut budget = AllocBudget::default(); + budget.spend(&limits, "GIF canvas", canvas_bytes)?; loop { let block = r.u8()?; @@ -497,6 +516,14 @@ pub fn decode_animation(data: &[u8], limits: Limits) -> Result Result) -> Result { let bytes = @@ -186,10 +187,11 @@ impl Limits { } } -/// Accumulates bytes spent across every segment of one decode call and -/// refuses once the running total crosses [`Limits::max_total_alloc`] — the -/// guard for `segment_count x segment_size`, which [`Limits::check_bytes`] -/// alone never sees since it only ever looks at one buffer at a time. +/// Accumulates bytes spent across every frame or segment of one decode call +/// and refuses once the running total crosses [`Limits::max_total_alloc`] — +/// the guard for `frame_count x canvas` or `segment_count x segment_size`, +/// which [`Limits::check_bytes`] alone never sees since it only ever looks +/// at one buffer at a time. #[derive(Debug, Default)] pub struct AllocBudget(usize); @@ -546,4 +548,31 @@ mod tests { assert!(limits.check(0, 10).is_err()); assert!(limits.check(100_000, 100_000).is_err()); } + + #[test] + fn check_bytes_refuses_past_max_alloc_before_a_frame_size_carries_it() { + let limits = Limits::default(); + assert!(limits.check_bytes("test", Some(1024)).is_ok()); + assert!(limits.check_bytes("test", Some(limits.max_alloc + 1)).is_err()); + assert!(limits.check_bytes("test", None).is_err()); + } + + #[test] + fn alloc_budget_refuses_once_repeated_spends_cross_the_total() { + // The class this guards: no single spend is ever over budget on its + // own, but a canvas cloned once per animation frame is. + let limits = Limits::default(); + let mut budget = AllocBudget::default(); + let per_frame = limits.max_total_alloc / 4; + for i in 0..4 { + assert!( + budget.spend(&limits, "frame", per_frame).is_ok(), + "frame {i} alone is within budget" + ); + } + assert!( + budget.spend(&limits, "frame", per_frame).is_err(), + "a fifth frame the same size crosses the total" + ); + } } diff --git a/crates/ec-image/src/webp/mod.rs b/crates/ec-image/src/webp/mod.rs index c5db77e6..d673d27a 100644 --- a/crates/ec-image/src/webp/mod.rs +++ b/crates/ec-image/src/webp/mod.rs @@ -245,8 +245,11 @@ pub fn decode_frames(data: &[u8], limits: Limits) -> Result = None; + let mut budget = crate::AllocBudget::default(); + budget.spend(&limits, "WebP canvas", canvas_bytes)?; for chunk in &chunks { if &chunk.tag != b"ANMF" { @@ -267,6 +270,10 @@ pub fn decode_frames(data: &[u8], limits: Limits) -> Result, +} + +impl BitWriter { + fn new() -> Self { + BitWriter { + buffer: 0, + bits: 0, + out: Vec::new(), + } + } + + fn push(&mut self, value: u16, width: u8) { + self.buffer |= u64::from(value) << self.bits; + self.bits += width; + while self.bits >= 8 { + self.out.push((self.buffer & 0xff) as u8); + self.buffer >>= 8; + self.bits -= 8; + } + } + + fn finish(mut self) -> Vec { + if self.bits > 0 { + self.out.push((self.buffer & 0xff) as u8); + } + self.out + } +} + +/// A minimal GIF: no global colour table, one 0x2C image descriptor with a +/// 2-colour local table and a one-pixel LZW stream (clear, colour 0, end), +/// followed by the trailer. `canvas_w`/`canvas_h` size the logical screen; +/// the frame itself is always 1x1 so its own indices buffer is trivial — +/// what grows per frame is the *composited canvas* `composite` clones. +fn one_pixel_gif(canvas_w: u16, canvas_h: u16, frames: usize) -> Vec { + let mut w = BitWriter::new(); + w.push(4, 3); // clear code (min_code_size 2 -> clear = 1<<2) + w.push(0, 3); // colour index 0, literal + w.push(5, 3); // end code + let lzw = w.finish(); + + let mut data = Vec::new(); + data.extend_from_slice(b"GIF87a"); + data.extend_from_slice(&canvas_w.to_le_bytes()); + data.extend_from_slice(&canvas_h.to_le_bytes()); + data.push(0x00); // no global colour table + data.push(0); + data.push(0); + for _ in 0..frames { + data.push(0x2C); + data.extend_from_slice(&0u16.to_le_bytes()); // left + data.extend_from_slice(&0u16.to_le_bytes()); // top + data.extend_from_slice(&1u16.to_le_bytes()); // width + data.extend_from_slice(&1u16.to_le_bytes()); // height + data.push(0x80); // has LCT, sorted=0, size field 0 -> 2 colours + data.extend_from_slice(&[0, 0, 0, 255, 255, 255]); // 2-colour LCT + data.push(2); // min code size + data.push(lzw.len() as u8); + data.extend_from_slice(&lzw); + data.push(0); // sub-block terminator + } + data.push(0x3B); // trailer + data +} + +#[test] +fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() { + // A single 0x2C image descriptor declaring a 60000x60000 frame: the + // frame's own rectangle is a header field like the canvas is, and must + // be refused before it sizes the indices buffer below it. + let mut data = Vec::new(); + data.extend_from_slice(b"GIF87a"); + data.extend_from_slice(&4u16.to_le_bytes()); + data.extend_from_slice(&4u16.to_le_bytes()); + data.push(0x00); + data.push(0); + data.push(0); + data.push(0x2C); + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&60000u16.to_le_bytes()); + data.extend_from_slice(&60000u16.to_le_bytes()); + data.push(0x00); + + let start = std::time::Instant::now(); + let err = ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit"); + assert!(start.elapsed().as_millis() < 100, "{:?}", start.elapsed()); + assert!(format!("{err}").contains("limit"), "{err}"); +} + +#[test] +fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { + // Each frame is 1x1 -- cheap to encode, cheap to check on its own -- but + // `composite` clones the *whole* canvas onto the result once per frame. + // A canvas near the single-buffer limit, repeated a few dozen times, + // must be caught by the decode-wide budget even though no single frame + // or single buffer ever looks large by itself. + let data = one_pixel_gif(16000, 16000, 64); + let start = std::time::Instant::now(); + let err = ec_image::decode_animation(&data) + .expect_err("64 clones of a near-limit canvas is past the total budget"); + // A few real canvas clones run before the budget catches up (the budget + // is spent per frame, so it can't refuse before at least one clone), so + // this bounds "a handful of gigabyte copies", not "no allocation at all". + assert!(start.elapsed().as_secs() < 5, "{:?}", start.elapsed()); + assert!(format!("{err}").contains("limit"), "{err}"); +} + +#[test] +fn a_gif_with_a_few_tiny_frames_over_a_huge_canvas_still_decodes() { + // The other side of the same budget: a handful of frames over a large + // canvas is exactly what a real animation looks like, and must not be + // refused just because the guard above exists. + let data = one_pixel_gif(4000, 4000, 3); + let frames = ec_image::decode_animation(&data).expect("well within every limit"); + assert_eq!(frames.len(), 3); +} + +/// A minimal RIFF WebP with an ANIM/VP8X header and `frames` ANMF chunks, +/// each carrying a 1x1 VP8L payload (the smallest valid lossless image: a +/// bitstream header plus one pixel, no transforms, no colour cache). +fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec { + // VP8L bitstream for a 1x1 image: signature 0x2f, 14-bit width-1=0, + // 14-bit height-1=0, 1-bit alpha flag=0, 3-bit version=0, then the + // image data: no colour cache, no meta prefix, one simple prefix code + // per channel (colour index 0 for all four), then the single pixel. + let mut w = BitWriter::new(); + w.push(0, 14); // width - 1 + w.push(0, 14); // height - 1 + w.push(0, 1); // alpha_is_used + w.push(0, 3); // version + w.push(0, 1); // no transform + w.push(0, 1); // no colour cache + w.push(0, 1); // no meta prefix + for _ in 0..5 { + // green/red/blue/alpha/distance, in that order: a simple code, one + // symbol, value 0. + w.push(1, 1); // simple code + w.push(0, 1); // one symbol + w.push(0, 1); // symbol is not a literal byte read as 8 bits + w.push(0, 1); // symbol0 = 0 + } + let vp8l_bits = w.finish(); + let mut vp8l = vec![0x2f]; + vp8l.extend_from_slice(&vp8l_bits); + if vp8l.len() % 2 == 1 { + vp8l.push(0); + } + + fn chunk(tag: &[u8; 4], body: &[u8]) -> Vec { + let mut c = Vec::new(); + c.extend_from_slice(tag); + c.extend_from_slice(&(body.len() as u32).to_le_bytes()); + c.extend_from_slice(body); + if body.len() % 2 == 1 { + c.push(0); + } + c + } + + let mut vp8x = vec![0x02, 0, 0, 0]; // flags: bit 0x02 is "has animation" + let off24 = |v: u32| v.to_le_bytes()[..3].to_vec(); + let dim24 = |v: u32| (v - 1).to_le_bytes()[..3].to_vec(); + vp8x.extend_from_slice(&dim24(canvas_w)); + vp8x.extend_from_slice(&dim24(canvas_h)); + let mut anim = vec![0, 0, 0, 0, 0, 0]; // background colour + anim.extend_from_slice(&0u16.to_le_bytes()); // loop count + + let mut anmf_body = Vec::new(); + anmf_body.extend_from_slice(&off24(0)); // x offset (raw value, x = field*2) + anmf_body.extend_from_slice(&off24(0)); // y offset + anmf_body.extend_from_slice(&dim24(1)); // width - 1 + anmf_body.extend_from_slice(&dim24(1)); // height - 1 + anmf_body.extend_from_slice(&off24(1)); // duration + anmf_body.push(0x00); // reserved/blend/dispose + anmf_body.extend_from_slice(&chunk(b"VP8L", &vp8l)); + + let mut payload = Vec::new(); + payload.extend_from_slice(&chunk(b"VP8X", &vp8x)); + payload.extend_from_slice(&chunk(b"ANIM", &anim)); + for _ in 0..frames { + payload.extend_from_slice(&chunk(b"ANMF", &anmf_body)); + } + + let mut data = Vec::new(); + data.extend_from_slice(b"RIFF"); + data.extend_from_slice(&(4 + payload.len() as u32).to_le_bytes()); + data.extend_from_slice(b"WEBP"); + data.extend_from_slice(&payload); + data +} + +#[test] +fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { + // The WebP analogue of the GIF test above: `decode_frames` clones the + // whole composited canvas into the result once per ANMF chunk. + let data = one_pixel_animated_webp(16000, 16000, 64); + let start = std::time::Instant::now(); + let err = ec_image::decode_animation(&data) + .expect_err("64 clones of a near-limit canvas is past the total budget"); + assert!(start.elapsed().as_millis() < 2000, "{:?}", start.elapsed()); + assert!(format!("{err}").contains("limit"), "{err}"); +} + +/// Build an LZW-compressed data stream that keeps expanding after the +/// dictionary itself has stopped growing: a run of `cScSc` codes (each equal +/// to the not-yet-assigned `next_code`) fills the 4096-entry dictionary with +/// entries of increasing length, then a run of plain references to the +/// longest entry keeps emitting ~4 KB of output per 12-bit code with no +/// further dictionary growth to bound it. This is the classic GIF LZW bomb: +/// a stream well under 200 KB that decodes, uncapped, to hundreds of +/// megabytes. +fn lzw_bomb() -> Vec { + let min_code_size = 2u8; + let clear_code = 1u16 << min_code_size; // 4 + let end_code = clear_code + 1; // 5 + let mut next_code = clear_code + 2; // 6 + let mut code_size = min_code_size + 1; // 3 + + let mut w = BitWriter::new(); + w.push(clear_code, code_size); + w.push(0, code_size); // first code after clear: a literal, no dictionary entry + + // Phase 1: cScSc every time -- fills the dictionary, entries growing + // 2, 3, 4, ... bytes long (mirrors `Lzw::derive`'s widening rule exactly, + // so the decoder reads this stream at the same code width we wrote it). + while next_code < 4096 { + w.push(next_code, code_size); + if next_code >= (1u16 << code_size) - 1 && code_size < 12 { + code_size += 1; + } + next_code += 1; + } + + // Phase 2: dictionary is full (`derive` is now a no-op), so repeating the + // longest entry's code keeps producing ~4 KB per code with nothing left + // to cap it. + let longest = next_code - 1; + for _ in 0..100_000 { + w.push(longest, code_size); + } + + w.push(end_code, code_size); + w.finish() +} + +/// A GIF whose frame declares 4x4 (16 indices) but whose LZW stream, if +/// decoded past that point, expands to hundreds of megabytes: guards the +/// `lzw_decode` bound at gif.rs that stops the loop once `out` already holds +/// `expected` bytes, rather than only checking after the loop. +#[test] +fn a_gif_lzw_bomb_does_not_expand_past_its_declared_frame() { + let lzw = lzw_bomb(); + eprintln!("gif-lzw-bomb: {} bytes of LZW data", lzw.len()); + + let mut data = Vec::new(); + data.extend_from_slice(b"GIF87a"); + data.extend_from_slice(&4u16.to_le_bytes()); + data.extend_from_slice(&4u16.to_le_bytes()); + data.push(0x00); // no global colour table + data.push(0); + data.push(0); + data.push(0x2C); + data.extend_from_slice(&0u16.to_le_bytes()); // left + data.extend_from_slice(&0u16.to_le_bytes()); // top + data.extend_from_slice(&4u16.to_le_bytes()); // width + data.extend_from_slice(&4u16.to_le_bytes()); // height + data.push(0x81); // has LCT, size field 1 -> 4 colours (indices 0..3) + data.extend_from_slice(&[0, 0, 0, 64, 64, 64, 128, 128, 128, 255, 255, 255]); + data.push(2); // min code size + for chunk in lzw.chunks(255) { + data.push(chunk.len() as u8); + data.extend_from_slice(chunk); + } + data.push(0); // sub-block terminator + data.push(0x3B); // trailer + + let start = std::time::Instant::now(); + let _ = ec_image::decode(&data); + assert!(start.elapsed().as_secs() < 1, "{:?}", start.elapsed()); +} + fn crc32(data: &[u8]) -> u32 { let mut c = 0xffff_ffffu32; for &b in data { diff --git a/scripts/memguard-runner.sh b/scripts/memguard-runner.sh new file mode 100755 index 00000000..78161c65 --- /dev/null +++ b/scripts/memguard-runner.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Wraps a test/bin invocation in a transient user cgroup scope so a runaway +# allocation dies inside its own cgroup instead of triggering a machine-wide +# OOM kill. Used as the cargo target runner (see .cargo/config.toml) so every +# `cargo test`/`cargo run` invocation of this workspace is capped, from any +# checkout (main repo or worktree). +set -euo pipefail + +if [ "${EC_NOMEMGUARD:-0}" = "1" ]; then + echo "memguard-runner: EC_NOMEMGUARD=1, running without memory cap" >&2 + exec "$@" +fi + +if ! systemd-run --user --scope --quiet -p MemoryMax=10G true >/dev/null 2>&1; then + echo "memguard-runner: systemd-run --user --scope unavailable, running without memory cap" >&2 + exec "$@" +fi + +exec systemd-run --user --scope --quiet --same-dir \ + -p MemoryMax=10G -p MemorySwapMax=2G \ + -- "$@"