diff --git a/API.md b/API.md index 102db89..188a53d 100644 --- a/API.md +++ b/API.md @@ -462,23 +462,26 @@ 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. Container transforms for which -libheif first converts 4:2:0 chroma to 4:4:4 return `Unsupported`. Each is -judged at the size the image has when it applies: a `clap` with an odd left or -top edge, an anticlockwise 90° rotation (`irot` 1) of an odd width, a 180° -rotation with either side odd, an anticlockwise 270° rotation (`irot` 3) of an -odd height, or a mirror with either side odd. A display area that starts on an -odd source row or column is also refused, which is stricter than libheif when -a rotation or mirror comes before the crop. 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 +effective container orientation is present. When a container transform makes +libheif convert 4:2:0 chroma to 4:4:4 (the 4:2:0 rules under Container +transforms above), the output matches the regular decoders: bilinear chroma +with clamped edges, the limited-range round trip through RGB, and the `colr` +nclx override after all transforms. The 4:4:4 samples are built a band of rows +at a time while each tile is converted to RGB, so no full-size 4:4:4 image is +held. Grid tiles are then converted in units shifted one pixel up and left, so +each unit needs only the last chroma row and column of tiles decoded before +it; those edges are kept in strips as wide as the canvas. Clean apertures, +rotations and mirrors on individual grid tiles are refused. 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 +together with the largest tile workspace, which includes the 4:4:4 band +buffers when the conversion applies. 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 @@ -517,9 +520,9 @@ payloads. Use Path input when avoiding a caller-owned compressed input buffer is also important. This first subset retains limits of 16384 per coded side, 256 million display -pixels, bounded metadata, and a 64 KiB slice-header prefix. It supports one -clean-aperture crop before orientation, with chroma interpolation for odd -origins on a single coded image or one-tile grid. Odd-origin crops across -multiple grid items and repeated crops or crops after orientation are -unsupported. Exif orientation applies when no effective container orientation -is present. `decoder-tracing` disables bounded decoding. +pixels, bounded metadata, and a 64 KiB slice-header prefix. It applies +`clap`/`irot`/`imir` in property order and converts to 4:4:4 like +`decode_bounded` on a single coded image or a one-tile grid. Grids of several +coded items that need the 4:4:4 conversion return `Unsupported`. Exif +orientation applies when no effective container orientation is present. +`decoder-tracing` disables bounded decoding. diff --git a/TESTING.md b/TESTING.md index 0e4e21e..2de9e7f 100644 --- a/TESTING.md +++ b/TESTING.md @@ -195,11 +195,15 @@ These files are kept out of `incremental-corpus` because `verify.rb` requires every file there to decode with the incremental experiment. The script refuses an output folder that overlaps the incremental corpus, or that is not empty and lacks the `.generate-bounded` marker it writes, and it only replaces the -`pass-*` and `refuse-*` files in its own folder. `refuse-*` files use rotations, mirrors or -grid canvases for which libheif converts to 4:4:4, so `decode_bounded` must -refuse them; if one decodes, the pixel comparison fails. `pass-*` files are -the matching controls and the Display P3 and BT.2020 nclx cases. CI passes -every `pass-*` file, `IMG_0983.HEIC` and `1718_rotate_90_cw.HEIC` with +`pass-*` files in its own folder, deleting any `refuse-*` files left by older +versions. The files cover odd crops with rotations that keep 4:2:0 chroma, the +Display P3 and BT.2020 nclx cases, and transforms for which libheif converts +to 4:4:4: odd-origin crops and odd-sized rotations and mirrors, on one tile and +on 2×2 and 3×2 grids whose seams fall inside the converted area. Rotations and +mirrors that convert are followed by a crop that trims one pixel from every +side, because the pinned libheif 1.21.2 interpolates the converted image's +edge rows and columns differently from the fixed kernel the decoders use. CI +passes every `pass-*` file, `IMG_0983.HEIC` and `1718_rotate_90_cw.HEIC` with `--require-pass`, which fails the run unless that file passes at both sizes. Every HEIC, HEIF and AVIF file under the given paths is decoded at max side @@ -248,10 +252,11 @@ hidden: `heif-dec` writes visible tiles first, and `verify` would compare the primary decode against a tile. Cases whose grid tiles carry their own odd clean aperture are written to the `tile-crop` subdirectory. The incremental and bounded decoders refuse tile crops. Cases that rotate or mirror odd-sized -or 4:2:2 images are written to the `orientation` subdirectory, because the -incremental and bounded decoders do not yet reproduce libheif's 4:4:4 -conversion for them. The incremental runner below only receives the top-level -files, and default `verify` covers both subdirectories. +or 4:2:2 images are written to the `orientation` subdirectory. The bounded +decoder reproduces libheif's 4:4:4 conversion for the 4:2:0 cases there and +refuses the 4:2:2 ones, which its HEVC decoder does not support. The +incremental runner below only receives the top-level files, and default +`verify` and the bounded comparison cover both subdirectories. ```bash cmake -S scripts/incremental -B .heic-test-runs/incremental-oracle \ diff --git a/scripts/incremental/generate-bounded.rb b/scripts/incremental/generate-bounded.rb index f3e7212..637218c 100644 --- a/scripts/incremental/generate-bounded.rb +++ b/scripts/incremental/generate-bounded.rb @@ -25,20 +25,35 @@ 'pass-odd-canvas-grid-rotate-270' => { 'GRID' => '1', 'CANVAS' => '255x256', 'ROTATION' => '3' }, 'pass-nclx-display-p3' => { 'TILE_NCLX' => '12/13/6/0' }, 'pass-nclx-bt2020' => { 'TILE_NCLX' => '9/1/9/0' }, - 'refuse-odd-width-crop-rotate-90' => { 'CROP' => '131x192', 'ROTATION' => '1' }, - 'refuse-odd-width-crop-rotate-180' => { 'CROP' => '131x192', 'ROTATION' => '2' }, - 'refuse-odd-height-crop-rotate-180' => { 'CROP' => '192x129', 'ROTATION' => '2' }, - 'refuse-odd-height-crop-rotate-270' => { 'CROP' => '192x129', 'ROTATION' => '3' }, - 'refuse-odd-width-crop-mirror-vertical-axis' => { 'CROP' => '131x192', 'MIRROR' => '0' }, - 'refuse-odd-width-crop-mirror-horizontal-axis' => { 'CROP' => '131x192', 'MIRROR' => '1' }, - 'refuse-odd-canvas-grid-rotate-180' => { 'GRID' => '1', 'CANVAS' => '255x256', 'ROTATION' => '2' } + 'pass-odd-origin-crop' => { 'CROP' => '130x190' }, + 'pass-odd-origin-crop-rotate-90-mirror' => { 'CROP' => '130x190', 'ROTATION' => '1', 'MIRROR' => '1' }, + 'pass-odd-canvas-grid-rotate-90-trimmed' => { + 'GRID' => '1', 'CANVAS' => '255x256', 'ROTATION' => '1', 'CROP' => '254x253', 'TRANSFORM_ORDER' => 'ROTATION,CROP' + }, + 'pass-odd-canvas-grid-rotate-180-trimmed' => { + 'GRID' => '1', 'CANVAS' => '255x256', 'ROTATION' => '2', 'CROP' => '253x254', 'TRANSFORM_ORDER' => 'ROTATION,CROP' + }, + 'pass-odd-canvas-grid-mirror-trimmed' => { + 'GRID' => '1', 'CANVAS' => '256x255', 'MIRROR' => '0', 'CROP' => '254x253', 'TRANSFORM_ORDER' => 'MIRROR,CROP' + }, + 'pass-tiled-odd-origin-crop' => { 'TILES' => '2x2', 'CROP' => '510x510' }, + 'pass-tiled-rotate-90-odd-origin-crop' => { + 'TILES' => '2x2', 'ROTATION' => '1', 'CROP' => '510x508', 'TRANSFORM_ORDER' => 'ROTATION,CROP' + }, + 'pass-tiled-odd-canvas-rotate-90-trimmed' => { + 'TILES' => '2x2', 'CANVAS' => '511x512', 'ROTATION' => '1', 'CROP' => '510x509', 'TRANSFORM_ORDER' => 'ROTATION,CROP' + }, + 'pass-tiled-odd-canvas-mirror-trimmed' => { + 'TILES' => '3x2', 'CANVAS' => '767x511', 'MIRROR' => '1', 'CROP' => '765x509', 'TRANSFORM_ORDER' => 'MIRROR,CROP' + } } -keys = %w[GRID CANVAS CROP ROTATION MIRROR TILE_NCLX PRIMARY_NCLX REFERENCE_COUNT] +keys = %w[GRID CANVAS CROP ROTATION MIRROR TRANSFORM_ORDER TILE_NCLX PRIMARY_NCLX REFERENCE_COUNT] cases.each do |name, options| path = File.join(output, "#{name}.heic") - environment = keys.to_h { |key| [key, nil] }.merge(options) + columns, rows = options.fetch('TILES', '1x1').split('x') + environment = keys.to_h { |key| [key, nil] }.merge(options.except('TILES')) _, stderr, status = Open3.capture3(environment, RbConfig.ruby, File.join(__dir__, 'wrap.rb'), source, path, - '256', '256', '1', '1') + '256', '256', columns, rows) abort "wrap.rb failed for #{name}:\n#{stderr}" unless status.success? puts "Generated #{path}" end diff --git a/src/bounded.rs b/src/bounded.rs index feb73aa..3f3958d 100644 --- a/src/bounded.rs +++ b/src/bounded.rs @@ -1,3 +1,4 @@ +mod chroma; mod codec; mod color; mod container; @@ -13,6 +14,8 @@ use std::fmt::{Display, Formatter}; use std::path::Path; use crate::DecodedRgbImage; +use crate::heic_decoder::hevc::DecodedFrame; +use resample::Rectangle; #[derive(Clone, Copy, Debug)] pub enum BoundedInput<'a> { @@ -131,11 +134,6 @@ pub fn decode_bounded( let index = container::Index::parse(&metadata, source.len(), &budget)?; let grid = grid::Grid::preflight(&index, &mut source, &budget)?; let layout = resample::Layout::new(&grid, options.max_side)?; - if layout.left % 2 != 0 || layout.top % 2 != 0 || !grid.transforms_keep_subsampled_chroma()? { - return Err(BoundedDecodeError::Unsupported( - "transform that needs 4:4:4 chroma", - )); - } let first = &grid.tiles[0]; let mut color = first.color.clone(); if grid @@ -150,6 +148,7 @@ pub fn decode_bounded( if grid.properties.color.icc.is_some() { color.icc = grid.properties.color.icc; } + let yuv444 = chroma::Yuv444::new(&grid, &color)?; let transform = color::ColorTransform::new( &color, first.geometry.primaries, @@ -157,20 +156,19 @@ pub fn decode_bounded( &budget, )?; let mut accumulator = resample::Accumulator::new(layout, &budget)?; + let mut edges = if yuv444.is_some() && grid.tiles.len() > 1 { + Some(chroma::Edges::new(&grid, &budget)?) + } else { + None + }; let output_len = layout.display_width as usize * layout.display_height as usize * 3; - let max_job = grid - .tiles - .iter() - .enumerate() - .map(|(i, tile)| { - let region = layout.region( - (i as u32 % grid.columns) * first.geometry.width, - (i as u32 / grid.columns) * first.geometry.height, - tile.geometry.width, - tile.geometry.height, - ); - job_bytes(tile, region, layout) - }) + let plan = Plan { + grid: &grid, + layout, + converts: yuv444.is_some(), + }; + let max_job = (0..grid.tiles.len()) + .map(|i| plan.job_bytes(i)) .max() .unwrap(); { @@ -184,84 +182,55 @@ pub fn decode_bounded( )?; } let mut output = budget.zeroed(output_len, "RGB output")?; - #[cfg(feature = "parallel-grid")] - let (pool, _pool_reservation) = { - let threads = std::thread::available_parallelism() - .map_or(1, usize::from) - .min(8) - .min(grid.tiles.len()); - let mut workers = threads; - while workers > 1 - && max_job - .saturating_mul(workers) - .saturating_add(pool_bytes(workers)) - > budget.available() - { - workers -= 1; - } - if workers > 1 { - let reservation = budget.reserve(pool_bytes(workers), "worker pool")?; - let pool = rayon::ThreadPoolBuilder::new() - .num_threads(workers) - .stack_size(WORKER_STACK_BYTES) - .build() - .map_err(|_| BoundedDecodeError::AllocationFailed)?; - (Some(pool), Some(reservation)) - } else { - (None, None) - } - }; + let workers = Workers::new(grid.tiles.len(), max_job, &budget)?; let mut next = 0; while next < grid.tiles.len() { let mut jobs = Vec::with_capacity(8); - #[cfg(feature = "parallel-grid")] - let workers = pool - .as_ref() - .map_or(1, rayon::ThreadPool::current_num_threads); - #[cfg(not(feature = "parallel-grid"))] - let workers = 1; - while next < grid.tiles.len() && jobs.len() < workers { + while next < grid.tiles.len() && jobs.len() < workers.count() { let tile = &grid.tiles[next]; - let tile_x = (next as u32 % grid.columns) * first.geometry.width; - let tile_y = (next as u32 / grid.columns) * first.geometry.height; - let region = layout.region(tile_x, tile_y, tile.geometry.width, tile.geometry.height); - let bytes = job_bytes(tile, region, layout); + let bytes = plan.job_bytes(next); if bytes > budget.available() && !jobs.is_empty() { break; } let reservation = budget.reserve(bytes, "tile workspace")?; let mut payload = resample::zeroed(tile.payload_len)?; index.read_item(tile.item, &mut source, &mut payload)?; + let (unit, region) = plan.unit(next); + let tile_area = plan.tile(next); jobs.push(Job { index: next, tile, - tile_x, - tile_y, + origin: [tile_area.left, tile_area.top], + unit, region, + decode: plan.decodes(next), payload, reservation, }); next += 1; } - let run = |job| run_job(job, layout, &color, &transform); - #[cfg(feature = "parallel-grid")] - let results: Vec<_> = if let Some(pool) = &pool { - use rayon::prelude::*; - pool.install(|| jobs.into_par_iter().map(run).collect()) + let render = |job| render_job(job, layout, &color, &transform, yuv444.as_ref()); + let results = if let Some(edges) = &mut edges { + let mut decoded = workers + .map(jobs, decode_job) + .into_iter() + .collect::>>()?; + for job in &mut decoded { + job.halo = edges.advance(job.index, job.frame.as_ref(), job.tile.geometry)?; + } + workers.map(decoded, render) } else { - jobs.into_iter().map(run).collect() + workers.map(jobs, |job| decode_job(job).and_then(render)) }; - #[cfg(not(feature = "parallel-grid"))] - let results: Vec<_> = jobs.into_iter().map(run).collect(); for result in results { let result = result?; match &result.data { TileData::Pixels(pixels) => { for y in result.region.top..result.region.bottom { for x in result.region.left..result.region.right { - let src = ((y + layout.top - result.tile_y) as usize - * first.geometry.width as usize - + (x + layout.left - result.tile_x) as usize) + let src = ((y + layout.top - result.unit.top) as usize + * result.unit.width as usize + + (x + layout.left - result.unit.left) as usize) * 3; let dst = layout.pixel_index(x, y); output[dst..dst + 3].copy_from_slice(&pixels[src..src + 3]); @@ -290,23 +259,139 @@ 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 - .saturating_add(tile.payload_len) - .saturating_add(contributions) +struct Plan<'a, 'b> { + grid: &'b grid::Grid<'a>, + layout: resample::Layout, + converts: bool, } -fn render_tile( - tile: &grid::Tile<'_>, - payload: &[u8], - color: &grid::Color<'_>, - transform: &color::ColorTransform, -) -> Result> { +impl Plan<'_, '_> { + fn tile(&self, index: usize) -> Rectangle { + let first = self.grid.tiles[0].geometry; + let tile = self.grid.tiles[index].geometry; + Rectangle { + left: (index as u32 % self.grid.columns) * first.width, + top: (index as u32 / self.grid.columns) * first.height, + width: tile.width, + height: tile.height, + } + } + + fn unit(&self, index: usize) -> (Rectangle, resample::Region) { + let tile = self.tile(index); + let unit = if self.converts { + let column = index as u32 % self.grid.columns; + let row = index as u32 / self.grid.columns; + let rows = self.grid.tiles.len() as u32 / self.grid.columns; + Rectangle::from_edges( + tile.left.saturating_sub(1), + tile.top.saturating_sub(1), + tile.right() - u32::from(column + 1 < self.grid.columns), + tile.bottom() - u32::from(row + 1 < rows), + ) + .intersection(self.layout.source()) + } else { + tile + }; + let region = self + .layout + .region(unit.left, unit.top, unit.width, unit.height); + (unit, region) + } + + fn decodes(&self, index: usize) -> bool { + if self.converts { + !self + .tile(index) + .expanded(2) + .intersection(self.layout.source()) + .is_empty() + } else { + self.unit(index).1.len() != 0 + } + } + + fn job_bytes(&self, index: usize) -> usize { + let tile = &self.grid.tiles[index]; + let (unit, region) = self.unit(index); + let contributions = if self.layout.is_unscaled() { + 0 + } else { + resample::Contribution::workspace_bytes(region) + }; + let conversion = if self.converts { + 3 * (tile.geometry.width as usize + tile.geometry.height as usize + 1) + + chroma::Yuv444::workspace_bytes(unit.width) + + chroma::Halo::bytes(tile.geometry) + } else { + 0 + }; + tile.workspace_bytes + .saturating_add(tile.payload_len) + .saturating_add(contributions) + .saturating_add(conversion) + } +} + +struct Workers { + #[cfg(feature = "parallel-grid")] + pool: Option<(rayon::ThreadPool, memory::Reservation)>, +} + +impl Workers { + #[cfg(feature = "parallel-grid")] + fn new(tiles: usize, max_job: usize, budget: &memory::Budget) -> Result { + let threads = std::thread::available_parallelism() + .map_or(1, usize::from) + .min(8) + .min(tiles); + let mut workers = threads; + while workers > 1 + && max_job + .saturating_mul(workers) + .saturating_add(pool_bytes(workers)) + > budget.available() + { + workers -= 1; + } + if workers <= 1 { + return Ok(Self { pool: None }); + } + let reservation = budget.reserve(pool_bytes(workers), "worker pool")?; + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(workers) + .stack_size(WORKER_STACK_BYTES) + .build() + .map_err(|_| BoundedDecodeError::AllocationFailed)?; + Ok(Self { + pool: Some((pool, reservation)), + }) + } + + #[cfg(not(feature = "parallel-grid"))] + fn new(_tiles: usize, _max_job: usize, _budget: &memory::Budget) -> Result { + Ok(Self {}) + } + + fn count(&self) -> usize { + #[cfg(feature = "parallel-grid")] + if let Some((pool, _)) = &self.pool { + return pool.current_num_threads(); + } + 1 + } + + fn map(&self, items: Vec, f: impl Fn(T) -> U + Sync + Send) -> Vec { + #[cfg(feature = "parallel-grid")] + if let Some((pool, _)) = &self.pool { + use rayon::prelude::*; + return pool.install(|| items.into_par_iter().map(f).collect()); + } + items.into_iter().map(f).collect() + } +} + +fn decode_tile(tile: &grid::Tile<'_>, payload: &[u8]) -> Result { let prepared = codec::prepare(tile.config, payload)?; if prepared.reconstruction_bytes() + payload.len() as u64 * 3 + 1024 * 1024 > tile.workspace_bytes as u64 @@ -320,7 +405,15 @@ fn render_tile( "coded headers changed after preflight", )); } - let frame = prepared.decode()?; + Ok(prepared.decode()?) +} + +fn render_tile( + tile: &grid::Tile<'_>, + frame: DecodedFrame, + color: &grid::Color<'_>, + transform: &color::ColorTransform, +) -> Result> { let mut decoded = crate::DecodedHeicImage { width: frame.width, height: frame.height, @@ -376,6 +469,31 @@ fn render_tile( ) .map_err(|_| BoundedDecodeError::Unsupported("tile YCbCr conversion"))?; drop(decoded); + apply_color(rgb, transform) +} + +fn render_yuv444( + job: &Decoded<'_, '_>, + frame: DecodedFrame, + yuv444: &chroma::Yuv444, + transform: &color::ColorTransform, +) -> Result> { + let mut rgb = resample::zeroed(job.unit.width as usize * job.unit.height as usize * 3)?; + yuv444.convert( + &chroma::TileSamples { + frame: &frame, + geometry: job.tile.geometry, + origin: job.origin, + halo: &job.halo, + }, + job.unit, + &mut rgb, + )?; + drop(frame); + apply_color(rgb, transform) +} + +fn apply_color(rgb: Vec, transform: &color::ColorTransform) -> Result> { if transform.is_identity() { return Ok(rgb); } @@ -392,13 +510,25 @@ fn pool_bytes(workers: usize) -> usize { struct Job<'a, 'b> { index: usize, tile: &'b grid::Tile<'a>, - tile_x: u32, - tile_y: u32, + origin: [u32; 2], + unit: Rectangle, region: resample::Region, + decode: bool, payload: Vec, reservation: memory::Reservation, } +struct Decoded<'a, 'b> { + index: usize, + tile: &'b grid::Tile<'a>, + origin: [u32; 2], + unit: Rectangle, + region: resample::Region, + frame: Option, + halo: chroma::Halo, + reservation: memory::Reservation, +} + enum TileData { Pixels(Vec), Sums(resample::Contribution), @@ -406,41 +536,59 @@ enum TileData { struct TileResult { index: usize, - tile_x: u32, - tile_y: u32, + unit: Rectangle, region: resample::Region, data: TileData, _reservation: memory::Reservation, } -fn run_job( - job: Job<'_, '_>, +fn decode_job<'a, 'b>(job: Job<'a, 'b>) -> Result> { + let frame = if job.decode { + Some(decode_tile(job.tile, &job.payload)?) + } else { + None + }; + Ok(Decoded { + index: job.index, + tile: job.tile, + origin: job.origin, + unit: job.unit, + region: job.region, + frame, + halo: chroma::Halo::default(), + reservation: job.reservation, + }) +} + +fn render_job( + mut job: Decoded<'_, '_>, layout: resample::Layout, color: &grid::Color<'_>, transform: &color::ColorTransform, + yuv444: Option<&chroma::Yuv444>, ) -> Result { - let data = if job.region.len() == 0 { - TileData::Sums(resample::Contribution::default()) - } else { - let pixels = render_tile(job.tile, &job.payload, color, transform)?; - if layout.is_unscaled() { - TileData::Pixels(pixels) - } else { - TileData::Sums(resample::contributions( - layout, - job.region, - &pixels, - job.tile_x, - job.tile_y, - job.tile.geometry.width, - )?) + let (index, unit, region) = (job.index, job.unit, job.region); + let data = match job.frame.take() { + Some(frame) if region.len() != 0 => { + let tile = job.tile; + let pixels = match yuv444 { + Some(yuv444) => render_yuv444(&job, frame, yuv444, transform)?, + None => render_tile(tile, frame, color, transform)?, + }; + if layout.is_unscaled() { + TileData::Pixels(pixels) + } else { + TileData::Sums(resample::contributions( + layout, region, &pixels, unit.left, unit.top, unit.width, + )?) + } } + _ => TileData::Sums(resample::Contribution::default()), }; Ok(TileResult { - index: job.index, - tile_x: job.tile_x, - tile_y: job.tile_y, - region: job.region, + index, + unit, + region, data, _reservation: job.reservation, }) diff --git a/src/bounded/chroma.rs b/src/bounded/chroma.rs new file mode 100644 index 0000000..1cc44ca --- /dev/null +++ b/src/bounded/chroma.rs @@ -0,0 +1,383 @@ +use crate::chroma_upsampling::{HeicRegion, upsample_heic_region_to_yuv444}; +use crate::heic_decoder::hevc::DecodedFrame; +use crate::heic_decoder::hevc::bounded::Geometry; +use crate::isobmff::{PrimaryItemColorProperties, PrimaryItemTransformProperty as Transform}; +use crate::{ + DecodeHeicError, DecodedHeicImage, HeicColrOverride, HeicPixelLayout, HeicPlane, + YCbCrMatrixCoefficients, YCbCrRange, +}; + +use super::grid::{Color, Grid}; +use super::memory::{Budget, Buffer}; +use super::resample::{Rectangle, transformed_source, zeroed}; +use super::{BoundedDecodeError as Error, Result}; + +const BAND_PIXELS: usize = 1 << 14; + +pub(super) trait Samples { + fn luma(&self, x: u32, y: u32, out: &mut [u16]); + fn chroma(&self, plane: usize, x: u32, y: u32, out: &mut [u16]); +} + +pub(super) struct Yuv444 { + window: Rectangle, + range: YCbCrRange, + matrix: YCbCrMatrixCoefficients, + colr: HeicColrOverride, +} + +impl Yuv444 { + pub(super) fn new(grid: &Grid<'_>, color: &Color<'_>) -> Result> { + let transforms: Vec = grid + .properties + .transforms + .iter() + .flatten() + .copied() + .collect(); + for (index, transform) in transforms.iter().enumerate() { + let (plan, window) = transformed_source(grid.width, grid.height, &transforms[..index])?; + if crate::yuv_transforms::libheif_converts_to_yuv444_before( + HeicPixelLayout::Yuv420, + plan.destination_width, + plan.destination_height, + transform, + ) { + let geometry = grid.tiles[0].geometry; + return Ok(Some(Self { + window, + range: if geometry.full_range { + YCbCrRange::Full + } else { + YCbCrRange::Limited + }, + matrix: YCbCrMatrixCoefficients { + matrix_coefficients: u16::from(geometry.matrix), + colour_primaries: u16::from(geometry.primaries), + }, + colr: HeicColrOverride::from_colr(&PrimaryItemColorProperties { + nclx: color.nclx.clone(), + icc: None, + }), + })); + } + } + Ok(None) + } + + pub(super) fn workspace_bytes(width: u32) -> usize { + let width = width as usize; + (width + 5) * (band_rows(width) + 5) * 10 + } + + pub(super) fn convert( + &self, + samples: &impl Samples, + area: Rectangle, + out: &mut [u8], + ) -> Result<()> { + if area.is_empty() { + return Ok(()); + } + let window = self.window; + if !window.contains(area) { + return Err(Error::Malformed("4:4:4 area outside the converted image")); + } + let width = area.width as usize; + let first_column = (area.left.saturating_sub(1) / 2).max(window.left / 2); + let last_column = (area.right() / 2).min((window.right() - 1) / 2); + let chroma_width = (last_column - first_column + 1) as usize; + let luma_left = area.left - 2 * first_column; + let rows = band_rows(width) as u32; + let mut top = area.top; + while top < area.bottom() { + let bottom = area.bottom().min(top.saturating_add(rows)); + let first_row = (top.saturating_sub(1) / 2).max(window.top / 2); + let last_row = (bottom / 2).min((window.bottom() - 1) / 2); + let chroma_height = (last_row - first_row + 1) as usize; + let mut luma = zeroed::(4 * chroma_width * chroma_height)?; + for y in top..bottom { + let start = (y - 2 * first_row) as usize * 2 * chroma_width + luma_left as usize; + samples.luma(area.left, y, &mut luma[start..start + width]); + } + let mut planes = [ + zeroed::(chroma_width * chroma_height)?, + zeroed::(chroma_width * chroma_height)?, + ]; + for (plane, data) in planes.iter_mut().enumerate() { + for (row, y) in data.chunks_exact_mut(chroma_width).zip(first_row..) { + samples.chroma(plane, first_column, y, row); + } + } + let [u, v] = planes; + let chroma_plane = |samples| HeicPlane { + width: chroma_width as u32, + height: chroma_height as u32, + samples, + }; + let source = DecodedHeicImage { + width: 2 * chroma_width as u32, + height: 2 * chroma_height as u32, + bit_depth_luma: 8, + bit_depth_chroma: 8, + layout: HeicPixelLayout::Yuv420, + ycbcr_range: self.range, + ycbcr_matrix: self.matrix, + y_plane: HeicPlane { + width: 2 * chroma_width as u32, + height: 2 * chroma_height as u32, + samples: luma, + }, + u_plane: Some(chroma_plane(u)), + v_plane: Some(chroma_plane(v)), + }; + let mut band = upsample_heic_region_to_yuv444( + &source, + HeicRegion { + left: luma_left, + top: top - 2 * first_row, + width: area.width, + height: bottom - top, + }, + ) + .map_err(conversion_error)?; + drop(source); + self.colr.apply(&mut band); + let start = (top - area.top) as usize * width * 3; + let end = (bottom - area.top) as usize * width * 3; + crate::convert_heic_to_interleaved_rgb8_region_slice::<3>( + &band, + 0, + 0, + width, + (bottom - top) as usize, + &mut out[start..end], + crate::scale_heic_sample_to_image_rgb8, + "bounded RGB", + ) + .map_err(conversion_error)?; + top = bottom; + } + Ok(()) + } +} + +fn band_rows(width: usize) -> usize { + (BAND_PIXELS / width.max(1)).max(1) +} + +fn conversion_error(error: DecodeHeicError) -> Error { + match error { + DecodeHeicError::AllocationFailed { .. } => Error::AllocationFailed, + _ => Error::Unsupported("4:4:4 chroma conversion"), + } +} + +#[derive(Default)] +pub(super) struct Halo { + left: u32, + top_luma: Vec, + top_chroma: [Vec; 2], + left_luma: Vec, + left_chroma: [Vec; 2], +} + +impl Halo { + pub(super) fn bytes(geometry: Geometry) -> usize { + 8 * (geometry.width as usize + geometry.height as usize + 8) + } +} + +pub(super) struct TileSamples<'a> { + pub(super) frame: &'a DecodedFrame, + pub(super) geometry: Geometry, + pub(super) origin: [u32; 2], + pub(super) halo: &'a Halo, +} + +impl TileSamples<'_> { + fn plane(&self, plane: usize) -> &[u16] { + if plane == 0 { + &self.frame.cb_plane + } else { + &self.frame.cr_plane + } + } +} + +impl Samples for TileSamples<'_> { + fn luma(&self, x: u32, y: u32, out: &mut [u16]) { + let [origin_x, origin_y] = self.origin; + if y + 1 == origin_y { + let start = (x - self.halo.left) as usize; + out.copy_from_slice(&self.halo.top_luma[start..start + out.len()]); + return; + } + let (out, x) = if x + 1 == origin_x { + out[0] = self.halo.left_luma[(y - origin_y) as usize]; + (&mut out[1..], x + 1) + } else { + (out, x) + }; + let start = (self.geometry.crop[2] + y - origin_y) as usize * self.frame.y_stride() + + (self.geometry.crop[0] + x - origin_x) as usize; + out.copy_from_slice(&self.frame.y_plane[start..start + out.len()]); + } + + fn chroma(&self, plane: usize, x: u32, y: u32, out: &mut [u16]) { + let [origin_x, origin_y] = self.origin.map(|n| n / 2); + if y + 1 == origin_y { + let start = (x - self.halo.left / 2) as usize; + out.copy_from_slice(&self.halo.top_chroma[plane][start..start + out.len()]); + return; + } + let (out, x) = if x + 1 == origin_x { + out[0] = self.halo.left_chroma[plane][(y - origin_y) as usize]; + (&mut out[1..], x + 1) + } else { + (out, x) + }; + let start = (self.geometry.crop[2] / 2 + y - origin_y) as usize * self.frame.c_stride() + + (self.geometry.crop[0] / 2 + x - origin_x) as usize; + out.copy_from_slice(&self.plane(plane)[start..start + out.len()]); + } +} + +pub(super) struct Edges { + width: u32, + columns: u32, + rows: u32, + tile_width: u32, + tile_height: u32, + luma: Buffer, + chroma: [Buffer; 2], + left_luma: Buffer, + left_chroma: [Buffer; 2], + left_decoded: bool, +} + +impl Edges { + pub(super) fn new(grid: &Grid<'_>, budget: &Budget) -> Result { + let tile = grid.tiles[0].geometry; + let chroma_width = grid.width.div_ceil(2) as usize; + let stage = "4:4:4 tile edges"; + Ok(Self { + width: grid.width, + columns: grid.columns, + rows: grid.tiles.len() as u32 / grid.columns, + tile_width: tile.width, + tile_height: tile.height, + luma: budget.zeroed(grid.width as usize, stage)?, + chroma: [ + budget.zeroed(chroma_width, stage)?, + budget.zeroed(chroma_width, stage)?, + ], + left_luma: budget.zeroed(tile.height as usize, stage)?, + left_chroma: [ + budget.zeroed(tile.height as usize / 2, stage)?, + budget.zeroed(tile.height as usize / 2, stage)?, + ], + left_decoded: false, + }) + } + + pub(super) fn advance( + &mut self, + index: usize, + frame: Option<&DecodedFrame>, + geometry: Geometry, + ) -> Result { + let column = index as u32 % self.columns; + let row = index as u32 / self.columns; + let (tile_width, tile_height) = (self.tile_width, self.tile_height); + let x = column * tile_width; + let last_column = column + 1 == self.columns; + let chroma_width = self.width.div_ceil(2); + let mut halo = Halo::default(); + if frame.is_some() { + if row > 0 { + let start = x.saturating_sub(1); + halo.left = start; + halo.top_luma = + copy(&self.luma[start as usize..(x + tile_width).min(self.width) as usize])?; + let chroma_end = ((x + tile_width) / 2 + 1).min(chroma_width) as usize; + for (halo, edge) in halo.top_chroma.iter_mut().zip(&self.chroma) { + *halo = copy(&edge[start as usize / 2..chroma_end])?; + } + } + if column > 0 { + halo.left_luma = copy(&self.left_luma)?; + for (halo, edge) in halo.left_chroma.iter_mut().zip(&self.left_chroma) { + *halo = copy(edge)?; + } + } + } + if row + 1 < self.rows { + if column > 0 && self.left_decoded { + self.luma[x as usize - 1] = self.left_luma[tile_height as usize - 1]; + for (edge, left) in self.chroma.iter_mut().zip(&self.left_chroma) { + edge[x as usize / 2 - 1] = left[tile_height as usize / 2 - 1]; + } + } + if let Some(frame) = frame { + let end = if last_column { + (x + tile_width).min(self.width) + } else { + x + tile_width - 1 + }; + let start = (geometry.crop[2] + tile_height - 1) as usize * frame.y_stride() + + geometry.crop[0] as usize; + self.luma[x as usize..end as usize] + .copy_from_slice(&frame.y_plane[start..start + (end - x) as usize]); + let chroma_end = if last_column { + ((x + tile_width) / 2).min(chroma_width) + } else { + (x + tile_width) / 2 - 1 + }; + let start = (geometry.crop[2] / 2 + tile_height / 2 - 1) as usize + * frame.c_stride() + + geometry.crop[0] as usize / 2; + let count = (chroma_end - x / 2) as usize; + for (edge, plane) in self + .chroma + .iter_mut() + .zip([&frame.cb_plane, &frame.cr_plane]) + { + edge[x as usize / 2..chroma_end as usize] + .copy_from_slice(&plane[start..start + count]); + } + } + } + if !last_column { + self.left_decoded = frame.is_some(); + if let Some(frame) = frame { + let column = (geometry.crop[0] + tile_width - 1) as usize; + for (y, sample) in self.left_luma.iter_mut().enumerate() { + *sample = + frame.y_plane[(geometry.crop[2] as usize + y) * frame.y_stride() + column]; + } + let column = (geometry.crop[0] / 2 + tile_width / 2 - 1) as usize; + for (edge, plane) in self + .left_chroma + .iter_mut() + .zip([&frame.cb_plane, &frame.cr_plane]) + { + for (y, sample) in edge.iter_mut().enumerate() { + *sample = + plane[(geometry.crop[2] as usize / 2 + y) * frame.c_stride() + column]; + } + } + } + } + Ok(halo) + } +} + +fn copy(samples: &[u16]) -> Result> { + let mut copied = Vec::new(); + copied + .try_reserve_exact(samples.len()) + .map_err(|_| Error::AllocationFailed)?; + copied.extend_from_slice(samples); + Ok(copied) +} diff --git a/src/bounded/grid.rs b/src/bounded/grid.rs index 0c21230..ddeb868 100644 --- a/src/bounded/grid.rs +++ b/src/bounded/grid.rs @@ -225,41 +225,6 @@ impl<'a> Tile<'a> { } impl<'a> Grid<'a> { - pub(super) fn transforms_keep_subsampled_chroma(&self) -> Result { - let (mut width, mut height) = (self.width, self.height); - for transform in self.properties.transforms.iter().flatten() { - let (odd_width, odd_height) = (width % 2 != 0, height % 2 != 0); - match transform { - Transform::CleanAperture(aperture) => { - let crop = crate::clean_aperture_crop_bounds(width, height, *aperture) - .map_err(|_| Error::Malformed("display crop"))?; - if crop.left % 2 != 0 || crop.top % 2 != 0 { - return Ok(false); - } - (width, height) = (crop.width, crop.height); - } - Transform::Rotation(rotation) => { - let degrees = rotation.rotation_ccw_degrees % 360; - if (degrees == 90 && odd_width) - || (degrees == 180 && (odd_width || odd_height)) - || (degrees == 270 && odd_height) - { - return Ok(false); - } - if degrees % 180 == 90 { - (width, height) = (height, width); - } - } - Transform::Mirror(_) => { - if odd_width || odd_height { - return Ok(false); - } - } - } - } - Ok(true) - } - pub(super) fn preflight( index: &Index<'a>, source: &mut Source<'_>, diff --git a/src/bounded/incremental.rs b/src/bounded/incremental.rs index 5bdf7b4..460e9d0 100644 --- a/src/bounded/incremental.rs +++ b/src/bounded/incremental.rs @@ -3,10 +3,11 @@ use std::io::{BufReader, Read}; use crate::heic_decoder::hevc::DecodedFrame; use crate::heic_decoder::hevc::bounded::{Geometry, Prepared}; +use super::chroma::{Samples, Yuv444}; use super::container::{Index, Reader, Source}; use super::grid::{Grid, Properties, Tile}; use super::memory::Budget; -use super::resample::{Accumulator, Layout, Region, zeroed}; +use super::resample::{Accumulator, Layout, Rectangle, Region, zeroed}; use super::{ BoundedDecodeError as Error, BoundedDecodeOptions, BoundedInput, BoundedRgbImage, Result, codec, color, @@ -264,30 +265,6 @@ pub fn decode( 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() { - if i > 0 - && matches!( - transform, - crate::isobmff::PrimaryItemTransformProperty::CleanAperture(_) - ) - { - return Err(Error::Unsupported( - "repeated crop or crop after orientation", - )); - } - } - let bilinear = layout.left % 2 != 0 || layout.top % 2 != 0; - if bilinear && grid.tiles.len() != 1 { - return Err(Error::Unsupported("odd grid crop chroma interpolation")); - } - let _chroma_workspace = if bilinear { - Some(budget.reserve( - grid.tiles[0].geometry.coded_width as usize * 4 * 65, - "chroma interpolation band", - )?) - } else { - None - }; let mut color = grid.tiles[0].color.clone(); if grid .properties @@ -301,6 +278,19 @@ pub fn decode( if grid.properties.color.icc.is_some() { color.icc = grid.properties.color.icc; } + let yuv444 = Yuv444::new(&grid, &color)?; + if yuv444.is_some() && grid.tiles.len() != 1 { + return Err(Error::Unsupported("grid 4:4:4 chroma conversion")); + } + let _chroma_workspace = if yuv444.is_some() { + Some(budget.reserve( + grid.tiles[0].geometry.coded_width as usize * 4 * 65 + + Yuv444::workspace_bytes(layout.width), + "chroma interpolation band", + )?) + } else { + None + }; let transform = color::ColorTransform::new( &color, grid.tiles[0].geometry.primaries, @@ -335,7 +325,7 @@ pub fn decode( zeroes: 0, }; let mut conversion = Conversion::default(); - let mut bands = ChromaBands::new(if bilinear { + let mut bands = ChromaBands::new(if yuv444.is_some() { Some(prepared.output_band()?) } else { None @@ -353,28 +343,50 @@ pub fn decode( if first >= last { return Ok(()); } - let pixels = conversion.convert( - frame, - g, - ConversionRegion { - start, - y: first - start, - height: last - first, - halo, - }, - &color, - &transform, - )?; - for row in 0..last - first { - let y = ty + first - g.crop[2] + row; + let band = Rectangle { + left: tx, + top: ty + first - g.crop[2], + width: g.width, + height: last - first, + }; + let (area, pixels) = match (&yuv444, halo) { + (Some(yuv444), Some(halo)) => { + let area = band.intersection(layout.source()); + if area.is_empty() { + return Ok(()); + } + let samples = BandSamples { + frame, + start, + crop: [g.crop[0], g.crop[2]], + halo, + }; + let pixels = + conversion.convert_yuv444(yuv444, &samples, area, &transform)?; + (area, pixels) + } + _ => { + let pixels = conversion.convert( + frame, + g, + ConversionRegion { + y: first - start, + height: last - first, + }, + &color, + &transform, + )?; + (band, pixels) + } + }; + for (y, row) in (area.top..).zip(pixels.chunks_exact(area.width as usize * 3)) { if y < layout.top + region.top || y >= layout.top + region.bottom { continue; } - let offset = row as usize * g.width as usize * 3; rows.add( y - layout.top, - tx, - &pixels[offset..offset + g.width as usize * 3], + area.left, + row, &mut accumulator, &mut output, ); @@ -588,11 +600,44 @@ struct ChromaHalo<'a> { after: [&'a [u16]; 2], } -struct ConversionRegion<'a> { - start: u32, +struct ConversionRegion { y: u32, height: u32, - halo: Option>, +} + +struct BandSamples<'a> { + frame: &'a DecodedFrame, + start: u32, + crop: [u32; 2], + halo: ChromaHalo<'a>, +} + +impl Samples for BandSamples<'_> { + fn luma(&self, x: u32, y: u32, out: &mut [u16]) { + let start = (y + self.crop[1] - self.start) as usize * self.frame.y_stride() + + (x + self.crop[0]) as usize; + out.copy_from_slice(&self.frame.y_plane[start..start + out.len()]); + } + + fn chroma(&self, plane: usize, x: u32, y: u32, out: &mut [u16]) { + let y = y + self.crop[1] / 2; + let first = self.start / 2; + let stride = self.frame.c_stride(); + let row = if y < first { + self.halo.before[plane] + } else if y >= (self.start + self.frame.height) / 2 { + self.halo.after[plane] + } else { + let samples = if plane == 0 { + &self.frame.cb_plane + } else { + &self.frame.cr_plane + }; + &samples[(y - first) as usize * stride..][..stride] + }; + let x = (x + self.crop[0] / 2) as usize; + out.copy_from_slice(&row[x..x + out.len()]); + } } struct ChromaBands { @@ -666,20 +711,31 @@ impl ChromaBands { } impl Conversion { + fn convert_yuv444( + &mut self, + yuv444: &Yuv444, + samples: &BandSamples<'_>, + area: Rectangle, + transform: &color::ColorTransform, + ) -> Result<&[u8]> { + let len = area.width as usize * area.height as usize * 3; + self.rgb + .try_reserve_exact(len.saturating_sub(self.rgb.len())) + .map_err(|_| Error::AllocationFailed)?; + self.rgb.resize(len, 0); + yuv444.convert(samples, area, &mut self.rgb)?; + self.finish(transform) + } + fn convert( &mut self, frame: &DecodedFrame, geometry: Geometry, - region: ConversionRegion<'_>, + region: ConversionRegion, color: &super::grid::Color<'_>, transform: &color::ColorTransform, ) -> Result<&[u8]> { - let ConversionRegion { - start, - y, - height, - halo, - } = region; + let ConversionRegion { y, height } = region; let colr = crate::isobmff::PrimaryItemColorProperties { nclx: color.nclx.clone(), icc: None, @@ -708,51 +764,7 @@ impl Conversion { .try_reserve_exact(len.saturating_sub(self.rgb.len())) .map_err(|_| Error::AllocationFailed)?; self.rgb.resize(len, 0); - if let Some(halo) = halo { - for row in 0..height { - for column in 0..width { - let cy = (y + row) / 2; - let sy = start as usize + y + row; - let neighbor_y = crate::chroma_upsampling::bilinear_chroma_neighbour( - sy, - geometry.crop[2] as usize / 2, - ((geometry.crop[2] + geometry.height) as usize).div_ceil(2) - 1, - ); - let cx = (x + column) / 2; - let neighbor_x = crate::chroma_upsampling::bilinear_chroma_neighbour( - x + column, - x / 2, - (x + width).div_ceil(2) - 1, - ); - let chroma = |plane: &[u16], component: usize| { - let stride = frame.c_stride(); - let current = &plane[cy * stride..(cy + 1) * stride]; - let neighbor = if neighbor_y < start as usize / 2 { - halo.before[component] - } else if neighbor_y >= (start as usize + frame.height as usize) / 2 { - halo.after[component] - } else { - let local = neighbor_y - start as usize / 2; - &plane[local * stride..(local + 1) * stride] - }; - i32::from(crate::chroma_upsampling::bilinear_chroma_sample( - current[cx], - current[neighbor_x], - neighbor[cx], - neighbor[neighbor_x], - )) - }; - let (r, g, b) = converter.convert( - i32::from(frame.y_plane[(y + row) * frame.y_stride() + x + column]), - chroma(&frame.cb_plane, 0), - chroma(&frame.cr_plane, 1), - ); - self.rgb[(row * width + column) * 3..(row * width + column) * 3 + 3] - .copy_from_slice(&[r as u8, g as u8, b as u8]); - } - } - } else if let crate::PreparedYcbcrTransform::MatrixFull { coeffs, .. } = converter.transform - { + if let crate::PreparedYcbcrTransform::MatrixFull { coeffs, .. } = converter.transform { crate::heic_decoder::hevc::color_convert::convert_420_8bit_region_to_interleaved( &frame.y_plane, &frame.cb_plane, @@ -791,9 +803,14 @@ impl Conversion { } } } + self.finish(transform) + } + + fn finish(&mut self, transform: &color::ColorTransform) -> Result<&[u8]> { if transform.is_identity() { return Ok(&self.rgb); } + let len = self.rgb.len(); self.converted .try_reserve_exact(len.saturating_sub(self.converted.len())) .map_err(|_| Error::AllocationFailed)?; diff --git a/src/bounded/resample.rs b/src/bounded/resample.rs index f0ec35a..cc29881 100644 --- a/src/bounded/resample.rs +++ b/src/bounded/resample.rs @@ -5,6 +5,94 @@ use super::grid::Grid; use super::memory::{Budget, Buffer}; use super::{BoundedDecodeError as Error, Result}; +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct Rectangle { + pub(super) left: u32, + pub(super) top: u32, + pub(super) width: u32, + pub(super) height: u32, +} + +impl Rectangle { + pub(super) fn from_edges(left: u32, top: u32, right: u32, bottom: u32) -> Self { + Self { + left, + top, + width: right.saturating_sub(left), + height: bottom.saturating_sub(top), + } + } + + pub(super) fn right(&self) -> u32 { + self.left + self.width + } + + pub(super) fn bottom(&self) -> u32 { + self.top + self.height + } + + pub(super) fn is_empty(&self) -> bool { + self.width == 0 || self.height == 0 + } + + pub(super) fn contains(&self, other: Rectangle) -> bool { + other.left >= self.left + && other.top >= self.top + && other.right() <= self.right() + && other.bottom() <= self.bottom() + } + + pub(super) fn intersection(&self, other: Rectangle) -> Self { + let left = self.left.max(other.left); + let top = self.top.max(other.top); + Self::from_edges( + left, + top, + self.right().min(other.right()).max(left), + self.bottom().min(other.bottom()).max(top), + ) + } + + pub(super) fn expanded(&self, margin: u32) -> Self { + Self::from_edges( + self.left.saturating_sub(margin), + self.top.saturating_sub(margin), + self.right() + margin, + self.bottom() + margin, + ) + } +} + +pub(super) fn transformed_source( + width: u32, + height: u32, + transforms: &[Transform], +) -> Result<(RgbaTransformPlan, Rectangle)> { + let plan = RgbaTransformPlan::from_primary_transforms(width, height, transforms) + .map_err(|_| Error::Malformed("display transform"))?; + let mut left = usize::MAX; + let mut top = usize::MAX; + let mut right = 0; + let mut bottom = 0; + for (x, y) in [ + (0, 0), + (plan.destination_width - 1, 0), + (0, plan.destination_height - 1), + (plan.destination_width - 1, plan.destination_height - 1), + ] { + let (x, y) = plan + .map_destination_pixel(x as usize, y as usize) + .map_err(|_| Error::Malformed("display crop"))?; + left = left.min(x); + top = top.min(y); + right = right.max(x); + bottom = bottom.max(y); + } + let source = + Rectangle::from_edges(left as u32, top as u32, right as u32 + 1, bottom as u32 + 1); + Ok((plan, source)) +} + #[derive(Clone, Copy)] pub(super) struct Layout { pub(super) left: u32, @@ -30,28 +118,13 @@ impl Layout { { transforms.extend(exif); } - let plan = RgbaTransformPlan::from_primary_transforms(grid.width, grid.height, &transforms) - .map_err(|_| Error::Malformed("display transform"))?; - let mut left = usize::MAX; - let mut top = usize::MAX; - let mut right = 0; - let mut bottom = 0; - for (x, y) in [ - (0, 0), - (plan.destination_width - 1, 0), - (0, plan.destination_height - 1), - (plan.destination_width - 1, plan.destination_height - 1), - ] { - let (x, y) = plan - .map_destination_pixel(x as usize, y as usize) - .map_err(|_| Error::Malformed("display crop"))?; - left = left.min(x); - top = top.min(y); - right = right.max(x); - bottom = bottom.max(y); - } - let width = (right - left + 1) as u32; - let height = (bottom - top + 1) as u32; + let (plan, source) = transformed_source(grid.width, grid.height, &transforms)?; + let Rectangle { + left, + top, + width, + height, + } = source; let longest = width.max(height); let output_width = if longest <= max_side { width @@ -86,8 +159,8 @@ impl Layout { (output_width, output_height) }; Ok(Self { - left: left as u32, - top: top as u32, + left, + top, width, height, output_width, @@ -99,6 +172,15 @@ impl Layout { }) } + pub(super) fn source(&self) -> Rectangle { + Rectangle { + left: self.left, + top: self.top, + width: self.width, + height: self.height, + } + } + pub(super) fn is_unscaled(&self) -> bool { self.width == self.output_width && self.height == self.output_height } diff --git a/src/bounded/tests.rs b/src/bounded/tests.rs index d636ec7..48db56b 100644 --- a/src/bounded/tests.rs +++ b/src/bounded/tests.rs @@ -921,28 +921,43 @@ fn one_channel_pixi_is_accepted_without_relaxing_bit_depth_checks() { #[cfg(all(feature = "incremental-experiment", not(feature = "decoder-tracing")))] #[test] -fn incremental_rejects_unimplemented_chroma_transform_orders() { +fn incremental_converts_single_images_to_full_chroma_like_bounded() { let nals = nal_sets(); let config = configuration(&nals[1]); - let crop = [13u32, 1, 11, 1, 0, 1, 0, 1] - .into_iter() - .flat_map(u32::to_be_bytes) - .collect::>(); - let bytes = fixture( - std::slice::from_ref(&config), - &nals[3], - &[box_bytes(b"irot", &[1]), box_bytes(b"clap", &crop)], - ); - assert!(matches!( - incremental::decode(BoundedInput::Bytes(&bytes), Default::default()), - Err(BoundedDecodeError::Unsupported( - "repeated crop or crop after orientation" - )) - )); + let payload = asymmetric_payload(); + let crop = clean_aperture(13, 11, [0, 1], [0, 1]); + let quarter_turn = box_bytes(b"irot", &[1]); + for properties in [ + vec![quarter_turn.clone(), crop.clone()], + vec![crop.clone(), quarter_turn.clone()], + vec![ + clean_aperture(12, 12, [-1, 2], [1, 2]), + box_bytes(b"imir", &[1]), + ], + vec![box_bytes(b"imir", &[0])], + vec![ + clean_aperture(14, 14, [-1, 2], [-1, 2]), + box_bytes(b"irot", &[2]), + ], + ] { + let bytes = fixture(std::slice::from_ref(&config), &payload, &properties); + assert_matches_normal_decode(&bytes); + for max_side in [5, 6000] { + let options = BoundedDecodeOptions { + max_side, + ..Default::default() + }; + let bounded = decode_bounded(BoundedInput::Bytes(&bytes), options).unwrap(); + let (incremental, _) = + incremental::decode(BoundedInput::Bytes(&bytes), options).unwrap(); + assert_eq!(incremental.original_dimensions, bounded.original_dimensions); + assert_eq!(incremental.image.pixels, bounded.image.pixels); + } + } let bytes = fixture( std::slice::from_ref(&config), &nals[3], - &[box_bytes(b"clap", &crop), box_bytes(b"clap", &crop)], + &[crop.clone(), crop.clone()], ); assert!(matches!( incremental::decode(BoundedInput::Bytes(&bytes), Default::default()), @@ -950,15 +965,11 @@ fn incremental_rejects_unimplemented_chroma_transform_orders() { "duplicate transform property" )) )); - let bytes = fixture( - &[config.clone(), config], - &nals[3], - &[box_bytes(b"clap", &crop)], - ); + let bytes = fixture(&[config.clone(), config], &nals[3], &[crop]); assert!(matches!( incremental::decode(BoundedInput::Bytes(&bytes), Default::default()), Err(BoundedDecodeError::Unsupported( - "odd grid crop chroma interpolation" + "grid 4:4:4 chroma conversion" )) )); } @@ -1146,12 +1157,7 @@ fn mirrored_asymmetric_pixels_match_normal_decode() { box_bytes(b"imir", &[mirror]), ]; let odd = fixture(&configs, &asymmetric_payload(), &transforms); - assert!(matches!( - decode_bounded(BoundedInput::Bytes(&odd), Default::default()), - Err(BoundedDecodeError::Unsupported( - "transform that needs 4:4:4 chroma" - )) - )); + assert_matches_normal_decode(&odd); let bytes = fixture_with_canvas( &configs, &asymmetric_payload(), @@ -1296,16 +1302,15 @@ fn render_rejects_workspace_and_geometry_changes_after_preflight() { &budget, ) .unwrap(); + let frame = decode_tile(tile, &payload).unwrap(); assert_eq!( - render_tile(tile, &payload, &color, &transform) - .unwrap() - .len(), + render_tile(tile, frame, &color, &transform).unwrap().len(), 16 * 16 * 3 ); let geometry = tile.geometry; tile.geometry.width += 1; assert!(matches!( - render_tile(tile, &payload, &color, &transform), + decode_tile(tile, &payload), Err(BoundedDecodeError::Malformed( "coded headers changed after preflight" )) @@ -1313,7 +1318,7 @@ fn render_rejects_workspace_and_geometry_changes_after_preflight() { tile.geometry = geometry; tile.workspace_bytes = 0; assert!(matches!( - render_tile(tile, &payload, &color, &transform), + decode_tile(tile, &payload), Err(BoundedDecodeError::Malformed( "codec workspace changed after preflight" )) @@ -1658,27 +1663,117 @@ fn single_image_payloads_are_bounded_by_the_budget_instead_of_the_tile_cap() { )); } +#[cfg(not(feature = "decoder-tracing"))] +fn area_average(image: &crate::DecodedRgbImage, width: u32, height: u32) -> Vec { + let mut output = Vec::with_capacity(width as usize * height as usize * 3); + for oy in 0..height { + let y0 = f64::from(oy) * f64::from(image.height) / f64::from(height); + let y1 = f64::from(oy + 1) * f64::from(image.height) / f64::from(height); + for ox in 0..width { + let x0 = f64::from(ox) * f64::from(image.width) / f64::from(width); + let x1 = f64::from(ox + 1) * f64::from(image.width) / f64::from(width); + let mut sums = [0.0; 3]; + for sy in y0.floor() as u32..y1.ceil() as u32 { + for sx in x0.floor() as u32..x1.ceil() as u32 { + let weight = (x1.min(f64::from(sx + 1)) - x0.max(f64::from(sx))) + * (y1.min(f64::from(sy + 1)) - y0.max(f64::from(sy))); + let index = ((sy * image.width + sx) * 3) as usize; + for (sum, &value) in sums.iter_mut().zip(&image.pixels[index..index + 3]) { + *sum += f64::from(value) * weight; + } + } + } + output.extend(sums.map(|sum| (sum / ((x1 - x0) * (y1 - y0))).round() as u8)); + } + } + output +} + +#[cfg(not(feature = "decoder-tracing"))] +fn assert_matches_normal_decode(bytes: &[u8]) { + let normal = crate::decode_bytes_to_rgb8(bytes).unwrap(); + let bounded = decode_bounded(BoundedInput::Bytes(bytes), Default::default()).unwrap(); + assert_eq!( + (bounded.image.width, bounded.image.height), + (normal.width, normal.height) + ); + assert_eq!(bounded.image.pixels, normal.pixels); + for max_side in [5, 11] { + let scaled = decode_bounded( + BoundedInput::Bytes(bytes), + BoundedDecodeOptions { + max_side, + ..Default::default() + }, + ) + .unwrap(); + let expected = area_average(&normal, scaled.image.width, scaled.image.height); + assert!( + scaled + .image + .pixels + .iter() + .zip(&expected) + .all(|(&actual, &expected)| actual.abs_diff(expected) <= 1), + "max side {max_side}" + ); + } +} + +#[cfg(not(feature = "decoder-tracing"))] +fn tiled_fixture( + config: &[u8], + payload: &[u8], + (columns, rows): (u8, u8), + transforms: &[Vec], + canvas: (u32, u32), +) -> Vec { + let configs = vec![config.to_vec(); usize::from(columns) * usize::from(rows)]; + let mut bytes = fixture_with_canvas( + &configs, + payload, + transforms, + &(0..transforms.len()).collect::>(), + &[], + None, + b"Exif\0", + canvas, + ); + let idat = bytes.windows(4).position(|kind| kind == b"idat").unwrap() + 4; + bytes[idat + 2] = rows - 1; + bytes[idat + 3] = columns - 1; + bytes +} + +#[cfg(not(feature = "decoder-tracing"))] +fn clean_aperture( + width: i32, + height: i32, + horizontal_offset: [i32; 2], + vertical_offset: [i32; 2], +) -> Vec { + let crop: Vec<_> = [ + width, + 1, + height, + 1, + horizontal_offset[0], + horizontal_offset[1], + vertical_offset[0], + vertical_offset[1], + ] + .into_iter() + .flat_map(i32::to_be_bytes) + .collect(); + box_bytes(b"clap", &crop) +} + #[cfg(not(feature = "decoder-tracing"))] #[test] -fn transforms_that_need_full_chroma_are_refused() { +fn transforms_that_need_full_chroma_match_normal_decode() { let config = configuration(&nal_sets()[1]); let payload = asymmetric_payload(); - let clap = |width: i32, height: i32, horizontal_offset: [i32; 2], vertical_offset: [i32; 2]| { - let crop: Vec<_> = [ - width, - 1, - height, - 1, - horizontal_offset[0], - horizontal_offset[1], - vertical_offset[0], - vertical_offset[1], - ] - .into_iter() - .flat_map(i32::to_be_bytes) - .collect(); - box_bytes(b"clap", &crop) - }; + let clap = clean_aperture; let centred = [0, 1]; let back_half = [-1, 2]; let mirror = |axis| box_bytes(b"imir", &[axis]); @@ -1687,53 +1782,32 @@ fn transforms_that_need_full_chroma_are_refused() { let three_quarter_turn = box_bytes(b"irot", &[3]); let odd_width = clap(11, 12, back_half, centred); let odd_height = clap(12, 11, centred, back_half); - for (properties, refused) in [ - (vec![clap(12, 12, centred, centred)], false), - ( - vec![clap(12, 12, centred, centred), quarter_turn.clone()], - false, - ), - ( - vec![half_turn.clone(), clap(12, 12, centred, centred)], - false, - ), - (vec![odd_width.clone()], false), - (vec![odd_width.clone(), three_quarter_turn.clone()], false), - (vec![odd_height.clone()], false), - (vec![odd_height.clone(), quarter_turn.clone()], false), - (vec![clap(12, 10, centred, centred)], true), - (vec![clap(10, 12, centred, centred)], true), - ( - vec![quarter_turn.clone(), clap(12, 10, centred, centred)], - true, - ), - (vec![half_turn.clone(), clap(11, 12, [1, 2], centred)], true), - (vec![half_turn.clone(), odd_width.clone()], true), - (vec![odd_width.clone(), quarter_turn.clone()], true), - (vec![odd_width.clone(), half_turn.clone()], true), - (vec![odd_width.clone(), mirror(0)], true), - (vec![odd_width, mirror(1)], true), - (vec![odd_height.clone(), half_turn], true), - (vec![odd_height.clone(), three_quarter_turn], true), - (vec![odd_height.clone(), mirror(0)], true), - (vec![odd_height, mirror(1)], true), + for properties in [ + vec![clap(12, 12, centred, centred)], + vec![clap(12, 12, centred, centred), quarter_turn.clone()], + vec![half_turn.clone(), clap(12, 12, centred, centred)], + vec![odd_width.clone()], + vec![odd_width.clone(), three_quarter_turn.clone()], + vec![odd_height.clone()], + vec![odd_height.clone(), quarter_turn.clone()], + vec![clap(12, 10, centred, centred)], + vec![clap(10, 12, centred, centred)], + vec![quarter_turn.clone(), clap(12, 10, centred, centred)], + vec![half_turn.clone(), clap(11, 12, [1, 2], centred)], + vec![half_turn.clone(), odd_width.clone()], + vec![odd_width.clone(), quarter_turn.clone()], + vec![odd_width.clone(), half_turn.clone()], + vec![odd_width.clone(), mirror(0)], + vec![odd_width.clone(), mirror(1)], + vec![odd_height.clone(), half_turn.clone()], + vec![odd_height.clone(), three_quarter_turn.clone()], + vec![odd_height.clone(), mirror(0)], + vec![odd_height.clone(), mirror(1)], + vec![clap(9, 7, [1, 1], [-1, 1]), quarter_turn.clone(), mirror(1)], ] { for primary in [Primary::Single, Primary::Grid] { let bytes = coded_fixture(primary, &config, (16, 16), &[&payload], &properties, None); - let result = decode_bounded(BoundedInput::Bytes(&bytes), Default::default()); - if refused { - assert!( - matches!( - result, - Err(BoundedDecodeError::Unsupported( - "transform that needs 4:4:4 chroma" - )) - ), - "{result:?}" - ); - } else { - assert!(result.is_ok(), "{result:?}"); - } + assert_matches_normal_decode(&bytes); } } let rotated_then_cropped = fixture_with_canvas( @@ -1751,9 +1825,68 @@ fn transforms_that_need_full_chroma_are_refused() { Default::default(), ) .unwrap(); - let normal = crate::decode_bytes_to_rgb8(&rotated_then_cropped).unwrap(); assert_eq!((bounded.image.width, bounded.image.height), (10, 12)); - assert_eq!(bounded.image.pixels, normal.pixels); + assert_matches_normal_decode(&rotated_then_cropped); +} + +#[cfg(not(feature = "decoder-tracing"))] +#[test] +fn grids_convert_to_full_chroma_across_tile_edges_like_normal_decode() { + let config = configuration(&nal_sets()[1]); + let payload = asymmetric_payload(); + let mirror = |axis| box_bytes(b"imir", &[axis]); + let turn = |quarters| box_bytes(b"irot", &[quarters]); + for (layout, canvas, properties) in [ + ((2, 2), (31, 29), vec![turn(1)]), + ((2, 2), (31, 32), vec![turn(2)]), + ((2, 2), (32, 31), vec![turn(3), mirror(1)]), + ((2, 2), (32, 31), vec![turn(1), mirror(0)]), + ((3, 2), (47, 30), vec![mirror(1)]), + ((2, 3), (30, 47), vec![mirror(0)]), + ( + (2, 2), + (32, 32), + vec![clean_aperture(29, 30, [0, 1], [0, 1])], + ), + ( + (3, 3), + (48, 48), + vec![clean_aperture(45, 45, [-1, 1], [0, 1])], + ), + ( + (3, 3), + (48, 48), + vec![clean_aperture(3, 3, [-1, 1], [-1, 1])], + ), + ( + (3, 3), + (48, 48), + vec![clean_aperture(4, 5, [-17, 2], [17, 2])], + ), + ( + (3, 3), + (47, 46), + vec![clean_aperture(44, 43, [0, 1], [0, 1]), turn(2)], + ), + ( + (3, 3), + (48, 48), + vec![turn(1), clean_aperture(45, 44, [1, 1], [-1, 1]), mirror(1)], + ), + ( + (3, 1), + (47, 16), + vec![turn(1), clean_aperture(5, 45, [0, 1], [0, 1])], + ), + ( + (1, 3), + (16, 47), + vec![mirror(0), clean_aperture(14, 3, [0, 1], [-19, 1])], + ), + ] { + let bytes = tiled_fixture(&config, &payload, layout, &properties, canvas); + assert_matches_normal_decode(&bytes); + } } #[cfg(not(feature = "decoder-tracing"))]