From 4e4a497302c49b5ea5105e266b25955bd85f0ebe Mon Sep 17 00:00:00 2001 From: laurenspriem Date: Tue, 3 Nov 2026 12:04:16 +0530 Subject: [PATCH 1/5] Decode auxiliary alpha stored as a grid ImageIO stores the alpha of every transparent image with a side of 1024 px or more as a grid item tiled like the primary. The decoder only accepted coded alpha items, so all such images decoded fully opaque without an error. Extract a grid alpha item through the shared grid tile extraction, preflight it with the caller's guardrails, compose it with the existing grid decoder and use its luma plane as the alpha. Alpha decoded from ImageIO files between 1024x700 and 4096x4096 now matches ImageIO's own decode exactly. Only the first grid candidate that is an alpha item gets extracted, so a file listing thousands of crafted grid alpha candidates costs one tile budget instead of one per candidate: 3,000 candidates in a 2 MB file took 6.3 s and now take 30 ms. Coded alpha candidates keep their existing fallback. --- FUTURE_WORK.md | 15 +- src/geometry_tests.rs | 179 ++++++++++++++++++-- src/isobmff.rs | 95 +++++++++-- src/lib.rs | 88 ++++++++-- src/testdata/apple-alpha-grid-1030x520.heic | Bin 0 -> 8840 bytes 5 files changed, 333 insertions(+), 44 deletions(-) create mode 100644 src/testdata/apple-alpha-grid-1030x520.heic diff --git a/FUTURE_WORK.md b/FUTURE_WORK.md index 97e65bb..0bb3142 100644 --- a/FUTURE_WORK.md +++ b/FUTURE_WORK.md @@ -48,15 +48,12 @@ Pre-existing, unchanged by the audit, measured July 2026: A memory-diet pass on the decode pipeline is the biggest resource win available if decoding runs server-side. -## 4. Grid-typed and size-mismatched alpha channels - -The last known *silent* wrong-output class: an auxiliary alpha image that is -itself a `grid` item (tiled image with alpha), or an alpha plane whose -dimensions differ from the primary image, is currently ignored — the output -renders fully opaque with no error. libheif decodes grid alpha via its -generic item decode and nearest-neighbor-scales mismatched planes. Either -implement (route aux items through the grid decode path; scale mismatched -planes) or at least fail loudly. +## 4. Size-mismatched alpha channels + +The last known *silent* wrong-output class: an auxiliary alpha plane whose +dimensions differ from the primary image is currently ignored — the output +renders fully opaque with no error. libheif nearest-neighbor-scales +mismatched planes. Either scale them or at least fail loudly. ## 5. Continuous integration diff --git a/src/geometry_tests.rs b/src/geometry_tests.rs index 76a6314..231542a 100644 --- a/src/geometry_tests.rs +++ b/src/geometry_tests.rs @@ -207,6 +207,146 @@ fn hevc_payload() -> Vec { [&(slice.len() as u32).to_be_bytes()[..], &slice].concat() } +fn grid_alpha_fixture(candidates: &[(u16, bool)], tiles_per_side: u8) -> Vec { + let candidate_ids: Vec = (3..).take(candidates.len()).collect(); + let count = 2 + candidate_ids.len() as u16; + let mut info = count.to_be_bytes().to_vec(); + let mut locations = [vec![0x44, 0], count.to_be_bytes().to_vec()].concat(); + let mut associations = u32::from(count).to_be_bytes().to_vec(); + let mut references = Vec::new(); + let mut data = Vec::new(); + let output = (16 * u16::from(tiles_per_side)).to_be_bytes(); + let last_tile = tiles_per_side - 1; + let descriptor = [&[0, 0, last_tile, last_tile][..], &output, &output].concat(); + let coded = [ + (1, b"hvc1", hevc_payload(), true), + (2, b"hvc1", hevc_payload(), true), + ]; + let grids = candidate_ids + .iter() + .zip(candidates) + .map(|(&id, &(_, alpha))| (id, b"grid", descriptor.clone(), alpha)); + for (id, kind, payload, alpha) in coded.into_iter().chain(grids) { + info.extend(full_box( + b"infe", + 2, + &[&id.to_be_bytes()[..], &[0, 0], kind, &[0]].concat(), + )); + locations.extend_from_slice(&id.to_be_bytes()); + locations.extend_from_slice(&[0, 1, 0, 0, 0, 1]); + locations.extend_from_slice(&(data.len() as u32).to_be_bytes()); + locations.extend_from_slice(&(payload.len() as u32).to_be_bytes()); + data.extend(payload); + associations.extend_from_slice(&id.to_be_bytes()); + associations.extend_from_slice(match (kind, alpha) { + (b"hvc1", _) => &[2, 0x81, 0x82], + (_, true) => &[2, 0x82, 0x83], + (_, false) => &[1, 0x82], + }); + } + for (&id, &(tile_references, _)) in candidate_ids.iter().zip(candidates) { + references.extend(boxed( + b"auxl", + &[id.to_be_bytes(), 1u16.to_be_bytes(), 1u16.to_be_bytes()].concat(), + )); + let tiles = [2u16.to_be_bytes()].repeat(usize::from(tile_references)); + references.extend(boxed( + b"dimg", + &[ + &id.to_be_bytes()[..], + &tile_references.to_be_bytes(), + &tiles.concat(), + ] + .concat(), + )); + } + let properties = [ + hevc_configuration(small_hevc_sps()), + ispe(16, 16), + full_box(b"auxC", 0, b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha\0"), + ] + .concat(); + let meta = [ + full_box(b"pitm", 0, &1u16.to_be_bytes()), + full_box(b"iinf", 0, &info), + full_box(b"iloc", 1, &locations), + boxed( + b"iprp", + &[ + boxed(b"ipco", &properties), + full_box(b"ipma", 0, &associations), + ] + .concat(), + ), + boxed(b"idat", &data), + full_box(b"iref", 0, &references), + ] + .concat(); + [ + boxed(b"ftyp", &[&b"heic"[..], &[0, 0, 0, 0], b"mif1"].concat()), + full_box(b"meta", 0, &meta), + ] + .concat() +} + +fn decode_grid_alpha_fixture( + candidates: &[(u16, bool)], + tiles_per_side: u8, + guardrails: &DecodeGuardrails, +) -> Option { + decode_primary_heic_auxiliary_alpha_plane_internal( + &grid_alpha_fixture(candidates, tiles_per_side), + &mut None, + 16, + 16, + guardrails, + ) + .unwrap() +} + +fn decode_default_grid_alpha_fixture( + candidates: &[(u16, bool)], +) -> Option { + decode_grid_alpha_fixture(candidates, 1, &DecodeGuardrails::default()) +} + +#[test] +fn coded_primary_keeps_grid_alpha() { + let alpha = decode_default_grid_alpha_fixture(&[(1, true)]).unwrap(); + assert_eq!( + (alpha.width, alpha.height, alpha.samples.len()), + (16, 16, 256) + ); +} + +#[test] +fn only_the_first_grid_alpha_candidate_is_extracted() { + assert!(decode_default_grid_alpha_fixture(&[(1, true), (2, true)]).is_some()); + assert!(decode_default_grid_alpha_fixture(&[(2, true), (1, true)]).is_none()); +} + +#[test] +fn grids_without_alpha_auxc_do_not_use_the_grid_alpha_attempt() { + assert!(decode_default_grid_alpha_fixture(&[(1, false), (1, true)]).is_some()); +} + +#[test] +fn grid_alpha_is_held_to_the_callers_guardrails() { + let guardrails = DecodeGuardrails { + max_pixels: Some(64), + ..Default::default() + }; + assert!(decode_grid_alpha_fixture(&[(1, true)], 1, &guardrails).is_none()); +} + +#[test] +fn grid_alpha_of_another_size_is_dropped_before_decoding() { + let (alpha, largest) = + tracked(|| decode_grid_alpha_fixture(&[(256, true)], 16, &DecodeGuardrails::default())); + assert!(alpha.is_none()); + assert!(largest < 64 * 1024, "allocated a canvas: {largest}"); +} + #[test] fn heic_alpha_rejects_coded_geometry_before_plane_allocation() { let input = image_fixture( @@ -1470,15 +1610,19 @@ fn heic_grid_narrow_budget_stays_capped_by_max_pixels() { )); } -fn assert_alpha_ramp(input: &[u8], width: u32, height: u32, x_step: u32) { - let decoded = decode_bytes_to_rgba(input).unwrap(); +fn assert_alpha_ramp( + decoded: DecodedRgbaImage, + width: u32, + height: u32, + expected_alpha: impl Fn(u32, u32) -> u32, +) { assert_eq!((decoded.width, decoded.height), (width, height)); let DecodedRgbaPixels::U8(pixels) = decoded.pixels else { panic!("expected 8-bit RGBA output"); }; for (index, pixel) in pixels.chunks_exact(4).enumerate() { let (x, y) = (index as u32 % width, index as u32 / width); - let expected = x_step * x + y; + let expected = expected_alpha(x, y); assert!( u32::from(pixel[3]).abs_diff(expected) <= 2, "alpha at ({x}, {y}) is {}, expected {expected}", @@ -1489,15 +1633,30 @@ fn assert_alpha_ramp(input: &[u8], width: u32, height: u32, x_step: u32) { #[test] fn apple_monochrome_alpha_plane_decodes() { - assert_alpha_ramp( - include_bytes!("testdata/apple-alpha-192x64.heic"), - 192, - 64, - 1, - ); + let decoded = decode_bytes_to_rgba(include_bytes!("testdata/apple-alpha-192x64.heic")).unwrap(); + assert_alpha_ramp(decoded, 192, 64, |x, y| x + y); } #[test] fn apple_alpha_coded_at_the_minimum_frame_size_is_kept() { - assert_alpha_ramp(include_bytes!("testdata/apple-alpha-40x30.heic"), 40, 30, 5); + let decoded = decode_bytes_to_rgba(include_bytes!("testdata/apple-alpha-40x30.heic")).unwrap(); + assert_alpha_ramp(decoded, 40, 30, |x, y| 5 * x + y); +} + +#[test] +fn apple_grid_alpha_is_composed_from_its_tiles() { + let input = include_bytes!("testdata/apple-alpha-grid-1030x520.heic"); + let expected_alpha = |x: u32, y: u32| x * 160 / 1029 + y * 80 / 519; + assert_alpha_ramp( + decode_bytes_to_rgba(input).unwrap(), + 1030, + 520, + expected_alpha, + ); + assert_alpha_ramp( + decode_read_to_rgba(&input[..]).unwrap(), + 1030, + 520, + expected_alpha, + ); } diff --git a/src/isobmff.rs b/src/isobmff.rs index 444f64b..08631d4 100644 --- a/src/isobmff.rs +++ b/src/isobmff.rs @@ -4367,17 +4367,89 @@ fn extract_primary_heic_item_data_with_grid_internal( } } - let tile_item_ids: Vec = resolved - .primary_item - .references - .iter() + let tile_item_ids = grid_tile_item_ids(item_id, &resolved.primary_item.references)?; + let tiles = extract_heic_grid_tiles( + input, + source, + &meta, + &resolved, + item_id, + &descriptor, + &tile_item_ids, + )?; + + Ok(HeicPrimaryItemDataWithGrid::Grid(HeicGridPrimaryItemData { + item_id, + construction_method, + descriptor, + colr, + tile_item_ids, + tiles, + })) +} + +pub(crate) fn extract_heic_grid_item_data( + input: &[u8], + source: &mut Option<&mut dyn RandomAccessSource>, + meta: &MetaBox<'_>, + resolved: &ResolvedPrimaryItemGraph<'_>, + location: &ItemLocationItem, +) -> Result { + let item_id = location.item_id; + let (construction_method, grid_payload) = + extract_heic_item_payload_from_location(input, source, meta, location, item_id)?; + let descriptor = parse_heic_grid_descriptor(item_id, &grid_payload)?; + let tile_item_ids = grid_tile_item_ids( + item_id, + resolved + .iref + .iter() + .flat_map(|iref| &iref.references) + .filter(|reference| reference.from_item_id == item_id), + )?; + let tiles = extract_heic_grid_tiles( + input, + source, + meta, + resolved, + item_id, + &descriptor, + &tile_item_ids, + )?; + Ok(HeicGridPrimaryItemData { + item_id, + construction_method, + descriptor, + colr: PrimaryItemColorProperties::default(), + tile_item_ids, + tiles, + }) +} + +fn grid_tile_item_ids<'a>( + item_id: u32, + references: impl IntoIterator, +) -> Result, ExtractHeicItemDataError> { + let tile_item_ids: Vec = references + .into_iter() .filter(|reference| reference.reference_type.as_bytes() == DIMG_REFERENCE_TYPE) .flat_map(|reference| reference.to_item_ids.iter().copied()) .collect(); if tile_item_ids.is_empty() { return Err(ExtractHeicItemDataError::MissingGridTileReferences { item_id }); } + Ok(tile_item_ids) +} +fn extract_heic_grid_tiles( + input: &[u8], + source: &mut Option<&mut dyn RandomAccessSource>, + meta: &MetaBox<'_>, + resolved: &ResolvedPrimaryItemGraph<'_>, + item_id: u32, + descriptor: &HeicGridDescriptor, + tile_item_ids: &[u32], +) -> Result, ExtractHeicItemDataError> { let expected_tiles_u64 = u64::from(descriptor.rows) * u64::from(descriptor.columns); let expected_tiles = usize::try_from(expected_tiles_u64).map_err(|_| { ExtractHeicItemDataError::PayloadTooLarge { @@ -4408,7 +4480,7 @@ fn extract_primary_heic_item_data_with_grid_internal( for (index, item) in resolved.iloc.items.iter().enumerate() { iloc_index.entry(item.item_id).or_insert(index); } - let mut distinct_tile_ids: Vec = tile_item_ids.clone(); + let mut distinct_tile_ids = tile_item_ids.to_vec(); distinct_tile_ids.sort_unstable(); distinct_tile_ids.dedup(); let mut associations_by_item: BTreeMap> = BTreeMap::new(); @@ -4455,7 +4527,7 @@ fn extract_primary_heic_item_data_with_grid_internal( let mut total_tile_payload_bytes = 0_u64; let mut tiles = Vec::with_capacity(tile_item_ids.len()); - for &tile_item_id in &tile_item_ids { + for &tile_item_id in tile_item_ids { let tile_item_info = &resolved.iinf.entries[*iinf_index.get(&tile_item_id).ok_or( ExtractHeicItemDataError::MissingGridTileItemInfo { item_id, @@ -4508,7 +4580,7 @@ fn extract_primary_heic_item_data_with_grid_internal( extract_heic_item_payload_from_location_with_idat( input, source, - &meta, + meta, tile_location, tile_item_id, shared_idat_payload, @@ -4537,14 +4609,7 @@ fn extract_primary_heic_item_data_with_grid_internal( }); } - Ok(HeicPrimaryItemDataWithGrid::Grid(HeicGridPrimaryItemData { - item_id, - construction_method, - descriptor, - colr, - tile_item_ids, - tiles, - })) + Ok(tiles) } type GridTileProperties = ( diff --git a/src/lib.rs b/src/lib.rs index 9e66c90..1f5ec44 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7339,6 +7339,7 @@ const ICEF_SIZE_BITS_TABLE: [u8; 5] = [8, 16, 24, 32, 64]; const AV01_ITEM_TYPE: [u8; 4] = *b"av01"; const HVC1_ITEM_TYPE: [u8; 4] = *b"hvc1"; const HEV1_ITEM_TYPE: [u8; 4] = *b"hev1"; +const GRID_ITEM_TYPE: [u8; 4] = *b"grid"; const AUXL_REFERENCE_TYPE: [u8; 4] = *b"auxl"; const CDSC_REFERENCE_TYPE: [u8; 4] = *b"cdsc"; const EXIF_ITEM_TYPE: [u8; 4] = *b"Exif"; @@ -7913,6 +7914,8 @@ fn decode_primary_heic_auxiliary_alpha_plane_internal( return Ok(None); }; let primary_item_id = resolved.primary_item.item_id; + let expected = (expected_width, expected_height); + let mut grid_alpha_tried = false; for reference in &iref.references { if reference.reference_type.as_bytes() != AUXL_REFERENCE_TYPE { @@ -7922,16 +7925,24 @@ fn decode_primary_heic_auxiliary_alpha_plane_internal( continue; } - let Some(alpha_plane) = decode_auxiliary_alpha_item_candidate( - input, - source, - &meta, - &resolved, - reference.from_item_id, - (expected_width, expected_height), - guardrails, - )? - else { + let item_id = reference.from_item_id; + let candidate = if item_is_grid(&resolved, item_id) { + if grid_alpha_tried { + continue; + } + let Some(location) = auxiliary_alpha_grid_location(&resolved, item_id) else { + continue; + }; + grid_alpha_tried = true; + decode_auxiliary_alpha_grid( + input, source, &meta, &resolved, location, expected, guardrails, + )? + } else { + decode_auxiliary_alpha_item_candidate( + input, source, &meta, &resolved, item_id, expected, guardrails, + )? + }; + let Some(alpha_plane) = candidate else { continue; }; @@ -7978,6 +7989,63 @@ fn decode_auxiliary_alpha_item_candidate<'a>( })) } +fn item_is_grid(resolved: &isobmff::ResolvedPrimaryItemGraph<'_>, item_id: u32) -> bool { + resolved + .iinf + .entries + .iter() + .find(|entry| entry.item_id == item_id) + .and_then(|entry| entry.item_type) + .is_some_and(|item_type| item_type.as_bytes() == GRID_ITEM_TYPE) +} + +fn auxiliary_alpha_grid_location<'r>( + resolved: &'r isobmff::ResolvedPrimaryItemGraph<'_>, + item_id: u32, +) -> Option<&'r isobmff::ItemLocationItem> { + let location = resolved + .iloc + .items + .iter() + .find(|item| item.item_id == item_id)?; + let properties = resolved_item_properties_for_item(resolved, item_id)?; + properties + .iter() + .any(property_is_alpha_auxiliary_type_property) + .then_some(location) +} + +fn decode_auxiliary_alpha_grid<'a>( + input: &[u8], + source: &mut Option<&mut dyn RandomAccessSource>, + meta: &isobmff::MetaBox<'a>, + resolved: &isobmff::ResolvedPrimaryItemGraph<'a>, + location: &isobmff::ItemLocationItem, + expected: (u32, u32), + guardrails: &DecodeGuardrails, +) -> Result, DecodeHeicError> { + let Ok(grid) = isobmff::extract_heic_grid_item_data(input, source, meta, resolved, location) + else { + return Ok(None); + }; + if (grid.descriptor.output_width, grid.descriptor.output_height) != expected + || geometry::preflight_grid(&grid, guardrails).is_err() + { + return Ok(None); + } + let decoded = match decode_primary_heic_grid_to_image(&grid) { + Ok(decoded) => decoded, + Err(error @ DecodeHeicError::AllocationFailed { .. }) => return Err(error), + Err(_) => return Ok(None), + }; + Ok(Some(HeicAuxiliaryAlphaPlane { + width: decoded.width, + height: decoded.height, + bit_depth: decoded.bit_depth_luma, + samples: decoded.y_plane.samples, + })) +} + fn prepare_auxiliary_alpha_hevc_stream<'a>( input: &[u8], source: &mut Option<&mut dyn RandomAccessSource>, diff --git a/src/testdata/apple-alpha-grid-1030x520.heic b/src/testdata/apple-alpha-grid-1030x520.heic new file mode 100644 index 0000000000000000000000000000000000000000..65f6c5617afae3afcc23ce2344c8cd00ab482635 GIT binary patch literal 8840 zcmds6hdQYay-B3vSSWE0tvy$V^s z_r2;n9^cPj@H@QE>-l=V&N;8wd7amr_v8Hr0D#@z+t0(%4q*d;%@twKuZ2)m)I57%L8yNEC7x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3;jX`hdp2s{S+M5n3zfKphI8eSoO!Uhsl%9I9RS2#W z!VsDp+RtxWm-0dfY4}ANdrBAF0@kWlBsyE*S3xQRj096p^9KOz=v|_Ju^RsX`os$W zp~XmiOc?-dvly)ni56H%=pIK3-IJq}4shq8dowvOHN2SAyaW?-ks5Snu#v*kcxn-E z?r*4{ADq=*m9;0IjYw;8QjwrxzA+fwq#40-qlo_QQ(?Xtgy-uwM(Qqh$>zK%#p1mb z{&(B+LP$Ob5aOE*OnA0k#Z$P}DcN+pnUmsEEc}s51ddKT>^!-G#w#UEO-nr82iWzZT@zJ!lUzo(}UQZxf!YjT4nHpEC zA_(R2acI#u8i_CUnT!HI0h%bW5To}bkf&~hLIb#vF~OfdUtA{k1Tw#(--9Z!veXeiwTZE`wDhnVvFIxW+APtGsUY zwgJluBBKn4TDARWs&?Qf`d2;@?oO@M=w-z63>{9=Fb<*6S`91R3y2k}cL4yv4-)`7 uvVVO+f(ZXHUa9y4GQbGH5!mJ!L3cq1V`f4c&>VIOy1!U~$r6p#QU3=SQJR Date: Tue, 3 Nov 2026 16:01:44 +0530 Subject: [PATCH 2/5] Share grid tile payloads across repeated references A grid can reference the same tile item many times. Each reference got its own copy of the tile's data, so a 132 KB file whose 65,025 grid cells all point at one 2 KB tile made the decoder hold about 127 MiB of identical copies. Tiles that reference the same item now share one copy of its payload, as they already share its hvcC, colour and transform properties. The extracted buffer is moved into the Arc rather than copied, so peak memory for a single large tile does not grow. The tile data budget still counts every reference, so the set of accepted files does not change. HeicGridTileItemData::payload becomes an Arc>. --- src/geometry_tests.rs | 12 +++++---- src/isobmff.rs | 61 +++++++++++++++++++++++++++++++------------ src/lib.rs | 4 +-- 3 files changed, 54 insertions(+), 23 deletions(-) diff --git a/src/geometry_tests.rs b/src/geometry_tests.rs index 231542a..6b40d5d 100644 --- a/src/geometry_tests.rs +++ b/src/geometry_tests.rs @@ -402,7 +402,7 @@ fn grid_fixture() -> isobmff::HeicGridPrimaryItemData { hvcc: hvcc.into(), colr: Default::default(), transforms: Default::default(), - payload: hevc_payload(), + payload: hevc_payload().into(), }], } } @@ -659,7 +659,8 @@ fn heic_grid_checks_replacement_sps_in_payload() { &replacement, &hevc_payload(), ] - .concat(); + .concat() + .into(); let (result, largest) = tracked(|| decode_primary_heic_grid_to_image(&grid)); assert!(result.is_err()); assert!(largest < 128 * 128 * 2); @@ -976,7 +977,8 @@ fn grid_with_filler(tile_count: u16, filler_bytes: usize) -> isobmff::HeicGridPr &filler, &hevc_payload(), ] - .concat(); + .concat() + .into(); grid.descriptor.columns = tile_count; grid.descriptor.output_width = 16 * u32::from(tile_count); for index in 1..tile_count { @@ -1285,7 +1287,7 @@ fn grid_tile_streams_with_hidden_parameter_sets_decode_strictly() { .into(), colr: Default::default(), transforms: Default::default(), - payload: hevc_payload(), + payload: hevc_payload().into(), }; let (decoded, largest) = tracked(|| crate::decode_heic_grid_tile_to_image(&tile).unwrap()); assert_eq!((decoded.width, decoded.height), (16, 16)); @@ -1502,7 +1504,7 @@ fn tiled_grid( hvcc: hvcc.into(), colr: Default::default(), transforms: Default::default(), - payload: hevc_payload(), + payload: hevc_payload().into(), }; let tile_count = u32::from(columns) * u32::from(rows); isobmff::HeicGridPrimaryItemData { diff --git a/src/isobmff.rs b/src/isobmff.rs index c0e68dd..f09f19e 100644 --- a/src/isobmff.rs +++ b/src/isobmff.rs @@ -685,7 +685,7 @@ pub struct HeicGridTileItemData { pub hvcc: Arc, pub colr: Arc, pub transforms: Arc<[PrimaryItemTransformProperty]>, - pub payload: Vec, + pub payload: Arc>, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -4553,6 +4553,7 @@ fn extract_heic_grid_tiles( }; let mut property_cache = GridTilePropertyCache::default(); let mut tile_properties_by_item = BTreeMap::new(); + let mut tile_payloads_by_item = BTreeMap::new(); let tile_payload_budget = source .as_ref() .map_or(input.len() as u64, |source| source.len()) @@ -4604,21 +4605,28 @@ fn extract_heic_grid_tiles( } .clone(); - let tile_location = &resolved.iloc.items[*iloc_index.get(&tile_item_id).ok_or( - ExtractHeicItemDataError::MissingGridTileLocation { - item_id, - tile_item_id, - }, - )?]; - let (tile_construction_method, payload) = - extract_heic_item_payload_from_location_with_idat( - input, - source, - meta, - tile_location, - tile_item_id, - shared_idat_payload, - )?; + let (tile_construction_method, payload) = match tile_payloads_by_item.entry(tile_item_id) { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => { + let tile_location = &resolved.iloc.items[*iloc_index.get(&tile_item_id).ok_or( + ExtractHeicItemDataError::MissingGridTileLocation { + item_id, + tile_item_id, + }, + )?]; + let (construction_method, payload) = + extract_heic_item_payload_from_location_with_idat( + input, + source, + meta, + tile_location, + tile_item_id, + shared_idat_payload, + )?; + entry.insert((construction_method, Arc::new(payload))) + } + } + .clone(); total_tile_payload_bytes = total_tile_payload_bytes .checked_add(payload.len() as u64) .ok_or(ExtractHeicItemDataError::PayloadTooLarge { @@ -8365,6 +8373,27 @@ mod tests { grid } + #[test] + fn grid_tile_payloads_are_shared_across_duplicate_references() { + let grid = resolved_grid(&minimal_heic_grid_file( + (16, 16), + (64, 64), + &[2_u16; 256], + &[0x11; 16], + &[hvcc_box()], + &[1], + &[], + )); + + assert_eq!(grid.tiles.len(), 256); + assert_eq!(grid.tiles[0].payload.as_slice(), [0x11; 16]); + assert!( + grid.tiles + .iter() + .all(|tile| Arc::ptr_eq(&tile.payload, &grid.tiles[0].payload)) + ); + } + #[test] fn grid_tile_transforms_are_shared_across_duplicate_references() { let grid = resolved_grid(&minimal_heic_grid_file( diff --git a/src/lib.rs b/src/lib.rs index 1f5ec44..fdb3adf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14134,7 +14134,7 @@ mod tests { .into(), colr: Default::default(), transforms: Default::default(), - payload: Vec::new(), + payload: Default::default(), }; let sps = super::hevc_sps_from_nal(&sps_nal, 0).expect("SPS should parse"); @@ -14187,7 +14187,7 @@ mod tests { .into(), colr: Default::default(), transforms: Default::default(), - payload, + payload: payload.into(), }; let small = super::hevc_sps_from_nal(&small_sps, 0).expect("small SPS should parse"); From ee9a1b798b63db5bf3b0d89535347ad82f20efa6 Mon Sep 17 00:00:00 2001 From: laurenspriem Date: Tue, 3 Nov 2026 16:01:44 +0530 Subject: [PATCH 3/5] Check an alpha grid's size before copying its tiles A grid alpha item of the wrong size was only rejected after all of its tiles had been copied. The grid descriptor is now read first, and an alpha grid whose output size differs from the primary image is skipped before any tile is extracted. The primary's size has already passed the caller's max_pixels limit, so this also holds the alpha grid to that limit before anything is copied. --- src/geometry_tests.rs | 42 ++++++++++++++++++++++++++++++++++-------- src/isobmff.rs | 20 +++++++++++++++----- src/lib.rs | 21 +++++++++++++++++---- 3 files changed, 66 insertions(+), 17 deletions(-) diff --git a/src/geometry_tests.rs b/src/geometry_tests.rs index 6b40d5d..052170c 100644 --- a/src/geometry_tests.rs +++ b/src/geometry_tests.rs @@ -208,6 +208,22 @@ fn hevc_payload() -> Vec { } fn grid_alpha_fixture(candidates: &[(u16, bool)], tiles_per_side: u8) -> Vec { + grid_alpha_fixture_with_tile( + candidates, + tiles_per_side, + small_hevc_sps(), + 16, + hevc_payload(), + ) +} + +fn grid_alpha_fixture_with_tile( + candidates: &[(u16, bool)], + tiles_per_side: u8, + sps: Vec, + tile_extent: u16, + tile_payload: Vec, +) -> Vec { let candidate_ids: Vec = (3..).take(candidates.len()).collect(); let count = 2 + candidate_ids.len() as u16; let mut info = count.to_be_bytes().to_vec(); @@ -215,12 +231,12 @@ fn grid_alpha_fixture(candidates: &[(u16, bool)], tiles_per_side: u8) -> Vec let mut associations = u32::from(count).to_be_bytes().to_vec(); let mut references = Vec::new(); let mut data = Vec::new(); - let output = (16 * u16::from(tiles_per_side)).to_be_bytes(); + let output = (tile_extent * u16::from(tiles_per_side)).to_be_bytes(); let last_tile = tiles_per_side - 1; let descriptor = [&[0, 0, last_tile, last_tile][..], &output, &output].concat(); let coded = [ (1, b"hvc1", hevc_payload(), true), - (2, b"hvc1", hevc_payload(), true), + (2, b"hvc1", tile_payload, true), ]; let grids = candidate_ids .iter() @@ -261,8 +277,8 @@ fn grid_alpha_fixture(candidates: &[(u16, bool)], tiles_per_side: u8) -> Vec )); } let properties = [ - hevc_configuration(small_hevc_sps()), - ispe(16, 16), + hevc_configuration(sps), + ispe(u32::from(tile_extent), u32::from(tile_extent)), full_box(b"auxC", 0, b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha\0"), ] .concat(); @@ -340,11 +356,21 @@ fn grid_alpha_is_held_to_the_callers_guardrails() { } #[test] -fn grid_alpha_of_another_size_is_dropped_before_decoding() { - let (alpha, largest) = - tracked(|| decode_grid_alpha_fixture(&[(256, true)], 16, &DecodeGuardrails::default())); +fn grid_alpha_of_another_size_is_dropped_before_its_tiles_are_copied() { + let tile_payload = [hevc_payload(), vec![0; 256 * 1024]].concat(); + let input = grid_alpha_fixture_with_tile(&[(4, true)], 2, small_hevc_sps(), 16, tile_payload); + let (alpha, largest) = tracked(|| { + decode_primary_heic_auxiliary_alpha_plane_internal( + &input, + &mut None, + 16, + 16, + &DecodeGuardrails::default(), + ) + .unwrap() + }); assert!(alpha.is_none()); - assert!(largest < 64 * 1024, "allocated a canvas: {largest}"); + assert!(largest < 256 * 1024, "copied a tile: {largest}"); } #[test] diff --git a/src/isobmff.rs b/src/isobmff.rs index f09f19e..9b843a6 100644 --- a/src/isobmff.rs +++ b/src/isobmff.rs @@ -4422,17 +4422,27 @@ fn extract_primary_heic_item_data_with_grid_internal( })) } +pub(crate) fn extract_heic_grid_descriptor( + input: &[u8], + source: &mut Option<&mut dyn RandomAccessSource>, + meta: &MetaBox<'_>, + location: &ItemLocationItem, +) -> Result<(u8, HeicGridDescriptor), ExtractHeicItemDataError> { + let (construction_method, grid_payload) = + extract_heic_item_payload_from_location(input, source, meta, location, location.item_id)?; + let descriptor = parse_heic_grid_descriptor(location.item_id, &grid_payload)?; + Ok((construction_method, descriptor)) +} + pub(crate) fn extract_heic_grid_item_data( input: &[u8], source: &mut Option<&mut dyn RandomAccessSource>, meta: &MetaBox<'_>, resolved: &ResolvedPrimaryItemGraph<'_>, - location: &ItemLocationItem, + item_id: u32, + construction_method: u8, + descriptor: HeicGridDescriptor, ) -> Result { - let item_id = location.item_id; - let (construction_method, grid_payload) = - extract_heic_item_payload_from_location(input, source, meta, location, item_id)?; - let descriptor = parse_heic_grid_descriptor(item_id, &grid_payload)?; let tile_item_ids = grid_tile_item_ids( item_id, resolved diff --git a/src/lib.rs b/src/lib.rs index fdb3adf..d6cef7d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8024,13 +8024,26 @@ fn decode_auxiliary_alpha_grid<'a>( expected: (u32, u32), guardrails: &DecodeGuardrails, ) -> Result, DecodeHeicError> { - let Ok(grid) = isobmff::extract_heic_grid_item_data(input, source, meta, resolved, location) + let Ok((construction_method, descriptor)) = + isobmff::extract_heic_grid_descriptor(input, source, meta, location) else { return Ok(None); }; - if (grid.descriptor.output_width, grid.descriptor.output_height) != expected - || geometry::preflight_grid(&grid, guardrails).is_err() - { + if (descriptor.output_width, descriptor.output_height) != expected { + return Ok(None); + } + let Ok(grid) = isobmff::extract_heic_grid_item_data( + input, + source, + meta, + resolved, + location.item_id, + construction_method, + descriptor, + ) else { + return Ok(None); + }; + if geometry::preflight_grid(&grid, guardrails).is_err() { return Ok(None); } let decoded = match decode_primary_heic_grid_to_image(&grid) { From c91a2ba87fbd93856a4d5e582df002e48b82ffa5 Mon Sep 17 00:00:00 2001 From: laurenspriem Date: Tue, 3 Nov 2026 16:01:44 +0530 Subject: [PATCH 4/5] Test the grid alpha failure policy A grid alpha item that fails to decode is dropped, so the image is returned without alpha, while running out of memory is reported as an error like other allocation failures. Nothing tested either half of this on the grid path. --- src/geometry_tests.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/geometry_tests.rs b/src/geometry_tests.rs index 052170c..e48bd34 100644 --- a/src/geometry_tests.rs +++ b/src/geometry_tests.rs @@ -373,6 +373,44 @@ fn grid_alpha_of_another_size_is_dropped_before_its_tiles_are_copied() { assert!(largest < 256 * 1024, "copied a tile: {largest}"); } +#[test] +fn grid_alpha_that_fails_to_decode_is_dropped() { + let input = grid_alpha_fixture_with_tile( + &[(1, true)], + 1, + small_hevc_sps(), + 16, + hevc_payload_with_nal_header([0x28, 0x09]), + ); + let alpha = decode_primary_heic_auxiliary_alpha_plane_internal( + &input, + &mut None, + 16, + 16, + &DecodeGuardrails::default(), + ); + assert!(matches!(alpha, Ok(None))); +} + +#[test] +fn grid_alpha_allocation_failure_is_propagated() { + let input = + grid_alpha_fixture_with_tile(&[(1, true)], 1, large_hevc_sps(), 126, hevc_payload()); + let result = with_allocations_failing_at(128 * 128 * 2, || { + decode_primary_heic_auxiliary_alpha_plane_internal( + &input, + &mut None, + 126, + 126, + &DecodeGuardrails::default(), + ) + }); + assert!(matches!( + result, + Err(DecodeHeicError::AllocationFailed { .. }) + )); +} + #[test] fn heic_alpha_rejects_coded_geometry_before_plane_allocation() { let input = image_fixture( From c8a7a37a1423aee1954ddcbb3c1720ce58f75c6f Mon Sep 17 00:00:00 2001 From: laurenspriem Date: Tue, 3 Nov 2026 18:15:58 +0530 Subject: [PATCH 5/5] Cap grid tile copies at four times the file size The grid tile data budget is max(4 x file size, 128 MiB). The 128 MiB floor let a small file make the decoder copy far more data than it holds: distinct tile items whose locations overlap the same bytes each got their own copy, and one large ICC profile was copied once per tile colour combination. A 536 KB file reached about 139 MB of tile copies before preflight could reject the grid, on both the primary and the alpha path. Tile payloads and colour profiles that are actually copied are now also held to four times the file size, with no floor. Repeated references to one tile share a copy, so they do not count against this cap, and the existing per-reference budget still applies. The 536 KB file now peaks at 6.5 MB, and a 908 KB file repeating one ICC profile across 120 tiles drops from 114 MB to 9.7 MB. --- src/isobmff.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 63 insertions(+), 3 deletions(-) diff --git a/src/isobmff.rs b/src/isobmff.rs index 9b843a6..0e34714 100644 --- a/src/isobmff.rs +++ b/src/isobmff.rs @@ -4564,12 +4564,13 @@ fn extract_heic_grid_tiles( let mut property_cache = GridTilePropertyCache::default(); let mut tile_properties_by_item = BTreeMap::new(); let mut tile_payloads_by_item = BTreeMap::new(); - let tile_payload_budget = source + let tile_copy_budget = source .as_ref() .map_or(input.len() as u64, |source| source.len()) - .saturating_mul(4) - .max(MAX_GRID_TILE_PAYLOAD_BYTES); + .saturating_mul(4); + let tile_payload_budget = tile_copy_budget.max(MAX_GRID_TILE_PAYLOAD_BYTES); let mut total_tile_payload_bytes = 0_u64; + let mut copied_tile_payload_bytes = 0_u64; let mut tiles = Vec::with_capacity(tile_item_ids.len()); for &tile_item_id in tile_item_ids { @@ -4633,6 +4634,8 @@ fn extract_heic_grid_tiles( tile_item_id, shared_idat_payload, )?; + copied_tile_payload_bytes = + copied_tile_payload_bytes.saturating_add(payload.len() as u64); entry.insert((construction_method, Arc::new(payload))) } } @@ -4651,6 +4654,14 @@ fn extract_heic_grid_tiles( length: total_tile_data_bytes, }); } + let copied_tile_data_bytes = + copied_tile_payload_bytes.saturating_add(property_cache.color_profile_bytes); + if copied_tile_data_bytes > tile_copy_budget { + return Err(ExtractHeicItemDataError::PayloadTooLarge { + item_id, + length: copied_tile_data_bytes, + }); + } tiles.push(HeicGridTileItemData { item_id: tile_item_id, construction_method: tile_construction_method, @@ -8712,6 +8723,55 @@ mod tests { )); } + #[test] + fn grid_tile_payload_copies_are_budgeted_against_the_file_size() { + let tile_ids: Vec = (2..10).collect(); + + let err = extract_primary_heic_item_data_with_grid(&minimal_heic_grid_file( + (1, 8), + (512, 64), + &tile_ids, + &[0xAB; 64 * 1024], + &[hvcc_box()], + &[1], + &[], + )) + .expect_err("distinct tiles sharing one extent must not be copied past the budget"); + assert!(matches!( + err, + ExtractHeicItemDataError::PayloadTooLarge { .. } + )); + } + + #[test] + fn grid_tile_color_profile_copies_are_budgeted_against_the_file_size() { + let profile = vec![0x5A_u8; 64 * 1024]; + let tile_ids: Vec = (2..10).collect(); + let mut properties = vec![hvcc_box(), colr_icc_box(&profile)]; + properties.extend((0..8).map(|_| colr_nclx_box(1, 13, 6, true))); + let nclx_indices: Vec<[u8; 1]> = (3..11).map(|index| [index]).collect(); + let extra_associations: Vec<(u16, &[u8])> = tile_ids + .iter() + .zip(&nclx_indices) + .map(|(&tile_id, index)| (tile_id, &index[..])) + .collect(); + + let err = extract_primary_heic_item_data_with_grid(&minimal_heic_grid_file( + (1, 8), + (512, 64), + &tile_ids, + &[0x11; 16], + &properties, + &[1, 2], + &extra_associations, + )) + .expect_err("profile copies must not exceed the budget"); + assert!(matches!( + err, + ExtractHeicItemDataError::PayloadTooLarge { .. } + )); + } + #[test] fn grid_tile_payload_reuse_within_budget_still_resolves() { let tile_payload = vec![0xAB_u8; 3 * 1024 * 1024];