diff --git a/API.md b/API.md index 188a53d..16a0122 100644 --- a/API.md +++ b/API.md @@ -121,6 +121,11 @@ These are useful for tooling and specialized pipelines, but most applications should use the core entry points above. - `decode_primary_avif_to_image(input)` -> `Result` + - `ycbcr_range` and `ycbcr_matrix` come from the item's `colr` nclx + property, or from the AV1 sequence header when the item has none, as in + libheif. Earlier versions reported full range with unspecified + coefficients when the item had no nclx property, and the RGBA decode + converted such items that way. - `assemble_primary_heic_hevc_stream(input)` -> `Result, DecodeHeicError>` - `decode_primary_heic_to_image(input)` -> `Result` - `decode_primary_heic_to_metadata(input)` -> `Result` @@ -263,13 +268,14 @@ any of these, each judged at the size the image has when it applies: - on 4:2:2, any 90° or 270° `irot`, a 180° `irot` of an odd height, or a left-right `imir` (axis 1) of an odd width. -The HEVC decode paths do the same. Transforms before the conversion run on the -subsampled planes in property order, as in libheif; for example, a 180° +The HEVC and AVIF decode paths do the same. Transforms before the conversion +run on the subsampled planes in property order, as in libheif; for example, a 180° `irot` of an odd-width 4:2:2 image rotates its half-width chroma planes without converting them. If the coded colour is limited range, the conversion then passes the image through RGB to full-range 4:4:4, as libheif does. The coded -stream's colour drives that conversion; a `colr` nclx property replaces it only -after all transforms. The same applies to primary items, to grids as a whole, +stream's colour drives that conversion: the HEVC VUI, or the AV1 sequence +header's `color_config`. A `colr` nclx property replaces it only after all +transforms. The same applies to primary items, to grids as a whole, and to the clean apertures of individual grid tiles. A grid whose tile crops convert some tiles but not others is rejected with `DecodedLayoutMismatch`, because its tiles no longer share one chroma format; libheif rejects it too. @@ -277,7 +283,9 @@ For primary items and whole grids, the 4:4:4 image is built a few rows at a time while converting to RGB, so it is never held at full size. A grid that needs the conversion, or a transform of its subsampled planes, is first assembled into one canvas, which stays in memory alongside the output, instead -of being converted tile by tile. Image edges use clamped interpolation, +of being converted tile by tile. An 8-bit AVIF item that needs the conversion +has its planes widened to 16-bit samples first, which doubles the memory they +take during the decode. Image edges use clamped interpolation, matching libheif after its 2026-10 border fix. The pinned libheif 1.21.2 validator differs on output rows or columns that keep an edge of the converted image. diff --git a/TESTING.md b/TESTING.md index 2de9e7f..d384297 100644 --- a/TESTING.md +++ b/TESTING.md @@ -239,12 +239,14 @@ from the positive `*.heic` oracle comparisons. The external primary-image oracle is only a test executable; it adds no native dependency to the Rust decoder. After the existing harness builds libheif, build and run it with CMake, libpng development files, Ruby, and FFmpeg with -libx265. No incremental image assets are committed. The generator starts +libx265 and an AV1 encoder (libaom-av1, or libsvtav1 when FFmpeg lacks +libaom). No incremental image assets are committed. The generator starts from the existing external libheif corpus and creates the geometry, metadata, and height-growth cases missing from that corpus in the ignored `.heic-test-assets/incremental-corpus` directory. All reference PNGs come from -live strict libheif decoding. Its manifest records source, oracle, FFmpeg, -and input identities; encoded bytes can differ across libx265 versions. +live strict libheif decoding. Its manifest records source, oracle, FFmpeg, AV1 +encoder, and input identities; encoded bytes can differ across encoder +versions. Grid tiles are hidden items, so `heif-dec` writes only the primary image. Once the corpus exists, default `verify` runs also compare each of its `.heic` files exactly against `heif-dec`. Regenerate a corpus made before tiles were @@ -254,9 +256,11 @@ 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. 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 +refuses the 4:2:2 ones, which its HEVC decoder does not support. AVIF cases are +written to the `avif` subdirectory; the incremental and bounded decoders only +decode HEVC, so the bounded comparison records them as refusals. The incremental runner below only receives the top-level files, and default -`verify` and the bounded comparison cover both subdirectories. +`verify` and the bounded comparison cover all three subdirectories. ```bash cmake -S scripts/incremental -B .heic-test-runs/incremental-oracle \ @@ -320,10 +324,18 @@ the pinned 4:2:2 kernel has no border defect, and include a 180° turn of an odd width that libheif runs on the subsampled planes without converting. `odd-height-grid-quarter-turn`, `odd-three-quarter-turn`, and `chroma422-odd-vertical-mirror` need no conversion and guard against -converting too often. A 4:2:0 primary item reaches an odd size only through a -`clap`, so its converting rotations keep the cropped edges and differ from the -pinned validator there. Unit tests cover those; on such probes the decoder -matched `heif-dec` exactly once the pinned border was modelled. +converting too often. An HEVC 4:2:0 primary item reaches an odd size only +through a `clap`, so its converting rotations keep the cropped edges and differ +from the pinned validator there. Unit tests cover those; on such probes the +decoder matched `heif-dec` exactly once the pinned border was modelled. + +The `avif` cases run the same rules on AV1 items: `clap`s with an odd origin, +an odd left edge, or an odd top edge, and 90°, 180° and 270° `irot`s and +`imir`s of odd-sized stills followed by an edge-trimming `clap`. They cover +8-bit and 10-bit, full and limited range, a `colr` nclx override that differs +from the AV1 sequence header, and items without `colr` that convert with the +sequence header's colour. `even-clap` and `odd-width-three-quarter-turn` need +no conversion. The pinned libheif has a bilinear chroma-border indexing defect, fixed upstream by strukturag/libheif commit 215cbdad. The decoders implement the diff --git a/scripts/incremental/generate.rb b/scripts/incremental/generate.rb index 631399a..8d5a5ba 100644 --- a/scripts/incremental/generate.rb +++ b/scripts/incremental/generate.rb @@ -36,6 +36,23 @@ def oracle_png(oracle, input, output) '-c:v', 'libx265', '-preset', 'fast', '-crf', '28', '-x265-params', parameters, '-f', 'hevc', File.join(output, "#{name}.hevc")) end +av1_encoder = if execute('ffmpeg', '-hide_banner', '-encoders').include?(' libaom-av1 ') + %w[-c:v libaom-av1 -cpu-used 8] + else + %w[-c:v libsvtav1 -preset 8] + end +av1_encodes = [['av1-edge', 256, 256, 8, 'pc'], ['av1-edge-limited', 256, 256, 8, 'tv'], ['av1-edge10', 256, 256, 10, 'tv'], + ['av1-odd-width', 255, 256, 8, 'tv'], ['av1-odd-width10', 255, 256, 10, 'pc'], ['av1-odd-height', 256, 255, 8, 'pc']] +av1_encodes.each do |name, width, height, depth, range| + step = 1 << (depth - 8) + filters = "scale=#{width}:#{height},format=#{depth == 8 ? 'yuv420p' : 'yuv420p10le'}," \ + "geq=lum='lum(X,Y)':cb='#{16 * step}+mod(X*13+Y*7,224)*#{step}':cr='#{16 * step}+mod(X*5+Y*17,224)*#{step}'" + execute('ffmpeg', '-v', 'error', '-y', '-i', seed, '-vf', filters, '-frames:v', '1', *av1_encoder, '-crf', '30', + '-color_range', range, '-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'iec61966-2-1', + '-f', 'avif', File.join(output, "#{name}.av1")) +end +sources = encodes.to_h { |name, width, height| [name, ["#{name}.hevc", width, height]] } + .merge(av1_encodes.to_h { |name, width, height| [name, ["#{name}.av1", width, height]] }) cases = [ ['direct', 'direct', 1, 1, {}], @@ -74,25 +91,55 @@ def oracle_png(oracle, input, output) ['orientation/chroma422-odd-half-turn', 'edge422', 1, 1, { 'CROP' => '131x192', 'ROTATION' => '2' }], ['orientation/chroma422-odd-height-half-turn', 'edge422', 1, 1, { 'CROP' => '132x191', 'ROTATION' => '2' }], ['orientation/chroma422-odd-mirror', 'edge422', 1, 1, { 'CROP' => '131x192', 'MIRROR' => '1' }], - ['orientation/chroma422-odd-vertical-mirror', 'edge422', 1, 1, { 'CROP' => '131x192', 'MIRROR' => '0' }] + ['orientation/chroma422-odd-vertical-mirror', 'edge422', 1, 1, { 'CROP' => '131x192', 'MIRROR' => '0' }], + ['avif/odd-clap', 'av1-edge', 1, 1, { 'CROP' => '130x190', 'PRIMARY_NCLX' => '1/13/1/1' }], + ['avif/odd-clap-limited', 'av1-edge-limited', 1, 1, { 'CROP' => '130x190', 'PRIMARY_NCLX' => '1/13/1/0' }], + ['avif/odd-clap-10-bit', 'av1-edge10', 1, 1, { 'CROP' => '130x190', 'PRIMARY_NCLX' => '1/13/1/0' }], + ['avif/odd-left-clap', 'av1-edge-limited', 1, 1, { 'CROP' => '130x192', 'PRIMARY_NCLX' => '1/13/1/0' }], + ['avif/odd-top-clap-10-bit', 'av1-edge10', 1, 1, { 'CROP' => '128x190', 'PRIMARY_NCLX' => '1/13/1/0' }], + ['avif/odd-clap-colr-override', 'av1-edge-limited', 1, 1, { 'CROP' => '130x190', 'PRIMARY_NCLX' => '9/1/9/1' }], + ['avif/odd-clap-stream-nclx', 'av1-edge-limited', 1, 1, { 'CROP' => '130x190' }], + ['avif/stream-nclx', 'av1-edge-limited', 1, 1, {}], + ['avif/even-clap', 'av1-edge', 1, 1, { 'CROP' => '128x192', 'PRIMARY_NCLX' => '1/13/1/1' }], + ['avif/odd-width-quarter-turn', 'av1-odd-width', 1, 1, + { 'ROTATION' => '1', 'CROP' => '254x253', 'TRANSFORM_ORDER' => 'ROTATION,CROP', 'PRIMARY_NCLX' => '1/13/1/0' }], + ['avif/odd-width-half-turn-10-bit', 'av1-odd-width10', 1, 1, + { 'ROTATION' => '2', 'CROP' => '253x254', 'TRANSFORM_ORDER' => 'ROTATION,CROP', 'PRIMARY_NCLX' => '1/13/1/1' }], + ['avif/odd-width-mirror-10-bit', 'av1-odd-width10', 1, 1, + { 'MIRROR' => '1', 'CROP' => '253x254', 'TRANSFORM_ORDER' => 'MIRROR,CROP', 'PRIMARY_NCLX' => '1/13/1/1' }], + ['avif/odd-width-vertical-mirror-colr-override', 'av1-odd-width', 1, 1, + { 'MIRROR' => '0', 'CROP' => '253x254', 'TRANSFORM_ORDER' => 'MIRROR,CROP', 'PRIMARY_NCLX' => '9/1/9/1' }], + ['avif/odd-height-three-quarter-turn', 'av1-odd-height', 1, 1, + { 'ROTATION' => '3', 'CROP' => '253x254', 'TRANSFORM_ORDER' => 'ROTATION,CROP', 'PRIMARY_NCLX' => '1/13/1/1' }], + ['avif/odd-height-turn-then-mirror', 'av1-odd-height', 1, 1, + { 'ROTATION' => '1', 'MIRROR' => '0', 'CROP' => '253x254', 'TRANSFORM_ORDER' => 'ROTATION,MIRROR,CROP', + 'PRIMARY_NCLX' => '1/13/1/1' }], + ['avif/odd-width-three-quarter-turn', 'av1-odd-width', 1, 1, { 'ROTATION' => '3', 'PRIMARY_NCLX' => '1/13/1/0' }] ] +case_path = lambda do |name, encoded| + extension = if name == 'invalid-grid-references' then 'bin' + elsif sources.fetch(encoded)[0].end_with?('.av1') then 'avif' + else 'heic' + end + File.join(output, "#{name}.#{extension}") +end cases.each do |name, encoded, columns, rows, options| - _, width, height = encodes.find { |entry| entry[0] == encoded } - extension = name == 'invalid-grid-references' ? 'bin' : 'heic' - path = File.join(output, "#{name}.#{extension}") + input, width, height = sources.fetch(encoded) + path = case_path.call(name, encoded) FileUtils.mkdir_p(File.dirname(path)) environment = %w[GRID CANVAS CROP TILE_CROP ROTATION MIRROR TRANSFORM_ORDER TILE_NCLX PRIMARY_NCLX REFERENCE_COUNT].to_h { |key| [key, nil] }.merge(options) - execute(environment, RbConfig.ruby, File.join(__dir__, 'wrap.rb'), File.join(output, "#{encoded}.hevc"), + execute(environment, RbConfig.ruby, File.join(__dir__, 'wrap.rb'), File.join(output, input), path, width.to_s, height.to_s, columns.to_s, rows.to_s) - oracle_png(oracle, path, path.sub(/\.heic$/, '.png')) if extension == 'heic' + oracle_png(oracle, path, path.sub(/\.(heic|avif)$/, '.png')) unless path.end_with?('.bin') puts "Generated #{path}" end manifest = { source: { path: source, sha256: Digest::SHA256.file(source).hexdigest }, oracle_sha256: Digest::SHA256.file(oracle).hexdigest, ffmpeg: execute('ffmpeg', '-version').lines.first.strip, - inputs: cases.to_h do |name, *_| - path = File.join(output, "#{name}.#{name == 'invalid-grid-references' ? 'bin' : 'heic'}") + av1_encoder: av1_encoder[1], + inputs: cases.to_h do |name, encoded, *_| + path = case_path.call(name, encoded) [path.delete_prefix("#{output}/"), Digest::SHA256.file(path).hexdigest] end } diff --git a/scripts/incremental/wrap.rb b/scripts/incremental/wrap.rb index 428cc29..6ff9133 100644 --- a/scripts/incremental/wrap.rb +++ b/scripts/incremental/wrap.rb @@ -1,32 +1,10 @@ input, output, width, height, columns, rows = ARGV -abort 'Usage: wrap.rb ANNEX_B OUTPUT WIDTH HEIGHT [COLUMNS] [ROWS]' unless input && output && width && height +abort 'Usage: wrap.rb ANNEX_B_OR_AVIF OUTPUT WIDTH HEIGHT [COLUMNS] [ROWS]' unless input && output && width && height width = Integer(width) height = Integer(height) columns = Integer(columns || '1') rows = Integer(rows || '1') raise 'Invalid fixture dimensions' unless width.positive? && height.positive? && (1..256).cover?(columns) && (1..256).cover?(rows) -nals = File.binread(input).split(/\x00\x00\x00?\x01/n).reject(&:empty?) -parameters = (32..34).map do |kind| - nals.find { |nal| (nal.getbyte(0) >> 1 & 63) == kind } || raise('Missing parameter set') -end -pictures = nals.select { |nal| [19, 20].include?(nal.getbyte(0) >> 1 & 63) } -raise 'One IDR required' unless pictures.size == 1 -payload = pictures.map { |nal| [nal.bytesize].pack('N') + nal }.join -sps = parameters[1].byteslice(2..).gsub(/\x00\x00\x03/n, "\x00\x00".b) -raise 'SPS sub-layers are unsupported' unless (sps.getbyte(0) >> 1 & 7).zero? -bits = sps.byteslice(13..).unpack1('B*') -position = 0 -exp_golomb = lambda do - zeros = bits.index('1', position) - position - value = (1 << zeros) - 1 + bits[position + zeros + 1, zeros].to_i(2) - position += 2 * zeros + 1 - value -end -exp_golomb.call -chroma_format = exp_golomb.call -raise 'Only 4:2:0 and 4:2:2 streams are supported' unless [1, 2].include?(chroma_format) -hvcc = [1].pack('C') + sps.byteslice(1, 12) + [0xf0, 0, 0xfc, 0xfc | chroma_format, 0xf8, 0xf8, 0, 0, 0x0f, 3].pack('C*') -parameters.each_with_index { |nal, i| hvcc += [0x80 + 32 + i, 1, nal.bytesize].pack('Cnn') + nal } def box(kind, data) [data.bytesize + 8].pack('N') + kind + data end @@ -35,14 +13,64 @@ def full(kind, version, data, flags = 0) box(kind, [(version << 24) | flags].pack('N') + data) end +def child_boxes(data, offset) + boxes = {} + while offset < data.bytesize + size, kind = data.unpack('Na4', offset: offset) + boxes[kind] ||= data.byteslice(offset, size) + offset += size + end + boxes +end + +stream = File.binread(input) +if stream.byteslice(4, 4) == 'ftyp' + top = child_boxes(stream, 0) + ipco = child_boxes(child_boxes(top.fetch('meta'), 12).fetch('iprp'), 8).fetch('ipco') + config = child_boxes(ipco, 8).fetch('av1C') + payload = top.fetch('mdat').byteslice(8..) + flags = config.getbyte(10) + bit_depth = flags[6].zero? ? 8 : 10 + 2 * flags[5] + coded_type = 'av01' + brands = "avif\0\0\0\0mif1avifmiaf".b +else + nals = stream.split(/\x00\x00\x00?\x01/n).reject(&:empty?) + parameters = (32..34).map do |kind| + nals.find { |nal| (nal.getbyte(0) >> 1 & 63) == kind } || raise('Missing parameter set') + end + pictures = nals.select { |nal| [19, 20].include?(nal.getbyte(0) >> 1 & 63) } + raise 'One IDR required' unless pictures.size == 1 + payload = pictures.map { |nal| [nal.bytesize].pack('N') + nal }.join + sps = parameters[1].byteslice(2..).gsub(/\x00\x00\x03/n, "\x00\x00".b) + raise 'SPS sub-layers are unsupported' unless (sps.getbyte(0) >> 1 & 7).zero? + bits = sps.byteslice(13..).unpack1('B*') + position = 0 + exp_golomb = lambda do + zeros = bits.index('1', position) - position + value = (1 << zeros) - 1 + bits[position + zeros + 1, zeros].to_i(2) + position += 2 * zeros + 1 + value + end + exp_golomb.call + chroma_format = exp_golomb.call + raise 'Only 4:2:0 and 4:2:2 streams are supported' unless [1, 2].include?(chroma_format) + hvcc = [1].pack('C') + sps.byteslice(1, 12) + [0xf0, 0, 0xfc, 0xfc | chroma_format, 0xf8, 0xf8, 0, 0, 0x0f, 3].pack('C*') + parameters.each_with_index { |nal, i| hvcc += [0x80 + 32 + i, 1, nal.bytesize].pack('Cnn') + nal } + config = box('hvcC', hvcc) + bit_depth = 8 + coded_type = 'hvc1' + brands = "heic\0\0\0\0mif1heic".b +end + count = columns * rows grid = count > 1 || ENV['GRID'] == '1' +raise 'AV1 grids are unsupported' if grid && coded_type == 'av01' total = count + (grid ? 1 : 0) primary = grid ? total : 1 canvas_width, canvas_height = ENV.fetch('CANVAS', "#{width * columns}x#{height * rows}").split('x').map { |n| Integer(n) } raise 'Invalid canvas' unless canvas_width.positive? && canvas_height.positive? && canvas_width <= width * columns && canvas_height <= height * rows ispe = ->(w, h) { full('ispe', 0, [w, h].pack('NN')) } -properties = [box('hvcC', hvcc), ispe.call(width, height), full('pixi', 0, [3, 8, 8, 8].pack('C*'))] +properties = [config, ispe.call(width, height), full('pixi', 0, [3, bit_depth, bit_depth, bit_depth].pack('C*'))] properties << ispe.call(canvas_width, canvas_height) if grid tile_color = nil primary_color = nil @@ -74,7 +102,7 @@ def full(kind, version, data, flags = 0) extra << properties.length end items = (1..total).map do |id| - kind = id == primary && grid ? 'grid' : 'hvc1' + kind = id == primary && grid ? 'grid' : coded_type full('infe', 2, [id, 0].pack('nn') + kind + "\0", grid && id != primary ? 1 : 0) end.join ipma = [total].pack('N') + (1..total).map do |id| @@ -89,7 +117,7 @@ def full(kind, version, data, flags = 0) raise 'Invalid reference count' unless (1..65_535).cover?(targets.length) references = grid ? full('iref', 0, box('dimg', [primary, targets.length, *targets].pack('n*'))) : ''.b griddata = grid ? [0, 1, rows - 1, columns - 1, canvas_width, canvas_height].pack('CCCCNN') : ''.b -ftyp = box('ftyp', "heic\0\0\0\0mif1heic".b) +ftyp = box('ftyp', brands) make_meta = lambda do |offset| locations = [0x44, 0, total].pack('CCn') (1..total).each do |id| diff --git a/src/geometry_tests.rs b/src/geometry_tests.rs index e48bd34..1fb1a6d 100644 --- a/src/geometry_tests.rs +++ b/src/geometry_tests.rs @@ -600,6 +600,26 @@ fn avif_matching_alpha_is_preserved() { ); } +#[test] +fn avif_without_colr_reports_the_sequence_header_colour() { + let input = image_fixture( + b"av01", + (256, 2048), + boxed(b"av1C", &[0x81, 0x04, 0x0c, 0]), + av1_payload(), + None, + ); + let decoded = decode_primary_avif_to_image(&input).unwrap(); + assert_eq!(decoded.ycbcr_range, YCbCrRange::Limited); + assert_eq!( + decoded.ycbcr_matrix, + YCbCrMatrixCoefficients { + matrix_coefficients: 6, + colour_primaries: 2, + } + ); +} + #[test] fn avif_zero_pixel_limit_cannot_disable_backend_limit() { let input = image_fixture( diff --git a/src/lib.rs b/src/lib.rs index 681a1b3..445198d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1312,7 +1312,10 @@ fn decode_primary_avif_to_image_internal( source: &mut Option<&mut dyn RandomAccessSource>, ) -> Result { let (meta, resolved) = isobmff::resolve_primary_avif_item_graph(input)?; - decode_primary_avif_to_image_from_resolved_graph(input, source, &meta, &resolved, None) + let (mut decoded, colr) = + decode_primary_avif_to_image_from_resolved_graph(input, source, &meta, &resolved, None)?; + colr.apply_to_avif(&mut decoded); + Ok(decoded) } fn decode_primary_avif_to_image_from_resolved_graph( @@ -1321,7 +1324,7 @@ fn decode_primary_avif_to_image_from_resolved_graph( meta: &isobmff::MetaBox<'_>, resolved: &isobmff::ResolvedPrimaryItemGraph<'_>, max_pixels: Option, -) -> Result { +) -> Result<(DecodedAvifImage, HeicColrOverride), DecodeAvifError> { let item_id = resolved.primary_item.item_id; let item_type = resolved .primary_item @@ -1346,8 +1349,7 @@ fn decode_primary_avif_to_image_from_resolved_graph( let properties = isobmff::parse_primary_avif_item_preflight_properties_from_resolved_graph(resolved) .map_err(DecodeAvifError::ParsePrimaryProperties)?; - let ycbcr_range = ycbcr_range_from_primary_colr(&properties.colr); - let ycbcr_matrix = ycbcr_matrix_from_primary_colr(&properties.colr); + let colr = HeicColrOverride::from_colr(&properties.colr); let mut elementary_stream = properties.av1c.config_obus; elementary_stream.extend_from_slice(&payload); @@ -1356,8 +1358,6 @@ fn decode_primary_avif_to_image_from_resolved_graph( Some((properties.ispe.width, properties.ispe.height)), max_pixels, )?; - decoded.ycbcr_range = ycbcr_range; - decoded.ycbcr_matrix = ycbcr_matrix; if decoded.width != properties.ispe.width || decoded.height != properties.ispe.height { return Err(DecodeAvifError::DecodedGeometryMismatch { expected_width: properties.ispe.width, @@ -1377,7 +1377,7 @@ fn decode_primary_avif_to_image_from_resolved_graph( max_pixels, ); - Ok(decoded) + Ok((decoded, colr)) } pub fn assemble_primary_heic_hevc_stream(input: &[u8]) -> Result, DecodeHeicError> { @@ -6593,6 +6593,15 @@ impl HeicColrOverride { decoded.ycbcr_matrix = ycbcr_matrix; } } + + fn apply_to_avif(self, decoded: &mut DecodedAvifImage) { + if let Some(ycbcr_range) = self.ycbcr_range { + decoded.ycbcr_range = ycbcr_range; + } + if let Some(ycbcr_matrix) = self.ycbcr_matrix { + decoded.ycbcr_matrix = ycbcr_matrix; + } + } } const HEIC_YUV444_BAND_PIXELS: u32 = 1 << 18; @@ -8655,7 +8664,7 @@ fn decode_avif_to_rgba_from_resolved_graph( let transforms = isobmff::parse_primary_item_transform_properties_from_resolved_graph(resolved) .map_err(DecodeAvifError::ParsePrimaryTransforms)?; let icc_profile = primary_icc_profile_from_resolved_avif_graph(resolved); - let decoded = decode_primary_avif_to_image_from_resolved_graph( + let (decoded, colr) = decode_primary_avif_to_image_from_resolved_graph( input, source, meta, @@ -8663,7 +8672,7 @@ fn decode_avif_to_rgba_from_resolved_graph( guardrails.max_pixels, )?; guardrails.enforce_pixel_count(decoded.width, decoded.height)?; - decoded_avif_to_rgba_image(&decoded, &transforms.transforms, icc_profile) + decoded_avif_to_rgba_image(decoded, colr, &transforms.transforms, icc_profile) } fn decode_avif_source_to_rgba( @@ -9910,7 +9919,7 @@ fn decode_avif_bytes_to_rgba8_slice( isobmff::parse_primary_item_transform_properties_from_resolved_graph(&resolved) .map_err(DecodeAvifError::ParsePrimaryTransforms)?; let mut source: Option<&mut dyn RandomAccessSource> = None; - let decoded = decode_primary_avif_to_image_from_resolved_graph( + let (decoded, colr) = decode_primary_avif_to_image_from_resolved_graph( input, &mut source, &meta, @@ -9918,7 +9927,7 @@ fn decode_avif_bytes_to_rgba8_slice( guardrails.max_pixels, )?; guardrails.enforce_pixel_count(decoded.width, decoded.height)?; - decoded_avif_to_rgba8_slice(&decoded, &transforms.transforms, out) + decoded_avif_to_rgba8_slice(decoded, colr, &transforms.transforms, out) } #[cfg(feature = "image-integration")] @@ -9933,7 +9942,7 @@ fn decode_avif_bytes_to_rgba16_native_endian_bytes( isobmff::parse_primary_item_transform_properties_from_resolved_graph(&resolved) .map_err(DecodeAvifError::ParsePrimaryTransforms)?; let mut source: Option<&mut dyn RandomAccessSource> = None; - let decoded = decode_primary_avif_to_image_from_resolved_graph( + let (decoded, colr) = decode_primary_avif_to_image_from_resolved_graph( input, &mut source, &meta, @@ -9941,13 +9950,13 @@ fn decode_avif_bytes_to_rgba16_native_endian_bytes( guardrails.max_pixels, )?; guardrails.enforce_pixel_count(decoded.width, decoded.height)?; - let mut output = NativeEndianRgba16Output(out); - decoded_avif_to_rgba16_output(&decoded, &transforms.transforms, &mut output) + decoded_avif_to_rgba16_native_endian_bytes(decoded, colr, &transforms.transforms, out) } #[cfg(feature = "image-integration")] fn decoded_avif_to_rgba8_slice( - decoded: &DecodedAvifImage, + mut decoded: DecodedAvifImage, + colr: HeicColrOverride, transforms: &[isobmff::PrimaryItemTransformProperty], out: &mut [u8], ) -> Result<(), DecodeError> { @@ -9956,11 +9965,15 @@ fn decoded_avif_to_rgba8_slice( "AVIF storage is RGBA16, not RGBA8".to_string(), )); } - let mut output = SliceRgbaOutput(out); + if avif_needs_libheif_yuv_transforms(&decoded, transforms) { + let (decoded, alpha) = avif_into_heic_planes(decoded)?; + return decoded_heic_to_rgba8_slice(decoded, colr, transforms, alpha.as_ref(), out); + } + colr.apply_to_avif(&mut decoded); decoded_avif_to_rgba_output( - decoded, + &decoded, transforms, - &mut output, + &mut SliceRgbaOutput(out), "AVIF direct transformed RGBA8 image adapter output", plane_samples_u8, avif_auxiliary_alpha_sample_to_u8, @@ -9970,20 +9983,32 @@ fn decoded_avif_to_rgba8_slice( } #[cfg(feature = "image-integration")] -fn decoded_avif_to_rgba16_output>( - decoded: &DecodedAvifImage, +fn decoded_avif_to_rgba16_native_endian_bytes( + mut decoded: DecodedAvifImage, + colr: HeicColrOverride, transforms: &[isobmff::PrimaryItemTransformProperty], - out: &mut O, + out: &mut [u8], ) -> Result<(), DecodeError> { if decoded.bit_depth <= 8 { return Err(DecodeError::Unsupported( "AVIF storage is RGBA8, not RGBA16".to_string(), )); } + if avif_needs_libheif_yuv_transforms(&decoded, transforms) { + let (decoded, alpha) = avif_into_heic_planes(decoded)?; + return decoded_heic_to_rgba16_native_endian_bytes( + decoded, + colr, + transforms, + alpha.as_ref(), + out, + ); + } + colr.apply_to_avif(&mut decoded); decoded_avif_to_rgba_output( - decoded, + &decoded, transforms, - out, + &mut NativeEndianRgba16Output(out), "AVIF direct transformed RGBA16 image adapter output", plane_samples_u16, avif_auxiliary_alpha_sample_to_u16, @@ -11423,10 +11448,17 @@ fn colour_primaries_from_index(primaries_idx: u16) -> Option { } fn decoded_avif_to_rgba_image( - decoded: &DecodedAvifImage, + mut decoded: DecodedAvifImage, + colr: HeicColrOverride, transforms: &[isobmff::PrimaryItemTransformProperty], icc_profile: Option>, ) -> Result { + if avif_needs_libheif_yuv_transforms(&decoded, transforms) { + let (decoded, alpha) = avif_into_heic_planes(decoded)?; + return decoded_heic_to_rgba_image(decoded, colr, transforms, alpha.as_ref(), icc_profile); + } + colr.apply_to_avif(&mut decoded); + let decoded = &decoded; if decoded.bit_depth <= 8 { let pixels = convert_avif_to_rgba8(decoded)?; let (width, height, transformed) = @@ -11452,6 +11484,101 @@ fn decoded_avif_to_rgba_image( }) } +fn heic_layout_from_avif(layout: AvifPixelLayout) -> HeicPixelLayout { + match layout { + AvifPixelLayout::Yuv400 => HeicPixelLayout::Yuv400, + AvifPixelLayout::Yuv420 => HeicPixelLayout::Yuv420, + AvifPixelLayout::Yuv422 => HeicPixelLayout::Yuv422, + AvifPixelLayout::Yuv444 => HeicPixelLayout::Yuv444, + } +} + +fn avif_needs_libheif_yuv_transforms( + decoded: &DecodedAvifImage, + transforms: &[isobmff::PrimaryItemTransformProperty], +) -> bool { + yuv_transforms::libheif_yuv_transform_count( + heic_layout_from_avif(decoded.layout), + decoded.width, + decoded.height, + transforms, + ) > 0 +} + +fn avif_into_heic_planes( + decoded: DecodedAvifImage, +) -> Result<(DecodedHeicImage, Option), DecodeError> { + let DecodedAvifImage { + width, + height, + bit_depth, + layout, + ycbcr_range, + ycbcr_matrix, + y_plane, + u_plane, + v_plane, + alpha_plane, + } = decoded; + let plane = |plane: AvifPlane, label| { + Ok::<_, DecodeError>(HeicPlane { + width: plane.width, + height: plane.height, + samples: avif_samples_into_u16(plane.samples, bit_depth, label)?, + }) + }; + let alpha = alpha_plane + .map(|alpha| { + Ok::<_, DecodeError>(HeicAuxiliaryAlphaPlane { + width: alpha.width, + height: alpha.height, + bit_depth: alpha.bit_depth, + samples: avif_samples_into_u16(alpha.samples, alpha.bit_depth, "A")?, + }) + }) + .transpose()?; + let decoded = DecodedHeicImage { + width, + height, + bit_depth_luma: bit_depth, + bit_depth_chroma: bit_depth, + layout: heic_layout_from_avif(layout), + ycbcr_range, + ycbcr_matrix, + y_plane: plane(y_plane, "Y")?, + u_plane: u_plane.map(|u_plane| plane(u_plane, "U")).transpose()?, + v_plane: v_plane.map(|v_plane| plane(v_plane, "V")).transpose()?, + }; + Ok((decoded, alpha)) +} + +fn avif_samples_into_u16( + samples: AvifPlaneSamples, + bit_depth: u8, + plane: &'static str, +) -> Result, DecodeError> { + match samples { + AvifPlaneSamples::U8(samples) if bit_depth <= 8 => { + let mut widened = try_rgba_buffer(samples.len(), "AVIF plane widening")?; + widened.extend(samples.into_iter().map(u16::from)); + Ok(widened) + } + AvifPlaneSamples::U16(samples) if bit_depth > 8 => Ok(samples), + AvifPlaneSamples::U8(_) => Err(DecodeAvifError::PlaneSampleTypeMismatch { + plane, + expected: "u16", + actual: "u8", + } + .into()), + AvifPlaneSamples::U16(_) => Err(DecodeAvifError::PlaneSampleTypeMismatch { + plane, + expected: "u8", + actual: "u16", + } + .into()), + } +} + fn decoded_heic_to_rgba_image( decoded: DecodedHeicImage, colr: HeicColrOverride, @@ -14131,13 +14258,32 @@ fn picture_to_internal_image(picture: &Dav1dPicture) -> Result super::DecodedAvifImage { + let bit_depth = image.bit_depth_luma; + let plane = |plane: &super::HeicPlane| super::AvifPlane { + width: plane.width, + height: plane.height, + samples: if bit_depth <= 8 { + super::AvifPlaneSamples::U8( + plane.samples.iter().map(|&sample| sample as u8).collect(), + ) + } else { + super::AvifPlaneSamples::U16(plane.samples.clone()) + }, + }; + super::DecodedAvifImage { + width: image.width, + height: image.height, + bit_depth, + layout: match image.layout { + super::HeicPixelLayout::Yuv400 => super::AvifPixelLayout::Yuv400, + super::HeicPixelLayout::Yuv420 => super::AvifPixelLayout::Yuv420, + super::HeicPixelLayout::Yuv422 => super::AvifPixelLayout::Yuv422, + super::HeicPixelLayout::Yuv444 => super::AvifPixelLayout::Yuv444, + }, + ycbcr_range: image.ycbcr_range, + ycbcr_matrix: image.ycbcr_matrix, + y_plane: plane(&image.y_plane), + u_plane: image.u_plane.as_ref().map(plane), + v_plane: image.v_plane.as_ref().map(plane), + alpha_plane: None, + } + } + + fn bt2020_full_range_colr() -> super::HeicColrOverride { + super::HeicColrOverride { + ycbcr_range: Some(super::YCbCrRange::Full), + ycbcr_matrix: Some(super::YCbCrMatrixCoefficients { + matrix_coefficients: 9, + colour_primaries: 9, + }), + } + } + + #[test] + fn avif_transforms_follow_the_libheif_yuv_conversion_of_heic() { + use super::HeicPixelLayout::{Yuv420, Yuv422}; + use isobmff::ImageMirrorDirection::Horizontal; + let odd_crop = + isobmff::PrimaryItemTransformProperty::CleanAperture(synthetic_clean_aperture(-1, -1)); + let odd_left_crop = + isobmff::PrimaryItemTransformProperty::CleanAperture(synthetic_clean_aperture(-1, 0)); + let aligned_crop = + isobmff::PrimaryItemTransformProperty::CleanAperture(synthetic_clean_aperture(0, 0)); + let colr = bt2020_full_range_colr(); + for bit_depth in [8, 10] { + for (layout, width, height, transform, matches_rgba_transforms) in [ + (Yuv420, 8, 8, odd_crop, false), + (Yuv422, 8, 8, odd_left_crop, false), + (Yuv420, 7, 6, rotation(90), false), + (Yuv420, 6, 7, mirror(Horizontal), false), + (Yuv422, 6, 6, rotation(270), false), + (Yuv422, 7, 6, rotation(180), false), + (Yuv420, 8, 8, aligned_crop, true), + (Yuv420, 7, 6, rotation(270), true), + ] { + let context = format!("{bit_depth}-bit {layout:?} {width}x{height} {transform:?}"); + let image = super::DecodedHeicImage { + bit_depth_luma: bit_depth, + bit_depth_chroma: bit_depth, + ..patterned_yuv_image(layout, width, height) + }; + let transforms = [transform]; + let heic = + super::decoded_heic_to_rgba_image(image.clone(), colr, &transforms, None, None) + .expect("HEIC decode should succeed"); + let avif = + super::decoded_avif_to_rgba_image(avif_image(&image), colr, &transforms, None) + .expect("AVIF decode should succeed"); + assert_eq!(avif, heic, "{context}"); + + let mut relabelled = avif_image(&image); + colr.apply_to_avif(&mut relabelled); + let nearest = super::decoded_avif_to_rgba_image( + relabelled, + super::HeicColrOverride::default(), + &[], + None, + ) + .expect("untransformed AVIF decode should succeed"); + let nearest = match nearest.pixels { + super::DecodedRgbaPixels::U8(pixels) => super::DecodedRgbaPixels::U8( + super::apply_primary_item_transforms_rgba( + width, + height, + pixels, + &transforms, + ) + .expect("RGBA transform should succeed") + .2, + ), + super::DecodedRgbaPixels::U16(pixels) => super::DecodedRgbaPixels::U16( + super::apply_primary_item_transforms_rgba( + width, + height, + pixels, + &transforms, + ) + .expect("RGBA transform should succeed") + .2, + ), + }; + assert_eq!(avif.pixels == nearest, matches_rgba_transforms, "{context}"); + } + } + } + + #[cfg(feature = "image-integration")] + #[test] + fn avif_converting_transform_slice_decodes_match_owned_decodes() { + let transforms = [ + rotation(90), + mirror(isobmff::ImageMirrorDirection::Horizontal), + ]; + let colr = bt2020_full_range_colr(); + for bit_depth in [8_u8, 10] { + let image = super::DecodedHeicImage { + bit_depth_luma: bit_depth, + bit_depth_chroma: bit_depth, + ..patterned_yuv_image(super::HeicPixelLayout::Yuv420, 7, 6) + }; + let alpha = super::HeicAuxiliaryAlphaPlane { + width: 7, + height: 6, + bit_depth, + samples: (0..42).map(|index| index * 5).collect(), + }; + let mut avif = avif_image(&image); + avif.alpha_plane = Some(super::AvifAuxiliaryAlphaPlane { + width: 7, + height: 6, + bit_depth, + samples: avif_image(&super::DecodedHeicImage { + y_plane: super::HeicPlane { + width: 7, + height: 6, + samples: alpha.samples.clone(), + }, + ..image.clone() + }) + .y_plane + .samples, + }); + let owned = super::decoded_avif_to_rgba_image(avif.clone(), colr, &transforms, None) + .expect("owned AVIF decode should succeed"); + assert_eq!( + owned, + super::decoded_heic_to_rgba_image(image, colr, &transforms, Some(&alpha), None) + .expect("HEIC decode should succeed"), + "{bit_depth}-bit" + ); + match owned.pixels { + super::DecodedRgbaPixels::U8(pixels) => { + let mut out = vec![0_u8; pixels.len()]; + super::decoded_avif_to_rgba8_slice(avif, colr, &transforms, &mut out) + .expect("RGBA8 slice decode should succeed"); + assert_eq!(out, pixels); + } + super::DecodedRgbaPixels::U16(pixels) => { + let mut bytes = vec![0_u8; pixels.len() * 2]; + super::decoded_avif_to_rgba16_native_endian_bytes( + avif, + colr, + &transforms, + &mut bytes, + ) + .expect("RGBA16 slice decode should succeed"); + let decoded: Vec = bytes + .chunks_exact(2) + .map(|pair| u16::from_ne_bytes([pair[0], pair[1]])) + .collect(); + assert_eq!(decoded, pixels); + } + } + } + } + + #[test] + fn avif_plane_samples_must_match_the_bit_depth_to_widen() { + assert_eq!( + super::avif_samples_into_u16(super::AvifPlaneSamples::U8(vec![0, 7, 255]), 8, "Y") + .expect("8-bit samples should widen"), + [0, 7, 255] + ); + assert_eq!( + super::avif_samples_into_u16(super::AvifPlaneSamples::U16(vec![0, 1023]), 10, "Y") + .expect("10-bit samples should pass through"), + [0, 1023] + ); + for (samples, bit_depth) in [ + (super::AvifPlaneSamples::U8(vec![1]), 10), + (super::AvifPlaneSamples::U16(vec![1]), 8), + ] { + assert!(matches!( + super::avif_samples_into_u16(samples, bit_depth, "U"), + Err(super::DecodeError::AvifDecode( + super::DecodeAvifError::PlaneSampleTypeMismatch { plane: "U", .. } + )) + )); + } + } + #[test] fn chroma_aligned_clean_aperture_yuv_crop_matches_rgba_transform_path() { let image = synthetic_yuv_image(super::HeicPixelLayout::Yuv420); @@ -16034,17 +16390,26 @@ mod tests { rotation_ccw_degrees: 270, }), ]; - let owned = super::decoded_avif_to_rgba_image(&decoded, &transforms, None) - .expect("owned AVIF conversion should succeed"); + let owned = super::decoded_avif_to_rgba_image( + decoded.clone(), + super::HeicColrOverride::default(), + &transforms, + None, + ) + .expect("owned AVIF conversion should succeed"); let expected = match owned.pixels { super::DecodedRgbaPixels::U16(pixels) => pixels, other => panic!("expected RGBA16 pixels, got {other:?}"), }; let mut bytes = vec![0_u8; expected.len() * 2]; - let mut output = super::NativeEndianRgba16Output(&mut bytes); - super::decoded_avif_to_rgba16_output(&decoded, &transforms, &mut output) - .expect("direct AVIF byte conversion should succeed"); + super::decoded_avif_to_rgba16_native_endian_bytes( + decoded, + super::HeicColrOverride::default(), + &transforms, + &mut bytes, + ) + .expect("direct AVIF byte conversion should succeed"); let actual: Vec = bytes .chunks_exact(2) .map(|chunk| u16::from_ne_bytes([chunk[0], chunk[1]]))