Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<DecodedAvifImage, DecodeAvifError>`
- `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<Vec<u8>, DecodeHeicError>`
- `decode_primary_heic_to_image(input)` -> `Result<DecodedHeicImage, DecodeHeicError>`
- `decode_primary_heic_to_metadata(input)` -> `Result<DecodedHeicImageMetadata, DecodeHeicError>`
Expand Down Expand Up @@ -263,21 +268,24 @@ 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.
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.
Expand Down
30 changes: 21 additions & 9 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 \
Expand Down Expand Up @@ -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
Expand Down
63 changes: 55 additions & 8 deletions scripts/incremental/generate.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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, {}],
Expand Down Expand Up @@ -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
}
Expand Down
80 changes: 54 additions & 26 deletions scripts/incremental/wrap.rb
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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|
Expand All @@ -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|
Expand Down
20 changes: 20 additions & 0 deletions src/geometry_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading