From d372b81d6a8088cdd4ea4e48b13e7fb625d66016 Mon Sep 17 00:00:00 2001 From: laurenspriem Date: Thu, 5 Nov 2026 15:30:12 +0530 Subject: [PATCH] Decode non-grid HEIC images in bounded decoding A single hvc1/hev1 primary is decoded as a grid with one tile. Its reconstruction workspace is reserved during preflight, so an image that does not fit the budget is refused before decoding, and its payload is bounded by the budget instead of the 16 MiB grid tile cap. The bounded path also accepts a one-channel 8-bit pixi. --- API.md | 33 ++++ README.md | 1 + src/bounded.rs | 16 +- src/bounded/container.rs | 17 +- src/bounded/grid.rs | 142 ++++++++------ src/bounded/incremental.rs | 6 +- src/bounded/tests.rs | 390 +++++++++++++++++++++++++++++++++++-- 7 files changed, 508 insertions(+), 97 deletions(-) diff --git a/API.md b/API.md index 799a425..7a05f5c 100644 --- a/API.md +++ b/API.md @@ -6,6 +6,7 @@ This document is the practical API reference for integrating `heic_decoder` in a - Decode HEIF/HEIC/AVIF to RGBA (`u8` or `u16` storage). - Decode HEVC-coded HEIC/HEIF straight to RGB8 when alpha is not needed. +- Decode HEVC-coded HEIC within a memory budget to a size-capped, display-oriented sRGB RGB8 image (`decode_bounded`). - Decode from bytes, `Read`, `BufRead`, and file paths. - Optional `image` crate integration through hook registration. - Keep default decode output aligned with primary item transforms (`clap`/`irot`/`imir`) and expose explicit EXIF orientation helpers. @@ -417,6 +418,38 @@ fn decode(path: &Path) -> Result<(), heic_decoder::DecodeError> { } ``` +## Bounded decoding + +`decode_bounded(BoundedInput, BoundedDecodeOptions)` decodes a HEIC still image +to display-oriented sRGB RGB8 within a memory budget. It returns +`Result`. The output is reduced with area +averaging so that neither side exceeds `max_side` (1 through 6000, default +6000), and `original_dimensions` is the display size before reduction. +`max_memory_bytes` (at least 64 KiB, default 128 MiB) caps the decoder-owned +memory that depends on the input. `decoder-tracing` disables bounded decoding. + +The primary item may be a grid of uniform HEVC tiles or a single HEVC image +(`hvc1`/`hev1`). Every coded item must be opaque 8-bit 4:2:0 HEVC with one IDR +slice; WPP is supported. A single image is decoded as a grid with one tile. +`clap`/`irot`/`imir` are applied, and Exif orientation applies when no +effective container orientation is present. RGB matrix/TRC ICC profiles and +SDR nclx colour with BT.709, BT.2020 or Display P3 primaries are converted to +sRGB. HDR transfer functions, grayscale or +lookup-table ICC profiles, unprofiled wide-gamut HEVC colour, alpha, and +unknown required auxiliaries return errors. Known depth, semantic matte, and +gain-map auxiliaries are ignored. + +Before any pixel decoding, preflight reads every coded item's headers and +reserves its reconstruction workspace, and admission then reserves the output +together with the largest tile workspace. Inputs that do not fit return +`MemoryBudgetExceeded` or `LimitExceeded` without decoding pixels. Grid tiles +decode one at a time, or concurrently with `parallel-grid` when the budget +allows. A single image's full-resolution reconstruction must fit the budget at +once, so a large non-grid image needs a larger budget than a grid of the same +size. Grid tile payloads are limited to 16 MiB; a single image's payload is +bounded by the budget and the 512 MiB input limit. Admission is conservative, +and allocator overhead and process RSS are not included. + ## Experimental incremental bounded decoding Enable the `incremental-experiment` Cargo feature to use diff --git a/README.md b/README.md index 471683d..d1ffc06 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Pure Rust HEIF/HEIC/AVIF decoder with first-class `image` crate integration. - `path_extension_is_heif` - `DecodedRgbaImage::apply_exif_orientation` - `image_integration::apply_exif_orientation_dynamic` +- Memory-budgeted HEIC decoding with `decode_bounded`: grid and single-image HEVC primaries decode to display-oriented sRGB RGB8 with a capped maximum side, and inputs that would exceed the budget are refused before pixel decoding. - Optional guardrails for bounded production use: - max input bytes - max decoded pixel count diff --git a/src/bounded.rs b/src/bounded.rs index 2c90c63..b1b448a 100644 --- a/src/bounded.rs +++ b/src/bounded.rs @@ -183,7 +183,8 @@ pub fn decode_bounded( let (pool, _pool_reservation) = { let threads = std::thread::available_parallelism() .map_or(1, usize::from) - .min(8); + .min(8) + .min(grid.tiles.len()); let mut workers = threads; while workers > 1 && max_job @@ -285,13 +286,14 @@ pub fn decode_bounded( } fn job_bytes(tile: &grid::Tile<'_>, region: resample::Region, layout: resample::Layout) -> usize { + let contributions = if layout.is_unscaled() { + 0 + } else { + resample::Contribution::workspace_bytes(region) + }; tile.workspace_bytes - + tile.payload_len - + if layout.is_unscaled() { - 0 - } else { - resample::Contribution::workspace_bytes(region) - } + .saturating_add(tile.payload_len) + .saturating_add(contributions) } fn render_tile( diff --git a/src/bounded/container.rs b/src/bounded/container.rs index 793b6ad..0bce051 100644 --- a/src/bounded/container.rs +++ b/src/bounded/container.rs @@ -273,15 +273,6 @@ fn unique<'a>(slot: &mut Option<&'a [u8]>, data: &'a [u8]) -> Result<()> { impl<'a> Index<'a> { pub(super) fn parse(metadata: &'a [u8], source_len: u64, budget: &Budget) -> Result { - Self::parse_primary(metadata, source_len, budget, false) - } - - pub(super) fn parse_primary( - metadata: &'a [u8], - source_len: u64, - budget: &Budget, - direct: bool, - ) -> Result { let mut reader = Reader::new(metadata); if reader.full_box()? != (0, 0) { @@ -361,10 +352,10 @@ impl<'a> Index<'a> { let primary = items .binary_search_by_key(&primary_id, |item| item.id) .map_err(|_| Error::Malformed("primary item missing"))?; - if items[primary].kind != *b"grid" - && !(direct && matches!(&items[primary].kind, b"hvc1" | b"hev1")) - { - return Err(Error::Unsupported("primary item must be a HEIC grid")); + if !matches!(&items[primary].kind, b"grid" | b"hvc1" | b"hev1") { + return Err(Error::Unsupported( + "primary item must be a HEIC grid or HEVC image", + )); } let idat = idat.unwrap_or_default(); Self::locations( diff --git a/src/bounded/grid.rs b/src/bounded/grid.rs index 799a44e..5dfdd9f 100644 --- a/src/bounded/grid.rs +++ b/src/bounded/grid.rs @@ -24,20 +24,6 @@ pub(super) struct Properties<'a> { impl<'a> Properties<'a> { pub(super) fn read(index: &Index<'a>, item: usize, tile: bool) -> Result { - Self::read_with_compatibility(index, item, tile, false) - } - - #[cfg(feature = "incremental-experiment")] - pub(super) fn read_incremental(index: &Index<'a>, item: usize, tile: bool) -> Result { - Self::read_with_compatibility(index, item, tile, true) - } - - fn read_with_compatibility( - index: &Index<'a>, - item: usize, - tile: bool, - legacy_pixi: bool, - ) -> Result { let mut result = Self { config: None, dimensions: None, @@ -92,10 +78,8 @@ impl<'a> Properties<'a> { return Err(Error::Unsupported("pixi version or flags")); } let count = r.uint(1)? as usize; - if (count != 3 && !(legacy_pixi && count == 1)) - || r.take(count)?.iter().any(|&n| n != 8) - { - return Err(Error::Unsupported("8-bit RGB channels required")); + if !matches!(count, 1 | 3) || r.take(count)?.iter().any(|&n| n != 8) { + return Err(Error::Unsupported("8-bit channels required")); } r.finish()?; } @@ -195,12 +179,87 @@ pub(super) struct Grid<'a> { pub(super) exif: Option, } +impl<'a> Tile<'a> { + fn preflight( + index: &Index<'a>, + source: &mut Source<'_>, + budget: &Budget, + item: usize, + properties: &Properties<'a>, + max_payload: usize, + ) -> Result { + let config = properties.config.ok_or(Error::Malformed("missing hvcC"))?; + let payload_len = index.items[item] + .location + .ok_or(Error::Malformed("missing coded item location"))? + .length; + if payload_len == 0 || payload_len > max_payload { + return Err(Error::LimitExceeded("coded item payload bytes")); + } + let mut payload = budget.zeroed(payload_len, "preflight payload")?; + index.read_item(item, source, &mut payload)?; + let (geometry, reconstruction_bytes) = { + let _headers = budget.reserve( + payload_len.saturating_mul(5).saturating_add(1024 * 1024), + "HEVC header parsing", + )?; + let prepared = codec::prepare(config, &payload)?; + (prepared.geometry, prepared.reconstruction_bytes()) + }; + if properties.dimensions != Some((geometry.width, geometry.height)) { + return Err(Error::Malformed("ispe differs from SPS")); + } + let workspace_bytes = (reconstruction_bytes + payload_len as u64 * 3 + 1024 * 1024) + .try_into() + .map_err(|_| Error::LimitExceeded("codec workspace"))?; + let _admission = budget.reserve(workspace_bytes, "tile reconstruction")?; + Ok(Self { + item, + config, + geometry, + color: properties.color.clone(), + payload_len, + workspace_bytes, + }) + } +} + impl<'a> Grid<'a> { pub(super) fn preflight( index: &Index<'a>, source: &mut Source<'_>, budget: &Budget, ) -> Result { + if index.items[index.primary].kind == *b"grid" { + Self::tiled(index, source, budget) + } else { + Self::single(index, source, budget) + } + } + + fn single(index: &Index<'a>, source: &mut Source<'_>, budget: &Budget) -> Result { + let properties = Properties::read(index, index.primary, false)?; + let mut tiles = budget.buffer::>(1, "tile index")?; + tiles.push(Tile::preflight( + index, + source, + budget, + index.primary, + &properties, + usize::MAX, + )?)?; + let exif = validate_references(index, source, &tiles, budget)?; + Ok(Self { + width: tiles[0].geometry.width, + height: tiles[0].geometry.height, + columns: 1, + tiles, + properties, + exif, + }) + } + + fn tiled(index: &Index<'a>, source: &mut Source<'_>, budget: &Budget) -> Result { let primary = index.primary; let primary_id = index.items[primary].id; let location = index.items[primary] @@ -255,33 +314,15 @@ impl<'a> Grid<'a> { return Err(Error::Unsupported("grid requires direct HEVC tiles")); } let props = Properties::read(index, item, true)?; - let config = props.config.ok_or(Error::Malformed("missing tile hvcC"))?; - let payload_len = index.items[item] - .location - .ok_or(Error::Malformed("missing tile location"))? - .length; - if payload_len == 0 || payload_len > MAX_ITEM_BYTES { - return Err(Error::LimitExceeded("tile payload bytes")); - } - let mut payload = budget.zeroed(payload_len, "preflight payload")?; - index.read_item(item, source, &mut payload)?; - let (geometry, reconstruction_bytes) = { - let _headers = - budget.reserve(payload_len * 5 + 1024 * 1024, "HEVC header parsing")?; - let prepared = codec::prepare(config, &payload)?; - (prepared.geometry, prepared.reconstruction_bytes()) - }; - if props.dimensions != Some((geometry.width, geometry.height)) { - return Err(Error::Malformed("tile ispe differs from SPS")); - } + let tile = Tile::preflight(index, source, budget, item, &props, MAX_ITEM_BYTES)?; if tiles.first().is_some_and(|first| { ( - geometry.width, - geometry.height, - geometry.full_range, - geometry.matrix, - geometry.primaries, - geometry.transfer, + tile.geometry.width, + tile.geometry.height, + tile.geometry.full_range, + tile.geometry.matrix, + tile.geometry.primaries, + tile.geometry.transfer, ) != ( first.geometry.width, first.geometry.height, @@ -289,22 +330,11 @@ impl<'a> Grid<'a> { first.geometry.matrix, first.geometry.primaries, first.geometry.transfer, - ) || props.color != first.color + ) || tile.color != first.color }) { return Err(Error::Unsupported("nonuniform grid tiles")); } - let workspace_bytes = (reconstruction_bytes + payload_len as u64 * 3 + 1024 * 1024) - .try_into() - .map_err(|_| Error::LimitExceeded("codec workspace"))?; - let _admission = budget.reserve(workspace_bytes, "tile reconstruction")?; - tiles.push(Tile { - item, - config, - geometry, - color: props.color, - payload_len, - workspace_bytes, - })?; + tiles.push(tile)?; } let tile = &tiles[0]; if u64::from(tile.geometry.width) * u64::from(columns) < u64::from(width) diff --git a/src/bounded/incremental.rs b/src/bounded/incremental.rs index b346b06..dd73c4f 100644 --- a/src/bounded/incremental.rs +++ b/src/bounded/incremental.rs @@ -133,7 +133,7 @@ impl Read for Rbsp { fn plan<'a>(index: &Index<'a>, source: &mut Source<'_>, budget: &Budget) -> Result> { let primary = index.primary; - let properties = Properties::read_incremental(index, primary, false)?; + let properties = Properties::read(index, primary, false)?; let (width, height) = properties .dimensions .ok_or(Error::Malformed("primary dimensions"))?; @@ -203,7 +203,7 @@ fn plan<'a>(index: &Index<'a>, source: &mut Source<'_>, budget: &Budget) -> Resu if !matches!(&index.items[item].kind, b"hvc1" | b"hev1") { return Err(Error::Unsupported("direct HEVC item required")); } - let props = Properties::read_incremental(index, item, is_grid)?; + let props = Properties::read(index, item, is_grid)?; let config = props.config.ok_or(Error::Malformed("missing hvcC"))?; let _headers = budget.reserve(2 * 1024 * 1024, "header parsing")?; let slice = slice(index, source, item, config)?; @@ -261,7 +261,7 @@ pub fn decode( let _runtime = budget.reserve(65536, "runtime")?; let mut source = Source::new(input)?; let metadata = source.metadata(&budget)?; - let index = Index::parse_primary(&metadata, source.len(), &budget, true)?; + let index = Index::parse(&metadata, source.len(), &budget)?; let grid = plan(&index, &mut source, &budget)?; let layout = Layout::new(&grid, options.max_side)?; for (i, transform) in grid.properties.transforms.iter().flatten().enumerate() { diff --git a/src/bounded/tests.rs b/src/bounded/tests.rs index 245d259..a468989 100644 --- a/src/bounded/tests.rs +++ b/src/bounded/tests.rs @@ -204,6 +204,117 @@ fn fixture_with_exif_info( .concat() } +#[derive(Clone, Copy)] +enum Primary { + Single, + Grid, +} + +fn coded_fixture( + primary: Primary, + config: &[u8], + dimensions: (u32, u32), + nals: &[&[u8]], + extra_properties: &[Vec], + orientation: Option, +) -> Vec { + let ftyp = box_bytes(b"ftyp", b"heic\0\0\0\0mif1heic"); + let payload: Vec = nals + .iter() + .flat_map(|nal| [&(nal.len() as u32).to_be_bytes()[..], nal].concat()) + .collect(); + let descriptor = [ + vec![0, 0, 0, 0], + (dimensions.0 as u16).to_be_bytes().to_vec(), + (dimensions.1 as u16).to_be_bytes().to_vec(), + ] + .concat(); + let exif = orientation.map(|orientation| { + let mut exif = hex("0000000049492a0008000000010012010300010000000100000000000000"); + exif[22] = orientation; + exif + }); + let grid = matches!(primary, Primary::Grid); + let mut items = vec![(b"hvc1\0".as_slice(), payload.as_slice())]; + if grid { + items.push((b"grid\0", &descriptor)); + } + let primary_id = items.len() as u16; + if let Some(exif) = &exif { + items.push((b"Exif\0", exif)); + } + let item_count = items.len() as u16; + let mut data = Vec::new(); + let mut info = item_count.to_be_bytes().to_vec(); + let mut locations = vec![0x44, 0]; + locations.extend_from_slice(&item_count.to_be_bytes()); + for (id, (kind, bytes)) in (1u16..).zip(&items) { + info.extend(full_box( + b"infe", + 2, + &[&id.to_be_bytes()[..], &[0, 0], kind].concat(), + )); + locations.extend_from_slice(&id.to_be_bytes()); + locations.extend_from_slice(&[0, 0, 0, 0, 0, 1]); + locations.extend_from_slice(&((ftyp.len() + 8 + data.len()) as u32).to_be_bytes()); + locations.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); + data.extend_from_slice(bytes); + } + let mut properties = full_box( + b"ispe", + 0, + &[dimensions.0.to_be_bytes(), dimensions.1.to_be_bytes()].concat(), + ); + properties.extend(box_bytes(b"hvcC", config)); + let mut extras = Vec::new(); + for (i, property) in extra_properties.iter().enumerate() { + properties.extend(property); + extras.push(0x80 | (3 + i) as u8); + } + let mut associations = u32::from(primary_id).to_be_bytes().to_vec(); + let coded = [&[0x81, 0x82][..], if grid { &[] } else { &extras }].concat(); + associations.extend_from_slice(&1u16.to_be_bytes()); + associations.push(coded.len() as u8); + associations.extend(coded); + if grid { + associations.extend_from_slice(&primary_id.to_be_bytes()); + associations.push(1 + extras.len() as u8); + associations.push(0x81); + associations.extend(&extras); + } + let mut references = Vec::new(); + if grid { + references.extend(box_bytes( + b"dimg", + &[primary_id, 1, 1].map(u16::to_be_bytes).concat(), + )); + } + if exif.is_some() { + references.extend(box_bytes( + b"cdsc", + &[item_count, 1, primary_id].map(u16::to_be_bytes).concat(), + )); + } + let mut meta = [ + full_box(b"pitm", 0, &primary_id.to_be_bytes()), + full_box(b"iinf", 0, &info), + full_box(b"iloc", 1, &locations), + box_bytes( + b"iprp", + &[ + box_bytes(b"ipco", &properties), + full_box(b"ipma", 0, &associations), + ] + .concat(), + ), + ] + .concat(); + if !references.is_empty() { + meta.extend(full_box(b"iref", 0, &references)); + } + [ftyp, box_bytes(b"mdat", &data), full_box(b"meta", 0, &meta)].concat() +} + fn read_ue(bits: &[bool], position: &mut usize) -> u32 { let mut zeros = 0; while !bits[*position] { @@ -229,6 +340,10 @@ fn write_ue(bits: &mut Vec, value: u32) { } fn huge_cropped_sps() -> Vec { + sps_with_size(16384, 16384, Some([0, 8184, 0, 8184])) +} + +fn sps_with_size(width: u32, height: u32, crop: Option<[u32; 4]>) -> Vec { let nals = nal_sets(); let sps = crate::heic_decoder::hevc::bitstream::parse_single_nal(&nals[1]).unwrap(); let mut bits: Vec = sps @@ -245,11 +360,11 @@ fn huge_cropped_sps() -> Vec { assert!(!bits[cursor]); cursor += 1; let mut replacement = Vec::new(); - write_ue(&mut replacement, 16384); - write_ue(&mut replacement, 16384); - replacement.push(true); - for crop in [0, 8184, 0, 8184] { - write_ue(&mut replacement, crop); + write_ue(&mut replacement, width); + write_ue(&mut replacement, height); + replacement.push(crop.is_some()); + for offset in crop.into_iter().flatten() { + write_ue(&mut replacement, offset); } bits.splice(start..cursor, replacement); nal_from_bits(&nals[1][..2], bits) @@ -740,10 +855,11 @@ fn display_mapping_matches_existing_transform_plan() { } } -#[cfg(all(feature = "incremental-experiment", not(feature = "decoder-tracing")))] +#[cfg(not(feature = "decoder-tracing"))] #[test] -fn incremental_accepts_legacy_pixi_without_relaxing_bit_depth_checks() { +fn one_channel_pixi_is_accepted_without_relaxing_bit_depth_checks() { let nals = nal_sets(); + let config = configuration(&nals[1]); for (channels, expected) in [ (vec![1, 8], true), (vec![3, 8, 8, 8], true), @@ -753,13 +869,31 @@ fn incremental_accepts_legacy_pixi_without_relaxing_bit_depth_checks() { (vec![0], false), (vec![1, 8, 8], false), ] { - let bytes = fixture( - &[configuration(&nals[1])], - &nals[3], - &[full_box(b"pixi", 0, &channels)], - ); - let result = incremental::decode(BoundedInput::Bytes(&bytes), Default::default()); - assert_eq!(result.is_ok(), expected, "{channels:?}: {result:?}"); + let pixi = [full_box(b"pixi", 0, &channels)]; + let configs = std::slice::from_ref(&config); + for (shape, bytes) in [ + ( + "single", + coded_fixture(Primary::Single, &config, (16, 16), &[&nals[3]], &pixi, None), + ), + ( + "grid tile", + fixture_with_exif_info(configs, &nals[3], &pixi, &[], &[0], None, b"Exif\0"), + ), + ("grid", fixture(configs, &nals[3], &pixi)), + ] { + let result = decode_bounded(BoundedInput::Bytes(&bytes), Default::default()); + assert_eq!(result.is_ok(), expected, "{shape} {channels:?}: {result:?}"); + #[cfg(feature = "incremental-experiment")] + { + let result = incremental::decode(BoundedInput::Bytes(&bytes), Default::default()); + assert_eq!( + result.is_ok(), + expected, + "incremental {shape} {channels:?}: {result:?}" + ); + } + } } } @@ -833,8 +967,7 @@ fn shared_reference_validation_preserves_auxiliary_and_exif_rules() { let budget = memory::Budget::new(128 * 1024 * 1024); let mut source = container::Source::new(BoundedInput::Bytes(&bytes)).unwrap(); let metadata = source.metadata(&budget).unwrap(); - let index = - container::Index::parse_primary(&metadata, source.len(), &budget, true).unwrap(); + let index = container::Index::parse(&metadata, source.len(), &budget).unwrap(); let result = grid::validate_references(&index, &mut source, &[], &budget); match expected { None => assert!(result.is_ok()), @@ -849,8 +982,7 @@ fn shared_reference_validation_preserves_auxiliary_and_exif_rules() { let budget = memory::Budget::new(128 * 1024 * 1024); let mut source = container::Source::new(BoundedInput::Bytes(&bytes)).unwrap(); let metadata = source.metadata(&budget).unwrap(); - let index = - container::Index::parse_primary(&metadata, source.len(), &budget, true).unwrap(); + let index = container::Index::parse(&metadata, source.len(), &budget).unwrap(); assert_eq!( grid::validate_references(&index, &mut source, &[], &budget).unwrap(), Some(orientation) @@ -1267,3 +1399,225 @@ fn decodes_unprofiled_bt601_color_like_normal_decode() { assert_eq!(bounded.image.pixels, normal.pixels); } } + +#[cfg(not(feature = "decoder-tracing"))] +#[test] +fn single_image_primaries_decode_like_one_tile_grids() { + let config = configuration(&nal_sets()[1]); + let payload = asymmetric_payload(); + let crop: Vec<_> = [12u32, 1, 12, 1, 0, 1, 0, 1] + .into_iter() + .flat_map(u32::to_be_bytes) + .collect(); + let mut property_sets = vec![ + vec![], + vec![box_bytes(b"clap", &crop)], + vec![box_bytes(b"clap", &crop), box_bytes(b"irot", &[1])], + ]; + for rotation in 0..4 { + for mirror in 0..2 { + property_sets.push(vec![ + box_bytes(b"irot", &[rotation]), + box_bytes(b"imir", &[mirror]), + ]); + } + } + for properties in &property_sets { + for orientation in std::iter::once(None).chain((1..=8).map(Some)) { + let fixture = |primary| { + coded_fixture( + primary, + &config, + (16, 16), + &[&payload], + properties, + orientation, + ) + }; + let single = fixture(Primary::Single); + let grid = fixture(Primary::Grid); + for max_side in [6000, 7] { + let options = BoundedDecodeOptions { + max_side, + ..Default::default() + }; + let actual = decode_bounded(BoundedInput::Bytes(&single), options).unwrap(); + let expected = decode_bounded(BoundedInput::Bytes(&grid), options).unwrap(); + assert_eq!(actual.original_dimensions, expected.original_dimensions); + assert_eq!( + (actual.image.width, actual.image.height), + (expected.image.width, expected.image.height) + ); + assert_eq!(actual.image.pixels, expected.image.pixels); + } + let bounded = decode_bounded(BoundedInput::Bytes(&single), Default::default()).unwrap(); + #[cfg(feature = "incremental-experiment")] + { + let (incremental, _) = + incremental::decode(BoundedInput::Bytes(&single), Default::default()).unwrap(); + assert_eq!(incremental.original_dimensions, bounded.original_dimensions); + assert_eq!(incremental.image.pixels, bounded.image.pixels); + } + let normal = crate::decode_bytes_to_rgb8(&single).unwrap(); + let transforms = crate::exif_orientation_hint(&single) + .orientation_to_apply() + .and_then(|n| crate::exif_orientation_to_primary_item_transforms(u16::from(n))) + .unwrap_or_default(); + let plan = crate::RgbaTransformPlan::from_primary_transforms( + normal.width, + normal.height, + &transforms, + ) + .unwrap(); + assert_eq!( + bounded.original_dimensions, + (plan.destination_width, plan.destination_height) + ); + for y in 0..bounded.image.height as usize { + for x in 0..bounded.image.width as usize { + let (sx, sy) = plan.map_destination_pixel(x, y).unwrap(); + let src = (sy * normal.width as usize + sx) * 3; + let dst = (y * bounded.image.width as usize + x) * 3; + assert_eq!( + &bounded.image.pixels[dst..dst + 3], + &normal.pixels[src..src + 3] + ); + } + } + } + } +} + +#[cfg(not(feature = "decoder-tracing"))] +#[test] +fn single_image_primaries_handle_color_like_one_tile_grids() { + let payload = hex("2801af78f70403fe65f7f877430938"); + let decode = |sps: &[u8], properties: &[Vec]| { + let fixture = |primary| { + coded_fixture( + primary, + &configuration(sps), + (16, 16), + &[&payload], + properties, + None, + ) + }; + let single = fixture(Primary::Single); + let actual = decode_bounded(BoundedInput::Bytes(&single), Default::default()); + let expected = decode_bounded( + BoundedInput::Bytes(&fixture(Primary::Grid)), + Default::default(), + ); + match (actual, expected) { + (Ok(actual), Ok(expected)) => { + assert_eq!(actual.image.pixels, expected.image.pixels); + assert_eq!( + actual.image.pixels, + crate::decode_bytes_to_rgb8(&single).unwrap().pixels + ); + Ok(actual.image.pixels) + } + ( + Err(BoundedDecodeError::Unsupported(actual)), + Err(BoundedDecodeError::Unsupported(expected)), + ) if actual == expected => Err(actual), + (actual, expected) => panic!("{actual:?} != {expected:?}"), + } + }; + let wide_gamut = + hex("4201010408000003009fa800000300001ea0884596eaaf2bc05a848684820000030002000003003210"); + assert_eq!(decode(&wide_gamut, &[]), Err("unprofiled HEVC color")); + decode(&wide_gamut, &[box_bytes(b"colr", b"prof")]).unwrap(); + for sps in [ + "4201010408000003009fa800000300001ea0884596eaaf2bc05b828302820000030002000003003210", + "4201010408000003009fa800000300001ea0884596eaaf2bc05a830303020000030002000003003210", + ] { + decode(&hex(sps), &[]).unwrap(); + } + let nclx = box_bytes( + b"colr", + &[b"nclx".as_slice(), &[0, 1, 0, 13, 0, 6, 0x80]].concat(), + ); + let sps = &nal_sets()[1]; + assert_ne!(decode(sps, &[]).unwrap(), decode(sps, &[nclx]).unwrap()); +} + +#[test] +fn single_images_exceeding_the_budget_are_refused_during_preflight_like_grids() { + let nals = nal_sets(); + for primary in [Primary::Single, Primary::Grid] { + for (sps, dimensions) in [ + (sps_with_size(8192, 8192, None), (8192, 8192)), + (huge_cropped_sps(), (16, 16)), + ] { + let bytes = coded_fixture( + primary, + &configuration(&sps), + dimensions, + &[&nals[3]], + &[], + None, + ); + let budget = memory::Budget::new(128 * 1024 * 1024); + let mut source = container::Source::new(BoundedInput::Bytes(&bytes)).unwrap(); + let metadata = source.metadata(&budget).unwrap(); + let index = container::Index::parse(&metadata, source.len(), &budget).unwrap(); + assert!(matches!( + grid::Grid::preflight(&index, &mut source, &budget), + Err(BoundedDecodeError::MemoryBudgetExceeded { + stage: "tile reconstruction", + .. + }) + )); + #[cfg(not(feature = "decoder-tracing"))] + assert!(matches!( + decode_bounded(BoundedInput::Bytes(&bytes), Default::default()), + Err(BoundedDecodeError::MemoryBudgetExceeded { + stage: "tile reconstruction", + .. + }) + )); + } + } +} + +#[cfg(not(feature = "decoder-tracing"))] +#[test] +fn single_image_payloads_are_bounded_by_the_budget_instead_of_the_tile_cap() { + let nals = nal_sets(); + let config = configuration(&nals[1]); + let mut filler = vec![0xff; container::MAX_ITEM_BYTES]; + filler[..2].copy_from_slice(&[0x4c, 0x01]); + *filler.last_mut().unwrap() = 0x80; + let fixture = + |primary, nals: &[&[u8]]| coded_fixture(primary, &config, (16, 16), nals, &[], None); + let options = |megabytes: usize| BoundedDecodeOptions { + max_memory_bytes: megabytes * 1024 * 1024, + ..Default::default() + }; + assert!(matches!( + decode_bounded( + BoundedInput::Bytes(&fixture(Primary::Grid, &[&filler, &nals[3]])), + options(256) + ), + Err(BoundedDecodeError::LimitExceeded( + "coded item payload bytes" + )) + )); + let single = fixture(Primary::Single, &[&filler, &nals[3]]); + let expected = decode_bounded( + BoundedInput::Bytes(&fixture(Primary::Single, &[&nals[3]])), + Default::default(), + ) + .unwrap(); + let actual = decode_bounded(BoundedInput::Bytes(&single), options(256)).unwrap(); + assert_eq!(actual.image.pixels, expected.image.pixels); + assert!(matches!( + decode_bounded(BoundedInput::Bytes(&single), options(64)), + Err(BoundedDecodeError::MemoryBudgetExceeded { + stage: "HEVC header parsing", + .. + }) + )); +}