forge
Explore
Log in

Don't you dare go Hollow

Merge remote-tracking branch 'origin/main' into lane-image-tiff

Browse files at this commit

fd823fc734935a62ce0a0eb195872d8006869d36Ahmet Kaan GümüşParent: 6e80b0daeb8f71
# Conflicts:
#	crates/ec-image/src/lib.rs
.cargo/config.tomladded+7 -0
@@ -0,0 +1,7 @@
1+[target.x86_64-unknown-linux-gnu]
2+# Wrap every test/bin run in scripts/memguard-runner.sh so a runaway
3+# allocation gets killed inside its own cgroup instead of OOM-killing the
4+# machine. Located via `git rev-parse --show-toplevel` from the invoker's cwd
5+# (cargo does not resolve runner paths relative to this file, and an absolute
6+# path would break other worktree checkouts of this repo).
7+runner = ["bash", "-c", "root=$(git rev-parse --show-toplevel) && exec \"$root/scripts/memguard-runner.sh\" \"$@\"", "--"]
crates/ec-av1/src/cdf.rsmodified+236 -0
@@ -957,3 +957,239 @@ pub const INTRA_TX_TYPE_SET2_16: [[u16; 6]; 13] = [
957 [83, 5615, 12001, 17228, 32768, 0],957 [83, 5615, 12001, 17228, 32768, 0],
958 [1968, 5556, 12023, 18547, 32768, 0],958 [1968, 5556, 12023, 18547, 32768, 0],
959 ];959 ];
960+
961+// The inter-frame tables below (spec 9.4) support the syntax an inter block
962+// needs: whether it is coded as intra at all, which reference frame and
963+// motion vector it takes when it is not. Compound reference and compound
964+// prediction are not among them -- this encoder never sets
965+// `reference_select`, so their CDFs are never read.
966+
967+/// `Default_Intra_Inter_Cdf` (spec 9.4): whether an inter frame's block is
968+/// coded as intra, indexed by whether the block above and left are inter.
969+pub const INTRA_INTER: [[u16; 3]; 4] = [
970+ [806, 32768, 0],
971+ [16662, 32768, 0],
972+ [20186, 32768, 0],
973+ [26538, 32768, 0],
974+];
975+
976+/// `Default_Single_Ref_Cdf` (spec 9.4): the six binary decisions that narrow
977+/// an inter block's single reference frame down from the seven it can name,
978+/// indexed by the reference context of the blocks around it.
979+pub const SINGLE_REF: [[[u16; 3]; 6]; 3] = [
980+ [
981+ [4897, 32768, 0],
982+ [1555, 32768, 0],
983+ [4236, 32768, 0],
984+ [8650, 32768, 0],
985+ [904, 32768, 0],
986+ [1444, 32768, 0],
987+ ],
988+ [
989+ [16973, 32768, 0],
990+ [16751, 32768, 0],
991+ [19647, 32768, 0],
992+ [24773, 32768, 0],
993+ [11014, 32768, 0],
994+ [15087, 32768, 0],
995+ ],
996+ [
997+ [29744, 32768, 0],
998+ [30279, 32768, 0],
999+ [31194, 32768, 0],
1000+ [31895, 32768, 0],
1001+ [26875, 32768, 0],
1002+ [30304, 32768, 0],
1003+ ],
1004+];
1005+
1006+/// `Default_Y_Mode_Cdf` (spec 9.4): the thirteen luma intra modes of an inter
1007+/// frame's intra block, indexed by the block's size group -- unlike a key
1008+/// frame's [`KF_Y_MODE`], which is indexed by the neighbours' modes instead.
1009+pub const Y_MODE: [[u16; 14]; 4] = [
1010+ [
1011+ 22801, 23489, 24293, 24756, 25601, 26123, 26606, 27418, 27945, 29228, 29685, 30349, 32768,
1012+ 0,
1013+ ],
1014+ [
1015+ 18673, 19845, 22631, 23318, 23950, 24649, 25527, 27364, 28152, 29701, 29984, 30852, 32768,
1016+ 0,
1017+ ],
1018+ [
1019+ 19770, 20979, 23396, 23939, 24241, 24654, 25136, 27073, 27830, 29360, 29730, 30659, 32768,
1020+ 0,
1021+ ],
1022+ [
1023+ 20155, 21301, 22838, 23178, 23261, 23533, 23703, 24804, 25352, 26575, 27016, 28049, 32768,
1024+ 0,
1025+ ],
1026+];
1027+
1028+/// `Default_New_Mv_Cdf` (spec 9.4): whether an inter block's motion vector is
1029+/// coded explicitly rather than taken from a neighbour, indexed by how many
1030+/// neighbours already chose a new vector.
1031+pub const NEW_MV: [[u16; 3]; 6] = [
1032+ [24035, 32768, 0],
1033+ [16630, 32768, 0],
1034+ [15339, 32768, 0],
1035+ [8386, 32768, 0],
1036+ [12222, 32768, 0],
1037+ [4676, 32768, 0],
1038+];
1039+
1040+/// `Default_Zero_Mv_Cdf` (spec 9.4): whether an inter block's motion vector is
1041+/// the zero vector, indexed by whether the block's global motion type is
1042+/// identity.
1043+pub const ZERO_MV: [[u16; 3]; 2] = [[2175, 32768, 0], [1054, 32768, 0]];
1044+
1045+/// `Default_Ref_Mv_Cdf` (spec 9.4): which of the block's reference motion
1046+/// vector candidates it takes, indexed by how many candidates are available.
1047+pub const REF_MV: [[u16; 3]; 6] = [
1048+ [23974, 32768, 0],
1049+ [24188, 32768, 0],
1050+ [17848, 32768, 0],
1051+ [28622, 32768, 0],
1052+ [24312, 32768, 0],
1053+ [19923, 32768, 0],
1054+];
1055+
1056+/// `Default_Drl_Mode_Cdf` (spec 9.4): the dynamic reference list index a
1057+/// block's motion vector prediction is drawn from, indexed by the list's
1058+/// context.
1059+pub const DRL_MODE: [[u16; 3]; 3] = [[13104, 32768, 0], [24560, 32768, 0], [18945, 32768, 0]];
1060+
1061+// The motion vector tables below (spec 9.4's `Default_Mv_*`) are the shared
1062+// defaults for both components of a vector: [`crate::cdf_state::Cdfs`] holds
1063+// one owned copy of each per component, seeded from the same constant here,
1064+// since the spec's default state does not distinguish them -- only adaptation
1065+// does, once a tile has coded a few vectors.
1066+
1067+/// `Default_Mv_Joint_Cdf` (spec 9.4): which of a motion vector's two
1068+/// components change at all.
1069+pub const MV_JOINT: [u16; 5] = [4096, 11264, 19328, 32768, 0];
1070+
1071+/// `Default_Mv_Class_Cdf` (spec 9.4): the magnitude class of one motion
1072+/// vector component.
1073+pub const MV_CLASS: [u16; 12] = [
1074+ 28672, 30976, 31858, 32320, 32551, 32656, 32740, 32757, 32762, 32767, 32768, 0,
1075+];
1076+
1077+/// `Default_Mv_Class0_Bit_Cdf` (spec 9.4): the integer bit of a small-class
1078+/// motion vector's magnitude.
1079+pub const MV_CLASS0_BIT: [u16; 3] = [27648, 32768, 0];
1080+
1081+/// `Default_Mv_Class0_Fr_Cdf` (spec 9.4): the fractional part of a
1082+/// small-class motion vector's magnitude, indexed by its integer bit.
1083+pub const MV_CLASS0_FR: [[u16; 5]; 2] = [
1084+ [16384, 24576, 26624, 32768, 0],
1085+ [12288, 21248, 24128, 32768, 0],
1086+];
1087+
1088+/// `Default_Mv_Class0_Hp_Cdf` (spec 9.4): the half-pel bit of a small-class
1089+/// motion vector's magnitude.
1090+pub const MV_CLASS0_HP: [u16; 3] = [20480, 32768, 0];
1091+
1092+/// `Default_Mv_Bit_Cdf` (spec 9.4): one bit of a motion vector's integer
1093+/// magnitude above the small-class range, indexed by the bit's position.
1094+pub const MV_BIT: [[u16; 3]; 10] = [
1095+ [17408, 32768, 0],
1096+ [17920, 32768, 0],
1097+ [18944, 32768, 0],
1098+ [20480, 32768, 0],
1099+ [22528, 32768, 0],
1100+ [24576, 32768, 0],
1101+ [28672, 32768, 0],
1102+ [29952, 32768, 0],
1103+ [29952, 32768, 0],
1104+ [30720, 32768, 0],
1105+];
1106+
1107+/// `Default_Mv_Fr_Cdf` (spec 9.4): the fractional part of a motion vector's
1108+/// magnitude, outside the small-class range.
1109+pub const MV_FR: [u16; 5] = [8192, 17408, 21248, 32768, 0];
1110+
1111+/// `Default_Mv_Hp_Cdf` (spec 9.4): the half-pel bit of a motion vector's
1112+/// magnitude, outside the small-class range.
1113+pub const MV_HP: [u16; 3] = [16384, 32768, 0];
1114+
1115+/// `Default_Mv_Sign_Cdf` (spec 9.4): the sign of a motion vector component.
1116+pub const MV_SIGN: [u16; 3] = [16384, 32768, 0];
1117+
1118+#[cfg(test)]
1119+mod tests {
1120+ use super::*;
1121+
1122+ /// Every row of a CDF table is non-decreasing and ends with the
1123+ /// alphabet's total (`32768`) followed by the adaptation counter (`0`),
1124+ /// which is the shape [`crate::msac`] expects to read.
1125+ fn assert_row_shape(row: &[u16]) {
1126+ assert_eq!(row[row.len() - 2], 32768, "row does not total 32768");
1127+ assert_eq!(row[row.len() - 1], 0, "row's adaptation counter is not 0");
1128+ for w in row[..row.len() - 1].windows(2) {
1129+ assert!(w[0] <= w[1], "row is not non-decreasing: {row:?}");
1130+ }
1131+ }
1132+
1133+ #[test]
1134+ fn inter_frame_tables_are_well_formed_cdfs() {
1135+ for row in INTRA_INTER {
1136+ assert_row_shape(&row);
1137+ }
1138+ for ctx in SINGLE_REF {
1139+ for row in ctx {
1140+ assert_row_shape(&row);
1141+ }
1142+ }
1143+ for row in Y_MODE {
1144+ assert_row_shape(&row);
1145+ }
1146+ for row in NEW_MV {
1147+ assert_row_shape(&row);
1148+ }
1149+ for row in ZERO_MV {
1150+ assert_row_shape(&row);
1151+ }
1152+ for row in REF_MV {
1153+ assert_row_shape(&row);
1154+ }
1155+ for row in DRL_MODE {
1156+ assert_row_shape(&row);
1157+ }
1158+ assert_row_shape(&MV_JOINT);
1159+ assert_row_shape(&MV_CLASS);
1160+ assert_row_shape(&MV_CLASS0_BIT);
1161+ for row in MV_CLASS0_FR {
1162+ assert_row_shape(&row);
1163+ }
1164+ assert_row_shape(&MV_CLASS0_HP);
1165+ for row in MV_BIT {
1166+ assert_row_shape(&row);
1167+ }
1168+ assert_row_shape(&MV_FR);
1169+ assert_row_shape(&MV_HP);
1170+ assert_row_shape(&MV_SIGN);
1171+ }
1172+
1173+ /// Each table's row length matches the spec's symbol count for that
1174+ /// syntax element: two entries (total, counter) plus one fewer than the
1175+ /// alphabet.
1176+ #[test]
1177+ fn inter_frame_tables_have_the_spec_alphabet_size() {
1178+ assert_eq!(INTRA_INTER[0].len(), 2 + 1); // binary
1179+ assert_eq!(SINGLE_REF[0][0].len(), 2 + 1); // binary
1180+ assert_eq!(Y_MODE[0].len(), 2 + 13 - 1); // 13 luma intra modes
1181+ assert_eq!(NEW_MV[0].len(), 2 + 1);
1182+ assert_eq!(ZERO_MV[0].len(), 2 + 1);
1183+ assert_eq!(REF_MV[0].len(), 2 + 1);
1184+ assert_eq!(DRL_MODE[0].len(), 2 + 1);
1185+ assert_eq!(MV_JOINT.len(), 2 + 3); // MV_JOINTS = 4
1186+ assert_eq!(MV_CLASS.len(), 2 + 10); // MV_CLASSES = 11
1187+ assert_eq!(MV_CLASS0_BIT.len(), 2 + 1);
1188+ assert_eq!(MV_CLASS0_FR[0].len(), 2 + 3); // 4-way fraction
1189+ assert_eq!(MV_CLASS0_HP.len(), 2 + 1);
1190+ assert_eq!(MV_BIT[0].len(), 2 + 1);
1191+ assert_eq!(MV_FR.len(), 2 + 3);
1192+ assert_eq!(MV_HP.len(), 2 + 1);
1193+ assert_eq!(MV_SIGN.len(), 2 + 1);
1194+ }
1195+}
crates/ec-av1/src/cdf_state.rsmodified+90 -0
@@ -146,6 +146,63 @@ pub(crate) struct Cdfs {
146 pub intra_tx_type_16: [[u16; 6]; 13],146 pub intra_tx_type_16: [[u16; 6]; 13],
147 /// The DC sign of a chroma coefficient, shared by both chroma sets.147 /// The DC sign of a chroma coefficient, shared by both chroma sets.
148 pub dc_sign_chroma: [[u16; 3]; 3],148 pub dc_sign_chroma: [[u16; 3]; 3],
149+ /// Whether an inter frame's block is coded as intra.
150+ pub intra_inter: [[u16; 3]; 4],
151+ /// The six binary decisions of an inter block's single reference frame.
152+ pub single_ref: [[[u16; 3]; 6]; 3],
153+ /// The luma mode of an inter frame's intra block, by its size group.
154+ pub y_mode: [[u16; 14]; 4],
155+ /// Whether an inter block codes its motion vector explicitly.
156+ pub new_mv: [[u16; 3]; 6],
157+ /// Whether an inter block's motion vector is the zero vector.
158+ pub zero_mv: [[u16; 3]; 2],
159+ /// Which reference motion vector candidate an inter block takes.
160+ pub ref_mv: [[u16; 3]; 6],
161+ /// The dynamic reference list index of a motion vector prediction.
162+ pub drl_mode: [[u16; 3]; 3],
163+ /// A motion vector's joint (which components change), shared by both
164+ /// components since it is read once per vector, not once per component.
165+ pub mv_joint: [u16; 5],
166+ /// The two motion vector components' own tables: separate owned state,
167+ /// since spec 8.3.2 adapts one component without touching the other.
168+ pub mv_comp: [MvComponentCdfs; 2],
169+}
170+
171+/// One motion vector component's adapting state (spec 9.4's `Default_Mv_*`,
172+/// held once per component so that adapting one leaves the other alone).
173+#[derive(Clone)]
174+pub(crate) struct MvComponentCdfs {
175+ /// The magnitude class.
176+ pub class: [u16; 12],
177+ /// The integer bit of a small-class magnitude.
178+ pub class0_bit: [u16; 3],
179+ /// The fractional part of a small-class magnitude, by its integer bit.
180+ pub class0_fr: [[u16; 5]; 2],
181+ /// The half-pel bit of a small-class magnitude.
182+ pub class0_hp: [u16; 3],
183+ /// One bit of an above-small-class magnitude, by its position.
184+ pub bit: [[u16; 3]; 10],
185+ /// The fractional part of an above-small-class magnitude.
186+ pub fr: [u16; 5],
187+ /// The half-pel bit of an above-small-class magnitude.
188+ pub hp: [u16; 3],
189+ /// The component's sign.
190+ pub sign: [u16; 3],
191+}
192+
193+impl MvComponentCdfs {
194+ fn new() -> MvComponentCdfs {
195+ MvComponentCdfs {
196+ class: cdf::MV_CLASS,
197+ class0_bit: cdf::MV_CLASS0_BIT,
198+ class0_fr: cdf::MV_CLASS0_FR,
199+ class0_hp: cdf::MV_CLASS0_HP,
200+ bit: cdf::MV_BIT,
201+ fr: cdf::MV_FR,
202+ hp: cdf::MV_HP,
203+ sign: cdf::MV_SIGN,
204+ }
205+ }
149 }206 }
150 207
151 impl Cdfs {208 impl Cdfs {
@@ -199,6 +256,15 @@ impl Cdfs {
199 dc_sign_luma: cdf::DC_SIGN_LUMA,256 dc_sign_luma: cdf::DC_SIGN_LUMA,
200 intra_tx_type_16: cdf::INTRA_TX_TYPE_SET2_16,257 intra_tx_type_16: cdf::INTRA_TX_TYPE_SET2_16,
201 dc_sign_chroma: cdf::DC_SIGN_CHROMA,258 dc_sign_chroma: cdf::DC_SIGN_CHROMA,
259+ intra_inter: cdf::INTRA_INTER,
260+ single_ref: cdf::SINGLE_REF,
261+ y_mode: cdf::Y_MODE,
262+ new_mv: cdf::NEW_MV,
263+ zero_mv: cdf::ZERO_MV,
264+ ref_mv: cdf::REF_MV,
265+ drl_mode: cdf::DRL_MODE,
266+ mv_joint: cdf::MV_JOINT,
267+ mv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()],
202 }268 }
203 }269 }
204 270
@@ -328,5 +394,29 @@ mod tests {
328 cdf::EOB_EXTRA_CHROMA_16[2]394 cdf::EOB_EXTRA_CHROMA_16[2]
329 );395 );
330 assert_eq!(cdfs.partition_w64[2], cdf::PARTITION_W64[2]);396 assert_eq!(cdfs.partition_w64[2], cdf::PARTITION_W64[2]);
397+ assert_eq!(cdfs.intra_inter, cdf::INTRA_INTER);
398+ assert_eq!(cdfs.single_ref, cdf::SINGLE_REF);
399+ assert_eq!(cdfs.y_mode, cdf::Y_MODE);
400+ assert_eq!(cdfs.new_mv, cdf::NEW_MV);
401+ assert_eq!(cdfs.zero_mv, cdf::ZERO_MV);
402+ assert_eq!(cdfs.ref_mv, cdf::REF_MV);
403+ assert_eq!(cdfs.drl_mode, cdf::DRL_MODE);
404+ assert_eq!(cdfs.mv_joint, cdf::MV_JOINT);
405+ assert_eq!(cdfs.mv_comp[0].class, cdf::MV_CLASS);
406+ assert_eq!(cdfs.mv_comp[1].sign, cdf::MV_SIGN);
407+ }
408+
409+ /// A motion vector's two components are separate owned tables: adapting
410+ /// one component's CDFs must not be visible through the other, the same
411+ /// hazard the coefficient sets guard against above.
412+ #[test]
413+ fn the_mv_components_are_separate_and_do_not_share_adaptation() {
414+ let mut cdfs = Cdfs::new();
415+ cdfs.mv_comp[0].class[0] = 1;
416+ cdfs.mv_comp[0].bit[3][0] = 2;
417+ assert_ne!(cdfs.mv_comp[1].class[0], 1);
418+ assert_ne!(cdfs.mv_comp[1].bit[3][0], 2);
419+ assert_eq!(cdfs.mv_comp[1].class[0], cdf::MV_CLASS[0]);
420+ assert_eq!(cdfs.mv_comp[1].bit[3][0], cdf::MV_BIT[3][0]);
331 }421 }
332 }422 }
crates/ec-av1/src/encode.rsmodified+37 -0
@@ -256,6 +256,43 @@ pub fn key_frame_headers(
256 Ok((seq, header))256 Ok((seq, header))
257 }257 }
258 258
259+/// The frame header for a shown inter frame that predicts from the single
260+/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
261+/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
262+/// reused verbatim: an inter frame never changes the sequence.
263+///
264+/// # Errors
265+/// Returns an error under the same conditions as [`key_frame_headers`].
266+pub fn inter_frame_headers(
267+ width: usize,
268+ height: usize,
269+ base_q_idx: u8,
270+ order_hint: u32,
271+ last_slot: u8,
272+) -> Result<(SequenceHeader, FrameHeader)> {
273+ let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
274+ let header = FrameHeader {
275+ frame_type: FrameType::Inter,
276+ frame_is_intra: false,
277+ show_frame: true,
278+ error_resilient_mode: false,
279+ disable_cdf_update: false,
280+ disable_frame_end_update_cdf: true,
281+ force_integer_mv: false,
282+ order_hint,
283+ primary_ref_frame: 0,
284+ refresh_frame_flags: 1 << last_slot,
285+ ref_frame_idx: [last_slot; ec_av1_syntax::REFS_PER_FRAME],
286+ allow_high_precision_mv: false,
287+ interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
288+ is_motion_mode_switchable: false,
289+ use_ref_frame_mvs: false,
290+ reduced_tx_set: false,
291+ ..key
292+ };
293+ Ok((seq, header))
294+}
295+
259 fn too_large() -> Error {296 fn too_large() -> Error {
260 Error::unsupported(297 Error::unsupported(
261 "AV1 encode",298 "AV1 encode",
crates/ec-av1/src/frame.rsmodified+198 -37
@@ -1,18 +1,21 @@
1-//! The frame header OBU (spec 5.9), for shown key frames.1+//! The frame header OBU (spec 5.9), for shown key and inter frames.
2 //!2 //!
3 //! Every writer here is the bit-exact inverse of the matching reader in3 //! Every writer here is the bit-exact inverse of the matching reader in
4 //! [`ec_av1_syntax::frame`], and the tests prove it by parsing back what they4 //! [`ec_av1_syntax::frame`], and the tests prove it by parsing back what they
5-//! wrote. The subset is the one a stateless hardware encoder needs: a key frame5+//! wrote. The subset is the one a stateless hardware encoder needs: a key or
6-//! that is shown, in a sequence with no decoder model, no frame ids and no6+//! inter frame that is shown, in a sequence with no decoder model, no frame
7-//! still-picture shortcut. Everything outside it is refused by name rather than7+//! ids and no still-picture shortcut. Everything outside it is refused by name
8-//! written wrong — superres with a denominator other than 8, film grain8+//! rather than written wrong — superres with a denominator other than 8, film
9-//! synthesis, non-uniform tile spacing, and every non-key or hidden frame.9+//! grain synthesis, non-uniform tile spacing, every hidden frame, short
10+//! reference signalling, non-identity global motion, and compound reference
11+//! selection (with the skip mode and warped motion it would gate).
10 12
11 use ec_av1_syntax::obu::{ObuHeader, ObuType, tile_log2};13 use ec_av1_syntax::obu::{ObuHeader, ObuType, tile_log2};
12 use ec_av1_syntax::sequence::{SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS, SequenceHeader};14 use ec_av1_syntax::sequence::{SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS, SequenceHeader};
13 use ec_av1_syntax::{15 use ec_av1_syntax::{
14- FrameHeader, FrameType, MAX_SEGMENTS, MAX_TILE_AREA, MAX_TILE_COLS, MAX_TILE_ROWS,16+ FrameHeader, FrameType, InterpolationFilter, MAX_SEGMENTS, MAX_TILE_AREA, MAX_TILE_COLS,
15- MAX_TILE_WIDTH, PRIMARY_REF_NONE, RestorationType, SEG_LVL_MAX, TOTAL_REFS_PER_FRAME, TxMode,17+ MAX_TILE_ROWS, MAX_TILE_WIDTH, PRIMARY_REF_NONE, REFS_PER_FRAME, RestorationType, SEG_LVL_MAX,
18+ TOTAL_REFS_PER_FRAME, TxMode, WarpModel,
16 };19 };
17 use ec_core::{BitWriter, Error, Result};20 use ec_core::{BitWriter, Error, Result};
18 21
@@ -295,14 +298,47 @@ fn write_lr_params(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader, all
295 }298 }
296 }299 }
297 300
298-/// `uncompressed_header()` (spec 5.9.2) for a shown key frame.301+/// `frame_size()` + `render_size()` (spec 5.9.5, 5.9.6), shared by the intra
302+/// and inter paths: this writer never overrides the size mid-stream
303+/// (`frame_size_with_refs`, spec 5.9.7, is not written).
304+fn write_frame_size(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) -> Result<()> {
305+ if h.frame_size_override_flag {
306+ w.write_bits(h.frame_width - 1, seq.frame_width_bits);
307+ w.write_bits(h.frame_height - 1, seq.frame_height_bits);
308+ }
309+ if seq.enable_superres {
310+ w.write_bit(h.use_superres);
311+ }
312+ if h.use_superres || h.superres_denom != 8 {
313+ return Err(Error::unsupported(
314+ "AV1 superres",
315+ "only a superres denominator of 8 (no scaling) is written",
316+ ));
317+ }
318+ let render_differs = h.render_width != h.upscaled_width || h.render_height != h.frame_height;
319+ w.write_bit(render_differs);
320+ if render_differs {
321+ w.write_bits(h.render_width - 1, 16);
322+ w.write_bits(h.render_height - 1, 16);
323+ }
324+ Ok(())
325+}
326+
327+/// `uncompressed_header()` (spec 5.9.2) for a shown key or inter frame: no
328+/// decoder model, no frame ids, no still-picture shortcut, and (for an inter
329+/// frame) short reference signalling, non-identity global motion, compound
330+/// reference selection and warped motion are all refused rather than written.
299 pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) -> Result<()> {331 pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) -> Result<()> {
300- if h.frame_type != FrameType::Key || !h.show_frame || h.show_existing_frame {332+ if !matches!(h.frame_type, FrameType::Key | FrameType::Inter)
333+ || !h.show_frame
334+ || h.show_existing_frame
335+ {
301 return Err(Error::unsupported(336 return Err(Error::unsupported(
302 "AV1 frame header",337 "AV1 frame header",
303- "only a shown key frame is written",338+ "only a shown key or inter frame is written",
304 ));339 ));
305 }340 }
341+ let is_key = h.frame_type == FrameType::Key;
306 if seq.reduced_still_picture_header {342 if seq.reduced_still_picture_header {
307 return Err(Error::unsupported(343 return Err(Error::unsupported(
308 "AV1 frame header",344 "AV1 frame header",
@@ -323,9 +359,14 @@ pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHead
323 }359 }
324 360
325 w.write_bit(false); // show_existing_frame361 w.write_bit(false); // show_existing_frame
326- w.write_bits(0, 2); // frame_type: KEY_FRAME362+ w.write_bits(if is_key { 0 } else { 1 }, 2); // frame_type
327 w.write_bit(true); // show_frame363 w.write_bit(true); // show_frame
328- // showable_frame and error_resilient_mode are forced for a shown key frame.364+ // showable_frame is derived by the reader when show_frame is set, and not coded.
365+ if is_key {
366+ // error_resilient_mode is forced true for a shown key frame.
367+ } else {
368+ w.write_bit(h.error_resilient_mode);
369+ }
329 370
330 w.write_bit(h.disable_cdf_update);371 w.write_bit(h.disable_cdf_update);
331 if seq.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS {372 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
342 }383 }
343 w.write_bit(h.frame_size_override_flag);384 w.write_bit(h.frame_size_override_flag);
344 w.write_bits(h.order_hint, seq.order_hint_bits);385 w.write_bits(h.order_hint, seq.order_hint_bits);
345- // primary_ref_frame, buffer_removal_time, refresh_frame_flags and the
346- // ref_order_hint loop are all forced for a shown key frame.
347 386
348- if h.frame_size_override_flag {387+ if h.frame_is_intra || h.error_resilient_mode {
349- w.write_bits(h.frame_width - 1, seq.frame_width_bits);388+ // primary_ref_frame is forced PRIMARY_REF_NONE and not coded.
350- w.write_bits(h.frame_height - 1, seq.frame_height_bits);389+ } else {
351- }390+ w.write_bits(u32::from(h.primary_ref_frame), 3);
352- if seq.enable_superres {
353- w.write_bit(h.use_superres);
354 }391 }
355- if h.use_superres || h.superres_denom != 8 {392+ // buffer_removal_time is not coded: decoder_model_info is refused above.
356- return Err(Error::unsupported(393+
357- "AV1 superres",394+ if is_key {
358- "only a superres denominator of 8 (no scaling) is written",395+ // refresh_frame_flags is forced to every slot for a shown key frame.
359- ));396+ } else {
397+ w.write_bits(u32::from(h.refresh_frame_flags), 8);
360 }398 }
361- let render_differs = h.render_width != h.upscaled_width || h.render_height != h.frame_height;399+ if (!h.frame_is_intra || h.refresh_frame_flags != u8::MAX)
362- w.write_bit(render_differs);400+ && h.error_resilient_mode
363- if render_differs {401+ && seq.enable_order_hint
364- w.write_bits(h.render_width - 1, 16);402+ {
365- w.write_bits(h.render_height - 1, 16);403+ for hint in h.ref_order_hint {
404+ w.write_bits(hint, seq.order_hint_bits);
405+ }
366 }406 }
367- if h.allow_screen_content_tools && h.upscaled_width == h.frame_width {407+
368- w.write_bit(h.allow_intrabc);408+ if h.frame_is_intra {
409+ write_frame_size(w, seq, h)?;
410+ if h.allow_screen_content_tools && h.upscaled_width == h.frame_width {
411+ w.write_bit(h.allow_intrabc);
412+ }
413+ } else {
414+ w.write_bit(h.frame_refs_short_signaling);
415+ if h.frame_refs_short_signaling {
416+ return Err(Error::unsupported(
417+ "AV1 frame header",
418+ "short reference frame signalling is not written",
419+ ));
420+ }
421+ for &idx in &h.ref_frame_idx[..REFS_PER_FRAME] {
422+ w.write_bits(u32::from(idx), 3);
423+ }
424+ if h.frame_size_override_flag && !h.error_resilient_mode {
425+ return Err(Error::unsupported(
426+ "AV1 frame header",
427+ "frame_size_with_refs is not written",
428+ ));
429+ }
430+ write_frame_size(w, seq, h)?;
431+
432+ w.write_bit(h.allow_high_precision_mv); // force_integer_mv is false here
433+ if h.interpolation_filter == InterpolationFilter::Switchable {
434+ w.write_bit(true);
435+ } else {
436+ w.write_bit(false);
437+ w.write_bits(h.interpolation_filter as u32, 2);
438+ }
439+ w.write_bit(h.is_motion_mode_switchable);
440+ if h.error_resilient_mode || !seq.enable_ref_frame_mvs {
441+ // use_ref_frame_mvs is forced false and not coded.
442+ } else {
443+ w.write_bit(h.use_ref_frame_mvs);
444+ }
445+ // OrderHints and RefFrameSignBias are derived from decoder state, not coded.
369 }446 }
447+
370 if !h.disable_cdf_update {448 if !h.disable_cdf_update {
371 w.write_bit(h.disable_frame_end_update_cdf);449 w.write_bit(h.disable_frame_end_update_cdf);
372 }450 }
451+ // disable_frame_end_update_cdf is forced true when disable_cdf_update is set.
373 452
374 write_tile_info(w, seq, h)?;453 write_tile_info(w, seq, h)?;
375 write_quantization_params(w, seq, h);454 write_quantization_params(w, seq, h);
@@ -402,8 +481,35 @@ pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHead
402 } else {481 } else {
403 w.write_bit(h.tx_mode == TxMode::Select);482 w.write_bit(h.tx_mode == TxMode::Select);
404 }483 }
405- // reference_select, skip mode and warped motion are all forced for intra.484+ if h.frame_is_intra {
485+ // reference_select is forced false and not coded.
486+ } else if h.reference_select {
487+ return Err(Error::unsupported(
488+ "AV1 frame header",
489+ "reference_select (and the skip mode it gates) is not written",
490+ ));
491+ } else {
492+ w.write_bit(false);
493+ // skip_mode_present is forced false when reference_select is false
494+ // (spec 5.9.22), and not coded.
495+ }
496+ if h.frame_is_intra || h.error_resilient_mode || !seq.enable_warped_motion {
497+ // allow_warped_motion is forced false and not coded.
498+ } else {
499+ w.write_bit(h.allow_warped_motion);
500+ }
406 w.write_bit(h.reduced_tx_set);501 w.write_bit(h.reduced_tx_set);
502+ if !h.frame_is_intra {
503+ for warp in &h.global_motion[..REFS_PER_FRAME] {
504+ if warp.model != WarpModel::Identity {
505+ return Err(Error::unsupported(
506+ "AV1 global motion",
507+ "only the identity model is written",
508+ ));
509+ }
510+ w.write_bit(false); // is_global
511+ }
512+ }
407 // Global motion is the identity for intra and is not coded.513 // Global motion is the identity for intra and is not coded.
408 if seq.film_grain_params_present {514 if seq.film_grain_params_present {
409 w.write_bit(h.film_grain.apply_grain);515 w.write_bit(h.film_grain.apply_grain);
@@ -624,9 +730,13 @@ mod tests {
624 fn unsupported_frames_are_refused_by_name() {730 fn unsupported_frames_are_refused_by_name() {
625 let seq = sample_1080p();731 let seq = sample_1080p();
626 732
627- let mut inter = sample_key_frame();733+ let mut intra_only = sample_key_frame();
628- inter.frame_type = FrameType::Inter;734+ intra_only.frame_type = FrameType::IntraOnly;
629- assert!(frame_obu(&seq, &inter, &[0x00]).is_err());735+ assert!(frame_obu(&seq, &intra_only, &[0x00]).is_err());
736+
737+ let mut switch = sample_key_frame();
738+ switch.frame_type = FrameType::Switch;
739+ assert!(frame_obu(&seq, &switch, &[0x00]).is_err());
630 740
631 let mut hidden = sample_key_frame();741 let mut hidden = sample_key_frame();
632 hidden.show_frame = false;742 hidden.show_frame = false;
@@ -646,4 +756,55 @@ mod tests {
646 grain_frame.film_grain.apply_grain = true;756 grain_frame.film_grain.apply_grain = true;
647 assert!(frame_obu(&grainy, &grain_frame, &[0x00]).is_err());757 assert!(frame_obu(&grainy, &grain_frame, &[0x00]).is_err());
648 }758 }
759+
760+ /// A key frame followed by two inter frames, all referencing the single
761+ /// slot the key frame filled: every field the parser hands back, parsed
762+ /// through [`ec_av1_syntax::Av1Parser`]'s own `FrameState` threading, must
763+ /// equal what was asked to be written, and the header must consume
764+ /// exactly the bit count the writer produced (a shifted field would still
765+ /// often parse to *some* value, but not to the same bit length).
766+ #[test]
767+ fn key_and_inter_frames_roundtrip() {
768+ let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
769+ let (seq_again, inter1) = crate::encode::inter_frame_headers(64, 64, 100, 1, 0).unwrap();
770+ assert_eq!(
771+ seq, seq_again,
772+ "an inter frame must reuse the sequence header verbatim"
773+ );
774+ let (_, inter2) = crate::encode::inter_frame_headers(64, 64, 100, 2, 0).unwrap();
775+
776+ let mut stream = sequence_header_obu(&seq).unwrap();
777+ stream.extend_from_slice(&frame_obu(&seq, &key, &[0xAA]).unwrap());
778+ stream.extend_from_slice(&frame_obu(&seq, &inter1, &[0xBB]).unwrap());
779+ stream.extend_from_slice(&frame_obu(&seq, &inter2, &[0xCC]).unwrap());
780+
781+ let mut parser = Av1Parser::new();
782+ let obus = parser.parse_temporal_unit(&stream).unwrap();
783+ assert_eq!(obus.len(), 4);
784+
785+ for (obu, expected) in obus[1..].iter().zip([&key, &inter1, &inter2]) {
786+ let ObuKind::Frame(parsed, _tiles) = &obu.kind else {
787+ panic!("expected an OBU_FRAME, got {:?}", obu.kind);
788+ };
789+
790+ let mut w = BitWriter::new();
791+ write_frame_header(&mut w, &seq, expected).unwrap();
792+ assert_eq!(
793+ parsed.header_bits,
794+ w.bit_len(),
795+ "the header must consume exactly the bits it was written with"
796+ );
797+
798+ // showable_frame, OrderHints, RefFrameSignBias and header_bits are
799+ // all derived by the reader (spec 5.9.2, 7.8) rather than coded;
800+ // the writer does not fill them in, so they are taken from the
801+ // parse before the rest of the header is compared field by field.
802+ let mut expected = expected.clone();
803+ expected.showable_frame = parsed.showable_frame;
804+ expected.order_hints = parsed.order_hints;
805+ expected.ref_frame_sign_bias = parsed.ref_frame_sign_bias;
806+ expected.header_bits = parsed.header_bits;
807+ assert_eq!(**parsed, expected);
808+ }
809+ }
649 }810 }
crates/ec-av1/src/lib.rsmodified+2 -0
@@ -18,7 +18,9 @@ mod cdf_state;
18 pub mod encode;18 pub mod encode;
19 pub mod frame;19 pub mod frame;
20 pub mod intra;20 pub mod intra;
21+pub mod mc;
21 pub mod msac;22 pub mod msac;
23+pub mod mvstack;
22 pub mod obu;24 pub mod obu;
23 pub mod quant;25 pub mod quant;
24 pub mod sequence;26 pub mod sequence;
crates/ec-av1/src/mc.rsadded+304 -0
@@ -0,0 +1,304 @@
1+//! Sub-pel motion compensation, spec 7.11.3 ("Motion vector scaling process"
2+//! through "Block inter predictor process"), the REGULAR (`EIGHTTAP`) filter
3+//! only, 8-bit samples only.
4+//!
5+//! A block's inter prediction is separable: an 8-tap horizontal pass over the
6+//! reference, rounded down by `InterRound0`, feeds an 8-tap vertical pass
7+//! over that intermediate, rounded down by `InterRound1`. Both fractions run
8+//! in 1/16-pel steps -- luma motion vectors are stored at 1/8-pel and always
9+//! land on an even step; chroma vectors, once scaled for subsampling, can
10+//! land on any of the 16.
11+
12+/// `Round2` (spec 4.7): halves round up.
13+fn round2(value: i32, shift: u32) -> i32 {
14+ if shift == 0 {
15+ value
16+ } else {
17+ (value + (1 << (shift - 1))) >> shift
18+ }
19+}
20+
21+/// `InterRound0` (spec 7.11.3.2), 8-bit, non-compound: the shift the
22+/// horizontal pass's sum is brought down by before it is stored as the
23+/// intermediate.
24+const INTER_ROUND_0: u32 = 3;
25+/// `InterRound1` (spec 7.11.3.2), 8-bit, non-compound: the shift the vertical
26+/// pass's sum is brought down by to land back on an 8-bit sample. Composed
27+/// with `INTER_ROUND_0` the two shifts are the filter's own gain (each pass
28+/// sums to 128, `128 * 128 == 1 << 14 == 1 << (INTER_ROUND_0 + INTER_ROUND_1)`)
29+/// -- so an identity or DC input comes back exactly, by construction of the
30+/// table rather than by a fitted constant.
31+const INTER_ROUND_1: u32 = 11;
32+
33+/// `Subpel_Filters[EIGHTTAP]` (spec 7.11.3.3): 16 rows, one per 1/16-pel
34+/// fraction, each an 8-tap kernel centred so tap index 3 lands on the integer
35+/// sample (fraction 0 is the identity tap `[.., 128, ..]`).
36+const SUBPEL_FILTERS: [[i32; 8]; 16] = [
37+ [0, 0, 0, 128, 0, 0, 0, 0],
38+ [0, 2, -6, 126, 8, -2, 0, 0],
39+ [0, 2, -10, 122, 18, -4, 0, 0],
40+ [0, 2, -12, 116, 28, -8, 2, 0],
41+ [0, 2, -14, 110, 38, -10, 2, 0],
42+ [0, 2, -14, 102, 48, -12, 2, 0],
43+ [0, 2, -16, 94, 58, -12, 2, 0],
44+ [0, 2, -14, 84, 66, -12, 2, 0],
45+ [0, 2, -14, 76, 76, -14, 2, 0],
46+ [0, 2, -12, 66, 84, -14, 2, 0],
47+ [0, 2, -12, 58, 94, -16, 2, 0],
48+ [0, 2, -12, 48, 102, -14, 2, 0],
49+ [0, 2, -10, 38, 110, -14, 2, 0],
50+ [0, 2, -8, 28, 116, -12, 2, 0],
51+ [0, 0, -4, 18, 122, -10, 2, 0],
52+ [0, 0, -2, 8, 126, -6, 2, 0],
53+];
54+
55+/// A reference sample at `(x, y)`, clamped to the plane's bounds (spec
56+/// 7.11.3.4's `Clip3` against the frame's edges) rather than read out of
57+/// range -- a motion vector that points past the frame repeats the edge
58+/// sample instead of panicking.
59+fn sample(reference: &[u8], ref_width: usize, ref_height: usize, x: i32, y: i32) -> i32 {
60+ let cx = x.clamp(0, ref_width as i32 - 1) as usize;
61+ let cy = y.clamp(0, ref_height as i32 - 1) as usize;
62+ i32::from(reference[cy * ref_width + cx])
63+}
64+
65+/// Predicts one `block_w * block_h` block into `dst`, row-major, from
66+/// `reference` (row-major, `ref_width * ref_height`, stride `ref_width`).
67+///
68+/// `x_q4` / `y_q4` are the block's top-left position in the reference, in
69+/// 1/16-pel units (an integer MV has its low 4 bits zero); this function
70+/// splits each into its whole-sample part and its 0..16 fraction itself, so
71+/// the caller need not pre-split a motion vector.
72+///
73+/// # Panics
74+/// Panics when `dst` is not `block_w * block_h` long, or the reference is
75+/// empty.
76+#[allow(clippy::too_many_arguments)] // one reference plane, one position, one block shape
77+pub fn predict(
78+ reference: &[u8],
79+ ref_width: usize,
80+ ref_height: usize,
81+ x_q4: i32,
82+ y_q4: i32,
83+ block_w: usize,
84+ block_h: usize,
85+ dst: &mut [u8],
86+) {
87+ assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
88+ assert!(!reference.is_empty(), "a reference plane has samples");
89+
90+ let x0 = x_q4.div_euclid(16);
91+ let xfrac = x_q4.rem_euclid(16) as usize;
92+ let y0 = y_q4.div_euclid(16);
93+ let yfrac = y_q4.rem_euclid(16) as usize;
94+
95+ let h_filter = &SUBPEL_FILTERS[xfrac];
96+ let v_filter = &SUBPEL_FILTERS[yfrac];
97+
98+ // The vertical pass reads 3 rows above and 4 below the block, so the
99+ // horizontal pass must produce that many extra intermediate rows.
100+ let rows = block_h + 7;
101+ let mut intermediate = vec![0i32; rows * block_w];
102+ for r in 0..rows {
103+ let y = y0 - 3 + r as i32;
104+ for c in 0..block_w {
105+ let mut sum = 0;
106+ for (t, &tap) in h_filter.iter().enumerate() {
107+ let x = x0 + c as i32 + t as i32 - 3;
108+ sum += tap * sample(reference, ref_width, ref_height, x, y);
109+ }
110+ intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0);
111+ }
112+ }
113+
114+ for row in 0..block_h {
115+ for col in 0..block_w {
116+ let mut sum = 0;
117+ for (t, &tap) in v_filter.iter().enumerate() {
118+ sum += tap * intermediate[(row + t) * block_w + col];
119+ }
120+ dst[row * block_w + col] = round2(sum, INTER_ROUND_1).clamp(0, 255) as u8;
121+ }
122+ }
123+}
124+
125+#[cfg(test)]
126+mod tests {
127+ use super::predict;
128+
129+ #[test]
130+ fn integer_mv_is_identity() {
131+ let width = 12;
132+ let height = 12;
133+ let reference: Vec<u8> = (0..width * height).map(|i| (i * 7 % 251) as u8).collect();
134+ let mut dst = vec![0u8; 6 * 6];
135+ predict(&reference, width, height, 3 * 16, 4 * 16, 6, 6, &mut dst);
136+ for row in 0..6 {
137+ for col in 0..6 {
138+ assert_eq!(
139+ dst[row * 6 + col],
140+ reference[(4 + row) * width + 3 + col],
141+ "integer MV must reproduce the reference block byte-for-byte"
142+ );
143+ }
144+ }
145+ }
146+
147+ #[test]
148+ fn half_pel_reproduces_the_ramp_midpoint() {
149+ // Step 2 so every half-pel position lands on an exact integer.
150+ let width = 16;
151+ let height = 16;
152+ let reference: Vec<u8> = (0..width * height)
153+ .map(|i| (2 * (i % width)) as u8)
154+ .collect();
155+ let mut dst = vec![0u8; 4 * 4];
156+ // Half-pel in x only: fraction 8/16, integer part at column 5.
157+ predict(
158+ &reference,
159+ width,
160+ height,
161+ 5 * 16 + 8,
162+ 5 * 16,
163+ 4,
164+ 4,
165+ &mut dst,
166+ );
167+ for row in 0..4 {
168+ for col in 0..4 {
169+ let midpoint = 2 * (5 + col) + 1; // halfway between col and col+1
170+ assert_eq!(
171+ dst[row * 4 + col] as i32,
172+ midpoint as i32,
173+ "half-pel MV over a linear ramp must land exactly on the midpoint"
174+ );
175+ }
176+ }
177+ }
178+
179+ #[test]
180+ fn constant_plane_has_unit_dc_gain_at_every_subpel_position() {
181+ let width = 20;
182+ let height = 20;
183+ let reference = vec![142u8; width * height];
184+ for yfrac in 0..16 {
185+ for xfrac in 0..16 {
186+ let mut dst = vec![0u8; 5 * 5];
187+ predict(
188+ &reference,
189+ width,
190+ height,
191+ 5 * 16 + xfrac,
192+ 5 * 16 + yfrac,
193+ 5,
194+ 5,
195+ &mut dst,
196+ );
197+ assert!(
198+ dst.iter().all(|&v| v == 142),
199+ "DC gain must be exactly 1 at fraction ({xfrac}, {yfrac}), got {dst:?}"
200+ );
201+ }
202+ }
203+ }
204+
205+ #[test]
206+ fn horizontal_and_vertical_only_filtering_differ() {
207+ // A plane linear in both x and y with different, even coefficients so
208+ // each axis's half-pel interpolation lands on an exact integer: this
209+ // pins the actual value each pass produces, not just that the two
210+ // differ, so swapping which pass reads which axis is caught even if
211+ // it happened to produce two merely-different numbers.
212+ let width = 10;
213+ let height = 10;
214+ let reference: Vec<u8> = (0..height)
215+ .flat_map(|y| (0..width).map(move |x| (20 * x + 4 * y) as u8))
216+ .collect();
217+
218+ let mut horiz = vec![0u8; 4 * 4];
219+ predict(
220+ &reference,
221+ width,
222+ height,
223+ 3 * 16 + 8,
224+ 3 * 16,
225+ 4,
226+ 4,
227+ &mut horiz,
228+ );
229+ let mut vert = vec![0u8; 4 * 4];
230+ predict(
231+ &reference,
232+ width,
233+ height,
234+ 3 * 16,
235+ 3 * 16 + 8,
236+ 4,
237+ 4,
238+ &mut vert,
239+ );
240+
241+ for row in 0..4 {
242+ for col in 0..4 {
243+ // Horizontal half-pel: x interpolates to x0+col+0.5, y stays put.
244+ assert_eq!(
245+ horiz[row * 4 + col] as i32,
246+ 20 * (3 + col as i32) + 10 + 4 * (3 + row as i32),
247+ "horizontal-only MV must interpolate along x only"
248+ );
249+ // Vertical half-pel: y interpolates to y0+row+0.5, x stays put.
250+ assert_eq!(
251+ vert[row * 4 + col] as i32,
252+ 20 * (3 + col as i32) + 4 * (3 + row as i32) + 2,
253+ "vertical-only MV must interpolate along y only"
254+ );
255+ }
256+ }
257+ assert_ne!(
258+ horiz, vert,
259+ "horizontal-only and vertical-only sub-pel MVs must give different outputs"
260+ );
261+ }
262+
263+ #[test]
264+ fn mv_past_the_edge_clamps_instead_of_panicking() {
265+ let width = 8;
266+ let height = 8;
267+ let reference: Vec<u8> = (0..width * height).map(|i| (i * 3 % 200) as u8).collect();
268+ let mut dst = vec![0u8; 4 * 4];
269+ // Whole-sample position far above and to the left of the plane, with
270+ // an odd fraction so both filter passes exercise the clamp.
271+ predict(
272+ &reference,
273+ width,
274+ height,
275+ -50 * 16 + 5,
276+ -50 * 16 + 5,
277+ 4,
278+ 4,
279+ &mut dst,
280+ );
281+ let expected = reference[0]; // the whole plane clamps to the top-left corner
282+ assert!(
283+ dst.iter().all(|&v| v == expected),
284+ "an MV past the top-left edge must clamp to the corner sample, got {dst:?}"
285+ );
286+
287+ let mut dst2 = vec![0u8; 4 * 4];
288+ predict(
289+ &reference,
290+ width,
291+ height,
292+ 50 * 16 + 5,
293+ 50 * 16 + 5,
294+ 4,
295+ 4,
296+ &mut dst2,
297+ );
298+ let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner
299+ assert!(
300+ dst2.iter().all(|&v| v == expected2),
301+ "an MV past the bottom-right edge must clamp to the corner sample, got {dst2:?}"
302+ );
303+ }
304+}
crates/ec-av1/src/mvstack.rsadded+399 -0
@@ -0,0 +1,399 @@
1+//! Reference MV list construction (AV1 spec 7.10.2, `find_mv_stack`),
2+//! reduced to the single-reference, non-compound, `use_ref_frame_mvs = 0`
3+//! case a key/inter frame without temporal MV projection needs.
4+//!
5+//! Implemented from the spec: the row-above scan (7.10.2.2), the col-left
6+//! scan (7.10.2.3), a single top-right probe (the first of 7.10.2.4's extra
7+//! positions), weight-based dedupe (7.10.2.5's `add_ref_mv_candidate`), the
8+//! weight-descending sort (7.10.2.6), and the DRL context derivation from
9+//! `REF_CAT_LEVEL` (7.10.2.8, the one piece of that section whose constant
10+//! and shape is unambiguous from the spec text).
11+//!
12+//! Deliberately reduced away (see the crate report, not reproduced bit-exact
13+//! here): compound/multi-reference candidates, the temporal MV projection
14+//! scan, the `>1` row/col scans at offset 3 and their skip-by-block-size
15+//! stepping, and the exact `NewMvContext`/`RefMvContext`/`ZeroMvContext`
16+//! tables — spec 7.10.2.8 derives those through several more match classes
17+//! than this reduction tracks, and nothing in this crate consumes them yet
18+//! (no CDF wiring), so the formulas below are a documented, monotonic
19+//! stand-in rather than a proven port. Also reduced away: clamping
20+//! `NearestMv`/`NearMv`/`PredMv` to the frame's allowed MV range
21+//! (7.10.2.14) — the caller gets unclamped values.
22+
23+/// One 4x4 `mi` unit's motion state, as the encode loop will have filled it
24+/// in by the time it asks for a block's MV stack.
25+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26+pub struct MiInfo {
27+ /// Whether this unit was coded inter (as opposed to intra).
28+ pub is_inter: bool,
29+ /// The single reference frame this unit's MV points into. Ignored (and
30+ /// the unit contributes no candidate) when `is_inter` is `false`.
31+ pub ref_frame: i8,
32+ /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units.
33+ pub mv: (i32, i32),
34+}
35+
36+/// The whole frame's `mi` grid, one [`MiInfo`] per 4x4 unit, in raster order.
37+/// A unit an encode pass hasn't visited yet (or that sits outside the tile)
38+/// reads as `None` and contributes nothing to any block's MV stack.
39+#[derive(Clone, Debug)]
40+pub struct MiGrid {
41+ cols: usize,
42+ rows: usize,
43+ cells: Vec<Option<MiInfo>>,
44+}
45+
46+impl MiGrid {
47+ /// A grid of `cols` by `rows` 4x4 units, all initially unset.
48+ pub fn new(cols: usize, rows: usize) -> Self {
49+ Self {
50+ cols,
51+ rows,
52+ cells: vec![None; cols * rows],
53+ }
54+ }
55+
56+ /// Records the unit at `(row, col)`. Out-of-range coordinates are a
57+ /// no-op — the caller only ever addresses units inside the grid it built.
58+ pub fn set(&mut self, row: usize, col: usize, info: MiInfo) {
59+ if row < self.rows && col < self.cols {
60+ self.cells[row * self.cols + col] = Some(info);
61+ }
62+ }
63+
64+ /// The unit at `(row, col)`, or `None` when it is outside the grid (the
65+ /// tile) or hasn't been coded.
66+ pub fn get(&self, row: usize, col: usize) -> Option<&MiInfo> {
67+ if row < self.rows && col < self.cols {
68+ self.cells[row * self.cols + col].as_ref()
69+ } else {
70+ None
71+ }
72+ }
73+}
74+
75+/// One entry of the reference MV stack: a candidate motion vector and the
76+/// total weight the neighbours that agreed on it contributed.
77+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78+pub struct StackEntry {
79+ /// The candidate `(row, col)` motion vector.
80+ pub mv: (i32, i32),
81+ /// The summed weight of every neighbour cell that voted for this MV.
82+ pub weight: u32,
83+}
84+
85+/// The result of [`find_mv_stack`]: the sorted candidate list, the two
86+/// predictors a `NEARESTMV`/`NEARMV` block reads from it, the predictor a
87+/// `NEWMV` residual is coded against, and the symbol contexts the block's
88+/// mode and DRL-index syntax elements are coded with.
89+#[derive(Clone, Debug, PartialEq, Eq)]
90+pub struct MvStack {
91+ /// The candidates, highest weight first (ties keep scan order: above,
92+ /// then left, then top-right).
93+ pub entries: Vec<StackEntry>,
94+ /// `RefStackMv[0]`, or `(0, 0)` when the stack is empty.
95+ pub nearest_mv: (i32, i32),
96+ /// `RefStackMv[1]`, or `(0, 0)` when the stack has fewer than two
97+ /// entries.
98+ pub near_mv: (i32, i32),
99+ /// The predictor a `NEWMV` block's MV difference is coded against:
100+ /// `nearest_mv` when the stack is non-empty, `(0, 0)` otherwise.
101+ pub pred_mv: (i32, i32),
102+ /// Context for the `new_mv` symbol.
103+ pub new_mv_ctx: usize,
104+ /// Context for the `ref_mv` symbol.
105+ pub ref_mv_ctx: usize,
106+ /// Context for the `zero_mv` symbol.
107+ pub zero_mv_ctx: usize,
108+ /// Context for each `drl_mode` symbol between consecutive stack
109+ /// entries, `entries.len().saturating_sub(1)` long.
110+ pub drl_ctx: Vec<usize>,
111+}
112+
113+/// Spec 7.10.2.8's threshold a candidate's weight is compared against to
114+/// pick its DRL context.
115+const REF_CAT_LEVEL: u32 = 640;
116+
117+/// The most candidates a stack keeps (spec `MAX_REF_MV_STACK_SIZE`).
118+const MAX_STACK_SIZE: usize = 8;
119+
120+/// Weight one immediate (row `-1` / col `-1`) neighbour 4x4 unit's vote
121+/// counts for (spec: `len * 2` with `len = 1` per unit for the reduction
122+/// this module makes — see the module doc).
123+const IMMEDIATE_WEIGHT: u32 = 2;
124+
125+/// Adds one candidate MV with `weight` to `candidates`, merging it into an
126+/// existing entry with the same MV rather than duplicating it (spec
127+/// `add_ref_mv_candidate`, 7.10.2.5).
128+fn add_candidate(candidates: &mut Vec<StackEntry>, mv: (i32, i32), weight: u32) {
129+ if let Some(entry) = candidates.iter_mut().find(|e| e.mv == mv) {
130+ entry.weight += weight;
131+ } else {
132+ candidates.push(StackEntry { mv, weight });
133+ }
134+}
135+
136+/// The row-above scan (spec 7.10.2.2): every 4x4 unit directly above the
137+/// block's span. Returns whether any unit voted.
138+fn scan_row(
139+ grid: &MiGrid,
140+ mi_row: usize,
141+ mi_col: usize,
142+ bw4: usize,
143+ ref_frame: i8,
144+ candidates: &mut Vec<StackEntry>,
145+) -> bool {
146+ let Some(row) = mi_row.checked_sub(1) else {
147+ return false;
148+ };
149+ let mut found = false;
150+ for col in mi_col..mi_col + bw4 {
151+ if let Some(info) = grid.get(row, col)
152+ && info.is_inter
153+ && info.ref_frame == ref_frame
154+ {
155+ found = true;
156+ add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
157+ }
158+ }
159+ found
160+}
161+
162+/// The col-left scan (spec 7.10.2.3): every 4x4 unit directly left of the
163+/// block's span. Returns whether any unit voted.
164+fn scan_col(
165+ grid: &MiGrid,
166+ mi_row: usize,
167+ mi_col: usize,
168+ bh4: usize,
169+ ref_frame: i8,
170+ candidates: &mut Vec<StackEntry>,
171+) -> bool {
172+ let Some(col) = mi_col.checked_sub(1) else {
173+ return false;
174+ };
175+ let mut found = false;
176+ for row in mi_row..mi_row + bh4 {
177+ if let Some(info) = grid.get(row, col)
178+ && info.is_inter
179+ && info.ref_frame == ref_frame
180+ {
181+ found = true;
182+ add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
183+ }
184+ }
185+ found
186+}
187+
188+/// The single top-right probe this reduction keeps of spec 7.10.2.4's extra
189+/// scan positions, at the unit diagonally above-right of the block. Its
190+/// vote is folded into the row scan's candidates (it sits on the same row
191+/// as the block's neighbours above), which is what makes the row and column
192+/// scans asymmetric under transposing a grid — spec has no matching
193+/// bottom-left probe.
194+fn scan_top_right(
195+ grid: &MiGrid,
196+ mi_row: usize,
197+ mi_col: usize,
198+ bw4: usize,
199+ ref_frame: i8,
200+ candidates: &mut Vec<StackEntry>,
201+) -> bool {
202+ let Some(row) = mi_row.checked_sub(1) else {
203+ return false;
204+ };
205+ let col = mi_col + bw4;
206+ if let Some(info) = grid.get(row, col)
207+ && info.is_inter
208+ && info.ref_frame == ref_frame
209+ {
210+ add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
211+ return true;
212+ }
213+ false
214+}
215+
216+/// Builds the reference MV stack for the `bw4`-by-`bh4` (in 4x4 units)
217+/// block at `(mi_row, mi_col)`, predicting against `ref_frame`.
218+pub fn find_mv_stack(
219+ grid: &MiGrid,
220+ mi_row: usize,
221+ mi_col: usize,
222+ bw4: usize,
223+ bh4: usize,
224+ ref_frame: i8,
225+) -> MvStack {
226+ let mut candidates = Vec::new();
227+ let found_above = scan_row(grid, mi_row, mi_col, bw4, ref_frame, &mut candidates);
228+ let found_left = scan_col(grid, mi_row, mi_col, bh4, ref_frame, &mut candidates);
229+ let found_top_right = scan_top_right(grid, mi_row, mi_col, bw4, ref_frame, &mut candidates);
230+
231+ // Highest weight first; a stable sort keeps scan order (above, left,
232+ // top-right) among ties, matching spec 7.10.2.6.
233+ candidates.sort_by_key(|e| std::cmp::Reverse(e.weight));
234+ candidates.truncate(MAX_STACK_SIZE);
235+
236+ let nearest_mv = candidates.first().map_or((0, 0), |e| e.mv);
237+ let near_mv = candidates.get(1).map_or((0, 0), |e| e.mv);
238+ let pred_mv = if candidates.is_empty() {
239+ (0, 0)
240+ } else {
241+ nearest_mv
242+ };
243+
244+ let close_matches = usize::from(found_above) + usize::from(found_left);
245+ let total_matches = close_matches + usize::from(found_top_right);
246+
247+ // Reduced context tables (see module doc): monotonic in how much
248+ // neighbour agreement was found, not a bit-exact port of 7.10.2.8.
249+ let new_mv_ctx = match (found_above, found_left, candidates.len()) {
250+ (false, false, _) => 0,
251+ (true, false, _) | (false, true, _) => 1,
252+ (true, true, 1) => 2,
253+ (true, true, _) => 3,
254+ };
255+ let ref_mv_ctx = total_matches.min(5);
256+ let zero_mv_ctx = usize::from(nearest_mv != (0, 0));
257+
258+ let drl_ctx = candidates
259+ .windows(2)
260+ .map(|w| {
261+ let (a, b) = (w[0].weight, w[1].weight);
262+ if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL {
263+ 1
264+ } else if a < REF_CAT_LEVEL && b < REF_CAT_LEVEL {
265+ 2
266+ } else {
267+ 0
268+ }
269+ })
270+ .collect();
271+
272+ MvStack {
273+ entries: candidates,
274+ nearest_mv,
275+ near_mv,
276+ pred_mv,
277+ new_mv_ctx,
278+ ref_mv_ctx,
279+ zero_mv_ctx,
280+ drl_ctx,
281+ }
282+}
283+
284+#[cfg(test)]
285+mod tests {
286+ use super::*;
287+
288+ fn inter(mv: (i32, i32)) -> MiInfo {
289+ MiInfo {
290+ is_inter: true,
291+ ref_frame: 1,
292+ mv,
293+ }
294+ }
295+
296+ #[test]
297+ fn all_same_mv_neighbourhood_dedupes_to_one_entry() {
298+ let mut grid = MiGrid::new(8, 8);
299+ // Block at (2, 2), 2x2 mi units. Above row 1, cols 2..4; left col 1,
300+ // rows 2..4; top-right at (1, 4). All the same MV.
301+ let mv = (4, 4);
302+ grid.set(1, 2, inter(mv));
303+ grid.set(1, 3, inter(mv));
304+ grid.set(2, 1, inter(mv));
305+ grid.set(3, 1, inter(mv));
306+ grid.set(1, 4, inter(mv));
307+
308+ let stack = find_mv_stack(&grid, 2, 2, 2, 2, 1);
309+
310+ assert_eq!(stack.entries.len(), 1);
311+ assert_eq!(stack.entries[0].mv, mv);
312+ // 2 above cells + 2 left cells + 1 top-right, each weight 2.
313+ assert_eq!(stack.entries[0].weight, 10);
314+ assert_eq!(stack.nearest_mv, mv);
315+ // Documented reduced-context value (see module doc): both sides
316+ // found a match and they collapsed to a single stack entry.
317+ assert_eq!(stack.new_mv_ctx, 2);
318+ }
319+
320+ #[test]
321+ fn two_distinct_neighbour_mvs_yield_two_entries_in_weight_order() {
322+ let mut grid = MiGrid::new(8, 8);
323+ // Block at (3, 3), bw4=2, bh4=3: above spans 2 cells (weight 4),
324+ // left spans 3 cells (weight 6) — distinct MVs, distinct weights.
325+ let above_mv = (4, 4);
326+ let left_mv = (8, 8);
327+ grid.set(2, 3, inter(above_mv));
328+ grid.set(2, 4, inter(above_mv));
329+ grid.set(3, 2, inter(left_mv));
330+ grid.set(4, 2, inter(left_mv));
331+ grid.set(5, 2, inter(left_mv));
332+
333+ let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1);
334+
335+ assert_eq!(stack.entries.len(), 2);
336+ assert_eq!(
337+ stack.entries[0],
338+ StackEntry {
339+ mv: left_mv,
340+ weight: 6
341+ }
342+ );
343+ assert_eq!(
344+ stack.entries[1],
345+ StackEntry {
346+ mv: above_mv,
347+ weight: 4
348+ }
349+ );
350+ assert_eq!(stack.nearest_mv, left_mv);
351+ assert_eq!(stack.near_mv, above_mv);
352+ }
353+
354+ #[test]
355+ fn transposing_above_and_left_produces_a_different_stack() {
356+ // Grid A: above = (4,4) x2 cells, left = (8,8) x2 cells, top-right
357+ // matches the above MV (so it folds into the above bucket, making
358+ // it heavier than left).
359+ let mut a = MiGrid::new(8, 8);
360+ a.set(1, 2, inter((4, 4)));
361+ a.set(1, 3, inter((4, 4)));
362+ a.set(2, 1, inter((8, 8)));
363+ a.set(3, 1, inter((8, 8)));
364+ a.set(1, 4, inter((4, 4)));
365+ let stack_a = find_mv_stack(&a, 2, 2, 2, 2, 1);
366+
367+ // Grid B: the naive transpose — swap which MV sits above vs left —
368+ // with the top-right probe again matching whatever now sits above.
369+ let mut b = MiGrid::new(8, 8);
370+ b.set(1, 2, inter((8, 8)));
371+ b.set(1, 3, inter((8, 8)));
372+ b.set(2, 1, inter((4, 4)));
373+ b.set(3, 1, inter((4, 4)));
374+ b.set(1, 4, inter((8, 8)));
375+ let stack_b = find_mv_stack(&b, 2, 2, 2, 2, 1);
376+
377+ assert_ne!(stack_a, stack_b);
378+ assert_eq!(stack_a.entries[0].mv, (4, 4));
379+ assert_eq!(stack_b.entries[0].mv, (8, 8));
380+ }
381+
382+ #[test]
383+ fn mi_units_outside_the_tile_contribute_nothing() {
384+ let grid = MiGrid::new(4, 4);
385+ // Block at the tile's top-left corner: no row above, no col left,
386+ // and the top-right probe is also off the top edge.
387+ let stack = find_mv_stack(&grid, 0, 0, 2, 2, 1);
388+
389+ assert!(stack.entries.is_empty());
390+ assert_eq!(stack.nearest_mv, (0, 0));
391+ assert_eq!(stack.near_mv, (0, 0));
392+ assert_eq!(stack.pred_mv, (0, 0));
393+ assert!(stack.drl_ctx.is_empty());
394+
395+ // Out-of-range reads are also inert directly against the grid.
396+ assert!(grid.get(0, 10).is_none());
397+ assert!(grid.get(10, 0).is_none());
398+ }
399+}
crates/ec-h265-syntax/src/slice.rsmodified+11 -0
@@ -430,6 +430,17 @@ impl SliceHeader {
430 if h.slice_type == SliceType::B {430 if h.slice_type == SliceType::B {
431 h.num_ref_idx_l1_active_minus1 = r.read_ue()?;431 h.num_ref_idx_l1_active_minus1 = r.read_ue()?;
432 }432 }
433+ // 7.4.7.1: both fields are in range 0..=14. Past that is
434+ // a corrupt stream, not a bigger reference list -- and
435+ // pred_weight_table below sizes a Vec from this value, so
436+ // an unchecked ue(v) is a header-declared allocation an
437+ // attacker fully controls (up to 2^32 entries from a
438+ // handful of bits).
439+ if h.num_ref_idx_l0_active_minus1 > 14 || h.num_ref_idx_l1_active_minus1 > 14 {
440+ return Err(Error::corrupt(
441+ "HEVC slice header: num_ref_idx_lX_active_minus1 out of range",
442+ ));
443+ }
433 }444 }
434 let num_pic_total_curr = h.short_term_ref_pic_set.num_used_by_curr + num_long_term;445 let num_pic_total_curr = h.short_term_ref_pic_set.num_used_by_curr + num_long_term;
435 if pps.lists_modification_present && num_pic_total_curr > 1 {446 if pps.lists_modification_present && num_pic_total_curr > 1 {
crates/ec-image/src/gif.rsmodified+30 -3
@@ -14,7 +14,7 @@
14 //! so a decoder that waits one code longer reads small pictures correctly and14 //! so a decoder that waits one code longer reads small pictures correctly and
15 //! large ones as noise.15 //! large ones as noise.
16 16
17-use crate::{AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels};17+use crate::{AllocBudget, AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels};
18 use ec_core::{Error, Result};18 use ec_core::{Error, Result};
19 19
20 /// GIF interlace: `(start, step)` for each of the four passes.20 /// 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<Vec<u8>
150 let mut pos = 0;150 let mut pos = 0;
151 151
152 while let Some(code) = lzw.read_code(data, &mut pos) {152 while let Some(code) = lzw.read_code(data, &mut pos) {
153+ if out.len() >= expected {
154+ // Output already satisfies the declared frame size; a bomb-style
155+ // stream can keep growing the dictionary and emitting further
156+ // codes after this point, so stop before decoding any more of
157+ // them rather than let `out` expand unbounded (LZW bomb).
158+ break;
159+ }
153 if code == lzw.clear_code {160 if code == lzw.clear_code {
154 lzw.reset();161 lzw.reset();
155 continue;162 continue;
@@ -328,7 +335,13 @@ fn indices_to_rgba(indices: &[u8], palette: &[[u8; 3]], gce: Option<&Gce>) -> Re
328 /// Composite every raw frame onto a full-canvas buffer: blend the frame over335 /// Composite every raw frame onto a full-canvas buffer: blend the frame over
329 /// the canvas, then apply its disposal method to the canvas the next frame336 /// the canvas, then apply its disposal method to the canvas the next frame
330 /// starts from.337 /// starts from.
331-fn composite(frames: Vec<RawFrame>, canvas_w: u32, canvas_h: u32) -> Result<Vec<AnimationFrame>> {338+fn composite(
339+ frames: Vec<RawFrame>,
340+ canvas_w: u32,
341+ canvas_h: u32,
342+ limits: &Limits,
343+ budget: &mut AllocBudget,
344+) -> Result<Vec<AnimationFrame>> {
332 let cw = canvas_w as usize;345 let cw = canvas_w as usize;
333 let ch = canvas_h as usize;346 let ch = canvas_h as usize;
334 let n = cw * ch;347 let n = cw * ch;
@@ -337,6 +350,10 @@ fn composite(frames: Vec<RawFrame>, canvas_w: u32, canvas_h: u32) -> Result<Vec<
337 let mut result: Vec<(Vec<[u8; 4]>, u32)> = Vec::with_capacity(frames.len());350 let mut result: Vec<(Vec<[u8; 4]>, u32)> = Vec::with_capacity(frames.len());
338 351
339 for frame in frames {352 for frame in frames {
353+ // Every frame clones the whole canvas -- the real multiplier a
354+ // single buffer's own bound never catches -- so it is spent from the
355+ // decode-wide budget just like the frame's own indices were above.
356+ budget.spend(limits, "GIF composited canvas", n * 4)?;
340 let indices = if frame.interlaced {357 let indices = if frame.interlaced {
341 deinterlace(&frame.indices, frame.width as usize, frame.height as usize)358 deinterlace(&frame.indices, frame.width as usize, frame.height as usize)
342 } else {359 } else {
@@ -482,6 +499,8 @@ pub fn decode_animation(data: &[u8], limits: Limits) -> Result<Vec<AnimationFram
482 // Block loop499 // Block loop
483 let mut frames = Vec::new();500 let mut frames = Vec::new();
484 let mut pending_gce: Option<Gce> = None;501 let mut pending_gce: Option<Gce> = None;
502+ let mut budget = AllocBudget::default();
503+ budget.spend(&limits, "GIF canvas", canvas_bytes)?;
485 504
486 loop {505 loop {
487 let block = r.u8()?;506 let block = r.u8()?;
@@ -497,6 +516,14 @@ pub fn decode_animation(data: &[u8], limits: Limits) -> Result<Vec<AnimationFram
497 if width == 0 || height == 0 {516 if width == 0 || height == 0 {
498 return Err(Error::corrupt("GIF: zero-size frame"));517 return Err(Error::corrupt("GIF: zero-size frame"));
499 }518 }
519+ // A frame's own rectangle is a header field like any other --
520+ // nothing says it has to fit inside the canvas the logical
521+ // screen descriptor already bounded, so it gets its own check
522+ // before it sizes the indices buffer below.
523+ limits.check(width, height)?;
524+ let indices_bytes =
525+ limits.check_bytes("GIF frame indices", (width as usize).checked_mul(height as usize))?;
526+ budget.spend(&limits, "GIF frame indices", indices_bytes)?;
500 527
501 let has_lct = fpacked & 0x80 != 0;528 let has_lct = fpacked & 0x80 != 0;
502 let interlaced = fpacked & 0x40 != 0;529 let interlaced = fpacked & 0x40 != 0;
@@ -567,5 +594,5 @@ pub fn decode_animation(data: &[u8], limits: Limits) -> Result<Vec<AnimationFram
567 return Err(Error::corrupt("GIF: no image data"));594 return Err(Error::corrupt("GIF: no image data"));
568 }595 }
569 596
570- composite(frames, canvas_w, canvas_h)597+ composite(frames, canvas_w, canvas_h, &limits, &mut budget)
571 }598 }
crates/ec-image/src/lib.rsmodified+38 -9
@@ -136,9 +136,10 @@ pub struct Limits {
136 /// Largest total bytes accepted across every frame of one decode call.136 /// Largest total bytes accepted across every frame of one decode call.
137 ///137 ///
138 /// A single frame can pass [`Limits::check_bytes`] on its own and still138 /// A single frame can pass [`Limits::check_bytes`] on its own and still
139- /// be a bomb once a segment count multiplies it — a stripped or tiled139+ /// be a bomb once a frame or segment count multiplies it — GIF and WebP
140- /// TIFF decompresses many segments per call, so a file whose segments140+ /// both composite onto a full canvas per frame, and a stripped or tiled
141- /// each look small on their own can still retain gigabytes nothing ever141+ /// TIFF decompresses many segments per call, so a file whose parts each
142+ /// look small on their own can still retain gigabytes nothing ever
142 /// checked one buffer at a time. [`AllocBudget`] enforces this across a143 /// checked one buffer at a time. [`AllocBudget`] enforces this across a
143 /// decode call.144 /// decode call.
144 pub max_total_alloc: usize,145 pub max_total_alloc: usize,
@@ -170,8 +171,8 @@ impl Limits {
170 Ok(())171 Ok(())
171 }172 }
172 173
173- /// Check a byte count computed from header-declared fields (a strip's174+ /// Check a byte count computed from header-declared fields (a frame's or
174- /// `width * height * bpp`, a palette size, a chunk length) before it175+ /// strip's `width * height * bpp`, a palette size, a chunk length) before it
175 /// sizes a single allocation. `what` names the buffer for the error.176 /// sizes a single allocation. `what` names the buffer for the error.
176 pub fn check_bytes(&self, what: &str, bytes: Option<usize>) -> Result<usize> {177 pub fn check_bytes(&self, what: &str, bytes: Option<usize>) -> Result<usize> {
177 let bytes =178 let bytes =
@@ -186,10 +187,11 @@ impl Limits {
186 }187 }
187 }188 }
188 189
189-/// Accumulates bytes spent across every segment of one decode call and190+/// Accumulates bytes spent across every frame or segment of one decode call
190-/// refuses once the running total crosses [`Limits::max_total_alloc`] — the191+/// and refuses once the running total crosses [`Limits::max_total_alloc`] —
191-/// guard for `segment_count x segment_size`, which [`Limits::check_bytes`]192+/// the guard for `frame_count x canvas` or `segment_count x segment_size`,
192-/// alone never sees since it only ever looks at one buffer at a time.193+/// which [`Limits::check_bytes`] alone never sees since it only ever looks
194+/// at one buffer at a time.
193 #[derive(Debug, Default)]195 #[derive(Debug, Default)]
194 pub struct AllocBudget(usize);196 pub struct AllocBudget(usize);
195 197
@@ -546,4 +548,31 @@ mod tests {
546 assert!(limits.check(0, 10).is_err());548 assert!(limits.check(0, 10).is_err());
547 assert!(limits.check(100_000, 100_000).is_err());549 assert!(limits.check(100_000, 100_000).is_err());
548 }550 }
551+
552+ #[test]
553+ fn check_bytes_refuses_past_max_alloc_before_a_frame_size_carries_it() {
554+ let limits = Limits::default();
555+ assert!(limits.check_bytes("test", Some(1024)).is_ok());
556+ assert!(limits.check_bytes("test", Some(limits.max_alloc + 1)).is_err());
557+ assert!(limits.check_bytes("test", None).is_err());
558+ }
559+
560+ #[test]
561+ fn alloc_budget_refuses_once_repeated_spends_cross_the_total() {
562+ // The class this guards: no single spend is ever over budget on its
563+ // own, but a canvas cloned once per animation frame is.
564+ let limits = Limits::default();
565+ let mut budget = AllocBudget::default();
566+ let per_frame = limits.max_total_alloc / 4;
567+ for i in 0..4 {
568+ assert!(
569+ budget.spend(&limits, "frame", per_frame).is_ok(),
570+ "frame {i} alone is within budget"
571+ );
572+ }
573+ assert!(
574+ budget.spend(&limits, "frame", per_frame).is_err(),
575+ "a fifth frame the same size crosses the total"
576+ );
577+ }
549 }578 }
crates/ec-image/src/webp/mod.rsmodified+8 -1
@@ -245,8 +245,11 @@ pub fn decode_frames(data: &[u8], limits: Limits) -> Result<Vec<crate::Animation
245 // advice to a viewer about what to show behind the animation, not a colour245 // advice to a viewer about what to show behind the animation, not a colour
246 // the frames are composited onto -- libwebp's own animation decoder246 // the frames are composited onto -- libwebp's own animation decoder
247 // ignores it the same way.247 // ignores it the same way.
248- let mut canvas = vec![0u8; canvas_width as usize * canvas_height as usize * 4];248+ let canvas_bytes = canvas_width as usize * canvas_height as usize * 4;
249+ let mut canvas = vec![0u8; canvas_bytes];
249 let mut dispose: Option<(u32, u32, u32, u32)> = None;250 let mut dispose: Option<(u32, u32, u32, u32)> = None;
251+ let mut budget = crate::AllocBudget::default();
252+ budget.spend(&limits, "WebP canvas", canvas_bytes)?;
250 253
251 for chunk in &chunks {254 for chunk in &chunks {
252 if &chunk.tag != b"ANMF" {255 if &chunk.tag != b"ANMF" {
@@ -267,6 +270,10 @@ pub fn decode_frames(data: &[u8], limits: Limits) -> Result<Vec<crate::Animation
267 "WebP: frame {width}x{height}+{x}+{y} runs off a {canvas_width}x{canvas_height} canvas"270 "WebP: frame {width}x{height}+{x}+{y} runs off a {canvas_width}x{canvas_height} canvas"
268 )));271 )));
269 }272 }
273+ // Every ANMF frame clones the whole composited canvas below -- the
274+ // real multiplier a single buffer's own bound never catches -- so
275+ // it is spent from the decode-wide budget before that clone runs.
276+ budget.spend(&limits, "WebP composited canvas", canvas_bytes)?;
270 277
271 // The previous frame's disposal happens before this one is drawn, so a278 // The previous frame's disposal happens before this one is drawn, so a
272 // caller that keeps every frame still sees each one whole.279 // caller that keeps every frame still sees each one whole.
crates/ec-image/tests/fuzz.rsmodified+289 -0
@@ -273,6 +273,295 @@ fn a_header_asking_for_more_pixels_than_the_limit_is_refused() {
273 assert!(format!("{err}").contains("limit"), "{err}");273 assert!(format!("{err}").contains("limit"), "{err}");
274 }274 }
275 275
276+/// LSB-first bit packer, matching how every decoder in this crate reads a
277+/// GIF LZW or VP8L bitstream: used to hand-craft the smallest possible valid
278+/// compressed payload for the budget tests below.
279+struct BitWriter {
280+ buffer: u64,
281+ bits: u8,
282+ out: Vec<u8>,
283+}
284+
285+impl BitWriter {
286+ fn new() -> Self {
287+ BitWriter {
288+ buffer: 0,
289+ bits: 0,
290+ out: Vec::new(),
291+ }
292+ }
293+
294+ fn push(&mut self, value: u16, width: u8) {
295+ self.buffer |= u64::from(value) << self.bits;
296+ self.bits += width;
297+ while self.bits >= 8 {
298+ self.out.push((self.buffer & 0xff) as u8);
299+ self.buffer >>= 8;
300+ self.bits -= 8;
301+ }
302+ }
303+
304+ fn finish(mut self) -> Vec<u8> {
305+ if self.bits > 0 {
306+ self.out.push((self.buffer & 0xff) as u8);
307+ }
308+ self.out
309+ }
310+}
311+
312+/// A minimal GIF: no global colour table, one 0x2C image descriptor with a
313+/// 2-colour local table and a one-pixel LZW stream (clear, colour 0, end),
314+/// followed by the trailer. `canvas_w`/`canvas_h` size the logical screen;
315+/// the frame itself is always 1x1 so its own indices buffer is trivial —
316+/// what grows per frame is the *composited canvas* `composite` clones.
317+fn one_pixel_gif(canvas_w: u16, canvas_h: u16, frames: usize) -> Vec<u8> {
318+ let mut w = BitWriter::new();
319+ w.push(4, 3); // clear code (min_code_size 2 -> clear = 1<<2)
320+ w.push(0, 3); // colour index 0, literal
321+ w.push(5, 3); // end code
322+ let lzw = w.finish();
323+
324+ let mut data = Vec::new();
325+ data.extend_from_slice(b"GIF87a");
326+ data.extend_from_slice(&canvas_w.to_le_bytes());
327+ data.extend_from_slice(&canvas_h.to_le_bytes());
328+ data.push(0x00); // no global colour table
329+ data.push(0);
330+ data.push(0);
331+ for _ in 0..frames {
332+ data.push(0x2C);
333+ data.extend_from_slice(&0u16.to_le_bytes()); // left
334+ data.extend_from_slice(&0u16.to_le_bytes()); // top
335+ data.extend_from_slice(&1u16.to_le_bytes()); // width
336+ data.extend_from_slice(&1u16.to_le_bytes()); // height
337+ data.push(0x80); // has LCT, sorted=0, size field 0 -> 2 colours
338+ data.extend_from_slice(&[0, 0, 0, 255, 255, 255]); // 2-colour LCT
339+ data.push(2); // min code size
340+ data.push(lzw.len() as u8);
341+ data.extend_from_slice(&lzw);
342+ data.push(0); // sub-block terminator
343+ }
344+ data.push(0x3B); // trailer
345+ data
346+}
347+
348+#[test]
349+fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() {
350+ // A single 0x2C image descriptor declaring a 60000x60000 frame: the
351+ // frame's own rectangle is a header field like the canvas is, and must
352+ // be refused before it sizes the indices buffer below it.
353+ let mut data = Vec::new();
354+ data.extend_from_slice(b"GIF87a");
355+ data.extend_from_slice(&4u16.to_le_bytes());
356+ data.extend_from_slice(&4u16.to_le_bytes());
357+ data.push(0x00);
358+ data.push(0);
359+ data.push(0);
360+ data.push(0x2C);
361+ data.extend_from_slice(&0u16.to_le_bytes());
362+ data.extend_from_slice(&0u16.to_le_bytes());
363+ data.extend_from_slice(&60000u16.to_le_bytes());
364+ data.extend_from_slice(&60000u16.to_le_bytes());
365+ data.push(0x00);
366+
367+ let start = std::time::Instant::now();
368+ let err = ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit");
369+ assert!(start.elapsed().as_millis() < 100, "{:?}", start.elapsed());
370+ assert!(format!("{err}").contains("limit"), "{err}");
371+}
372+
373+#[test]
374+fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() {
375+ // Each frame is 1x1 -- cheap to encode, cheap to check on its own -- but
376+ // `composite` clones the *whole* canvas onto the result once per frame.
377+ // A canvas near the single-buffer limit, repeated a few dozen times,
378+ // must be caught by the decode-wide budget even though no single frame
379+ // or single buffer ever looks large by itself.
380+ let data = one_pixel_gif(16000, 16000, 64);
381+ let start = std::time::Instant::now();
382+ let err = ec_image::decode_animation(&data)
383+ .expect_err("64 clones of a near-limit canvas is past the total budget");
384+ // A few real canvas clones run before the budget catches up (the budget
385+ // is spent per frame, so it can't refuse before at least one clone), so
386+ // this bounds "a handful of gigabyte copies", not "no allocation at all".
387+ assert!(start.elapsed().as_secs() < 5, "{:?}", start.elapsed());
388+ assert!(format!("{err}").contains("limit"), "{err}");
389+}
390+
391+#[test]
392+fn a_gif_with_a_few_tiny_frames_over_a_huge_canvas_still_decodes() {
393+ // The other side of the same budget: a handful of frames over a large
394+ // canvas is exactly what a real animation looks like, and must not be
395+ // refused just because the guard above exists.
396+ let data = one_pixel_gif(4000, 4000, 3);
397+ let frames = ec_image::decode_animation(&data).expect("well within every limit");
398+ assert_eq!(frames.len(), 3);
399+}
400+
401+/// A minimal RIFF WebP with an ANIM/VP8X header and `frames` ANMF chunks,
402+/// each carrying a 1x1 VP8L payload (the smallest valid lossless image: a
403+/// bitstream header plus one pixel, no transforms, no colour cache).
404+fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec<u8> {
405+ // VP8L bitstream for a 1x1 image: signature 0x2f, 14-bit width-1=0,
406+ // 14-bit height-1=0, 1-bit alpha flag=0, 3-bit version=0, then the
407+ // image data: no colour cache, no meta prefix, one simple prefix code
408+ // per channel (colour index 0 for all four), then the single pixel.
409+ let mut w = BitWriter::new();
410+ w.push(0, 14); // width - 1
411+ w.push(0, 14); // height - 1
412+ w.push(0, 1); // alpha_is_used
413+ w.push(0, 3); // version
414+ w.push(0, 1); // no transform
415+ w.push(0, 1); // no colour cache
416+ w.push(0, 1); // no meta prefix
417+ for _ in 0..5 {
418+ // green/red/blue/alpha/distance, in that order: a simple code, one
419+ // symbol, value 0.
420+ w.push(1, 1); // simple code
421+ w.push(0, 1); // one symbol
422+ w.push(0, 1); // symbol is not a literal byte read as 8 bits
423+ w.push(0, 1); // symbol0 = 0
424+ }
425+ let vp8l_bits = w.finish();
426+ let mut vp8l = vec![0x2f];
427+ vp8l.extend_from_slice(&vp8l_bits);
428+ if vp8l.len() % 2 == 1 {
429+ vp8l.push(0);
430+ }
431+
432+ fn chunk(tag: &[u8; 4], body: &[u8]) -> Vec<u8> {
433+ let mut c = Vec::new();
434+ c.extend_from_slice(tag);
435+ c.extend_from_slice(&(body.len() as u32).to_le_bytes());
436+ c.extend_from_slice(body);
437+ if body.len() % 2 == 1 {
438+ c.push(0);
439+ }
440+ c
441+ }
442+
443+ let mut vp8x = vec![0x02, 0, 0, 0]; // flags: bit 0x02 is "has animation"
444+ let off24 = |v: u32| v.to_le_bytes()[..3].to_vec();
445+ let dim24 = |v: u32| (v - 1).to_le_bytes()[..3].to_vec();
446+ vp8x.extend_from_slice(&dim24(canvas_w));
447+ vp8x.extend_from_slice(&dim24(canvas_h));
448+ let mut anim = vec![0, 0, 0, 0, 0, 0]; // background colour
449+ anim.extend_from_slice(&0u16.to_le_bytes()); // loop count
450+
451+ let mut anmf_body = Vec::new();
452+ anmf_body.extend_from_slice(&off24(0)); // x offset (raw value, x = field*2)
453+ anmf_body.extend_from_slice(&off24(0)); // y offset
454+ anmf_body.extend_from_slice(&dim24(1)); // width - 1
455+ anmf_body.extend_from_slice(&dim24(1)); // height - 1
456+ anmf_body.extend_from_slice(&off24(1)); // duration
457+ anmf_body.push(0x00); // reserved/blend/dispose
458+ anmf_body.extend_from_slice(&chunk(b"VP8L", &vp8l));
459+
460+ let mut payload = Vec::new();
461+ payload.extend_from_slice(&chunk(b"VP8X", &vp8x));
462+ payload.extend_from_slice(&chunk(b"ANIM", &anim));
463+ for _ in 0..frames {
464+ payload.extend_from_slice(&chunk(b"ANMF", &anmf_body));
465+ }
466+
467+ let mut data = Vec::new();
468+ data.extend_from_slice(b"RIFF");
469+ data.extend_from_slice(&(4 + payload.len() as u32).to_le_bytes());
470+ data.extend_from_slice(b"WEBP");
471+ data.extend_from_slice(&payload);
472+ data
473+}
474+
475+#[test]
476+fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() {
477+ // The WebP analogue of the GIF test above: `decode_frames` clones the
478+ // whole composited canvas into the result once per ANMF chunk.
479+ let data = one_pixel_animated_webp(16000, 16000, 64);
480+ let start = std::time::Instant::now();
481+ let err = ec_image::decode_animation(&data)
482+ .expect_err("64 clones of a near-limit canvas is past the total budget");
483+ assert!(start.elapsed().as_millis() < 2000, "{:?}", start.elapsed());
484+ assert!(format!("{err}").contains("limit"), "{err}");
485+}
486+
487+/// Build an LZW-compressed data stream that keeps expanding after the
488+/// dictionary itself has stopped growing: a run of `cScSc` codes (each equal
489+/// to the not-yet-assigned `next_code`) fills the 4096-entry dictionary with
490+/// entries of increasing length, then a run of plain references to the
491+/// longest entry keeps emitting ~4 KB of output per 12-bit code with no
492+/// further dictionary growth to bound it. This is the classic GIF LZW bomb:
493+/// a stream well under 200 KB that decodes, uncapped, to hundreds of
494+/// megabytes.
495+fn lzw_bomb() -> Vec<u8> {
496+ let min_code_size = 2u8;
497+ let clear_code = 1u16 << min_code_size; // 4
498+ let end_code = clear_code + 1; // 5
499+ let mut next_code = clear_code + 2; // 6
500+ let mut code_size = min_code_size + 1; // 3
501+
502+ let mut w = BitWriter::new();
503+ w.push(clear_code, code_size);
504+ w.push(0, code_size); // first code after clear: a literal, no dictionary entry
505+
506+ // Phase 1: cScSc every time -- fills the dictionary, entries growing
507+ // 2, 3, 4, ... bytes long (mirrors `Lzw::derive`'s widening rule exactly,
508+ // so the decoder reads this stream at the same code width we wrote it).
509+ while next_code < 4096 {
510+ w.push(next_code, code_size);
511+ if next_code >= (1u16 << code_size) - 1 && code_size < 12 {
512+ code_size += 1;
513+ }
514+ next_code += 1;
515+ }
516+
517+ // Phase 2: dictionary is full (`derive` is now a no-op), so repeating the
518+ // longest entry's code keeps producing ~4 KB per code with nothing left
519+ // to cap it.
520+ let longest = next_code - 1;
521+ for _ in 0..100_000 {
522+ w.push(longest, code_size);
523+ }
524+
525+ w.push(end_code, code_size);
526+ w.finish()
527+}
528+
529+/// A GIF whose frame declares 4x4 (16 indices) but whose LZW stream, if
530+/// decoded past that point, expands to hundreds of megabytes: guards the
531+/// `lzw_decode` bound at gif.rs that stops the loop once `out` already holds
532+/// `expected` bytes, rather than only checking after the loop.
533+#[test]
534+fn a_gif_lzw_bomb_does_not_expand_past_its_declared_frame() {
535+ let lzw = lzw_bomb();
536+ eprintln!("gif-lzw-bomb: {} bytes of LZW data", lzw.len());
537+
538+ let mut data = Vec::new();
539+ data.extend_from_slice(b"GIF87a");
540+ data.extend_from_slice(&4u16.to_le_bytes());
541+ data.extend_from_slice(&4u16.to_le_bytes());
542+ data.push(0x00); // no global colour table
543+ data.push(0);
544+ data.push(0);
545+ data.push(0x2C);
546+ data.extend_from_slice(&0u16.to_le_bytes()); // left
547+ data.extend_from_slice(&0u16.to_le_bytes()); // top
548+ data.extend_from_slice(&4u16.to_le_bytes()); // width
549+ data.extend_from_slice(&4u16.to_le_bytes()); // height
550+ data.push(0x81); // has LCT, size field 1 -> 4 colours (indices 0..3)
551+ data.extend_from_slice(&[0, 0, 0, 64, 64, 64, 128, 128, 128, 255, 255, 255]);
552+ data.push(2); // min code size
553+ for chunk in lzw.chunks(255) {
554+ data.push(chunk.len() as u8);
555+ data.extend_from_slice(chunk);
556+ }
557+ data.push(0); // sub-block terminator
558+ data.push(0x3B); // trailer
559+
560+ let start = std::time::Instant::now();
561+ let _ = ec_image::decode(&data);
562+ assert!(start.elapsed().as_secs() < 1, "{:?}", start.elapsed());
563+}
564+
276 fn crc32(data: &[u8]) -> u32 {565 fn crc32(data: &[u8]) -> u32 {
277 let mut c = 0xffff_ffffu32;566 let mut c = 0xffff_ffffu32;
278 for &b in data {567 for &b in data {
scripts/memguard-runner.shadded+21 -0
@@ -0,0 +1,21 @@
1+#!/usr/bin/env bash
2+# Wraps a test/bin invocation in a transient user cgroup scope so a runaway
3+# allocation dies inside its own cgroup instead of triggering a machine-wide
4+# OOM kill. Used as the cargo target runner (see .cargo/config.toml) so every
5+# `cargo test`/`cargo run` invocation of this workspace is capped, from any
6+# checkout (main repo or worktree).
7+set -euo pipefail
8+
9+if [ "${EC_NOMEMGUARD:-0}" = "1" ]; then
10+ echo "memguard-runner: EC_NOMEMGUARD=1, running without memory cap" >&2
11+ exec "$@"
12+fi
13+
14+if ! systemd-run --user --scope --quiet -p MemoryMax=10G true >/dev/null 2>&1; then
15+ echo "memguard-runner: systemd-run --user --scope unavailable, running without memory cap" >&2
16+ exec "$@"
17+fi
18+
19+exec systemd-run --user --scope --quiet --same-dir \
20+ -p MemoryMax=10G -p MemorySwapMax=2G \
21+ -- "$@"