use super::SIGNATURE;
use crate::synth;
use crate::{
Association, ChannelDefinition, ChannelType, ColorSpace, ColorSpecification, DecodeOptions,
Error, FileType, Image, ImageHeader, Jp2Metadata, Ratio, Res, Resolution, UuidBox, XmlBox,
decode, decode_with, read_header,
};
use synth::bx;
mod after;
mod channels;
mod matrix;
mod palette;
mod rreq;
mod uuid_info;
const CODESTREAM: &[u8] = include_bytes!("../../tests/fixtures/multicomponent_lossless.j2k");
const WIDTH: u32 = 24;
const HEIGHT: u32 = 16;
const COMPONENTS: u16 = 3;
fn xl_box(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
let mut out = 1u32.to_be_bytes().to_vec();
out.extend_from_slice(kind);
out.extend_from_slice(&(16 + payload.len() as u64).to_be_bytes());
out.extend_from_slice(payload);
out
}
fn open_box(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
let mut out = 0u32.to_be_bytes().to_vec();
out.extend_from_slice(kind);
out.extend_from_slice(payload);
out
}
fn header_only(lbox: u32, kind: &[u8; 4]) -> Vec<u8> {
let mut out = lbox.to_be_bytes().to_vec();
out.extend_from_slice(kind);
out
}
fn xl_header_only(xlbox: u64, kind: &[u8; 4]) -> Vec<u8> {
let mut out = header_only(1, kind);
out.extend_from_slice(&xlbox.to_be_bytes());
out
}
fn ftyp(brand: &[u8; 4], compatible: &[&[u8; 4]]) -> Vec<u8> {
let mut payload = brand.to_vec();
payload.extend_from_slice(&0u32.to_be_bytes()); for code in compatible {
payload.extend_from_slice(*code);
}
bx(b"ftyp", &payload)
}
fn jp2_ftyp() -> Vec<u8> {
ftyp(b"jp2 ", &[b"jp2 "])
}
fn ihdr(height: u32, width: u32, components: u16) -> Vec<u8> {
let mut payload = height.to_be_bytes().to_vec();
payload.extend_from_slice(&width.to_be_bytes());
payload.extend_from_slice(&components.to_be_bytes());
payload.extend_from_slice(&[7, 7, 0, 0]); bx(b"ihdr", &payload)
}
fn good_ihdr() -> Vec<u8> {
ihdr(HEIGHT, WIDTH, COMPONENTS)
}
fn colr() -> Vec<u8> {
bx(b"colr", &[1, 0, 0, 0, 0, 0, 16])
}
fn jp2h(children: &[Vec<u8>]) -> Vec<u8> {
bx(b"jp2h", &children.concat())
}
fn good_jp2h() -> Vec<u8> {
jp2h(&[good_ihdr(), colr()])
}
fn jp2c() -> Vec<u8> {
bx(b"jp2c", CODESTREAM)
}
fn file(boxes: &[Vec<u8>]) -> Vec<u8> {
let mut out = SIGNATURE.to_vec();
out.extend_from_slice(&boxes.concat());
out
}
fn minimal() -> Vec<u8> {
file(&[jp2_ftyp(), good_jp2h(), jp2c()])
}
fn raw() -> Image {
decode(CODESTREAM).expect("the fixture codestream decodes")
}
#[track_caller]
fn assert_decodes_like_raw(bytes: &[u8]) {
let image = decode(bytes).unwrap_or_else(|e| panic!("JP2 decode failed: {e}"));
let raw = raw();
assert_eq!((image.width, image.height), (raw.width, raw.height));
assert_eq!(image.components, raw.components);
assert!(image.jp2.is_some(), "a JP2 file carries metadata");
}
#[track_caller]
fn file_format(bytes: &[u8], fragment: &str) {
match decode(bytes) {
Err(Error::FileFormat(message)) => assert!(
message.message().contains(fragment),
"expected a FileFormat error mentioning {fragment:?}, got {message:?}"
),
other => panic!("expected FileFormat mentioning {fragment:?}, got {other:?}"),
}
}
#[track_caller]
fn incomplete(bytes: &[u8], fragment: &str) {
match decode(bytes) {
Err(Error::Incomplete(message)) => assert!(
message.message().contains(fragment),
"expected an Incomplete error mentioning {fragment:?}, got {message:?}"
),
other => panic!("expected Incomplete mentioning {fragment:?}, got {other:?}"),
}
}
#[track_caller]
fn unsupported(bytes: &[u8], fragment: &str) {
match decode(bytes) {
Err(Error::Unsupported(message)) => assert!(
message.message().contains(fragment),
"expected an Unsupported error mentioning {fragment:?}, got {message:?}"
),
other => panic!("expected Unsupported mentioning {fragment:?}, got {other:?}"),
}
}
fn xml_payloads(metadata: &Jp2Metadata) -> Vec<&[u8]> {
metadata.xml.iter().map(|x| x.payload.as_slice()).collect()
}
#[test]
fn the_fixture_is_what_the_tests_assume() {
let raw = raw();
assert_eq!((raw.width, raw.height), (WIDTH, HEIGHT));
assert_eq!(raw.components.len(), usize::from(COMPONENTS));
assert_eq!(raw.jp2, None, "a raw codestream carries no JP2 metadata");
}
#[test]
fn a_minimal_jp2_decodes_to_its_codestream() {
assert_decodes_like_raw(&minimal());
}
#[test]
fn a_jp2_decode_carries_the_metadata_skeleton() {
let image = decode(&minimal()).expect("decodes");
let color = |n| ChannelDefinition {
kind: ChannelType::Color,
association: Association::Color(n),
};
assert_eq!(
image.jp2,
Some(Jp2Metadata {
color: ColorSpace::Srgb,
channels: vec![color(1), color(2), color(3)],
palette_applied: false,
palette: None,
channel_mapping: None,
channel_definitions: None,
resolution: Resolution::default(),
xml: Vec::new(),
uuid: Vec::new(),
ipr: Vec::new(),
uuid_info: Vec::new(),
image_header: ImageHeader {
compression: 7,
unknown_color_space: 0,
ipr_flag: 0,
},
color_specifications: vec![ColorSpecification {
method: 1,
precedence: 0,
approximation: 0,
payload: vec![0, 0, 0, 16],
}],
file_type: FileType {
brand: *b"jp2 ",
minor_version: 0,
compatibility: vec![*b"jp2 "],
},
reader_requirements: None,
})
);
}
#[test]
fn a_jp2c_with_a_64_bit_length_decodes() {
assert_decodes_like_raw(&file(&[
jp2_ftyp(),
good_jp2h(),
xl_box(b"jp2c", CODESTREAM),
]));
}
#[test]
fn a_reduced_decode_of_a_jp2_matches_its_codestream() {
let options = DecodeOptions::default().with_resolution_reduction(1);
let file = decode_with(&minimal(), &options).expect("reduced JP2 decode");
let raw = decode_with(CODESTREAM, &options).expect("reduced codestream decode");
assert_eq!((file.width, file.height), (raw.width, raw.height));
assert_eq!((file.width, file.height), (WIDTH / 2, HEIGHT / 2));
assert_eq!(file.components, raw.components);
assert!(file.jp2.is_some());
}
#[test]
fn a_last_jp2c_with_length_zero_decodes() {
assert_decodes_like_raw(&file(&[
jp2_ftyp(),
good_jp2h(),
open_box(b"jp2c", CODESTREAM),
]));
}
#[test]
fn unknown_and_repeated_boxes_are_skipped() {
assert_decodes_like_raw(&file(&[
jp2_ftyp(),
bx(b"xml ", b"<a/>"),
xl_box(b"uuid", &[0; 20]),
jp2h(&[good_ihdr(), bx(b"zzzz", b"unknown"), colr(), ihdr(1, 1, 1)]),
bx(b"xml ", b"<b/>"),
jp2c(),
]));
}
#[test]
fn bytes_after_the_codestream_that_openjpeg_accepts_decode() {
let tails: Vec<(&str, Vec<u8>)> = vec![
("a second jp2c", bx(b"jp2c", b"not a codestream")),
(
"a bad length after a second jp2c, which ends the walk",
[bx(b"jp2c", b"zz"), header_only(3, b"junk")].concat(),
),
("a box past the end of the file", header_only(100, b"junk")),
(
"a bad length after a box past the end",
[header_only(100, b"junk"), header_only(3, b"junk")].concat(),
),
("ASCII text", b"hello, trailing text\n".to_vec()),
("three bytes", b"abc".to_vec()),
("seven zero bytes", vec![0; 7]),
("sixteen zero bytes (LBox 0)", vec![0; 16]),
("LBox 0", [header_only(0, b"junk"), b"zz".to_vec()].concat()),
(
"a truncated XLBox field",
[header_only(1, b"junk"), vec![0; 3]].concat(),
),
("a well-formed box", bx(b"xml ", b"<after/>")),
];
for (what, tail) in tails {
let mut bytes = minimal();
bytes.extend_from_slice(&tail);
let image = decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(image.components, raw().components, "{what}");
}
}
#[test]
fn a_short_box_length_after_the_codestream_is_rejected() {
for lbox in 2..=7 {
let mut bytes = minimal();
bytes.extend_from_slice(&header_only(lbox, b"junk"));
file_format(&bytes, "after the codestream has length");
}
for xlbox in [0, 8, 15] {
let mut bytes = minimal();
bytes.extend_from_slice(&xl_header_only(xlbox, b"junk"));
file_format(&bytes, "after the codestream has `XLBox`");
}
let mut bytes = minimal();
bytes.extend_from_slice(&bx(b"xml ", b"<a/>"));
bytes.extend_from_slice(&xl_box(b"uuid", &[0; 8]));
bytes.extend_from_slice(&header_only(3, b"junk"));
file_format(&bytes, "after the codestream has length 3");
}
#[test]
fn jp2_compatibility_in_brand_or_list_is_enough() {
assert_decodes_like_raw(&file(&[
ftyp(b"jpx ", &[b"jpx ", b"jp2 "]),
good_jp2h(),
jp2c(),
]));
assert_decodes_like_raw(&file(&[ftyp(b"jp2 ", &[]), good_jp2h(), jp2c()]));
}
#[test]
fn jph_compatibility_in_brand_or_list_is_enough() {
for bytes in [
file(&[ftyp(b"jph ", &[b"jph "]), good_jp2h(), jp2c()]),
file(&[ftyp(b"jph ", &[]), good_jp2h(), jp2c()]),
file(&[ftyp(b"jpx ", &[b"jpx ", b"jph "]), good_jp2h(), jp2c()]),
] {
assert_decodes_like_raw(&bytes);
}
let image = decode(&file(&[ftyp(b"jph ", &[b"jph "]), good_jp2h(), jp2c()])).unwrap();
let file_type = &image.jp2.as_ref().expect("metadata").file_type;
assert_eq!(file_type.brand, *b"jph ");
assert_eq!(file_type.compatibility, [*b"jph "]);
}
#[test]
fn a_jpx_jpm_or_mj2_without_jp2_or_jph_compatibility_is_unsupported() {
let refused: [(&[u8; 4], &[&[u8; 4]]); 6] = [
(b"jpx ", &[b"jpx ", b"jpxb"]),
(b"jpm ", &[b"jpm "]),
(b"mjp2", &[b"mjp2", b"mj2s"]),
(b"jph2", &[b"jp2h"]),
(b"JPH ", &[b"JP2 "]),
(b"jph\0", &[b"jp2\0"]),
];
for (brand, compatibility) in refused {
unsupported(
&file(&[ftyp(brand, compatibility), good_jp2h(), jp2c()]),
"without `jp2 ` or `jph ` compatibility (a JPX, JPM or MJ2 file",
);
}
}
#[test]
fn a_palette_box_decodes() {
let image = decode(&file(&[
jp2_ftyp(),
jp2h(&[
good_ihdr(),
palette::pclr_box(),
colr(),
palette::cmap_box(),
]),
jp2c(),
]))
.expect("a palettized file decodes");
palette::assert_palette_applied(&image);
}
#[test]
fn a_palette_box_without_a_component_mapping_box_is_ignored() {
let bytes = file(&[
jp2_ftyp(),
jp2h(&[good_ihdr(), colr(), palette::pclr_box()]),
jp2c(),
]);
assert_decodes_like_raw(&bytes);
assert!(!decode(&bytes).unwrap().jp2.unwrap().palette_applied);
}
#[test]
fn a_channel_definition_box_is_applied() {
let bytes = file(&[
jp2_ftyp(),
jp2h(&[good_ihdr(), colr(), channels::reversed()]),
jp2c(),
]);
channels::assert_reversed(&decode(&bytes).expect("decodes"));
}
#[test]
fn a_box_length_of_1_to_7_is_rejected() {
for lbox in 2..=7 {
let bytes = file(&[jp2_ftyp(), header_only(lbox, b"zzzz"), good_jp2h(), jp2c()]);
file_format(&bytes, "shorter than its 8-byte header");
}
let mut truncated = file(&[jp2_ftyp(), good_jp2h()]);
truncated.extend_from_slice(&header_only(1, b"jp2c"));
truncated.extend_from_slice(&[0, 0, 0]);
incomplete(&truncated, "inside the 16-byte header of box `jp2c`");
}
#[test]
fn an_xlbox_of_zero_or_past_the_end_is_rejected() {
for xlbox in [0, 8, 15] {
let bytes = file(&[
jp2_ftyp(),
xl_header_only(xlbox, b"zzzz"),
good_jp2h(),
jp2c(),
]);
file_format(&bytes, "shorter than its 16-byte header");
}
for xlbox in [16 + 4 + 1, 1 << 40, u64::MAX] {
let mut bytes = file(&[jp2_ftyp(), good_jp2h()]);
bytes.extend_from_slice(&xl_header_only(xlbox, b"xml "));
bytes.extend_from_slice(b"<a/>");
incomplete(
&bytes,
&format!("inside box `xml `, which is {xlbox} bytes, after 20"),
);
}
}
#[test]
fn a_child_box_overrunning_its_superbox_is_rejected() {
let mut children = good_ihdr();
children.extend_from_slice(&header_only(100, b"colr"));
children.extend_from_slice(&colr()[8..]);
file_format(
&file(&[jp2_ftyp(), bx(b"jp2h", &children), jp2c()]),
"remain in the `jp2h` box",
);
}
#[test]
fn a_jp2c_overrunning_the_file_is_clamped_and_decodes() {
let claimed = u32::try_from(8 + CODESTREAM.len() + 100).unwrap();
let mut bytes = file(&[jp2_ftyp(), good_jp2h()]);
bytes.extend_from_slice(&header_only(claimed, b"jp2c"));
bytes.extend_from_slice(CODESTREAM);
assert_decodes_like_raw(&bytes);
for xlbox in [16 + CODESTREAM.len() as u64 + 1, 1 << 40, u64::MAX] {
let mut bytes = file(&[jp2_ftyp(), good_jp2h()]);
bytes.extend_from_slice(&xl_header_only(xlbox, b"jp2c"));
bytes.extend_from_slice(CODESTREAM);
assert_decodes_like_raw(&bytes);
}
}
#[test]
fn a_clamped_jp2c_with_a_truncated_codestream_is_still_rejected() {
let cut = &CODESTREAM[..CODESTREAM.len() - 40];
let mut bytes = file(&[jp2_ftyp(), good_jp2h()]);
bytes.extend_from_slice(&header_only(
u32::try_from(8 + CODESTREAM.len()).unwrap(),
b"jp2c",
));
bytes.extend_from_slice(cut);
assert!(
matches!(decode(&bytes), Err(Error::Codestream(_))),
"{:?}",
decode(&bytes)
);
}
#[test]
fn an_ihdr_after_other_header_boxes_decodes() {
assert_decodes_like_raw(&file(&[
jp2_ftyp(),
jp2h(&[colr(), bx(b"zzzz", b"?"), good_ihdr()]),
jp2c(),
]));
}
#[test]
fn a_second_jp2h_is_merged_into_the_first() {
let bytes = file(&[
jp2_ftyp(),
good_jp2h(),
jp2h(&[ihdr(1, 1, 1), bx(b"colr", &[1, 0, 0, 0, 0, 0, 17])]),
jp2c(),
]);
assert_decodes_like_raw(&bytes);
let parsed = super::parse(&bytes, &crate::WorkLimit::Default).expect("parses");
assert_eq!(parsed.header.ihdr.width, WIDTH, "the first ihdr wins");
assert_eq!(parsed.header.colr().len(), 2, "both colr boxes, in order");
assert_eq!(parsed.header.colr()[0], &colr()[8..]);
}
#[test]
fn a_cdef_in_a_second_jp2h_or_after_jp2h_is_applied() {
let cdef = channels::reversed();
let in_second_jp2h = file(&[
jp2_ftyp(),
good_jp2h(),
jp2h(&[good_ihdr(), cdef.clone()]),
jp2c(),
]);
channels::assert_reversed(&decode(&in_second_jp2h).expect("decodes"));
let after_jp2h = file(&[jp2_ftyp(), good_jp2h(), cdef, jp2c()]);
channels::assert_reversed(&decode(&after_jp2h).expect("decodes"));
}
#[test]
fn palette_boxes_in_a_second_jp2h_or_after_jp2h_are_applied() {
let (pclr, cmap) = (palette::pclr_box(), palette::cmap_box());
let shapes = [
(
"both in a second jp2h",
file(&[
jp2_ftyp(),
good_jp2h(),
jp2h(&[good_ihdr(), pclr.clone(), cmap.clone()]),
jp2c(),
]),
),
(
"pclr in jp2h, cmap in a second jp2h",
file(&[
jp2_ftyp(),
jp2h(&[good_ihdr(), colr(), pclr.clone()]),
jp2h(&[good_ihdr(), cmap.clone()]),
jp2c(),
]),
),
(
"both after jp2h",
file(&[jp2_ftyp(), good_jp2h(), pclr.clone(), cmap.clone(), jp2c()]),
),
(
"pclr in jp2h, cmap after it",
file(&[
jp2_ftyp(),
jp2h(&[good_ihdr(), colr(), pclr.clone()]),
cmap.clone(),
jp2c(),
]),
),
];
for (what, bytes) in shapes {
let image = decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
palette::assert_palette_applied(&image);
}
}
#[test]
fn header_boxes_misplaced_before_jp2h_are_ignored() {
let bytes = file(&[
jp2_ftyp(),
bx(b"cdef", &[0, 0]),
bx(b"pclr", &[0; 8]),
bx(b"cmap", &[0; 4]),
bx(b"colr", &[1, 0, 0, 0, 0, 0, 17]),
good_jp2h(),
jp2c(),
]);
assert_decodes_like_raw(&bytes);
let parsed = super::parse(&bytes, &crate::WorkLimit::Default).expect("parses");
assert_eq!(parsed.header.colr(), vec![&colr()[8..]]);
assert_eq!(parsed.other.len(), 4);
}
#[test]
fn every_header_colr_is_reported_in_file_order() {
let colr_with = |head: [u8; 3], data: &[u8]| bx(b"colr", &[&head[..], data].concat());
let bytes = file(&[
jp2_ftyp(),
colr_with([1, 9, 9], &[0, 0, 0, 18]),
jp2h(&[
colr_with([3, 1, 2], &[0xAB]),
good_ihdr(),
colr_with([1, 0, 0], &[0, 0, 0, 17]),
]),
jp2h(&[good_ihdr(), colr_with([2, 4, 5], b"icc")]),
colr_with([1, 6, 7], &[0, 0, 0, 21, 0xFF]),
jp2c(),
colr_with([1, 8, 8], &[0, 0, 0, 16]),
]);
assert_decodes_like_raw(&bytes);
let jp2 = decode(&bytes).unwrap().jp2.unwrap();
assert_eq!(read_header(&bytes).unwrap().jp2.as_ref(), Some(&jp2));
assert_eq!(jp2.color, ColorSpace::Grayscale);
let spec = |[method, precedence, approximation]: [u8; 3], payload: &[u8]| ColorSpecification {
method,
precedence,
approximation,
payload: payload.to_vec(),
};
assert_eq!(
jp2.color_specifications,
[
spec([3, 1, 2], &[0xAB]),
spec([1, 0, 0], &[0, 0, 0, 17]),
spec([2, 4, 5], b"icc"),
spec([1, 6, 7], &[0, 0, 0, 21, 0xFF]),
]
);
}
#[test]
fn a_structural_fault_wins_over_a_malformed_cdef() {
let with_cdef = |ihdr_box: Vec<u8>, stream: &[u8]| {
file(&[
jp2_ftyp(),
jp2h(&[ihdr_box, colr(), bx(b"cdef", &[0, 0])]),
bx(b"jp2c", stream),
])
};
file_format(
&with_cdef(ihdr(1, 1, 1), CODESTREAM),
"`ihdr` declares a 1x1 image",
);
assert!(matches!(
decode(&with_cdef(good_ihdr(), b"not a codestream")),
Err(Error::Codestream(_))
));
}
#[test]
fn reject_matrix_maps_every_malformed_box_shape_to_its_typed_error() {
let ihdr_payload = good_ihdr()[8..].to_vec();
let rows: Vec<(&str, Vec<u8>, &str)> = vec![
(
"signature box with the wrong contents",
{
let mut bytes = minimal();
bytes[11] = 0x0B;
bytes
},
"signature box",
),
(
"signature box one byte too long",
[
bx(b"jP ", &[0x0D, 0x0A, 0x87, 0x0A, 0x00]),
jp2_ftyp(),
good_jp2h(),
jp2c(),
]
.concat(),
"signature box",
),
(
"ftyp not second",
file(&[good_jp2h(), jp2_ftyp(), jp2c()]),
"`ftyp` box must follow the signature, not `jp2h`",
),
(
"ftyp too short",
file(&[bx(b"ftyp", b"jp2 "), good_jp2h(), jp2c()]),
"`ftyp` box holds 4 bytes",
),
(
"ftyp with a partial compatibility code",
file(&[bx(b"ftyp", b"jp2 \0\0\0\0jp2 xx"), good_jp2h(), jp2c()]),
"`ftyp` box holds 14 bytes",
),
(
"no jp2h (signature, ftyp, jp2c)",
file(&[jp2_ftyp(), jp2c()]),
"no `jp2h` header box before its `jp2c`",
),
(
"jp2c before jp2h",
file(&[jp2_ftyp(), jp2c(), good_jp2h()]),
"no `jp2h` header box before its `jp2c`",
),
(
"empty jp2h",
file(&[jp2_ftyp(), jp2h(&[]), jp2c()]),
"`jp2h` box has no `ihdr`",
),
(
"jp2h without ihdr",
file(&[jp2_ftyp(), jp2h(&[colr()]), jp2c()]),
"`jp2h` box has no `ihdr`",
),
(
"a second jp2h without ihdr",
file(&[jp2_ftyp(), good_jp2h(), jp2h(&[colr()]), jp2c()]),
"`jp2h` box has no `ihdr`",
),
(
"ihdr of 13 bytes",
file(&[
jp2_ftyp(),
jp2h(&[bx(b"ihdr", &ihdr_payload[..13]), colr()]),
jp2c(),
]),
"`ihdr` box holds 13 bytes",
),
(
"ihdr of 15 bytes",
file(&[
jp2_ftyp(),
jp2h(&[
bx(b"ihdr", &[ihdr_payload.as_slice(), &[0]].concat()),
colr(),
]),
jp2c(),
]),
"`ihdr` box holds 15 bytes",
),
(
"ihdr width differs from SIZ",
file(&[
jp2_ftyp(),
jp2h(&[ihdr(HEIGHT, WIDTH + 1, COMPONENTS), colr()]),
jp2c(),
]),
"`ihdr` declares a 25x16 image",
),
(
"ihdr height differs from SIZ",
file(&[
jp2_ftyp(),
jp2h(&[ihdr(HEIGHT - 1, WIDTH, COMPONENTS), colr()]),
jp2c(),
]),
"`ihdr` declares a 24x15 image",
),
(
"ihdr NC of 0",
file(&[jp2_ftyp(), jp2h(&[ihdr(HEIGHT, WIDTH, 0), colr()]), jp2c()]),
"none may be 0",
),
(
"ihdr width of 0",
file(&[
jp2_ftyp(),
jp2h(&[ihdr(HEIGHT, 0, COMPONENTS), colr()]),
jp2c(),
]),
"none may be 0",
),
(
"ihdr height of 0",
file(&[
jp2_ftyp(),
jp2h(&[ihdr(0, WIDTH, COMPONENTS), colr()]),
jp2c(),
]),
"none may be 0",
),
(
"ihdr NC over 16384",
file(&[
jp2_ftyp(),
jp2h(&[ihdr(HEIGHT, WIDTH, 16385), colr()]),
jp2c(),
]),
"declares 16385 components",
),
(
"LBox 0 inside jp2h",
file(&[
jp2_ftyp(),
jp2h(&[good_ihdr(), open_box(b"colr", &colr()[8..])]),
jp2c(),
]),
"has length 0",
),
(
"LBox 0 on a box that is not last",
file(&[jp2_ftyp(), open_box(b"xml ", b""), good_jp2h(), jp2c()]),
"a box of length 0 (to the end of the file) swallowed the rest",
),
(
"LBox 2..7 after the codestream",
[minimal(), header_only(5, b"junk")].concat(),
"after the codestream has length 5",
),
(
"XLBox below 16 after the codestream",
[minimal(), xl_header_only(15, b"junk")].concat(),
"after the codestream has `XLBox` 15",
),
(
"a jp2h child header cut short",
file(&[jp2_ftyp(), jp2h(&[good_ihdr(), vec![0, 0, 0, 9]]), jp2c()]),
"a box header needs 8 bytes but 4 remain in the `jp2h` box",
),
];
for (what, bytes, fragment) in rows {
match decode(&bytes) {
Err(Error::FileFormat(message)) => assert!(
message.message().contains(fragment),
"{what}: expected a message mentioning {fragment:?}, got {message:?}"
),
other => panic!("{what}: expected FileFormat, got {other:?}"),
}
}
}
#[test]
fn input_with_neither_magic_is_a_codestream_error() {
for bytes in [
&b"not a codestream"[..],
b"\x00\x00\x00\x0cjQ",
b"\x01",
b"\xFF\x4E",
] {
assert!(
matches!(decode(bytes), Err(Error::Codestream(_))),
"{bytes:?}"
);
}
}
#[test]
fn a_cut_box_is_judged_on_its_type() {
let not_ftyp = file(&[xl_header_only(100, b"jp2h")]);
for length in 20..=not_ftyp.len() {
file_format(
¬_ftyp[..length],
"the `ftyp` box must follow the signature, not `jp2h`",
);
}
let no_jp2h = file(&[jp2_ftyp(), xl_header_only(100, b"jp2c")]);
let jp2c_at = no_jp2h.len() - 16;
for length in jp2c_at + 8..no_jp2h.len() {
file_format(&no_jp2h[..length], "no `jp2h` header box before its `jp2c`");
}
let cut = file(&[jp2_ftyp(), good_jp2h(), header_only(1, b"jp2c")]);
incomplete(&cut, "inside the 16-byte header of box `jp2c`");
}
#[test]
fn a_file_cut_before_its_codestream_is_incomplete() {
let rows: Vec<(&str, Vec<u8>, &str)> = vec![
(
"empty input",
Vec::new(),
"before the codestream's `SOC` marker",
),
(
"one signature byte",
SIGNATURE[..1].to_vec(),
"inside the JP2 signature box",
),
(
"signature box cut short",
SIGNATURE[..6].to_vec(),
"inside the JP2 signature box",
),
(
"signature box but its last byte",
SIGNATURE[..11].to_vec(),
"inside the JP2 signature box",
),
(
"signature box alone",
SIGNATURE.to_vec(),
"ends after the JP2 signature box",
),
(
"ftyp header cut short",
file(&[jp2_ftyp()])[..15].to_vec(),
"inside a box header, after 3 of its 8 bytes",
),
(
"neither jp2h nor jp2c",
file(&[jp2_ftyp()]),
"before the `jp2c` codestream box",
),
(
"no jp2c",
file(&[jp2_ftyp(), good_jp2h()]),
"before the `jp2c` codestream box",
),
(
"a box header cut short before jp2c",
[file(&[jp2_ftyp(), good_jp2h()]), vec![0, 0, 0]].concat(),
"inside a box header, after 3 of its 8 bytes",
),
(
"jp2h cut short",
{
let whole = file(&[jp2_ftyp(), good_jp2h()]);
whole[..whole.len() - 1].to_vec()
},
"inside box `jp2h`",
),
(
"jp2c header and one codestream byte",
[
file(&[jp2_ftyp(), good_jp2h()]),
header_only(0, b"jp2c"),
vec![0xFF],
]
.concat(),
"before the codestream's `SOC` marker",
),
];
for (what, bytes, fragment) in rows {
match decode(&bytes) {
Err(Error::Incomplete(message)) => assert!(
message.message().contains(fragment),
"{what}: expected a message mentioning {fragment:?}, got {message:?}"
),
other => panic!("{what}: expected Incomplete, got {:?}", other.map(|_| ())),
}
}
}
#[test]
fn truncations_and_header_corruptions_never_panic() {
let bytes = minimal();
let codestream_at = bytes.len() - CODESTREAM.len();
for end in 0..bytes.len() {
let _ = decode(&bytes[..end]);
}
for at in 0..codestream_at {
for value in [0x00, 0x01, 0x07, 0x0F, 0x80, 0xFF] {
let mut corrupt = bytes.clone();
corrupt[at] = value;
let _ = decode(&corrupt);
}
}
}
#[test]
fn the_walk_records_header_boxes_and_the_bytes_around_the_codestream() {
let trailing = bx(b"xml ", b"<after/>");
let bytes = file(&[
jp2_ftyp(),
bx(b"xml ", b"<before/>"),
jp2h(&[
good_ihdr(),
colr(),
bx(b"colr", &[3, 0, 0]),
bx(b"bpcc", &[7, 7, 7]),
bx(b"res ", &[1, 2]),
bx(b"zzzz", b"?"),
]),
jp2c(),
trailing.clone(),
]);
let parsed = super::parse(&bytes, &crate::WorkLimit::Default).expect("parses");
let header = &parsed.header;
assert_eq!(
(
header.ihdr.height,
header.ihdr.width,
header.ihdr.components
),
(HEIGHT, WIDTH, COMPONENTS)
);
let first_colr = colr();
assert_eq!(header.colr(), vec![&first_colr[8..], &[3, 0, 0][..]]);
assert_eq!(header.bpcc(), vec![&[7, 7, 7][..]]);
assert_eq!(header.res(), vec![&[1, 2][..]]);
assert!(header.pclr().is_empty() && header.cmap().is_empty() && header.cdef().is_empty());
assert_eq!(header.unknown().len(), 1);
assert_eq!(&header.unknown()[0].kind, b"zzzz");
assert_eq!(parsed.codestream, CODESTREAM);
assert_eq!(parsed.other.len(), 1);
assert_eq!(parsed.other[0].payload, b"<before/>");
assert_eq!(parsed.after_codestream.len(), 1);
assert_eq!(&parsed.after_codestream[0].kind, b"xml ");
assert_eq!(parsed.after_codestream[0].payload, b"<after/>");
}
#[test]
fn an_ihdr_component_count_unlike_csiz_decodes() {
for nc in [1, 2, 4, 9, 16384] {
let bytes = file(&[jp2_ftyp(), jp2h(&[ihdr(HEIGHT, WIDTH, nc), colr()]), jp2c()]);
assert_decodes_like_raw(&bytes);
let header = read_header(&bytes).unwrap_or_else(|e| panic!("NC {nc}: {e}"));
assert_eq!(header.components.len(), usize::from(COMPONENTS), "NC {nc}");
}
let with_bpcc = |nc: u16, bytes: usize| {
file(&[
jp2_ftyp(),
jp2h(&[
ihdr(HEIGHT, WIDTH, nc),
bx(b"bpcc", &vec![7; bytes]),
colr(),
]),
jp2c(),
])
};
assert_decodes_like_raw(&with_bpcc(4, 4));
file_format(&with_bpcc(4, 3), "a `bpcc` box holds 3 bytes");
}
#[test]
fn a_header_fault_wins_over_a_truncated_codestream() {
let truncated = &CODESTREAM[..CODESTREAM.len() - 40];
assert!(matches!(decode(truncated), Err(Error::Codestream(_))));
let with = |children: &[Vec<u8>], wide: bool| {
let width = if wide { WIDTH + 1 } else { WIDTH };
let mut all = vec![ihdr(HEIGHT, width, COMPONENTS), colr()];
all.extend_from_slice(children);
file(&[jp2_ftyp(), jp2h(&all), bx(b"jp2c", truncated)])
};
file_format(&with(&[], true), "`ihdr` declares a 25x16 image");
file_format(
&with(&[bx(b"cmap", &[0, 0, 1, 0])], false),
"a `cmap` box but no `pclr` box",
);
file_format(
&with(&[bx(b"cdef", &[0, 0])], false),
"declares 0 channel definitions",
);
assert!(matches!(
decode(&with(&[], false)),
Err(Error::Codestream(_))
));
}
fn res_box(children: &[Vec<u8>]) -> Vec<u8> {
bx(b"res ", &children.concat())
}
fn res_payload(v: (u16, u16, i8), h: (u16, u16, i8)) -> Vec<u8> {
let mut out = Vec::new();
for value in [v.0, v.1, h.0, h.1] {
out.extend_from_slice(&value.to_be_bytes());
}
out.extend_from_slice(&[v.2 as u8, h.2 as u8]);
out
}
fn ratio(numerator: u16, denominator: u16, exponent: i8) -> Ratio {
Ratio {
numerator,
denominator,
exponent,
}
}
#[test]
fn the_resolution_box_is_read() {
let resc = res_payload((10000, 254, 0), (3, 4, -2));
let resd = res_payload((12901, 32768, 4), (1, 2, 127));
let bytes = file(&[
jp2_ftyp(),
jp2h(&[
good_ihdr(),
colr(),
res_box(&[bx(b"resc", &resc), bx(b"resd", &resd)]),
]),
jp2c(),
]);
assert_decodes_like_raw(&bytes);
let want = Resolution {
capture: Some(Res {
vertical: ratio(10000, 254, 0),
horizontal: ratio(3, 4, -2),
}),
display: Some(Res {
vertical: ratio(12901, 32768, 4),
horizontal: ratio(1, 2, 127),
}),
};
assert_eq!(decode(&bytes).unwrap().jp2.unwrap().resolution, want);
assert_eq!(read_header(&bytes).unwrap().jp2.unwrap().resolution, want);
}
#[test]
fn a_ratio_converts_to_grid_points_per_meter() {
assert_eq!(ratio(3, 4, 2).grid_points_per_meter(), Some(75.0));
assert_eq!(ratio(5, 1, -1).grid_points_per_meter(), Some(0.5));
assert_eq!(ratio(1, 0, 0).grid_points_per_meter(), None);
}
#[test]
fn a_malformed_resolution_box_never_fails_a_decode() {
let good = res_payload((10000, 254, 0), (10000, 254, 0));
let capture = |v| {
Some(Res {
vertical: v,
horizontal: v,
})
};
let dpi = capture(ratio(10000, 254, 0));
let cases: Vec<(&str, Vec<u8>, Resolution)> = vec![
("empty res", res_box(&[]), Resolution::default()),
(
"garbage in res",
bx(b"res ", &[1, 2, 3]),
Resolution::default(),
),
(
"resc of 9 bytes",
res_box(&[bx(b"resc", &good[..9])]),
Resolution::default(),
),
(
"resc of 11 bytes",
res_box(&[bx(b"resc", &[good.as_slice(), &[0]].concat())]),
Resolution::default(),
),
(
"empty resd",
res_box(&[bx(b"resd", &[])]),
Resolution::default(),
),
(
"a child with LBox 3",
bx(b"res ", &[header_only(3, b"resc"), good.clone()].concat()),
Resolution::default(),
),
(
"a child past the end of res",
bx(b"res ", &[header_only(200, b"resc"), good.clone()].concat()),
Resolution::default(),
),
(
"a zero denominator",
res_box(&[bx(b"resc", &res_payload((1, 0, 0), (1, 0, 0)))]),
Resolution {
capture: capture(ratio(1, 0, 0)),
display: None,
},
),
(
"a good resc before a broken child",
res_box(&[bx(b"resc", &good), header_only(3, b"resd")]),
Resolution {
capture: dpi,
display: None,
},
),
(
"a short resc, then a good one",
res_box(&[bx(b"resc", &good[..4]), bx(b"resc", &good)]),
Resolution {
capture: dpi,
display: None,
},
),
(
"two good resc: the first counts",
res_box(&[
bx(b"resc", &good),
bx(b"resc", &res_payload((1, 1, 1), (1, 1, 1))),
]),
Resolution {
capture: dpi,
display: None,
},
),
(
"an unknown child",
res_box(&[bx(b"zzzz", b"?"), bx(b"resd", &good)]),
Resolution {
capture: None,
display: dpi,
},
),
];
for (what, res, want) in cases {
let bytes = file(&[jp2_ftyp(), jp2h(&[good_ihdr(), colr(), res]), jp2c()]);
let image = decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(image.jp2.unwrap().resolution, want, "{what}");
}
}
#[test]
fn a_resolution_box_at_the_top_level_is_not_read() {
let res = res_box(&[bx(b"resc", &res_payload((10000, 254, 0), (10000, 254, 0)))]);
let bytes = file(&[jp2_ftyp(), good_jp2h(), res, jp2c()]);
assert_eq!(
decode(&bytes).unwrap().jp2.unwrap().resolution,
Resolution::default()
);
}
#[test]
fn xml_and_uuid_boxes_are_passed_through_in_file_order() {
let id: [u8; 16] = core::array::from_fn(|i| i as u8);
let other_id = [0xAB; 16];
let bytes = file(&[
jp2_ftyp(),
bx(b"xml ", b"<one/>"),
bx(b"uuid", &[id.as_slice(), b"first"].concat()),
bx(b"uuid", b"too short"),
bx(b"rreq", &[1, 0x80, 0, 0]),
bx(b"asoc", &bx(b"xml ", b"<nested/>")),
jp2h(&[good_ihdr(), colr(), bx(b"xml ", b"<in jp2h/>")]),
xl_box(b"xml ", b"<two/>"),
jp2c(),
bx(b"uuid", &other_id),
bx(b"xml ", b"<three/>"),
]);
assert_decodes_like_raw(&bytes);
let metadata = decode(&bytes).unwrap().jp2.unwrap();
assert_eq!(
metadata
.xml
.iter()
.map(|x| x.payload.as_slice())
.collect::<Vec<_>>(),
[&b"<one/>"[..], b"<two/>", b"<three/>"]
);
assert_eq!(
metadata.uuid,
vec![
UuidBox {
id,
payload: b"first".to_vec(),
},
UuidBox {
id: other_id,
payload: Vec::new(),
},
]
);
assert_eq!(read_header(&bytes).unwrap().jp2, Some(metadata));
}
#[test]
fn boxes_after_the_codestream_are_collected_as_far_as_the_walk_goes() {
let xml = |text: &[u8]| bx(b"xml ", text);
let tails: Vec<(&str, Vec<u8>, usize)> = vec![
("two xml", [xml(b"<a/>"), xml(b"<b/>")].concat(), 2),
(
"an xml past the end of the file",
[xml(b"<a/>"), header_only(100, b"xml ")].concat(),
1,
),
(
"an open-ended xml",
[xml(b"<a/>"), open_box(b"xml ", b"<b/>")].concat(),
2,
),
(
"after a second jp2c",
[xml(b"<a/>"), bx(b"jp2c", b"zz"), xml(b"<b/>")].concat(),
1,
),
(
"three stray bytes",
[xml(b"<a/>"), vec![0, 0, 0]].concat(),
1,
),
];
for (what, tail, count) in tails {
let bytes = [minimal(), tail].concat();
let image = decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(image.jp2.unwrap().xml.len(), count, "{what}");
}
}
#[test]
fn read_header_reads_no_tile_data() {
let sot = CODESTREAM
.windows(2)
.position(|w| w == [0xFF, 0x90])
.expect("the fixture has a tile-part");
let whole = read_header(&minimal()).expect("header");
let jp2c_at = minimal().len() - CODESTREAM.len();
for cut in [sot + 2, sot + 6, sot + 20, CODESTREAM.len() - 1] {
let bytes = file(&[jp2_ftyp(), good_jp2h(), bx(b"jp2c", &CODESTREAM[..cut])]);
assert_eq!(
crate::error::keyed(read_header(&bytes)),
Ok(whole.clone()),
"cut at {cut}"
);
assert!(decode(&bytes).is_err(), "cut at {cut}");
let clamped = &minimal()[..jp2c_at + cut];
assert_eq!(
crate::error::keyed(read_header(clamped)),
Ok(whole.clone()),
"clamped at {cut}"
);
let raw = read_header(&CODESTREAM[..cut]).expect("raw header");
assert_eq!(
(raw.width, raw.height, &raw.components),
(whole.width, whole.height, &whole.components)
);
}
assert!(matches!(
read_header(&CODESTREAM[..sot]),
Err(Error::Incomplete(_))
));
}
#[test]
fn default_labels_stop_at_the_color_spaces_count() {
let icc = |space: &[u8; 4]| {
let mut profile = vec![0u8; 128];
profile[16..20].copy_from_slice(space);
ColorSpace::RestrictedIcc(profile)
};
let enumerated = [
(0, 1),
(1, 3),
(3, 3),
(4, 3),
(9, 3),
(11, 3),
(12, 4),
(13, 4),
(14, 3),
(15, 1),
(19, 3),
(20, 3),
(21, 3),
(22, 3),
(23, 3),
(24, 3),
];
let mut cases = vec![
(ColorSpace::Srgb, 3),
(ColorSpace::Sycc, 3),
(ColorSpace::Grayscale, 1),
(icc(b"GRAY"), 1),
(icc(b"RGB "), 3),
(icc(b"YCbr"), 3),
(icc(b"CMYK"), 4),
(icc(b"2CLR"), 2),
(icc(b"5CLR"), 5),
(icc(b"9CLR"), 9),
(icc(b"ACLR"), 10),
(icc(b"FCLR"), 15),
];
cases.extend(
enumerated
.iter()
.map(|&(value, n)| (ColorSpace::Enumerated(value), n)),
);
for (space, colors) in cases {
let labels = super::color_channels(6, &space).unwrap();
for (i, label) in labels.iter().enumerate() {
let want = if i < colors {
(ChannelType::Color, Association::Color(i as u16 + 1))
} else {
(ChannelType::Unspecified, Association::None)
};
assert_eq!(
(label.kind, label.association),
want,
"{space:?} channel {i}"
);
}
}
for (space, want) in [
(icc(b"9CLR"), Some(9)),
(icc(b"ACLR"), Some(10)),
(icc(b"FCLR"), Some(15)),
(icc(b"aCLR"), None),
(icc(b"fCLR"), None),
(icc(b"GCLR"), None),
(icc(b"0CLR"), None),
(icc(b"1CLR"), None),
] {
assert_eq!(super::color_count(&space), want, "{space:?}");
}
for space in [
ColorSpace::Unknown,
ColorSpace::Enumerated(2),
ColorSpace::Enumerated(5),
ColorSpace::Enumerated(10),
ColorSpace::Enumerated(25),
ColorSpace::Enumerated(99),
ColorSpace::RestrictedIcc(Vec::new()),
icc(b"0CLR"),
icc(b"1CLR"),
icc(b"aCLR"),
icc(b"fCLR"),
icc(b"GCLR"),
] {
let labels = super::color_channels(6, &space).unwrap();
assert!(
labels.iter().all(|l| l.kind == ChannelType::Color),
"{space:?}"
);
}
}