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..e48bd34 100644 --- a/src/geometry_tests.rs +++ b/src/geometry_tests.rs @@ -207,6 +207,210 @@ 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 { + 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(); + 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 = (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", tile_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(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(); + 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_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 < 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( @@ -262,7 +466,7 @@ fn grid_fixture() -> isobmff::HeicGridPrimaryItemData { hvcc: hvcc.into(), colr: Default::default(), transforms: Default::default(), - payload: hevc_payload(), + payload: hevc_payload().into(), }], } } @@ -519,7 +723,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); @@ -836,7 +1041,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 { @@ -1145,7 +1351,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)); @@ -1362,7 +1568,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 { @@ -1470,15 +1676,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 +1699,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 87f8659..0e34714 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)] @@ -4401,17 +4401,99 @@ 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_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<'_>, + item_id: u32, + construction_method: u8, + descriptor: HeicGridDescriptor, +) -> Result { + 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 { @@ -4442,7 +4524,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(); @@ -4481,15 +4563,17 @@ fn extract_primary_heic_item_data_with_grid_internal( }; let mut property_cache = GridTilePropertyCache::default(); let mut tile_properties_by_item = BTreeMap::new(); - let tile_payload_budget = source + let mut tile_payloads_by_item = BTreeMap::new(); + 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 { + 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, @@ -4532,21 +4616,30 @@ fn extract_primary_heic_item_data_with_grid_internal( } .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, + )?; + copied_tile_payload_bytes = + copied_tile_payload_bytes.saturating_add(payload.len() as u64); + 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 { @@ -4561,6 +4654,14 @@ fn extract_primary_heic_item_data_with_grid_internal( 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, @@ -4571,14 +4672,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 = ( @@ -8300,6 +8394,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( @@ -8608,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]; diff --git a/src/lib.rs b/src/lib.rs index 9e66c90..d6cef7d 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,76 @@ 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((construction_method, descriptor)) = + isobmff::extract_heic_grid_descriptor(input, source, meta, location) + else { + return Ok(None); + }; + 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) { + 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>, @@ -14066,7 +14147,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"); @@ -14119,7 +14200,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"); diff --git a/src/testdata/apple-alpha-grid-1030x520.heic b/src/testdata/apple-alpha-grid-1030x520.heic new file mode 100644 index 0000000..65f6c56 Binary files /dev/null and b/src/testdata/apple-alpha-grid-1030x520.heic differ