diff --git a/CHANGELOG.md b/CHANGELOG.md index a5bc8ff0..648f1597 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -83,8 +83,10 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). can no longer build a `ColorSpace::RestrictedIcc`: match on it and read the profile (#769). - `Jp2Metadata::xml`, `uuid`, `ipr`, `uuid_info` and `color_specifications`, - and `ReaderRequirements::standard_features` and `vendor_features`, are a - `MetadataList`, not a `Vec`. A clone shares its items, so + `ReaderRequirements::standard_features` and `vendor_features`, + `FileType::compatibility` and `UuidInfo::ids` are a `MetadataList`, not a + `Vec`, and `Jp2Metadata::channel_definitions` is an + `Option>`. A clone shares its items, so `IncrementalDecoder::header` reads only the boxes fed since the last call. It is not a slice, so `&list[..]` and slice methods do not work: use `.iter()`, `for item in &list`, or `for item in list` (a @@ -94,7 +96,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). to a slice, `Vec` or array of the same items, either way round. It has no public constructor but `Default`, an empty list. It cannot be changed in place: assign `Default::default()` to empty it, or edit a `.to_vec()` (#769, - #780, #783). + #780, #783, #786). - `IncrementalDecoder::header` leaves out of the metadata a last box of length 0 after the codestream of a type the metadata reports (`xml `, `uuid`, `jp2i`, `uinf`, `rreq`), as more bytes can still change it. `finish`, @@ -250,6 +252,30 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). which copied it in 4.9 ms, takes about 2 µs. Its entries hold at most about 4.6 MiB, so the metadata holds up to about 3.2 bytes for each byte of metadata boxes and about 4.6 MiB more for the first `rreq` (#783). +- The `ftyp`, `pclr`, `cmap` and `cdef` boxes and the `uinf` UUIDs are read + once too, and a later header shares them. Each was read twice by a read of + the file, once for the checks and once for the metadata, and copied by each + `header` call. A 4 MiB `ftyp` peaked at 2.0 bytes of heap for each byte of + it and now peaks at 1.16, what it holds; a 65535-entry `cdef` 3.4 and now + 1.8; a 1024 x 255 `pclr` 8.2 and now 4.3. A `header` call with nothing new + fed copied each again, 4.9 ms and 8.4 MB of heap for the `ftyp`, and now + allocates about 1 KiB. It still checks the boxes before the codestream, + which takes 0.5 ms for the `ftyp` or the `cdef` and 24 µs for the `pclr`, + where it took 4.9, 1.0 and 1.6 ms. A palette holds 4 bytes + for each entry of a column, at most about 1 MiB, so the metadata holds up + to about 3.2 bytes for each byte of metadata boxes, about 4.6 MiB more for + the first `rreq` and about 1 MiB more for a palette (#786). +- While the codestream is fed, each `IncrementalDecoder::header` call shares + what the boxes before it built, where it built them again: on a file of + 4.8 MB of header boxes with an 8 MiB tile-part fed 4 KiB at a time, a call + took 2.0 ms and allocated 6.5 MB, and 200 headers held 690 MB; now 0.34 ms + and 1.8 KB, and 2.5 MB. A call keeps no record of the boxes before the + codestream the metadata reports, and builds no name for a box it walks: + 100000 empty `xml ` boxes there took 6.4 ms and 7.1 MB a call, and now take + 0.89 ms and allocate nothing for them. Under `ColorOutput::Srgb`, the + decoder keeps what it read of an ICC profile and the transform it built, + so a later call builds neither again: it took 0.8 to 11 ms and 52 to 281 + KB on the conformance files, and now 2 to 3 µs and about 2 KB (#786). - `cargo test` on the unpacked package now runs the part of each mixed fixture test that uses the files the package ships, and skips only the entries it leaves out. A test that reads only left-out files still skips whole. diff --git a/README.md b/README.md index 19a2d2ed..6798ebd9 100644 --- a/README.md +++ b/README.md @@ -245,8 +245,8 @@ has the value R, which is how eccodes and NCEP's g2clib read it. Every failure comes back as an `Error`. With the default limits, decoding never panics or hangs, whatever the input, and needs at most about 6.4 GiB of memory for an input of up to 64 MiB, or about 102 bytes per byte of input past that, -plus up to about 3.2 bytes for each byte of JP2 metadata boxes and about 4.6 -MiB more for the first `rreq`. If the machine +plus up to about 3.2 bytes for each byte of JP2 metadata boxes, about 4.6 +MiB more for the first `rreq` and about 1 MiB more for a palette. If the machine can't supply that, the allocation fails and the process aborts, as in any Rust program. Those figures cover the one-shot decode functions; `IncrementalDecoder` keeps per-tile state and can hold one decode's peak plus diff --git a/SECURITY.md b/SECURITY.md index 80418e72..b5aacb6d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -46,8 +46,8 @@ the setters) return either a result or a typed `Error` for any input. They never panic, read out of bounds or hang, and they allocate at most what the limits allow. For the one-shot functions that is about 6.4 GiB at peak for an input of up to 64 MiB, and about 102 bytes per byte of input past that, plus -up to about 3.2 bytes for each byte of JP2 metadata boxes and about 4.6 MiB -more for the first `rreq` (step 1 of [Running a decode +up to about 3.2 bytes for each byte of JP2 metadata boxes, about 4.6 MiB +more for the first `rreq` and about 1 MiB more for a palette (step 1 of [Running a decode service](#running-a-decode-service)). An `IncrementalDecoder` holds one decode's peak plus the packet walks it keeps, at most twice the image's samples plus twice the walk of the largest tile walked so far, plus up to @@ -68,14 +68,14 @@ docs](https://docs.rs/rust-j2k/latest/rust_j2k/fn.decode.html)). A file that spends its bytes on code-block segments peaks past 43 with square tiles too: a 96 MB file of one such tile after 39 tiles of samples peaked at about 77 bytes per byte. About 102 is the bound for any file, plus up to -about 3.2 for each byte of JP2 metadata boxes and about 4.6 MiB more for -the first `rreq`. Padding counts as input, even in +about 3.2 for each byte of JP2 metadata boxes, about 4.6 MiB more for +the first `rreq` and about 1 MiB more for a palette. Padding counts as input, even in a conformant file (`COM` segments, a JP2 `xml ` box, bytes after `EOC`), and it compresses well: 67 MB of zeros gzips to 65 KB. Bound the input's size (step 1 of [Running a decode service](#running-a-decode-service)). Past 64 MiB the worst-case peak is about 102 times that size, plus up to about 3.2 bytes for each byte of JP2 metadata boxes, about 4.6 MiB more for the first -`rreq`, and, for an `IncrementalDecoder`, one decode's peak plus the packet +`rreq`, about 1 MiB more for a palette, and, for an `IncrementalDecoder`, one decode's peak plus the packet walks it keeps and the bytes fed (see below). A one-tile 1 x 2^30 image followed by 128 MiB of zeros after `EOC` (134,283,241 bytes) decodes at the defaults (`strict` on) in 23.5 s with a peak RSS of 8.30 GiB, measured. The @@ -105,10 +105,10 @@ its calls, `header` also holds: - once a call has walked the tile-parts for the decode's error, that walk's heap: up to 14 bytes a tile of the grid, and the coding of each tile that later tile-parts restate with headers that differ; -- in a JP2 file, the walks past the boxes before the codestream, 1424 bytes +- in a JP2 file, the walks past the boxes before the codestream, 2448 bytes and up to four error messages. Of a box after the codestream it holds nothing but, for a last box of length 0, a fixed record of where its read - stopped, 152 of those 1424 bytes, and, for a box the metadata reports, a + stopped, 152 of those 2448 bytes, and, for a box the metadata reports, a 24-byte record until the box is in the lists below; - in a JP2 file, the boxes the metadata reports (`xml `, `uuid`, `jp2i`, `uinf`, the first `rreq`), each read once and shared by every later @@ -120,10 +120,18 @@ its calls, `header` also holds: ones, and 2.4 for 24-byte ones fed one box a call. The first `rreq` holds an entry of 32 or 40 bytes (24 or 36 on a 32-bit target) for each feature, at most about 4.6 MiB more, read once and shared the same way; +- in a JP2 file, the `ftyp` codes (4 bytes each), the `cdef` entries (10 + bytes each) and the palette (4 bytes for each entry of a column, at most + about 1 MiB), read once and shared the same way; - in a JP2 file, the `colr` list (`jp2::Lists::colr`, a `MetadataList`): an entry of 32 bytes (24 on a 32-bit target) for each `colr` box before the codestream, so bounded by the header boxes there, with its payload held as - above. + above; +- in a JP2 file decoded under `ColorOutput::Srgb` with an ICC profile, what + the plan read of the profile and built from it, kept so that a later call + builds none of it again: its curves and a transform for each output + format, at most three, of 50 to 400 KB each, until a call plans another + profile. The `IncrementalDecoder::header` rustdoc gives each of these in full (see also "Work and memory" in @@ -168,7 +176,8 @@ service](docs/resource-bounds.md#figures-for-a-decode-service). through the decode and after it, measured (a `jp2c` box longer than its codestream makes the boxes after it walked twice, which adds time but no records). The first `rreq` keeps an entry for each of its features, up - to about 4.6 MiB more, which it also peaks at. A box before the + to about 4.6 MiB more, which it also peaks at, and a palette 4 bytes for + each entry of a column, up to about 1 MiB more. A box before the codestream that is neither read nor reported holds nothing (see "JP2 box records" in [`docs/resource-bounds.md`](docs/resource-bounds.md)). 2. **Set a fixed sample ceiling.** Set `DecodeOptions::sample_limit` to diff --git a/docs/incremental-decoding.md b/docs/incremental-decoding.md index 4d7f7b64..ffefd2a7 100644 --- a/docs/incremental-decoding.md +++ b/docs/incremental-decoding.md @@ -406,7 +406,18 @@ file (4.4 to 5.0 s before, when each call copied it), and a million 8-byte (about 7 s before, when each call built the lists of every box so far). So a call costs the main header (`PPM` data included), the boxes before the codestream, and the child of a last `jp2h` of length 0 that the input ends -inside, plus the tile-parts, boxes and children fed since. While the bytes fed +inside, plus the tile-parts, boxes and children fed since. The lists as the +boxes before the codestream left them, with the `ftyp`, the palette and the +`cdef`, are kept apart (`jp2::Walks::before`) for as long as the `jp2c` box +starts at the same place, so the walk after the codestream, which starts +again on each call while the codestream's end is not yet fed, starts from +them and reads only the boxes after it. The walk of the boxes before the +codestream runs on each call to check them, about 9 ns a box at the top +level with nothing allocated for them, and a 24-byte record for each child +of a `jp2h` for the length of the call. Under `ColorOutput::Srgb` the +decoder also keeps what the plan read of an ICC profile and the transform it +built (`jp2::IccMemo`), at most three transforms of 50 to 400 KB, until a +call plans another profile. `docs/resource-bounds.md` gives the figures. While the bytes fed end before the main header is whole, a call goes on from where the last one stopped instead, in `pipeline::header::KeptCut`: after the last whole box before a JP2 file's `jp2c`, and after the main header's last whole marker @@ -448,7 +459,7 @@ finds where it ends is kept with it (`HeaderCache::end`), a few dozen bytes, over a change of options. What it keeps of the tiles is for one selected area and reduction, and a change of options drops it. The JP2 walks are kept from the first call on a JP2 file, a change of options included, for as long as the -decoder lives: 1424 bytes (`size_of::()`) and up to four error +decoder lives: 2448 bytes (`size_of::()`) and up to four error messages, plus the reported boxes in `jp2::Lists`. The walk lets go of the record of a box once the lists hold it. Each box is an entry of 24 bytes (40 for a `uuid`, 56 for a `uinf`; on a 32-bit target 20, and 36 for both), a @@ -457,14 +468,17 @@ allocation shared with the payloads read in the same call, behind a 16-byte header (8 on a 32-bit target). The first `rreq` is an entry for each of its features, 32 bytes for a standard one and 40 for a vendor one (24 and 36 on a 32-bit target), with its masks held as payloads are, so it keeps at most about -4.6 MiB more. So the lists keep at most about 3 bytes for each byte of the +4.6 MiB more. The lists also keep the `ftyp` codes (4 bytes each), the +`cdef` entries (10 bytes each) and the palette (4 bytes for each entry of a +column, at most about 1 MiB more), read once by the first call that finds the +`jp2c` box, as the boxes before it are then fixed. So the lists keep at most about 3 bytes for each byte of the other boxes fed, whatever the pieces: a million 8-byte `xml ` boxes after the codestream keep 25.8 MB, 3.1 bytes for each byte of them, and a million of 9 bytes 2.7, fed 4 KiB or one box at a time; a million 24-byte `xml ` boxes keep 1.7 fed 4 KiB at a time and 2.4 fed one box at a time (counted by a test allocator over the bytes fed, release build, at a 1-minute load of about 9). -Each header returned shares the lists, and holds 48 bytes of its own for them. -A call with nothing new fed peaks at 692 bytes allocated, with 2^17 + 319 +Each header returned shares the lists, and holds 44 bytes of its own for them. +A call with nothing new fed peaks at 688 bytes allocated, with 2^17 + 319 boxes of each type kept, so that every list has blocks and a tail (`tests/incremental_header_list_alloc.rs`). diff --git a/docs/resource-bounds.md b/docs/resource-bounds.md index d65724b2..5def596e 100644 --- a/docs/resource-bounds.md +++ b/docs/resource-bounds.md @@ -223,7 +223,8 @@ A tiled image peaks lower, as each tile is reconstructed in turn, and a one-tile image is also held to the code-blocks and precincts a tile allows ([Code-blocks and precincts per tile](#code-blocks-and-precincts-per-tile)), which grow with the limit. JP2 metadata boxes add up to about 3.2 bytes for -each byte of them, and the first `rreq` about 4.6 MiB more (see [JP2 box +each byte of them, the first `rreq` about 4.6 MiB more and a palette about 1 +MiB more (see [JP2 box records](#jp2-box-records)). An `IncrementalDecoder` can hold one decode's peak plus the packet walks it keeps, at most twice the image's samples plus twice the walk of the largest @@ -245,7 +246,8 @@ counted are the bytes in memory, not on the wire, and padding compresses well: 67 MB of zeros gzips to 65 KB. So a service should bound the input size it accepts, measured after any decompression. Past 64 MiB the worst-case peak is about 102 times that size, plus up to about 3.2 bytes for each byte of JP2 -metadata boxes, about 4.6 MiB more for the first `rreq`, and, for an +metadata boxes, about 4.6 MiB more for the first `rreq`, about 1 MiB more for +a palette, and, for an `IncrementalDecoder`, one decode's peak plus the packet walks it keeps and the bytes fed (see below). A one-tile 1 x 2^30 image needs 128 MiB of input to fit the default. Measured: with 128 MiB of zeros @@ -287,8 +289,9 @@ service](#figures-for-a-decode-service)). So below about 2^26 the records, not the samples, set the peak. The figure to plan on is 3.2 x 4n for the samples, plus about 0.8 GiB for one tile's records, plus up to about 65 bytes for each byte of input for [segment records](#segment-records), plus up to about 3.2 -bytes for each byte of JP2 metadata boxes and about 4.6 MiB more for the -first `rreq` ([JP2 box records](#jp2-box-records)), plus the input. The +bytes for each byte of JP2 metadata boxes, about 4.6 MiB more for the +first `rreq` and about 1 MiB more for a palette ([JP2 box +records](#jp2-box-records)), plus the input. The measured peaks against `n` are in that section. An `IncrementalDecoder` can hold one decode's peak plus the packet walks it keeps, at most twice the image's samples plus twice the walk of the largest @@ -501,6 +504,101 @@ bytes of heap for each byte of it in the three full rows, and now allocates entries, so they hold less than the `ML` 0 box for each byte of it; the lists' blocks add the 0.07 the `ML` 0 rows hold over 4.0. +The `ftyp`, `pclr`, `cmap` and `cdef` boxes are read once too, and the +`uinf` UUIDs, as the first `rreq` is: a read of the file checks them +without building anything, and builds the metadata's copy once, and an +`IncrementalDecoder` keeps that copy in `jp2::Lists` from the first call +that finds the `jp2c` box, as the boxes before it are then fixed. An `ftyp` +holds 4 bytes for each code of 4 bytes, and a `cdef` 10 bytes for each entry +of 6, so both stay under the 3.2 above. A palette holds an `i32` for each +entry of each column, 4 bytes for each byte of an 8-bit column, but has at +most 1024 entries of 255 columns, so it holds at most about 1 MiB, whatever +its box. What a header builds for each read is what depends on the +options: entries for each output channel, in its `components`, `channels` +and `channel_mapping`, 20 to 26 bytes a channel. A file has at most 16384 +output channels, one for each component when it has no palette, where a +header holds 320 KiB of them; a palette's 255 columns take 6.5 KB. + +These were measured as the `rreq` was, on the same file with an `ftyp` of +4 MiB, or with a `cdef` of 65535 entries or a `pclr` of 1024 entries by 255 +8-bit columns and its `cmap` added to the `jp2h` box. The heap columns are +in bytes for each byte the boxes add to the file, from a `decode` call. The +resident column is `/usr/bin/time -v`'s peak resident set of that decode +less that of the file alone (2.9 MiB), input included, in MiB. "A later +call" is the median time of a `header` call with nothing new fed, and what +it allocated. "Before #786" is the same program on the parent commit, when +the checks and the metadata each read a copy of these boxes and each +`header` call read them again. The 1-minute load was about 13. + +| Box (bytes added) | Heap peak before #786 | Heap peak now | Heap held before #786 | Heap held now | Resident peak before #786 | Resident peak now | A later call before #786 | A later call now | +| ----------------- | --------------------- | ------------- | --------------------- | ------------- | ------------------------- | ----------------- | ------------------------ | ---------------- | +| `ftyp` (4.19 MB) | 2.00 | 1.16 | 1.00 | 1.16 | 11.8 | 8.7 | 4.9 ms, 8.4 MB | 0.48 ms, 1092 bytes | +| `cdef` (393 KB) | 3.36 | 1.80 | 1.67 | 1.77 | 2.1 | 0.9 | 0.95 ms, 2.4 MB | 0.50 ms, 1247 bytes | +| `pclr` and `cmap` (262 KB) | 8.24 | 4.26 | 4.25 | 4.25 | 2.2 | 1.2 | 1.6 ms, 3.2 MB | 24 µs, 16 KB | + +Each box now peaks at what it holds. The `ftyp` holds a little more than +before, as its codes are in a `MetadataList` (1.16 bytes a byte where a `Vec` +held 1.00), and the `cdef` a little more for the same reason, so that a later +header shares them. A later call still checks the boxes before the +codestream, which is the 0.5 ms of the `ftyp` and `cdef` rows; it holds 68 +to 80 bytes of its own for them, and for the 255 channels of the palette +6.6 KB, the entries built for the options. + +An `IncrementalDecoder` keeps what the boxes before the codestream built +from the first call that finds the `jp2c` box, for as long as that box +starts at the same place (`jp2::Walks::before`). While the codestream's end +is not yet fed, the walk of the boxes after it starts again on each call, +as the bytes it last read as boxes are now codestream; it starts from these +lists, which it shares, and reads only the boxes after the codestream. A +call still walks the boxes before the codestream to check them, but keeps +no record of a box the metadata reports there, only a count. So a call +costs about 9 ns and nothing allocated for each box at the top level before +the codestream, plus the contents it checks (the `ftyp` codes, the +`cdef`, `pclr` and `cmap` entries). Of the children of a `jp2h` it keeps a +24-byte record each for the length of the call, in a list that grows by +doubling, so a `jp2h` of many children costs about 10 bytes allocated for +each byte of it on each call, freed when the call returns. Under +`ColorOutput::Srgb`, the decoder also keeps what the plan read of an ICC +profile and the transform it built (`jp2::IccMemo`), at most three +transforms of 50 to 400 KB, so a later call builds none of them again. + +These were measured with the same program, on more shapes: the base file +alone; with 100000 empty `xml ` boxes or 100000 empty `free` boxes before +the `jp2c` box; with 50000 `colr` children of `METH` 3, which no reader +uses, in its `jp2h`; a file of 16384 components of 1 x 1 and no palette; +and the file of `tests/header_boxes_alloc.rs` with 3 and with 255 palette +columns (4.8 and 5.0 MB of boxes, among them 200 small `uuid` and 200 small +`uinf` boxes). "Later call" is a `header` call with nothing new fed: its +median time, what it allocated, and what the header it returns holds. The +streaming column is the same file with an 8 MiB tile-part fed 4 KiB at a +time, over 200 calls: the time and the allocation of a call, and what the +200 headers held hold together with the room the bytes fed grow into. +"Before #786" is the parent commit, and "first #786 head" the change before +it kept the lists across a walk that starts again. The 1-minute load was +about 1. + +| File | Later call before #786 | Later call, first #786 head | Later call now | Header holds before #786 | Header holds now | +| ---- | ---------------------- | --------------------------- | -------------- | ------------------------ | ---------------- | +| base (390 bytes) | 2.1 µs, 1172 bytes | 1.9 µs, 1092 bytes | 1.7 µs, 1052 bytes | 72 | 68 | +| 100000 `xml ` (800 KB) | 6.4 ms, 7.1 MB | 6.6 ms, 7.1 MB | 0.89 ms, 1052 bytes | 72 | 68 | +| 100000 `free` (800 KB) | 6.1 ms, 801 KB | 6.2 ms, 801 KB | 0.81 ms, 1052 bytes | 72 | 68 | +| 50000 `colr` children (550 KB) | 3.3 ms, 5.6 MB | 3.4 ms, 5.6 MB | 0.64 ms, 5.2 MB | 72 | 68 | +| 16384 components | 1.9 ms, 2.4 MB | 1.5 ms, 2.0 MB | 1.5 ms, 2.0 MB | 327684 | 327680 | +| header boxes, 3 columns | 1.8 ms, 4.5 MB | 0.37 ms, 29 KB | 0.34 ms, 1304 bytes | 1716318 | 98 | +| header boxes, 255 columns | 2.8 ms, 7.7 MB | 0.39 ms, 58 KB | 0.36 ms, 31 KB | 2755566 | 6650 | + +| Streaming, 200 calls | Before #786 | First #786 head | Now | +| -------------------- | ----------- | --------------- | --- | +| header boxes, 3 columns | 2.0 ms, 6.5 MB a call; 690 MB held | 2.8 ms, 6.0 MB a call; 733 MB held | 0.34 ms, 1752 bytes a call; 2.5 MB held | +| header boxes, 255 columns | 3.4 ms, 9.6 MB a call; 898 MB held | 3.6 ms, 7.0 MB a call; 941 MB held | 0.36 ms, 31 KB a call; 4.0 MB held | + +The 0.81 to 0.89 ms of the 100000 boxes is the walk that checks them, which +took about 6 ms before, as it built a name for each box it read, for an +error it might give. The 16384 +components cost the same in every column, as the main header is parsed again +on each call, and the 320 KiB a header holds are its entries for the +channels. + ### Segment records The caps count code-blocks, not codeword segments. With the code-block style @@ -745,7 +843,10 @@ the walk, which lets go of the records the lists hold: an entry of 24 to 56 bytes a box, 20 to 36 on a 32-bit target, and a payload of over 15 bytes in an allocation shared with those read in the same call, behind a 16-byte header (8 on a 32-bit target); about 3 bytes at most for each byte of the boxes fed, and -about 4.6 MiB more for the first `rreq`). A last box of length 0 runs to the +about 4.6 MiB more for the first `rreq` and about 1 MiB more for a palette). +The `ftyp`, `pclr`, `cmap` and `cdef` boxes and the `uinf` UUIDs are read +once too, by the first call that finds the `jp2c` box, and shared the same +way. A last box of length 0 runs to the end of the bytes fed, so each call reads it, but only as far as it has not been read: a `jp2h` there is read on from its last whole child, so each child is read once in all, and a `colr`, `pclr`, `cmap` or `cdef` that passed is not diff --git a/src/incremental.rs b/src/incremental.rs index c3aa1980..3ba2e047 100644 --- a/src/incremental.rs +++ b/src/incremental.rs @@ -437,15 +437,33 @@ impl IncrementalDecoder { /// 13 MB at most under the 65536 segments a main header may have. /// /// Once the main header is whole, each call parses it again (its `PPM` data - /// included). In a JP2 file it also reads the boxes before the codestream - /// again. The boxes the metadata reports after them (`xml `, `uuid`, - /// `jp2i`, `uinf`, the first `rreq`), and the `colr` payloads, are read - /// once, by the first call that finds them whole, and each later header - /// shares their lists ([`MetadataList`](crate::MetadataList)) and their - /// payloads ([`Payload`](crate::Payload)). The walk that finds where the - /// codestream ends and the walk of the boxes after it go on from where the - /// last call left them, and the header boxes after the codestream (`colr`, - /// `jp2h` and the like) are read once, as the walk reaches them. A last box + /// included). In a JP2 file it also walks the boxes before the codestream + /// again, to check them, but builds none of what they hold again: the + /// `ftyp` codes, the `pclr`, `cmap` and `cdef` tables, the `colr` payloads + /// and the boxes the metadata reports (`xml `, `uuid`, `jp2i`, `uinf` and + /// its UUIDs, the first `rreq`) are read once, by the first call that + /// finds the `jp2c` box, and each later header shares their lists + /// ([`MetadataList`](crate::MetadataList)), tables and payloads + /// ([`Payload`](crate::Payload)). Under + /// [`ColorOutput::Srgb`](crate::ColorOutput::Srgb), what the plan read of + /// an ICC profile and the transform it built are kept too. The walk costs + /// time for each box: about 9 ns, and nothing allocated, for each box at + /// the top level (100000 empty `xml ` or `free` boxes take 0.8 to 0.9 ms + /// a call), plus the contents it checks, 0.5 ms for a 4 MiB `ftyp` or a + /// 65535-entry `cdef`. Of the children of a `jp2h` it keeps a 24-byte + /// record each for the length of the call, in a list that grows by + /// doubling: 50000 `colr` children that no reader uses (550 KB) take + /// 0.65 ms a call and allocate 5.2 MB, 3.1 MB at its peak. What a header + /// builds for each call is what depends on the options: entries for each + /// output channel in `components`, `channels` and `channel_mapping`, + /// which the header holds, 20 to 26 bytes a channel. There are at most + /// 16384 output channels, one for each component without a palette: + /// such a header holds 320 KiB, and with the parse of its main header a + /// call allocates 2.0 MB. A palette's 255 columns take 6.5 KB. The walk + /// that finds where the codestream ends and the walk of the boxes after + /// it go on from where the last call left them, and the header boxes + /// after the codestream (`colr`, `jp2h` and the like) are read once, as + /// the walk reaches them. A last box /// of length 0 there runs to the end of the bytes fed: a `jp2h` is read on /// from its last whole child, a `colr`, `pclr`, `cmap` or `cdef` that /// passed is not read again, and any other is checked on at most its first @@ -501,12 +519,12 @@ impl IncrementalDecoder { /// tiles' sizes show them within the caps; otherwise a few hundred bytes, /// plus the counts above. In a JP2 file the walks past the boxes before the /// codestream are kept from the first call, a change of options included, - /// for as long as the decoder lives: 1424 bytes and up to four error + /// for as long as the decoder lives: 2448 bytes and up to four error /// messages, and the boxes the metadata reports. Each such box is read /// once, by the first call that finds it whole, and kept in the lists that /// every later header shares ([`MetadataList`](crate::MetadataList)), so a /// call reads only the boxes fed since the last, and one with nothing new - /// peaks at 692 bytes allocated, and the header it returns holds 48 bytes + /// peaks at 688 bytes allocated, and the header it returns holds 44 bytes /// of its own for the lists, measured. A box is kept as an entry of 24 /// bytes (40 for a `uuid`, 56 for a `uinf`; on a 32-bit target 20, and 36 /// for both) and, for a payload of over 15 bytes, its bytes, in an @@ -519,8 +537,10 @@ impl IncrementalDecoder { /// read of the file in all. The first `rreq` is kept as an entry of 32 /// bytes for each standard feature and 40 for each vendor feature (24 and /// 36 on a 32-bit target), with its masks held as payloads are: at most - /// about 4.6 MiB more, read once and shared the same way. A call made - /// while another thread is in one reads from the start. + /// about 4.6 MiB more, read once and shared the same way. A palette is + /// kept as 4 bytes for each entry of each column, at most about 1 MiB + /// more, a `cdef` as 10 bytes an entry and an `ftyp` as 4 bytes a code. + /// A call made while another thread is in one reads from the start. pub fn header(&self) -> Result> { // A call on another thread holding the lock reads from the start. A // call that panicked may have left the walk half done, so it is diff --git a/src/jp2/after.rs b/src/jp2/after.rs index 3fcd2b82..254ad305 100644 --- a/src/jp2/after.rs +++ b/src/jp2/after.rs @@ -273,10 +273,8 @@ impl State { if self.palette.is_some() { return Err(fault("the file has a second `pclr` box")); } - let columns = palette::Palette::parse(payload) - .map_err(context)? - .columns() - .len(); + // The table is checked, not read: nothing uses it. + let columns = palette::Palette::check(payload).map_err(context)?; self.palette = Some(columns); self.mapped = false; } diff --git a/src/jp2/boxes.rs b/src/jp2/boxes.rs index 13bc4729..d124eac6 100644 --- a/src/jp2/boxes.rs +++ b/src/jp2/boxes.rs @@ -46,10 +46,20 @@ pub(crate) struct Jp2Box<'a> { /// A four-character box type as printable text: `jp2h`, `xml `, or escaped /// bytes for a type that is not ASCII. pub(crate) fn type_name(kind: [u8; 4]) -> String { - kind.iter() - .flat_map(|&b| std::ascii::escape_default(b)) - .map(char::from) - .collect() + TypeName(kind).to_string() +} + +/// [`type_name`] as it is written, building no `String`, for a walk that +/// names a box only if it fails. +struct TypeName([u8; 4]); + +impl std::fmt::Display for TypeName { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0 + .iter() + .flat_map(|&b| std::ascii::escape_default(b)) + .try_for_each(|c| std::fmt::Write::write_char(f, char::from(c))) + } } /// Iterates the boxes laid end to end in one byte slice: the whole file, or @@ -194,7 +204,8 @@ impl<'a> Boxes<'a> { && !codestream && rest.len() < 16 && rest.get(8..).is_some_and(|xl| xl.iter().all(|&b| b == 0)); - let name = type_name(kind); + // Written only into an error. + let name = TypeName(kind); self.last_open_ended = lbox == 0; // The box's total length (header included) and its header length. A diff --git a/src/jp2/channels.rs b/src/jp2/channels.rs index 32995e98..729d4229 100644 --- a/src/jp2/channels.rs +++ b/src/jp2/channels.rs @@ -36,6 +36,7 @@ //! [`ChannelPlan::apply`] then reorders the channels the palette step built, //! and [`ChannelPlan::describe`] labels them. +use super::list::{Extender, MetadataList}; use super::metadata::{ Association, ChannelDefinition, ChannelDefinitionEntry, ChannelType, Jp2Metadata, }; @@ -49,7 +50,7 @@ const APPLICATION_DEFINED: u16 = 3; /// One `cdef` entry. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) struct Entry { +struct Entry { /// `Cn`: the channel the entry describes. channel: u16, /// `Typ`. @@ -61,16 +62,6 @@ pub(super) struct Entry { } impl Entry { - /// The color position this entry moves its channel to: `Asoc - 1` for a - /// color channel associated with a color. `None` when the entry moves - /// nothing (another type, `Asoc` 0 or 65535). - fn target(self) -> Option { - match (self.kind, self.association) { - (0, 1..=65534) => Some(usize::from(self.association) - 1), - _ => None, - } - } - /// Whether the entry is an application-defined channel: `Typ` 3 in a /// JPH file, whose `Asoc` the application gives meaning to. Elsewhere /// `Typ` 3 is a reserved value. @@ -98,9 +89,9 @@ impl Entry { } } -/// Parse a `cdef` payload into its entries, for a JPH file when `jph`. The -/// length is checked before anything is allocated. -pub(super) fn parse(payload: &[u8], jph: bool) -> Result> { +/// The entries of a `cdef` payload, for a JPH file when `jph`. The length +/// is checked before anything is read, and nothing is allocated. +fn entries_of(payload: &[u8], jph: bool) -> Result + '_> { let &[n0, n1, ref body @ ..] = payload else { return Err(Error::file_format(format!( "the `cdef` box holds {} bytes, fewer than its 2-byte count", @@ -122,31 +113,45 @@ pub(super) fn parse(payload: &[u8], jph: bool) -> Result> { body.len() ))); }; - Ok(entries - .chunks_exact(ENTRY_BYTES) - .map(|e| Entry { - channel: u16::from_be_bytes([e[0], e[1]]), - kind: u16::from_be_bytes([e[2], e[3]]), - association: u16::from_be_bytes([e[4], e[5]]), - jph, - }) - .collect()) + Ok(entries.chunks_exact(ENTRY_BYTES).map(move |e| Entry { + channel: u16::from_be_bytes([e[0], e[1]]), + kind: u16::from_be_bytes([e[2], e[3]]), + association: u16::from_be_bytes([e[4], e[5]]), + jph, + })) } -/// The file's `cdef` entries as written, for the metadata. -pub(super) fn definitions(entries: &[Entry]) -> Vec { - entries - .iter() - .map(|e| ChannelDefinitionEntry { - channel: e.channel, - definition: e.definition(), - }) - .collect() +/// Read a `cdef` payload into its entries as the metadata reports them, for +/// a JPH file when `jph`. The length is checked before anything is +/// allocated. The plans read the same list, so the box is read once. +pub(super) fn parse(payload: &[u8], jph: bool) -> Result> { + let mut list = Extender::default(); + for entry in entries_of(payload, jph)? { + list.push(ChannelDefinitionEntry { + channel: entry.channel, + definition: entry.definition(), + }); + } + Ok(list.finish()) } -/// Check a `cdef` payload's layout only, as OpenJPEG reads the box. +/// Check a `cdef` payload's layout only, as OpenJPEG reads the box. Nothing +/// is allocated. pub(super) fn check_layout(payload: &[u8]) -> Result<()> { - parse(payload, false).map(|_| ()) + entries_of(payload, false).map(drop) +} + +/// The color position an entry moves its channel to: `Asoc - 1` for a color +/// channel associated with a color (`Typ` 0, `Asoc` 1 to 65534). `None` when +/// the entry moves nothing (another type, `Asoc` 0 or 65535). +fn target(entry: &ChannelDefinitionEntry) -> Option { + match entry.definition { + ChannelDefinition { + kind: ChannelType::Color, + association: Association::Color(n), + } => Some(usize::from(n) - 1), + _ => None, + } } /// What the `cdef` box does to the file's channels. Computed before any tile @@ -173,7 +178,7 @@ pub(crate) enum ChannelPlan { /// the entries say, as OpenJPEG does with its "ignore palette and channel /// definitions" flag. pub(crate) fn plan( - entries: Option>, + entries: Option<&MetadataList>, channels: usize, raw_channels: bool, ) -> Result { @@ -183,15 +188,15 @@ pub(crate) fn plan( if raw_channels { return Ok(ChannelPlan::None); } - check(&entries, channels)?; - Ok(place(&entries, channels)) + check(entries, channels)?; + Ok(place(entries, channels)) } /// Check the entries against the channel count as `opj_jp2_check_color` does: /// each entry's `Cn` and `Asoc - 1` in range, then every channel named. The /// `Asoc` of an application-defined channel is not a color and is not /// checked. -fn check(entries: &[Entry], channels: usize) -> Result<()> { +fn check(entries: &MetadataList, channels: usize) -> Result<()> { for (i, entry) in entries.iter().enumerate() { if usize::from(entry.channel) >= channels { return Err(Error::file_format(format!( @@ -199,19 +204,20 @@ fn check(entries: &[Entry], channels: usize) -> Result<()> { entry.channel ))); } - if !entry.application_defined() - && !matches!(entry.association, 0 | 65535) - && usize::from(entry.association) > channels - { - return Err(Error::file_format(format!( - "`cdef` entry {i} associates channel {} with color {}, but the file has \ - {channels} channels", - entry.channel, entry.association - ))); + // `Asoc` 0 and 65535 are not colors, nor is an application-defined + // channel's. + if let Association::Color(color) = entry.definition.association { + if usize::from(color) > channels { + return Err(Error::file_format(format!( + "`cdef` entry {i} associates channel {} with color {color}, but the file \ + has {channels} channels", + entry.channel + ))); + } } } let mut named = vec![false; channels]; - for entry in entries { + for entry in entries.iter() { // In range: checked above. if let Some(slot) = named.get_mut(usize::from(entry.channel)) { *slot = true; @@ -227,7 +233,7 @@ fn check(entries: &[Entry], channels: usize) -> Result<()> { /// Run OpenJPEG's placement over checked entries: each color entry swaps its /// channel to `Asoc - 1`, and later entries follow their channels. -fn place(entries: &[Entry], channels: usize) -> ChannelPlan { +fn place(entries: &MetadataList, channels: usize) -> ChannelPlan { // `order[p]` is the input channel at position `p`; `position[c]` is where // input channel `c` is now. let mut order: Vec = (0..channels).collect(); @@ -241,10 +247,10 @@ fn place(entries: &[Entry], channels: usize) -> ChannelPlan { }; channels ]; - for entry in entries { + for entry in entries.iter() { let channel = usize::from(entry.channel); - labels[channel] = entry.definition(); - let Some(target) = entry.target() else { + labels[channel] = entry.definition; + let Some(target) = target(entry) else { continue; }; let from = position[channel]; @@ -297,17 +303,20 @@ mod tests { use super::*; use crate::Component; + /// Entries of a JPH file when `jph`, and of a JP2 file otherwise. + fn entries_in(triples: &[(u16, u16, u16)], jph: bool) -> MetadataList { + let mut payload = u16::try_from(triples.len()).unwrap().to_be_bytes().to_vec(); + for &(channel, kind, association) in triples { + for field in [channel, kind, association] { + payload.extend(field.to_be_bytes()); + } + } + parse(&payload, jph).unwrap() + } + /// Entries of a JPH file. - fn entries(triples: &[(u16, u16, u16)]) -> Vec { - triples - .iter() - .map(|&(channel, kind, association)| Entry { - channel, - kind, - association, - jph: true, - }) - .collect() + fn entries(triples: &[(u16, u16, u16)]) -> MetadataList { + entries_in(triples, true) } /// The order `place` gives, which is the same in a JPH file and in a JP2 @@ -316,10 +325,7 @@ mod tests { let orders: Vec> = [true, false] .into_iter() .map(|jph| { - let entries: Vec = entries(triples) - .into_iter() - .map(|entry| Entry { jph, ..entry }) - .collect(); + let entries = entries_in(triples, jph); check(&entries, channels).expect("valid entries"); match place(&entries, channels) { ChannelPlan::Apply { order, .. } => order, @@ -335,15 +341,9 @@ mod tests { /// accepted; elsewhere it is refused, as OpenJPEG refuses it. #[test] fn a_typ_3_asoc_past_the_last_channel_is_checked_outside_jph() { - let jph = entries(&[(0, 0, 1), (1, 0, 2), (2, 3, 18284)]); - check(&jph, 3).expect("a JPH file"); - let jp2: Vec = jph - .into_iter() - .map(|entry| Entry { - jph: false, - ..entry - }) - .collect(); + let triples = [(0, 0, 1), (1, 0, 2), (2, 3, 18284)]; + check(&entries(&triples), 3).expect("a JPH file"); + let jp2 = entries_in(&triples, false); let err = check(&jp2, 3).unwrap_err(); assert!(matches!(err, Error::FileFormat(_)), "{err:?}"); } @@ -481,6 +481,12 @@ mod tests { #[test] fn parse_reads_entries_and_ignores_trailing_bytes() { let payload = [0, 1, 0, 2, 0, 1, 0, 0, 0xFF, 0xFF]; - assert_eq!(parse(&payload, true).unwrap(), entries(&[(2, 1, 0)])); + let parsed = parse(&payload, true).unwrap(); + assert_eq!(parsed.len(), 1); + assert_eq!(parsed[0].channel, 2); + assert_eq!(parsed[0].definition.kind, ChannelType::Opacity); + assert_eq!(parsed[0].definition.association, Association::WholeImage); + check_layout(&payload).unwrap(); + assert!(check_layout(&payload[..7]).is_err()); } } diff --git a/src/jp2/header.rs b/src/jp2/header.rs index e57deb97..32133d6c 100644 --- a/src/jp2/header.rs +++ b/src/jp2/header.rs @@ -7,6 +7,7 @@ use super::BoxFault; use super::boxes::{Boxes, Jp2Box, type_name}; +use super::list::Extender; use super::metadata::FileType; use crate::{Error, Result}; @@ -16,12 +17,50 @@ const JP2_BRAND: [u8; 4] = *b"jp2 "; /// The brand and compatibility code of a JPH file (ISO/IEC 15444-15 D.3). const JPH_BRAND: [u8; 4] = *b"jph "; +/// A File Type box (`ftyp`, I.5.2) as the file holds it: its fields, with the +/// compatibility list left in the input. It is read once into the metadata's +/// [`FileType`] ([`FileTypeBox::to_metadata`]), so a walk of the boxes +/// copies nothing of it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct FileTypeBox<'a> { + /// `BR`: the brand. + pub(crate) brand: [u8; 4], + /// `MinV`: the minor version. + pub(crate) minor_version: u32, + /// `CLi`: the compatibility codes, whole 4-byte codes. + pub(crate) compatibility: &'a [u8], + /// Whether `jph ` is the brand or in the list ([`is_jph`]). + jph: bool, +} + +impl FileTypeBox<'_> { + /// The compatibility codes, in box order. + fn codes(&self) -> impl Iterator + '_ { + self.compatibility + .chunks_exact(4) + .map(|code| [code[0], code[1], code[2], code[3]]) + } + + /// The box's fields, as the metadata reports them. + pub(crate) fn to_metadata(self) -> FileType { + let mut compatibility = Extender::default(); + for code in self.codes() { + compatibility.push(code); + } + FileType { + brand: self.brand, + minor_version: self.minor_version, + compatibility: compatibility.finish(), + } + } +} + /// Check a File Type box: `BR` (4 bytes), `MinV` (4 bytes), then any number of /// 4-byte compatibility codes. A file is read only if `jp2 ` or `jph ` is its /// brand or in its compatibility list (I.5.2, ISO/IEC 15444-15 D.3); anything /// else is a JPX, JPM or MJ2 file that claims neither, and is -/// [`Error::Unsupported`]. Returns the box's fields. -pub(crate) fn check_file_type(ftyp: &Jp2Box<'_>) -> Result { +/// [`Error::Unsupported`]. Returns the box's fields, allocating nothing. +pub(crate) fn check_file_type<'a>(ftyp: &Jp2Box<'a>) -> Result> { let payload = ftyp.payload; if payload.len() < 8 || !payload.len().is_multiple_of(4) { return Err(Error::file_format(format!( @@ -30,33 +69,34 @@ pub(crate) fn check_file_type(ftyp: &Jp2Box<'_>) -> Result { payload.len() ))); } - let brand = [payload[0], payload[1], payload[2], payload[3]]; - let minor_version = u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]); - // Whole 4-byte codes, as checked above, so nothing is dropped. - let compatibility: Vec<[u8; 4]> = payload[8..] - .chunks_exact(4) - .map(|code| [code[0], code[1], code[2], code[3]]) - .collect(); - let readable = |code: &[u8; 4]| *code == JP2_BRAND || *code == JPH_BRAND; - let compatible = readable(&brand) || compatibility.iter().any(readable); - if !compatible { + let mut file_type = FileTypeBox { + brand: [payload[0], payload[1], payload[2], payload[3]], + minor_version: u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]), + // Whole 4-byte codes, as checked above, so nothing is dropped. + compatibility: &payload[8..], + jph: false, + }; + // One pass over the list for both codes. + let (mut jp2, mut jph) = (file_type.brand == JP2_BRAND, file_type.brand == JPH_BRAND); + for code in file_type.codes() { + jp2 |= code == JP2_BRAND; + jph |= code == JPH_BRAND; + } + file_type.jph = jph; + if !jp2 && !jph { return Err(Error::unsupported(format!( "file brand `{}` without `jp2 ` or `jph ` compatibility (a JPX, JPM or MJ2 \ file that does not claim to be readable as JP2 or JPH)", - type_name(brand) + type_name(file_type.brand) ))); } - Ok(FileType { - brand, - minor_version, - compatibility, - }) + Ok(file_type) } /// Whether a file is a JPH file: `jph ` is its brand or in its /// compatibility list (ISO/IEC 15444-15 D.3). -pub(crate) fn is_jph(file_type: &FileType) -> bool { - file_type.brand == JPH_BRAND || file_type.compatibility.contains(&JPH_BRAND) +pub(crate) fn is_jph(file_type: &FileTypeBox<'_>) -> bool { + file_type.jph } /// The most components `ihdr` may declare: `NC` is 1..=16384 (I.5.3.1), the diff --git a/src/jp2/layout.rs b/src/jp2/layout.rs index 795faf96..b503eb59 100644 --- a/src/jp2/layout.rs +++ b/src/jp2/layout.rs @@ -6,18 +6,24 @@ //! `opj_jp2_read_cdef`), so the first fault in file order is the one //! reported. What the boxes say about the components is checked later, by //! the plans. +//! +//! The boxes are read once ([`super::box_layout`]): the plans and the +//! metadata share what this read builds, and a clone of it copies nothing. -use super::channels::{self, Entry}; +use super::channels; use super::header::Jp2Header; +use super::list::MetadataList; +use super::metadata::ChannelDefinitionEntry; use super::palette::{self, Palette, PaletteBoxes}; use crate::{Error, Result}; /// What the palette and channel definition boxes hold. -pub(super) struct BoxLayout { +#[derive(Debug, Clone, Default)] +pub(crate) struct BoxLayout { /// The palette, and its `cmap` entries when the file has a `cmap`. pub(super) palette: Option, /// The `cdef` entries, when the file has a `cdef`. - pub(super) cdef: Option>, + pub(super) cdef: Option>, } /// Read the boxes' layout, refusing its first fault in file order. `jph` diff --git a/src/jp2/metadata.rs b/src/jp2/metadata.rs index e0e13619..3a208bf3 100644 --- a/src/jp2/metadata.rs +++ b/src/jp2/metadata.rs @@ -301,6 +301,9 @@ pub struct Jp2Metadata { /// unknown (the file gives no color space, the enumerated value is not /// one this decoder knows, or an ICC profile is too short to name its /// color space) every channel is a color. + /// + /// A `Vec`, not shared: one entry of 8 bytes per output channel, which + /// depends on the options, so each read builds it. pub channels: Vec, /// Whether the samples went through the file's palette. `false` when the /// file has no palette (or a `pclr` without a `cmap`), or the caller set @@ -370,7 +373,9 @@ pub struct Jp2Metadata { /// /// [`channels`](Self::channels) itself is only relabeled when the `cdef` /// applies: under `raw_channels` every channel keeps its default label. - pub channel_definitions: Option>, + /// + /// The box is read once, and a clone shares the entries. + pub channel_definitions: Option>, /// The file's palette, from its `pclr` box. Present when the palette /// applies, and also when /// [`raw_channels`](crate::DecodeOptions::raw_channels) left it unapplied @@ -390,6 +395,9 @@ pub struct Jp2Metadata { /// Only a `cmap` the default decode refuses is reported as written, and /// only under `raw_channels`, which does not check it; an `MTYP` other /// than 0 or 1 is then [`Reserved`](crate::MappingKind::Reserved). + /// + /// A `Vec`, not shared: at most 255 entries, one per palette column, + /// which depend on the options, so each read builds it. pub channel_mapping: Option>, /// The capture and default display resolutions from the header's `res ` /// box, each `None` when the file does not give it. @@ -486,8 +494,9 @@ pub struct FileType { /// `MinV`: the minor version. The standard requires 0, and a reader /// ignores it. pub minor_version: u32, - /// `CLi`: the compatibility list, in box order. - pub compatibility: Vec<[u8; 4]>, + /// `CLi`: the compatibility list, in box order. The box is read once, + /// and a clone shares the list. + pub compatibility: MetadataList<[u8; 4]>, } /// A Reader Requirements box (`rreq`, ISO/IEC 15444-2 M.11.1): the features @@ -686,8 +695,9 @@ pub struct UuidBox { #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub struct UuidInfo { - /// The UUIDs from the `ulst` box (`ID0` to `ID(NU-1)`), in box order. - pub ids: Vec<[u8; 16]>, + /// The UUIDs from the `ulst` box (`ID0` to `ID(NU-1)`), in box order. A + /// clone shares them. + pub ids: MetadataList<[u8; 16]>, /// `VERS` from the `url ` box; the standard requires 0. pub version: u8, /// `FLAG` from the `url ` box, as stored (big-endian); the standard diff --git a/src/jp2/mod.rs b/src/jp2/mod.rs index dad14af8..f20fd64e 100644 --- a/src/jp2/mod.rs +++ b/src/jp2/mod.rs @@ -96,9 +96,10 @@ pub(crate) use after::EndWalk; use boxes::{AfterWalk, BoxList, Boxes, Jp2Box, type_name, walk_after_codestream_kept}; use channels::ChannelPlan; pub(crate) use header::is_jph; -use header::{Jp2Header, check_file_type}; +use header::{FileTypeBox, Jp2Header, check_file_type}; +pub(crate) use layout::BoxLayout; use palette::PalettePlan; -pub(crate) use srgb::SrgbPlan; +pub(crate) use srgb::{IccMemo, SrgbPlan}; /// The JP2 signature box (I.5.1): length 12, type `jP `, contents /// `0D 0A 87 0A`. @@ -121,8 +122,8 @@ pub(crate) fn looks_like_jp2(bytes: &[u8]) -> bool { /// A JP2 file's boxes up to and including its first `jp2c`. #[derive(Debug, Clone)] pub(crate) struct Jp2File<'a> { - /// The `ftyp` box's fields. - pub(crate) file_type: FileType, + /// The `ftyp` box's fields, its compatibility list left in the input. + pub(crate) file_type: FileTypeBox<'a>, /// The `jp2h` contents, merged over every `jp2h` box and every header box /// misplaced at the top level after the first `jp2h`. pub(crate) header: Jp2Header<'a>, @@ -138,8 +139,11 @@ pub(crate) struct Jp2File<'a> { /// the first `rreq` ([`Reported`]). The rest (header boxes misplaced /// before `jp2h`, which OpenJPEG ignores, the JPX boxes and unknown ones) /// are skipped without a record, so padding of such boxes holds no - /// memory. + /// memory. Empty where the walks kept hold the lists of these boxes + /// ([`Walks`]), which `other_count` is then all that is checked of. pub(crate) other: Vec>, + /// How many boxes `other` holds, or would. + pub(crate) other_count: usize, /// The boxes after the codestream, from just after its last /// tile-part, as far as OpenJPEG's walk there follows them (see /// [`boxes::walk_after_codestream_kept`]): those the metadata copies, where @@ -334,9 +338,31 @@ pub(crate) fn parse_boxes_kept<'a>( walks: &mut Walks, ) -> std::result::Result, BoxFault> { let (mut boxes, file_type) = read_file_type(bytes)?; - let mut kept = Kept::default(); - let item = walk_to_codestream(&mut boxes, &mut kept)?; - let Kept { header, other, .. } = kept; + // Where the walks hold the metadata's lists of the boxes before the + // codestream, only their count is checked, so none is kept: a call + // allocates nothing for them. A walk whose `jp2c` start the walks were + // not kept for reads them again, keeping them. + let mut kept = Kept { + count_only: walks.before.is_some(), + ..Kept::default() + }; + let mut item = walk_to_codestream(&mut boxes, &mut kept)?; + if kept.count_only { + let start = bytes + .len() + .checked_sub(boxes.rest().len() + item.payload.len()); + if !start.is_some_and(|start| walks.keeps_for(start, bytes.len())) { + (boxes, _) = read_file_type(bytes)?; + kept = Kept::default(); + item = walk_to_codestream(&mut boxes, &mut kept)?; + } + } + let Kept { + header, + other, + count, + .. + } = kept; let Some(header) = header else { return Err(no_jp2h().into()); }; @@ -371,6 +397,7 @@ pub(crate) fn parse_boxes_kept<'a>( color, codestream, other, + other_count: count, after_codestream: after.boxes, after_checked, after_box, @@ -396,7 +423,7 @@ pub(crate) fn parse_boxes_kept<'a>( /// Read the signature box and the `ftyp` box after it, for /// [`parse_boxes`] and [`BoxesCut::start`]. Returns the walk of the /// top-level boxes, just past the `ftyp`. -fn read_file_type(bytes: &[u8]) -> std::result::Result<(Boxes<'_>, FileType), BoxFault> { +fn read_file_type(bytes: &[u8]) -> std::result::Result<(Boxes<'_>, FileTypeBox<'_>), BoxFault> { if SIGNATURE.starts_with(bytes) && bytes.len() < SIGNATURE.len() { return Err(Error::incomplete("the input ends inside the JP2 signature box").into()); } @@ -464,6 +491,10 @@ trait BeforeCodestream<'a> { struct Kept<'a> { header: Option>, other: Vec>, + /// Whether `other` is left empty, the boxes only counted. + count_only: bool, + /// How many boxes `other` holds, or would. + count: usize, reported: Reported, } @@ -487,7 +518,10 @@ impl<'a> BeforeCodestream<'a> for Kept<'a> { .as_mut() .is_some_and(|header| header.add_misplaced(item)); if !taken && self.reported.keeps(item.kind) { - self.other.push(item); + self.count += 1; + if !self.count_only { + self.other.push(item); + } } } } @@ -735,16 +769,50 @@ pub(crate) struct Walks { after: AfterWalk, /// The walk after the `jp2c` box ([`Jp2File::after_box`]). after_box: AfterWalk, + /// What the metadata read of the boxes before the codestream: the lists + /// of [`Lists`] as they stand before any box after it, with the `ftyp`, + /// the `colr` list and the box layout. Those boxes are the same for as + /// long as the walks are kept, for one `jp2c` start, so a walk after + /// the codestream that starts again (its start moves with each feed + /// while the codestream's end is not found) starts from a clone of + /// these and reads only the boxes after the codestream. + before: Option, + /// The transforms the sRGB plans built from the file's ICC profile, + /// which each read plans again ([`IccMemo`]). + icc: IccMemo, +} + +/// The lists a read of a JP2 file shares and adds to: those of the walk +/// after the codestream it reads ([`Walks::reported`]), and what the +/// metadata read of the boxes before the codestream, which those lists +/// start from. +pub(crate) struct KeptLists<'k> { + pub(crate) lists: &'k mut Lists, + pub(crate) before: &'k mut Option, + /// The transforms the sRGB plans built, kept with the walks too. + pub(crate) icc: &'k mut IccMemo, } impl Walks { /// What the metadata kept of the boxes it reported from the walk after /// the codestream that `file` reads them from ([`Jp2File::after_box`]). - pub(crate) fn reported(&mut self, file: &Jp2File<'_>) -> &mut Lists { - if file.after_box.is_some() { + /// Lists that the walk started again with hold nothing yet, so they + /// start from what was read of the boxes before the codestream, shared. + pub(crate) fn reported(&mut self, file: &Jp2File<'_>) -> KeptLists<'_> { + let lists = if file.after_box.is_some() { &mut self.after_box.reported } else { &mut self.after.reported + }; + if lists.other.is_none() { + if let Some(before) = &self.before { + *lists = before.clone(); + } + } + KeptLists { + lists, + before: &mut self.before, + icc: &mut self.icc, } } @@ -758,10 +826,15 @@ impl Walks { } } + /// Whether [`fit`](Self::fit) keeps the walks. + fn keeps_for(&self, start: usize, len: usize) -> bool { + self.start == start && self.len <= len + } + /// Keep the walks only if they were kept for a `jp2c` box whose /// contents start at `start` of an input no longer than `len`. fn fit(&mut self, start: usize, len: usize) { - if self.start != start || self.len > len { + if !self.keeps_for(start, len) { *self = Walks { start, ..Walks::default() @@ -940,13 +1013,22 @@ fn probe_packets(codestream: &[u8], tile: u16, packet_work: &WorkLimit) -> (bool (ends, meter.spent()) } -/// Check the layout of the file's palette and channel definition boxes -/// (`pclr`, `cmap` and `cdef`), which needs nothing from the codestream: how -/// many there are, their order and their payloads. OpenJPEG refuses these as -/// it reads `jp2h`, before the codestream. What the boxes say about the -/// components is checked with the plans. -pub(crate) fn check_box_layout(file: &Jp2File<'_>) -> Result<()> { - layout::read(&file.header, is_jph(&file.file_type)).map(drop) +/// Read the file's palette and channel definition boxes (`pclr`, `cmap` and +/// `cdef`) and check their layout, which needs nothing from the codestream: +/// how many there are, their order and their payloads. OpenJPEG refuses +/// these as it reads `jp2h`, before the codestream. What the boxes say about +/// the components is checked with the plans ([`ChannelPlans::plan`]). +/// +/// `kept` holds what an earlier read of the same input read of them +/// ([`Lists`]): the boxes are before the codestream, so a longer input holds +/// the same ones, and they are read once and shared from there. +pub(crate) fn box_layout(file: &Jp2File<'_>, kept: &mut Lists) -> Result { + if let Some(layout) = &kept.layout { + return Ok(layout.clone()); + } + let layout = layout::read(&file.header, is_jph(&file.file_type))?; + kept.layout = Some(layout.clone()); + Ok(layout) } /// Hold `ihdr` to the codestream: `HEIGHT` and `WIDTH` must equal the SIZ image @@ -972,8 +1054,9 @@ pub(crate) fn check_against_siz(header: &Jp2Header<'_>, siz: &Siz) -> Result<()> pub(crate) struct ChannelPlans { palette: PalettePlan, channels: ChannelPlan, - /// The `cdef` entries as written, when the file has a `cdef`. - definitions: Option>, + /// The `cdef` entries as written, when the file has a `cdef`, shared + /// with the [`BoxLayout`] they were read into. + definitions: Option>, } impl ChannelPlans { @@ -981,26 +1064,24 @@ impl ChannelPlans { /// holding a palette's expanded channels to `cap` samples. `siz` is the /// codestream's SIZ with its image area cut to what the decode returns /// (the selection's area), as the expansion covers only that. - /// The box layout is read first ([`layout::read`]), so its first fault in - /// file order is the one reported, as OpenJPEG reads the boxes. `jph` - /// says whether the file is a JPH file ([`is_jph`]). + /// `layout` is the boxes as [`box_layout`] read them, which checked + /// their layout first, so its first fault in file order is the one + /// reported, as OpenJPEG reads the boxes. The plans share the boxes + /// with it. pub(crate) fn plan( - header: &Jp2Header<'_>, + layout: &BoxLayout, siz: &Siz, reduction: u8, cap: crate::samples::Cap, raw_channels: bool, - jph: bool, ) -> Result { - let layout = layout::read(header, jph)?; - let palette = palette::plan(layout.palette, siz, reduction, cap, raw_channels)?; - let count = palette.output_channels(siz, reduction).len(); - let definitions = layout.cdef.as_deref().map(channels::definitions); - let channels = channels::plan(layout.cdef, count, raw_channels)?; + let palette = palette::plan(layout.palette.as_ref(), siz, reduction, cap, raw_channels)?; + let count = palette.output_count(siz); + let channels = channels::plan(layout.cdef.as_ref(), count, raw_channels)?; Ok(ChannelPlans { palette, channels, - definitions, + definitions: layout.cdef.clone(), }) } @@ -1023,55 +1104,46 @@ impl ChannelPlans { /// relabel them. `siz` is the codestream's. /// /// `kept` is what an earlier read of the same input, no longer than this -/// one, reported from the same walk after the codestream ([`Lists`]): -/// its lists are shared, and only the boxes the walk recorded since are -/// read, then kept there too. With `open_last` off, a last box of length 0 -/// after the codestream, whose contents grow with the input, is left out; -/// with it on, it is reported after the kept lists, and not kept. +/// one, reported from the same walk after the codestream ([`Lists`]), or +/// empty: its lists are shared, and only the boxes the walk recorded since +/// are read, then kept there too, as are the `ftyp` and the `colr` boxes, +/// read once. Empty, the boxes before the codestream are read first, apart, +/// and `before` keeps the lists as they stand then, for a walk after the +/// codestream that starts again to start from ([`Walks::reported`]). With +/// `open_last` off, a last box of length 0 after the codestream, whose +/// contents grow with the input, is left out; with it on, it is reported +/// after the kept lists, and not kept. pub(crate) fn metadata( file: &Jp2File<'_>, plans: &ChannelPlans, siz: &Siz, - kept: Option<&mut Lists>, + kept: &mut Lists, + before: &mut Option, open_last: bool, ) -> Result { - let mut fresh = Lists::default(); - let kept = kept.unwrap_or(&mut fresh); let after = file.after_box(); - if kept.other.is_some_and(|other| other != file.other.len()) { + if kept.other.is_some_and(|other| other != file.other_count) { return Err(Error::inconsistent( "the boxes before the codestream differ from those kept", )); } - let other: &[Jp2Box<'_>] = if kept.other.is_none() { - &file.other - } else { - &[] - }; + if kept.other.is_none() { + read_before(file, kept)?; + *before = Some(kept.clone()); + } let open = after.open_last().filter(|_| open_last); - let (done, read_colr) = (kept.records, kept.colr.is_none()); + let done = kept.records; let built = Copier::twice(|copier| { - let colr = read_colr - .then(|| color_specifications(file, copier)) - .transpose()?; let mut whole = Passthrough::of(kept); - passthrough( - other.iter().copied().map(Ok).chain(after.whole_from(done)?), - copier, - &mut whole, - )?; + passthrough(after.whole_from(done)?, copier, &mut whole)?; let mut open_boxes = Passthrough { rreq_seen: whole.rreq_seen, ..Passthrough::default() }; passthrough(open.into_iter().map(Ok), copier, &mut open_boxes)?; - Ok::<_, Error>((colr, whole, open_boxes)) + Ok::<_, Error>((whole, open_boxes)) })?; - let (colr, whole, open) = built; - if let Some(colr) = colr { - kept.colr = Some(colr); - } - kept.other = Some(file.other.len()); + let (whole, open) = built; kept.records = after.recorded(); kept.xml = whole.xml.finish(); kept.uuid = whole.uuid.finish(); @@ -1097,7 +1169,7 @@ pub(crate) fn metadata( }; let ihdr = &file.header.ihdr; let mut metadata = Jp2Metadata { - channels: color_channels(plans.outputs(siz, 0)?.len(), &color)?, + channels: color_channels(plans.palette.output_count(siz), &color)?, color, palette_applied: false, palette: None, @@ -1114,7 +1186,11 @@ pub(crate) fn metadata( ipr_flag: ihdr.ipr, }, color_specifications, - file_type: file.file_type.clone(), + // A clone shares the compatibility list. + file_type: kept + .file_type + .clone() + .ok_or_else(|| Error::inconsistent("no `ftyp` read"))?, // A clone shares the masks and the lists. reader_requirements: kept.rreq.clone().flatten().or(open.rreq), }; @@ -1123,6 +1199,35 @@ pub(crate) fn metadata( Ok(metadata) } +/// Read into the empty `kept` what the metadata reports of the boxes before +/// the codestream: the `ftyp`, the `colr` boxes, and the top-level boxes +/// [`passthrough`] collects. +fn read_before(file: &Jp2File<'_>, kept: &mut Lists) -> Result<()> { + // A walk that only counted these boxes holds none to read. + if file.other.len() != file.other_count { + return Err(Error::inconsistent( + "the boxes before the codestream were counted, not kept", + )); + } + let (colr, whole) = Copier::twice(|copier| { + let colr = color_specifications(file, copier)?; + let mut whole = Passthrough::default(); + passthrough(file.other.iter().copied().map(Ok), copier, &mut whole)?; + Ok::<_, Error>((colr, whole)) + })?; + kept.colr = Some(colr); + kept.file_type = Some(file.file_type.to_metadata()); + kept.other = Some(file.other_count); + kept.xml = whole.xml.finish(); + kept.uuid = whole.uuid.finish(); + kept.ipr = whole.ipr.finish(); + kept.uuid_info = whole.uuid_info.finish(); + if whole.rreq_seen { + kept.rreq = Some(whole.rreq); + } + Ok(()) +} + /// `list` with the items of `open` after its own, sharing them. fn with_open(list: &MetadataList, open: Extender) -> MetadataList { let mut list = list.clone(); @@ -1197,7 +1302,7 @@ fn passthrough<'a>( } } b"uinf" => { - let info = uuid_info::parse(item.payload, |location| copier.copy(location)); + let info = uuid_info::parse(item.payload, keeps, |location| copier.copy(location)); if let Some(info) = info.filter(|_| keeps) { out.uuid_info.push(info); } @@ -1326,6 +1431,7 @@ pub(crate) fn plan_srgb( siz: &Siz, reduction: u8, cap: crate::samples::Cap, + memo: &mut IccMemo, ) -> Result { srgb::plan( &metadata.color, @@ -1334,5 +1440,6 @@ pub(crate) fn plan_srgb( siz, reduction, cap, + memo, ) } diff --git a/src/jp2/palette.rs b/src/jp2/palette.rs index f1663d36..8b088fd1 100644 --- a/src/jp2/palette.rs +++ b/src/jp2/palette.rs @@ -46,6 +46,8 @@ //! palette" flag. The budget bounds the expanded channels; with the decoded //! components still held, the peak is about twice it (`check_budget`). +use std::sync::Arc; + use super::metadata::{Association, ChannelDefinition, ChannelType, Jp2Metadata}; use crate::codestream::markers::Siz; use crate::samples; @@ -54,6 +56,14 @@ use crate::{Component, ComponentInfo, Error, Result}; /// The most entries a palette may hold (I.5.3.4: `NE` is 1..=1024). const MAX_ENTRIES: u16 = 1024; +/// A column's format from its `Bi` byte. +fn column(bi: u8) -> PaletteColumn { + PaletteColumn { + bit_depth: (bi & 0x7F) + 1, + signed: bi & 0x80 != 0, + } +} + /// One palette column's sample format, from its `Bi` byte. #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] @@ -95,24 +105,28 @@ impl PaletteColumn { /// past the last entry. /// /// The table is at most 1024 entries by 255 columns of `i32`, about 1 MiB, and -/// is bounded by the bytes the `pclr` box holds. It is `#[non_exhaustive]` and -/// built only by the decoder. +/// is bounded by the bytes the `pclr` box holds. It is read once, and a clone +/// shares it, so a [`Header`](crate::Header) or an [`Image`](crate::Image) +/// that holds the palette costs a pointer for it. It is `#[non_exhaustive]` +/// and built only by the decoder. #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub struct Palette { /// `NE`, 1..=1024. entries: u16, /// One per column (`NPC`, 1..=255). - pub(super) columns: Vec, + pub(super) columns: Arc>, /// `NE * NPC` values, entry-major: entry `j` column `i` at /// `j * NPC + i`. - values: Vec, + values: Arc>, } impl Palette { - /// Parse a `pclr` box: `NE` (2 bytes), `NPC` (1 byte), `NPC` `Bi` bytes, - /// then `NE` rows of `NPC` entries (see [`PaletteColumn::entry_bytes`]). - pub(super) fn parse(payload: &[u8]) -> Result { + /// Check a `pclr` box's layout: `NE` (2 bytes), `NPC` (1 byte), `NPC` + /// `Bi` bytes, then `NE` rows of `NPC` entries (see + /// [`PaletteColumn::entry_bytes`]). Returns `NE`, the `Bi` bytes and the + /// table, allocating nothing. + fn layout(payload: &[u8]) -> Result<(u16, &[u8], &[u8])> { let &[ne0, ne1, npc, ref rest @ ..] = payload else { return Err(Error::file_format(format!( "the `pclr` box holds {} bytes, fewer than its 3-byte header", @@ -135,16 +149,8 @@ impl Palette { "the `pclr` box declares {npc} columns but ends inside their `Bi` bytes" ))); }; - let columns: Vec = bi - .iter() - .map(|&b| PaletteColumn { - bit_depth: (b & 0x7F) + 1, - signed: b & 0x80 != 0, - }) - .collect(); - // Bound the table by the bytes the box holds before allocating it. - let row_bytes: usize = columns.iter().map(|c| c.entry_bytes()).sum(); + let row_bytes: usize = bi.iter().map(|&b| column(b).entry_bytes()).sum(); let needed = row_bytes .checked_mul(usize::from(entries)) .ok_or_else(|| Error::file_format("the `pclr` box's entry table size overflows"))?; @@ -154,7 +160,20 @@ impl Palette { table.len() ))); } + Ok((entries, bi, table)) + } + + /// Check a `pclr` box as [`parse`](Self::parse) does, without reading + /// its table: the number of columns, `NPC`. + pub(super) fn check(payload: &[u8]) -> Result { + Self::layout(payload).map(|(_, bi, _)| bi.len()) + } + /// Parse a `pclr` box (see [`layout`](Self::layout)). The table is read + /// once: a clone of the palette shares it. + pub(super) fn parse(payload: &[u8]) -> Result { + let (entries, bi, table) = Self::layout(payload)?; + let columns: Vec = bi.iter().map(|&b| column(b)).collect(); let mut values = Vec::with_capacity(usize::from(entries) * columns.len()); let mut at = 0; for _ in 0..entries { @@ -169,8 +188,8 @@ impl Palette { } Ok(Palette { entries, - columns, - values, + columns: Arc::new(columns), + values: Arc::new(values), }) } @@ -339,15 +358,16 @@ pub(crate) enum PalettePlan { }, } -/// A palette and its `cmap` entries, when the file has a `cmap`. -pub(super) type PaletteBoxes = (Palette, Option>); +/// A palette and its `cmap` entries, when the file has a `cmap`. Both are +/// read once and shared by every plan made from them. +pub(super) type PaletteBoxes = (Palette, Option>); /// Plan the palette the file's boxes hold (`layout`, from /// [`super::layout::read`], which checked the box layout) for a decode at /// `reduction` resolution levels down. The mapping, the column depths and the /// expanded sample count are checked only when the palette is applied. pub(crate) fn plan( - layout: Option, + layout: Option<&PaletteBoxes>, siz: &Siz, reduction: u8, cap: samples::Cap, @@ -356,9 +376,11 @@ pub(crate) fn plan( let Some((palette, Some(entries))) = layout else { return Ok(PalettePlan::None); }; + // A clone shares the table. + let palette = palette.clone(); if raw_channels { let mut index_components = vec![false; siz.components.len()]; - for &(component, mtyp, _) in &entries { + for &(component, mtyp, _) in entries.iter() { if let (1, Some(slot)) = (mtyp, index_components.get_mut(usize::from(component))) { *slot = true; } @@ -366,9 +388,9 @@ pub(crate) fn plan( // The mapping the default decode would use, with OpenJPEG's // correction. A `cmap` the default decode would refuse has no such // mapping, so it is reported as written. - let mapping = match map_channels(&entries, palette.columns.len(), siz.components.len()) { + let mapping = match map_channels(entries, palette.columns.len(), siz.components.len()) { Ok(sources) => sources.into_iter().map(public_source).collect(), - Err(_) => public_mapping(&entries), + Err(_) => public_mapping(entries), }; return Ok(PalettePlan::Skipped { index_components, @@ -376,7 +398,7 @@ pub(crate) fn plan( mapping, }); } - let sources = map_channels(&entries, palette.columns.len(), siz.components.len())?; + let sources = map_channels(entries, palette.columns.len(), siz.components.len())?; let channels: Vec = sources .into_iter() .enumerate() @@ -388,7 +410,7 @@ pub(crate) fn plan( /// Parse a `cmap` box into `(CMP, MTYP, PCOL)` triples, one per palette /// column. Bytes after the last of them are ignored, as OpenJPEG does. -pub(super) fn parse_cmap(payload: &[u8], count: usize) -> Result> { +pub(super) fn parse_cmap(payload: &[u8], count: usize) -> Result> { let needed = count * 4; let Some(body) = payload.get(..needed) else { return Err(Error::file_format(format!( @@ -554,6 +576,15 @@ fn check_budget( } impl PalettePlan { + /// How many output channels there are: the palette's columns when it + /// applies, otherwise the codestream's components. + pub(crate) fn output_count(&self, siz: &Siz) -> usize { + match self { + PalettePlan::Apply { channels, .. } => channels.len(), + PalettePlan::None | PalettePlan::Skipped { .. } => siz.components.len(), + } + } + /// The format of each output channel, from the plan and SIZ alone: the /// palette's channels when it applies, otherwise the codestream's /// components as coded. @@ -679,9 +710,9 @@ mod tests { // 2 entries, columns of 8, 12 and 1 bits: 1 + 2 + 1 bytes per row. let palette = Palette::parse(&pclr(2, &[7, 11, 0], &[1, 0x0A, 0xBC, 1, 2, 0x0F, 0xFF, 0])).unwrap(); - assert_eq!(palette.values, [1, 0xABC, 1, 2, 0xFFF, 0]); + assert_eq!(*palette.values, [1, 0xABC, 1, 2, 0xFFF, 0]); assert_eq!( - palette.columns, + *palette.columns, [ PaletteColumn { bit_depth: 8, @@ -705,7 +736,7 @@ mod tests { fn a_deep_column_is_read_at_a_four_byte_stride() { let palette = Palette::parse(&pclr(2, &[37], &[0, 0, 0, 7, 0xFF, 0xFF, 0xFF, 0xFF])) .expect("4 bytes per entry is enough"); - assert_eq!(palette.values, [7, -1]); + assert_eq!(*palette.values, [7, -1]); assert!(matches!( Palette::parse(&pclr(2, &[37], &[0; 7])), Err(Error::FileFormat(_)) @@ -719,7 +750,7 @@ mod tests { fn entries_are_unsigned_and_unmasked_as_in_openjpeg() { let palette = Palette::parse(&pclr(1, &[0x8B, 11], &[0x0F, 0xFF, 0xF0, 0x00])).unwrap(); assert!(palette.columns[0].signed); - assert_eq!(palette.values, [4095, 0xF000]); + assert_eq!(*palette.values, [4095, 0xF000]); } #[test] diff --git a/src/jp2/payloads.rs b/src/jp2/payloads.rs index eeab9ca1..4cabc331 100644 --- a/src/jp2/payloads.rs +++ b/src/jp2/payloads.rs @@ -5,9 +5,11 @@ use std::sync::Arc; +use super::layout::BoxLayout; use super::list::MetadataList; use super::metadata::{ - ColorSpecification, IprBox, Payload, ReaderRequirements, UuidBox, UuidInfo, WHOLE, XmlBox, + ColorSpecification, FileType, IprBox, Payload, ReaderRequirements, UuidBox, UuidInfo, WHOLE, + XmlBox, }; /// What a read builds the metadata's [`Payload`]s with. The read runs twice @@ -141,7 +143,7 @@ impl<'a> Copier<'a> { /// boxes the walk recorded, which the walk lets go of once they are in /// here. A last box of length 0 is never in them: its contents grow with /// the input. -#[derive(Debug, Default)] +#[derive(Debug, Default, Clone)] pub(crate) struct Lists { /// How many boxes before the codestream the lists start with, once /// they are in. @@ -158,6 +160,11 @@ pub(crate) struct Lists { /// The header's `colr` specifications, and which one holds the ICC /// profile the color space is, once read. pub(crate) colr: Option<(MetadataList, Option)>, + /// The `ftyp` box's fields, once read. + pub(crate) file_type: Option, + /// The header's palette and channel definition boxes, once read + /// ([`box_layout`](super::box_layout)). + pub(crate) layout: Option, } #[cfg(test)] diff --git a/src/jp2/srgb.rs b/src/jp2/srgb.rs index bde466cd..cad8221e 100644 --- a/src/jp2/srgb.rs +++ b/src/jp2/srgb.rs @@ -53,8 +53,12 @@ //! `docs/srgb-output.md` ("Every input and its result") gives every case, what //! OpenJPEG does with it, and the rule behind the choice. +use std::sync::Arc; + use super::lcms::{Format, InputProfile, ToneCurve, Transform}; -use super::metadata::{Association, ChannelDefinition, ChannelType, ColorSpace, Jp2Metadata}; +use super::metadata::{ + Association, ChannelDefinition, ChannelType, ColorSpace, Jp2Metadata, Payload, +}; use crate::codestream::markers::Siz; use crate::samples; use crate::{Component, ComponentInfo, Error, Result}; @@ -80,7 +84,7 @@ pub(crate) enum SrgbPlan { /// A matrix/TRC profile applied to the R, G, B channels at these positions. IccRgb { channels: [usize; 3], - transform: Box, + transform: Arc, }, /// A monochrome profile applied to the gray channel at this position, /// through the RGB each 8-bit gray level maps to. When every level maps @@ -93,6 +97,90 @@ pub(crate) enum SrgbPlan { }, } +/// What the sRGB plans read and built from an ICC profile, for later plans +/// of the same profile to share: reading its curves and building a +/// transform take up to milliseconds and a few hundred KB, and an +/// `IncrementalDecoder` plans on each `header` call. It holds the profile +/// they are of (shared with the metadata), what was read of it for each +/// form, a refusal included, and a transform for each format built, at +/// most three, with the 768-byte table of a gray one. A plan of another +/// profile drops them. None of this depends on the options: the checks +/// that do run on each plan. +#[derive(Debug, Default)] +pub(crate) struct IccMemo { + profile: Option, + inputs: Vec<(Form, std::result::Result, Icc>)>, + built: Vec<(Format, Arc)>, + gray: Option<(Box<[[u8; 3]; 256]>, bool)>, +} + +impl IccMemo { + /// Keep what is held only if it is of `profile`'s bytes. + fn fit(&mut self, profile: &Payload) { + if self.profile.as_deref() != Some(&profile[..]) { + *self = IccMemo { + profile: Some(profile.clone()), + ..IccMemo::default() + }; + } + } + + /// What `read` gives of `profile` for `form`: what it gave before for + /// the same profile bytes and form, or a new read. + fn input( + &mut self, + profile: &Payload, + form: Form, + read: impl FnOnce() -> std::result::Result, + ) -> std::result::Result, Icc> { + self.fit(profile); + if let Some((_, input)) = self.inputs.iter().find(|(read, _)| *read == form) { + return input.clone(); + } + let input = read().map(Arc::new); + self.inputs.push((form, input.clone())); + input + } + + /// The transform of `input`, read from `profile`, for `format`: the one + /// built before for the same profile bytes and format, or a new one. + fn transform( + &mut self, + profile: &Payload, + input: &InputProfile, + format: Format, + ) -> Arc { + self.fit(profile); + if let Some((_, transform)) = self.built.iter().find(|(built, _)| *built == format) { + return transform.clone(); + } + let transform = Arc::new(Transform::new(input, format)); + self.built.push((format, transform.clone())); + transform + } + + /// The RGB each 8-bit gray level maps to through `input`, a gray + /// profile read from `profile`, and whether each is a gray. + fn gray_table( + &mut self, + profile: &Payload, + input: &InputProfile, + ) -> (Box<[[u8; 3]; 256]>, bool) { + self.fit(profile); + if let Some(gray) = &self.gray { + return gray.clone(); + } + let transform = self.transform(profile, input, Format::Gray8); + let mut table = Box::new([[0u8; 3]; 256]); + for (gray, rgb) in (0..=255u8).zip(table.iter_mut()) { + *rgb = transform.gray8(gray); + } + let neutral = table.iter().all(|&[r, g, b]| r == g && g == b); + self.gray = Some((table.clone(), neutral)); + (table, neutral) + } +} + /// How sYCC chroma is sampled relative to luma (always at full resolution). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum ChromaLayout { @@ -115,6 +203,7 @@ pub(crate) fn plan( siz: &Siz, reduction: u8, cap: samples::Cap, + memo: &mut IccMemo, ) -> Result { match color { // OpenJPEG reads any image of two or fewer components as gray (and @@ -138,7 +227,7 @@ pub(crate) fn plan( ColorSpace::Sycc if outputs.len() <= 2 => Ok(SrgbPlan::PassThrough), ColorSpace::Sycc => plan_sycc(channels, outputs, siz, reduction, cap), ColorSpace::RestrictedIcc(profile) => { - plan_icc(profile, channels, outputs, siz, reduction, cap) + plan_icc(profile, channels, outputs, siz, reduction, cap, memo) } // One or two channels with no color space this step converts: // OpenJPEG reads any image of two or fewer components as gray (and @@ -339,12 +428,13 @@ fn check_budget( } fn plan_icc( - profile: &[u8], + profile: &Payload, channels: &[ChannelDefinition], outputs: &[ComponentInfo], siz: &Siz, reduction: u8, cap: samples::Cap, + memo: &mut IccMemo, ) -> Result { // OpenJPEG converts a 4:2:0 or 4:2:2 image as sYCC before it opens the // profile, so this holds whatever the profile is, even one LittleCMS @@ -355,7 +445,7 @@ fn plan_icc( uniform(&[0, 1, 2], outputs)?; return Err(converted_as_sycc_error()); } - match plan_icc_or_refuse(profile, channels, outputs, siz, reduction, cap) { + match plan_icc_or_refuse(profile, channels, outputs, siz, reduction, cap, memo) { Ok(plan) => Ok(plan), // OpenJPEG skips the conversion when LittleCMS refuses the profile // and writes the samples as coded, and so does this step. The @@ -372,17 +462,18 @@ fn plan_icc( /// own checks on the profile and the channels, so a profile OpenJPEG leaves /// as coded passes through whatever the channels are. fn plan_icc_or_refuse( - profile: &[u8], + profile: &Payload, channels: &[ChannelDefinition], outputs: &[ComponentInfo], siz: &Siz, reduction: u8, cap: samples::Cap, + memo: &mut IccMemo, ) -> std::result::Result { let icc = Profile::parse(profile)?; match &icc.space { b"GRAY" => { - let input = icc.input_profile(Form::Gray)?; + let input = memo.input(profile, Form::Gray, || icc.input_profile(Form::Gray))?; let colors = color_channels(channels, outputs, 0); let [channel] = colors[..] else { return Err(Error::unsupported(format!( @@ -403,12 +494,7 @@ fn plan_icc_or_refuse( .into()); } check_icc_format(&outputs[channel], &[8], "monochrome")?; - let transform = Transform::new(&input, Format::Gray8); - let mut table = Box::new([[0u8; 3]; 256]); - for (gray, rgb) in (0..=255u8).zip(table.iter_mut()) { - *rgb = transform.gray8(gray); - } - let neutral = table.iter().all(|&[r, g, b]| r == g && g == b); + let (table, neutral) = memo.gray_table(profile, &input); if !neutral { check_gray_budget(outputs, channel, siz, reduction, cap)?; } @@ -428,7 +514,7 @@ fn plan_icc_or_refuse( if first_four_differ(outputs) { return Err(Icc::Refused); } - let input = icc.input_profile(Form::Rgb)?; + let input = memo.input(profile, Form::Rgb, || icc.input_profile(Form::Rgb))?; let colors = three_colors(channels, outputs, "an RGB ICC profile")?; uniform(&colors, outputs)?; let info = &outputs[colors[0]]; @@ -440,14 +526,14 @@ fn plan_icc_or_refuse( }; Ok(SrgbPlan::IccRgb { channels: colors, - transform: Box::new(Transform::new(&input, format)), + transform: memo.transform(profile, &input, format), }) } // OpenJPEG applies a YCbCr profile only to three or more components, // and LittleCMS refuses first, as for RGB. b"YCbr" if outputs.len() <= 2 => Ok(SrgbPlan::PassThrough), b"YCbr" => { - icc.input_profile(Form::Rgb)?; + memo.input(profile, Form::Rgb, || icc.input_profile(Form::Rgb))?; // OpenJPEG runs the transform as 16-bit YCbCr whatever the // depth: it converts 16-bit samples and crashes on 8-bit ones. // YCbCr is not one of Annex I's restricted forms, so this step @@ -521,7 +607,7 @@ const CORBIS_XYZ: [u8; 4] = 0x17A5_05B8u32.to_be_bytes(); const MONACO_CURVE: [u8; 4] = 0x9478_EE00u32.to_be_bytes(); /// Why a profile is not applied. -#[derive(Debug)] +#[derive(Debug, Clone)] enum Icc { /// OpenJPEG writes the samples as coded: LittleCMS refuses to open the /// profile or to build a transform from it, OpenJPEG has no transform @@ -546,7 +632,7 @@ fn unsupported_profile(what: &str) -> Icc { } /// The color space of a profile this step applies. -#[derive(Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq)] enum Form { Gray, Rgb, @@ -1245,3 +1331,84 @@ pub(crate) fn replicate( } } } + +#[cfg(test)] +mod memo_tests { + use super::*; + + /// The profile of the case `name` in `icc/profiles.json`, one that + /// OpenJPEG converts. + fn converted(name: &str) -> Payload { + let text = include_str!("../../tests/fixtures/icc/profiles.json"); + let profiles: serde_json::Value = serde_json::from_str(text).unwrap(); + let case = profiles["cases"] + .as_array() + .unwrap() + .iter() + .find(|case| case["name"] == name) + .unwrap(); + assert!(case.get("planes").is_some(), "{name} is converted"); + let hex = case["profile"].as_str().unwrap(); + let bytes: Vec = (0..hex.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap()) + .collect(); + Payload::copy_of(&bytes) + } + + /// The memo is keyed on the profile's bytes: a plan of another profile + /// reads that profile and builds its own transform, and does not get + /// the first one's. + #[test] + fn the_memo_reads_and_builds_again_for_another_profile() { + let (first, second) = (converted("identity"), converted("gamma22")); + let read = |profile: &Payload| Profile::parse(profile).unwrap().input_profile(Form::Rgb); + let mut memo = IccMemo::default(); + let mut reads = 0; + + let input = memo + .input(&first, Form::Rgb, || { + reads += 1; + read(&first) + }) + .unwrap(); + let built = memo.transform(&first, &input, Format::Rgb8); + // The same profile again is held, not read or built again. + let again = memo + .input(&first, Form::Rgb, || { + reads += 1; + read(&first) + }) + .unwrap(); + assert!(Arc::ptr_eq(&again, &input)); + assert!(Arc::ptr_eq( + &memo.transform(&first, &again, Format::Rgb8), + &built + )); + assert_eq!(reads, 1); + + // Another profile is read, and its own transform built. + let other = memo + .input(&second, Form::Rgb, || { + reads += 1; + read(&second) + }) + .unwrap(); + assert_eq!(reads, 2); + assert!(!Arc::ptr_eq(&other, &input)); + let rebuilt = memo.transform(&second, &other, Format::Rgb8); + assert!(!Arc::ptr_eq(&rebuilt, &built)); + let fresh = Transform::new(&read(&second).unwrap(), Format::Rgb8); + let samples = [[64, 128, 192], [10, 20, 30], [200, 100, 50]]; + for rgb in samples { + assert_eq!(rebuilt.rgb8(rgb), fresh.rgb8(rgb), "{rgb:?}"); + } + // The two profiles convert differently, so the first transform is + // not the second's. + assert!( + samples + .iter() + .any(|&rgb| built.rgb8(rgb) != rebuilt.rgb8(rgb)) + ); + } +} diff --git a/src/jp2/tests.rs b/src/jp2/tests.rs index 54446d96..7eece069 100644 --- a/src/jp2/tests.rs +++ b/src/jp2/tests.rs @@ -233,7 +233,11 @@ fn a_jp2_decode_carries_the_metadata_skeleton() { file_type: FileType { brand: *b"jp2 ", minor_version: 0, - compatibility: vec![*b"jp2 "], + compatibility: { + let mut list = crate::MetadataList::default(); + list.extend([*b"jp2 "]); + list + }, }, reader_requirements: None, }) @@ -1638,6 +1642,9 @@ fn the_walks_kept_past_the_boxes_start_again_for_another_codestream() { ), // A shorter file. file(&[], &codestream(1), &xml), + // A box the metadata reports before the codestream, which moves + // the box 12 bytes on. + file(std::slice::from_ref(&xml), &codestream(1), &xml), ]; let work = crate::WorkLimit::default(); for (index, then) in pairs.iter().enumerate() { @@ -1645,6 +1652,9 @@ fn the_walks_kept_past_the_boxes_start_again_for_another_codestream() { let mut walks = Walks::default(); let parsed = parse_boxes_kept(&first, &work, &mut walks).expect("parses"); walks.give_back(parsed); + // As a header read leaves them: the walk before the codestream then + // only counts the boxes it reports, unless the box moved. + walks.before = Some(super::Lists::default()); assert_eq!( format!("{:?}", parse_boxes_kept(then, &work, &mut walks)), format!("{:?}", parse_boxes(then, &work)), diff --git a/src/jp2/tests/channels.rs b/src/jp2/tests/channels.rs index 67359259..7382f46a 100644 --- a/src/jp2/tests/channels.rs +++ b/src/jp2/tests/channels.rs @@ -513,3 +513,29 @@ fn a_damaged_cdef_never_panics() { } } } + +/// The entry sizes the rustdoc and `docs/resource-bounds.md` give for the +/// lists a header builds for each output channel, and for a `cdef` entry, +/// on any target. +#[test] +fn a_channel_entry_is_the_size_the_docs_give() { + use crate::{ChannelDefinition, ChannelDefinitionEntry, ChannelMapping, ComponentInfo}; + assert_eq!( + [ + size_of::(), + size_of::(), + size_of::(), + size_of::(), + ], + [8, 10, 6, 12] + ); +} + +/// The size the `IncrementalDecoder::header` rustdoc, `SECURITY.md` and +/// `docs/incremental-decoding.md` give for the JP2 walks a decoder keeps, +/// which hold the lists of the header boxes, on a 64-bit target. +#[cfg(target_pointer_width = "64")] +#[test] +fn the_kept_walks_are_the_size_the_docs_give() { + assert_eq!(size_of::(), 2448); +} diff --git a/src/jp2/tests/uuid_info.rs b/src/jp2/tests/uuid_info.rs index 9043ec34..9d31f6ad 100644 --- a/src/jp2/tests/uuid_info.rs +++ b/src/jp2/tests/uuid_info.rs @@ -127,7 +127,11 @@ fn uuid_info_boxes_are_returned_in_file_order() { ]); let metadata = metadata_of(&bytes); let info = |ids: Vec<[u8; 16]>, version, flags, location: &[u8]| UuidInfo { - ids, + ids: { + let mut list = crate::MetadataList::default(); + list.extend(ids); + list + }, version, flags, location: crate::Payload::copy_of(location), @@ -338,3 +342,20 @@ fn any_uinf_contents_leave_the_decode_unchanged() { // Some edits leave the box well formed, so both paths are taken. assert!(read > 0 && read < ROUNDS, "{read} of {ROUNDS} read"); } + +/// The measure pass of the metadata's copy reads each `uinf` with `keeps` +/// off: it checks the box as the emit pass does but builds no UUID, so the +/// list of UUIDs is built once, by the emit pass. +#[test] +fn a_uinf_only_checked_builds_no_uuid() { + let ids = [[1; 16], [2; 16], [3; 16]]; + let payload = [ulst(3, &ids), url(0, [0; 3], b"a\0")].concat(); + let copy = crate::Payload::copy_of; + let checked = super::super::uuid_info::parse(&payload, false, copy).unwrap(); + assert!(checked.ids.is_empty()); + let kept = super::super::uuid_info::parse(&payload, true, copy).unwrap(); + assert_eq!(kept.ids.iter().copied().collect::>(), ids); + // A malformed `ulst` is refused either way. + let short = [ulst(4, &ids), url(0, [0; 3], b"")].concat(); + assert!(super::super::uuid_info::parse(&short, false, copy).is_none()); +} diff --git a/src/jp2/uuid_info.rs b/src/jp2/uuid_info.rs index 12bb87ae..9c6924bb 100644 --- a/src/jp2/uuid_info.rs +++ b/src/jp2/uuid_info.rs @@ -20,12 +20,15 @@ //! `docs/openjpeg-departures.md` records the choices. use super::boxes::{Boxes, Jp2Box}; +use super::list::{Extender, MetadataList}; use super::{Payload, UuidInfo}; /// Read a `uinf` box's contents, or `None` when it is malformed. The -/// location is built with `copy` from its bytes, a slice of `payload`. +/// location is built with `copy` from its bytes, a slice of `payload`. With +/// `keeps` off the box is only checked, and the UUIDs are left out. pub(crate) fn parse<'a>( payload: &'a [u8], + keeps: bool, copy: impl FnOnce(&'a [u8]) -> Payload, ) -> Option { let mut ulst: Option> = None; @@ -41,7 +44,7 @@ pub(crate) fn parse<'a>( return None; } } - let ids = parse_ulst(ulst?.payload)?; + let ids = parse_ulst(ulst?.payload, keeps)?; let [version, f0, f1, f2, location @ ..] = url?.payload else { return None; }; @@ -53,8 +56,9 @@ pub(crate) fn parse<'a>( }) } -/// Read a `ulst` box's contents: `NU`, then exactly `NU` UUIDs. -fn parse_ulst(payload: &[u8]) -> Option> { +/// Read a `ulst` box's contents: `NU`, then exactly `NU` UUIDs. With +/// `keeps` off they are only checked. +fn parse_ulst(payload: &[u8], keeps: bool) -> Option> { let (count, ids) = payload.split_first_chunk::<2>()?; // `NU * 16` is at most 2^20, so the product cannot overflow. if ids.len() != usize::from(u16::from_be_bytes(*count)) * 16 { @@ -62,13 +66,13 @@ fn parse_ulst(payload: &[u8]) -> Option> { } // The count was checked against the bytes, so the list is bounded by the // input. - Some( - ids.chunks_exact(16) - .map(|id| { - let mut out = [0; 16]; - out.copy_from_slice(id); - out - }) - .collect(), - ) + let mut list = Extender::default(); + if keeps { + for id in ids.chunks_exact(16) { + let mut out = [0; 16]; + out.copy_from_slice(id); + list.push(out); + } + } + Some(list.finish()) } diff --git a/src/lib.rs b/src/lib.rs index 83b3d3b1..2b9dfcf2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -328,8 +328,8 @@ mod readme_examples {} /// and more for a tall, narrow tile or while a palette expands (see [the /// sample limit][sample-limit]). A tile's code-block segment records can /// add up to about 65 bytes per byte of input, and JP2 metadata boxes up to -/// about 3.2 bytes for each byte of them and the first `rreq` about 4.6 MiB -/// more. The limit also sets the +/// about 3.2 bytes for each byte of them, the first `rreq` about 4.6 MiB +/// more and a palette about 1 MiB more. The limit also sets the /// code-blocks and precincts one tile may hold: one for each 512 and each /// 2048 samples it allows, and at least 2^20 and 2^18. This is for the /// one-shot functions; an [`IncrementalDecoder`] keeps per-tile state and can @@ -1460,8 +1460,9 @@ impl DecodeOptions { /// wide: about 4.1 GiB and 9.6 GiB for a file of 100 MB, input included. /// A file that spends its bytes on code-block segments can peak past 43 /// with square tiles; about 102 bytes per byte is the bound for any - /// file, plus up to about 3.2 bytes for each byte of JP2 metadata boxes - /// and about 4.6 MiB more for the first `rreq`. + /// file, plus up to about 3.2 bytes for each byte of JP2 metadata boxes, + /// about 4.6 MiB more for the first `rreq` and about 1 MiB more for a + /// palette. /// /// Under a window or a tile ([`region`](Self::region)), the count /// is the samples of the tiles the decode reads, in every component, as diff --git a/src/pipeline/header.rs b/src/pipeline/header.rs index 592ae67d..c267bea8 100644 --- a/src/pipeline/header.rs +++ b/src/pipeline/header.rs @@ -778,6 +778,8 @@ impl Over { /// | `jp2::AfterWalk` (in [`jp2::Walks`]) | start of the walk, and the report and check flags `==`; position within the input; not lent out | A box read whole by its length reads the same in a longer input, so the walk goes on past it. A box of length 0 or one cut short is never kept past. | /// | `jp2::after::OpenRead` (in `jp2::AfterWalk`) | the box's start from the walk's start and its type `==`; length of its contents `<=`; dropped with the walk | The box has length 0, so it runs to the end of the input, and a longer input holds the same box with more bytes. A `jp2h` read whole up to a child reads the same there, and a `colr`, `pclr`, `cmap` or `cdef` that passed passes with any bytes appended. | /// | `jp2::Lists` (in `jp2::AfterWalk`) | dropped with the walk; how many boxes before the codestream and how many of the walk's records it holds `==` | The bytes fed only grow and the walk is kept for one start, so a longer input holds the same boxes before the codestream, the same header and the same boxes after it up to where the walk stood. Each call reads the records the walk made since, and the walk lets go of those the lists hold. A box of length 0 runs to the end of the input, so the header leaves it out and it is never kept. A debug build checks each payload it copies against the input. | +/// | `jp2::Walks::before` (in [`jp2::Walks`]) | start of the `jp2c` box's contents `==`; length `<=`; dropped with the walks | The lists as the boxes before the codestream left them, with the `ftyp` (`file_type`), the `colr` payloads and the palette, `cmap` and `cdef` (`layout`): those boxes are fixed once the `jp2c` box is found. A walk after the codestream that starts again, as each call does while the codestream's end is not found, starts its lists from a clone of these, which shares them, so it reads only the boxes after the codestream. While they are held, the walk before the codestream counts the boxes the metadata reports there and keeps no record of them; one that finds the `jp2c` box at another start reads them again. | +/// | `jp2::IccMemo` (in [`jp2::Walks`]) | the ICC profile's bytes `==`; the form read (gray or RGB) and the transform's format `==` | Reading a profile's curves and building a transform depend on the profile and the format alone. The checks that depend on the options run on each plan. A plan of another profile drops what is held. | /// /// [`MainKey`] checks the main header against a hash, and [`KeptCut`] checks /// the prefix it was kept for in a debug build, but neither makes a cache @@ -798,12 +800,16 @@ impl Over { /// - [`KeptFault`]: the walk's heap, up to 14 bytes a tile of the grid, and /// the coding of each tile that later tile-parts restate with headers /// that differ; -/// - [`jp2::Walks`]: 1424 bytes and up to four error messages, and a +/// - [`jp2::Walks`]: 2448 bytes and up to four error messages, and a /// 24-byte record for each box after the codestream that the metadata /// reports, in a list that grows by doubling, until the lists below hold /// the box. Of any other box it holds nothing but, for a last box of /// length 0, a fixed record of where its read stopped -/// (`jp2::after::OpenRead`), 152 of those 1424 bytes; +/// (`jp2::after::OpenRead`), 152 of those 2448 bytes. Under +/// `ColorOutput::Srgb` with an ICC profile, it also holds what the plan +/// read of the profile and built from it (`jp2::IccMemo`): the curves +/// read and a transform for each output format, at most three, of 50 to +/// 400 KB each, and a 768-byte table for a gray one; /// - `jp2::Lists` (in `jp2::AfterWalk`): the reported boxes, each an entry /// of 24 bytes (40 for a `uuid`, 56 for a `uinf`; on a 32-bit target 20, and /// 36 for both) and, for a payload of over 15 bytes, its bytes in a chunk @@ -814,7 +820,12 @@ impl Over { /// KiB or one box at a time. The first `rreq` is an entry of 32 bytes for /// each standard feature and 40 for each vendor feature (24 and 36 on a /// 32-bit target), with its masks held as payloads are: at most about -/// 4.6 MiB more. +/// 4.6 MiB more. Once a `jp2c` box is found, the boxes before it are +/// fixed, so the lists also keep what the header builds of them: the +/// `ftyp` as a `FileType`, and the palette, its `cmap` and the `cdef` +/// (`jp2::BoxLayout`), 4 bytes for each entry of a palette column (at +/// most about 1 MiB), 10 for each `cdef` entry. `jp2::Walks::before` +/// shares all of these with the lists, so it holds no heap of its own. #[derive(Default)] pub(crate) struct HeaderCache { /// Boxed, so a decoder with nothing kept holds a pointer. @@ -1679,10 +1690,22 @@ fn read_jp2_file<'a>( streamed: bool, cut: Option<&mut KeptCut>, file: &jp2::Jp2File<'a>, - reported: Option<&mut jp2::Lists>, + reported: Option>, open_last: bool, ) -> std::result::Result, jp2::BoxFault> { - jp2::check_box_layout(file)?; + // A one-shot read keeps what it reads for itself alone. + let (mut fresh, mut fresh_before) = (jp2::Lists::default(), None); + let mut fresh_icc = jp2::IccMemo::default(); + let jp2::KeptLists { + lists: kept, + before, + icc, + } = reported.unwrap_or(jp2::KeptLists { + lists: &mut fresh, + before: &mut fresh_before, + icc: &mut fresh_icc, + }); + let layout = jp2::box_layout(file, kept)?; let parsed = match cut { Some(cut) => { // The boxes before the codestream are read and pass, and more @@ -1745,12 +1768,11 @@ fn read_jp2_file<'a>( let raw_channels = options.raw_channels || options.components.is_some(); // A palette expands the area the decode returns. let plans = jp2::ChannelPlans::plan( - &file.header, + &layout, &selection.area, options.resolution_reduction, cap, raw_channels, - jp2::is_jph(&file.file_type), )?; let mut held = match jp2::check_after_codestream(file, raw_channels) { Err(fault) if streamed && fault.open => Some(fault.error), @@ -1759,56 +1781,58 @@ fn read_jp2_file<'a>( None } }; - let mut metadata = jp2::metadata(file, &plans, siz, reported, open_last)?; + let mut metadata = jp2::metadata(file, &plans, siz, kept, before, open_last)?; if selection.subset { metadata.channels = pick(metadata.channels, &selection.order); } let hold = Hold::of(file); let srgb = match options.color { ColorOutput::AsCoded => None, - ColorOutput::Srgb => match plan_srgb_step(&metadata, &plans, &selection, siz, options, cap) - { - Ok(plan) => { - // A converted image is sRGB (or gray) and carries no - // profile, as OpenJPEG reports it. - plan.describe(&mut metadata); - Some(plan) - } - Err(error) if streamed => { - // The decode plans the step before it parses any tile-part, - // so none can bring a fault first: the refusal is held as a - // stop past tile-parts that closed is. Only the first error - // is held: it is the one the decode gives. - let stop = Stop { - error, - fault: false, - closed: true, - }; - // A guard that changes no answer today: the step's only - // check on the cap, its output against the sample limit, - // comes after every check that refuses it as `Unsupported`, - // and a size-limit refusal more bytes lift does not reach - // here (`Hold::gives`). So the step under the largest cap - // meets the same refusal. A check on the cap placed before - // one of those would need it: under a larger cap that check - // passes and another refusal comes, so the first must hold. - // It is kept for that, as `Hold::gives` says of its guards. - let largest = || { - let largest = samples::Cap { - allowed: samples::ADDRESSABLE_SAMPLES, - ..cap + ColorOutput::Srgb => { + match plan_srgb_step(&metadata, &plans, &selection, siz, options, cap, icc) { + Ok(plan) => { + // A converted image is sRGB (or gray) and carries no + // profile, as OpenJPEG reports it. + plan.describe(&mut metadata); + Some(plan) + } + Err(error) if streamed => { + // The decode plans the step before it parses any tile-part, + // so none can bring a fault first: the refusal is held as a + // stop past tile-parts that closed is. Only the first error + // is held: it is the one the decode gives. + let stop = Stop { + error, + fault: false, + closed: true, }; - plan_srgb_step(&metadata, &plans, &selection, siz, options, largest).err() - }; - if held.is_some() || !hold.gives(&stop, cap, largest) { - held.get_or_insert(stop.error); - None - } else { - return Err(stop.error.into()); + // A guard that changes no answer today: the step's only + // check on the cap, its output against the sample limit, + // comes after every check that refuses it as `Unsupported`, + // and a size-limit refusal more bytes lift does not reach + // here (`Hold::gives`). So the step under the largest cap + // meets the same refusal. A check on the cap placed before + // one of those would need it: under a larger cap that check + // passes and another refusal comes, so the first must hold. + // It is kept for that, as `Hold::gives` says of its guards. + let largest = || { + let largest = samples::Cap { + allowed: samples::ADDRESSABLE_SAMPLES, + ..cap + }; + plan_srgb_step(&metadata, &plans, &selection, siz, options, largest, icc) + .err() + }; + if held.is_some() || !hold.gives(&stop, cap, largest) { + held.get_or_insert(stop.error); + None + } else { + return Err(stop.error.into()); + } } + Err(error) => return Err(error.into()), } - Err(error) => return Err(error.into()), - }, + } }; Ok(Jp2Prefix { codestream: file.codestream, @@ -1831,6 +1855,7 @@ fn plan_srgb_step( siz: &codestream::markers::Siz, options: &DecodeOptions, cap: samples::Cap, + icc: &mut jp2::IccMemo, ) -> Result { let plan = jp2::plan_srgb( metadata, @@ -1838,6 +1863,7 @@ fn plan_srgb_step( &selection.area, options.resolution_reduction, cap, + icc, )?; // Chroma replication keys on the parity of the area's origin on the // reference grid (the full-resolution one, whatever the reduction), so diff --git a/tests/auto_traits.rs b/tests/auto_traits.rs index 360d78ea..f0745c2e 100644 --- a/tests/auto_traits.rs +++ b/tests/auto_traits.rs @@ -31,6 +31,9 @@ const _: () = { holds::>(); holds::>(); holds::>(); + holds::>(); + holds::>(); + holds::>(); holds::>(); holds::>(); holds::(); diff --git a/tests/header_boxes_alloc.rs b/tests/header_boxes_alloc.rs new file mode 100644 index 00000000..adda6e71 --- /dev/null +++ b/tests/header_boxes_alloc.rs @@ -0,0 +1,305 @@ +//! Every box the JP2 metadata reports or reads is read once, and a header +//! that holds it shares it: the guard for the whole class of per-call +//! copies, whatever box a later change adds. +//! +//! One file holds a large box of each type the metadata reports or reads: +//! an `ftyp` of 262144 compatibility codes (1 MiB), and in the `jp2h` a +//! `pclr` of 1024 entries by 8-bit columns, its `cmap`, a `cdef` of 65535 +//! entries, a second `colr` with a 256 KiB profile and a `res `. Before +//! the codestream it holds an `rreq` with masks of 255 bytes, an `xml `, a +//! `uuid`, a `jp2i` and a `uinf` of 4096 UUIDs, then 200 small `uuid` and +//! 200 small `uinf` boxes, and after it the same again with a `colr`. A +//! call of `IncrementalDecoder::header` with nothing new fed must allocate +//! a few KiB, and each header held must add a few hundred bytes, whatever +//! the boxes hold and however many there are: under 4 KiB and 1 KiB with 3 +//! palette columns (1304 and 98 bytes, measured). Each column is an output +//! channel, which the plans and the header hold an entry of in a `Vec` +//! built for the options, so with 255 columns a call allocates under 40 +//! KiB and a header holds under 8 KiB (30536 and 6650 bytes). The same +//! holds while the codestream is fed 4 KiB at a time, and each header then +//! shares the first one's lists. +//! +//! The bytes are counted with a counting global allocator, so this file holds +//! a single test. The shim is in `tests/support/alloc.rs`. + +#[path = "support/alloc.rs"] +mod alloc; +#[path = "support/synth.rs"] +mod synth; +use alloc::{ALLOCATED, CURRENT, PEAK}; +use std::sync::atomic::Ordering; + +use rust_j2k::{DecodeOptions, IncrementalDecoder, read_header}; + +#[global_allocator] +static ALLOCATOR: alloc::PeakAlloc = alloc::PeakAlloc; + +/// A `uinf` of `ids` UUIDs and a URL of 1 KiB. +fn uinf(ids: u16) -> Vec { + let mut ulst = ids.to_be_bytes().to_vec(); + for id in 0..ids { + ulst.extend([id as u8; 16]); + } + let mut url = vec![0; 4]; + url.extend(vec![b'x'; if ids > 1 { 1024 } else { 1 }]); + synth::bx( + b"uinf", + &[synth::bx(b"ulst", &ulst), synth::bx(b"url ", &url)].concat(), + ) +} + +/// An `rreq` of 255-byte masks and 1000 features of each kind. +fn rreq() -> Vec { + let mut payload = vec![255]; + payload.extend([0xFF; 255]); + payload.extend([0xFF; 255]); + payload.extend(1000u16.to_be_bytes()); + for feature in 0..1000u16 { + payload.extend(feature.to_be_bytes()); + payload.extend([feature as u8; 255]); + } + payload.extend(1000u16.to_be_bytes()); + for feature in 0..1000u16 { + payload.extend([feature as u8; 16]); + payload.extend([feature as u8; 255]); + } + synth::bx(b"rreq", &payload) +} + +/// The boxes the metadata reports at the top level, `fill` bytes each: +/// one large one of each type, then 200 small `uuid` and 200 small `uinf` +/// boxes. +fn reported(fill: u8) -> Vec> { + let mut uuid = vec![fill; 16]; + uuid.extend(vec![fill; 256 << 10]); + let mut boxes = vec![ + synth::bx(b"xml ", &vec![fill; 256 << 10]), + synth::bx(b"uuid", &uuid), + synth::bx(b"jp2i", &vec![fill; 256 << 10]), + uinf(4096), + rreq(), + ]; + for at in 0..200u8 { + boxes.push(synth::bx(b"uuid", &[at; 17])); + boxes.push(uinf(1)); + } + boxes +} + +/// The file, with a palette of `columns` columns and a tile-part of +/// `tile` bytes of packet data, the bytes of the boxes the metadata reports +/// or reads, and where the packet data starts. +fn file(columns: usize, tile: usize) -> (Vec, usize, usize) { + let siz = synth::siz_body([4, 4, 0, 0, 4, 4, 0, 0], &[[7, 1, 1]]); + let mut codestream = vec![0xFF, 0x4F]; + codestream.extend(synth::seg(0xFF51, &siz)); + codestream.extend(synth::seg(0xFF52, &synth::cod_body(1, 0, 0, 0))); + codestream.extend(synth::seg(0xFF5C, &synth::qcd_none_body(2, &[8]))); + let header = codestream.len(); + codestream.extend(synth::tile_part(0, 0, 1, &[], &vec![0; tile.max(1)])); + codestream.extend([0xFF, 0xD9]); + + let mut ftyp = b"jp2 \0\0\0\0".to_vec(); + for code in 0..(1u32 << 18) { + ftyp.extend(if code == 7 { + *b"jp2 " + } else { + code.to_be_bytes() + }); + } + let ftyp = synth::bx(b"ftyp", &ftyp); + + let mut pclr = 1024u16.to_be_bytes().to_vec(); + pclr.push(columns as u8); + pclr.extend(vec![7; columns]); + for entry in 0..1024 * columns { + pclr.push(entry as u8); + } + let mut cmap = Vec::new(); + for column in 0..columns { + cmap.extend([0, 0, 1, column as u8]); + } + let cdef: Vec<_> = (0..u16::MAX) + .map(|i| (i % columns as u16, 65535, 65535)) + .collect(); + let profile = synth::bx(b"colr", &synth::colr_icc(&vec![1; 256 << 10])); + let jp2h = [ + synth::ihdr_for(&codestream), + synth::bx(b"colr", &synth::colr_enum(16)), + profile.clone(), + synth::bx(b"pclr", &pclr), + synth::bx(b"cmap", &cmap), + synth::cdef(&cdef), + synth::bx( + b"res ", + &synth::bx(b"resc", &[0, 1, 0, 1, 0, 1, 0, 1, 0, 0]), + ), + ]; + let before = reported(1); + let mut after = reported(2); + after.push(profile); + + let mut bytes = synth::JP2_SIGNATURE.to_vec(); + bytes.extend(&ftyp); + bytes.extend(synth::bx(b"jp2h", &jp2h.concat())); + bytes.extend(before.concat()); + // The `jp2c` box header, the main header and the `SOT` and `SOD`. + let data = bytes.len() + 8 + header + 14; + bytes.extend(synth::bx(b"jp2c", &codestream)); + bytes.extend(after.concat()); + let boxes = ftyp.len() + + jp2h[1..].iter().map(Vec::len).sum::() + + before.iter().chain(&after).map(Vec::len).sum::(); + (bytes, boxes, data) +} + +/// What `run` allocates over the bytes live before it: the most live at +/// once, all it allocated, and what is still live after it. +fn measure(run: impl FnOnce()) -> (usize, usize, usize) { + let before = CURRENT.load(Ordering::SeqCst); + let allocated = ALLOCATED.load(Ordering::SeqCst); + PEAK.store(before, Ordering::SeqCst); + run(); + ( + PEAK.load(Ordering::SeqCst) - before, + ALLOCATED.load(Ordering::SeqCst) - allocated, + CURRENT.load(Ordering::SeqCst).saturating_sub(before), + ) +} + +#[test] +fn every_header_box_is_read_once_and_shared() { + // (palette columns, a call's allocation, a header's own heap) + for (columns, call, own) in [(3, 4 << 10, 1 << 10), (255, 40 << 10, 8 << 10)] { + let (bytes, boxes, _) = file(columns, 0); + let per_byte = |n: usize| n as f64 / boxes as f64; + + // One-shot: each box is built once and held once. + let mut header = None; + let (peak, allocated, held) = measure(|| header = Some(read_header(&bytes).unwrap())); + let jp2 = header.as_ref().unwrap().jp2.as_ref().unwrap(); + assert_eq!(jp2.file_type.compatibility.len(), 1 << 18); + let palette = jp2.palette.as_ref().unwrap(); + assert_eq!( + (palette.entry_count(), palette.columns().len()), + (1024, columns) + ); + assert_eq!(jp2.channel_definitions.as_ref().unwrap().len(), 65535); + assert_eq!(jp2.color_specifications.len(), 2); + assert_eq!(jp2.xml.len(), 2); + assert_eq!((jp2.uuid.len(), jp2.uuid_info.len()), (402, 402)); + assert_eq!(jp2.uuid_info[201].ids.len(), 4096); + assert!(jp2.reader_requirements.is_some()); + eprintln!( + "{columns} columns: read_header of {boxes} bytes of boxes: peak {:.2}, allocated \ + {:.2}, held {:.2} bytes a byte", + per_byte(peak), + per_byte(allocated), + per_byte(held) + ); + // Built once, so the peak is what is held, about 0.96 and 1.12 + // bytes for each byte of the boxes; over 1.4 when the plans and the + // metadata each read a copy. + assert!(per_byte(held) < 1.4, "held {held}"); + assert!(per_byte(peak) < 1.4, "peak {peak}"); + // No copy is held beside the one kept at the end: the peak is over + // what is held by the walks' records of the boxes, 24 bytes a box + // in lists that grow by doubling, and the entries of the channels: + // about 35 KB. + eprintln!( + "{columns} columns: read_header peaks {} bytes over what it holds", + peak - held + ); + assert!(peak - held < 48 << 10, "peak {peak}, held {held}"); + drop(header); + + // Incremental: a call with nothing new fed shares what the last one + // read, and a header held keeps nothing of its own but the entries + // of the output channels. + let mut decoder = IncrementalDecoder::new(DecodeOptions::default()).unwrap(); + decoder.feed(&bytes); + let first = decoder.header().unwrap().unwrap(); + let mut again = None; + let (_, allocated, held) = measure(|| again = Some(decoder.header().unwrap().unwrap())); + let mut more = Vec::with_capacity(10); + let (_, _, held_ten) = measure(|| { + for _ in 0..10 { + more.push(decoder.header().unwrap().unwrap()); + } + }); + eprintln!( + "{columns} columns: header: a call with nothing new allocated {allocated} bytes, \ + its header holds {held}, 10 more hold {held_ten}" + ); + assert_eq!(again.as_ref(), Some(&first)); + assert!( + allocated < call, + "a call with nothing new allocated {allocated}" + ); + assert!(held < own, "a header holds {held}"); + assert!(held_ten < 10 * own, "10 headers hold {held_ten}"); + drop((first, again, more)); + + // Streaming: while the tile-part comes in, the codestream's end is + // not found, so the walk after it starts again on each feed. Each + // call still shares what the first read of the boxes before the + // codestream built, and allocates as one with nothing new does. + let (bytes, _, data) = file(columns, 1 << 20); + let mut decoder = IncrementalDecoder::new(DecodeOptions::default()).unwrap(); + decoder.feed(&bytes[..data + 4096]); + let first = decoder.header().unwrap().unwrap(); + let first_jp2 = first.jp2.as_ref().unwrap(); + let mut most = 0; + let mut fed = data + 4096; + while fed < bytes.len() { + let next = (fed + 4096).min(bytes.len()); + decoder.feed(&bytes[fed..next]); + fed = next; + let mut header = None; + let (_, allocated, _) = measure(|| header = Some(decoder.header().unwrap().unwrap())); + let header = header.unwrap(); + let jp2 = header.jp2.as_ref().unwrap(); + assert!(std::ptr::eq( + &jp2.file_type.compatibility[7], + &first_jp2.file_type.compatibility[7] + )); + assert!(std::ptr::eq( + &jp2.palette.as_ref().unwrap().columns()[0], + &first_jp2.palette.as_ref().unwrap().columns()[0] + )); + let (cdef, first_cdef) = ( + jp2.channel_definitions.as_ref().unwrap(), + first_jp2.channel_definitions.as_ref().unwrap(), + ); + assert!(std::ptr::eq(&cdef[65534], &first_cdef[65534])); + assert!(std::ptr::eq( + &jp2.color_specifications[1].payload[0], + &first_jp2.color_specifications[1].payload[0] + )); + assert!(std::ptr::eq( + &jp2.xml[0].payload[0], + &first_jp2.xml[0].payload[0] + )); + assert!(std::ptr::eq( + &jp2.uuid_info[0].ids[4095], + &first_jp2.uuid_info[0].ids[4095] + )); + let (rreq, first_rreq) = ( + jp2.reader_requirements.as_ref().unwrap(), + first_jp2.reader_requirements.as_ref().unwrap(), + ); + assert!(std::ptr::eq( + &rreq.vendor_features[999], + &first_rreq.vendor_features[999] + )); + if fed < data + (1 << 20) { + most = most.max(allocated); + } + } + eprintln!( + "{columns} columns: header while the tile-part is fed 4 KiB at a time: a call \ + allocated at most {most} bytes" + ); + assert!(most < call, "a call while streaming allocated {most}"); + } +} diff --git a/tests/incremental_header_payloads.rs b/tests/incremental_header_payloads.rs index a7f73da5..49246fae 100644 --- a/tests/incremental_header_payloads.rs +++ b/tests/incremental_header_payloads.rs @@ -461,3 +461,100 @@ fn header_shares_the_rreq_across_calls() { ); } } + +/// A JP2 file whose `ftyp` lists 70 codes, whose `jp2h` holds a palette of +/// 70 entries by 3 columns with its `cmap` and a `cdef` of 70 entries, and +/// with a `uinf` of 70 UUIDs before the codestream and another after it. +fn header_boxes_file() -> Vec { + let codestream = codestream(); + let mut ftyp = b"jp2 \0\0\0\0".to_vec(); + for code in 0..70u32 { + ftyp.extend(if code == 0 { + *b"jp2 " + } else { + code.to_be_bytes() + }); + } + let mut pclr = 70u16.to_be_bytes().to_vec(); + pclr.extend([3, 7, 7, 7]); + pclr.extend((0..210).map(|v| v as u8)); + let cmap = [0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 2]; + let cdef: Vec<_> = (0..70).map(|i| (i % 3, 0, i % 3 + 1)).collect(); + let uinf = |fill: u8| { + let mut ulst = 70u16.to_be_bytes().to_vec(); + for id in 0..70 { + ulst.extend([id ^ fill; 16]); + } + let url = synth::bx(b"url ", b"\0\0\0\0x\0"); + synth::bx(b"uinf", &[synth::bx(b"ulst", &ulst), url].concat()) + }; + let bytes = synth::jp2_file( + &[ + synth::ihdr_for(&codestream), + synth::bx(b"colr", &synth::colr_enum(16)), + synth::bx(b"pclr", &pclr), + synth::bx(b"cmap", &cmap), + synth::cdef(&cdef), + ], + &[uinf(0)], + &codestream, + &[uinf(0xFF)], + ); + let standard = synth::JP2_SIGNATURE.len() + synth::ftyp_jp2().len(); + [ + &synth::JP2_SIGNATURE[..], + &synth::bx(b"ftyp", &ftyp), + &bytes[standard..], + ] + .concat() +} + +/// The `ftyp`, the palette, the `cdef` and the UUIDs of each `uinf` are +/// read once: a later call, and a call on more bytes, share their entries, +/// over more than one block of them, with the palette applied and not. +#[test] +fn header_shares_the_header_boxes_across_calls() { + let bytes = header_boxes_file(); + for raw in [false, true] { + let options = DecodeOptions::default().with_raw_channels(raw); + let mut decoder = IncrementalDecoder::new(options.clone()).unwrap(); + decoder.feed(&bytes); + let first = header_of(&decoder).jp2.unwrap(); + let again = header_of(&decoder).jp2.unwrap(); + decoder.feed(&reported(b"more").concat()); + let longer = header_of(&decoder).jp2.unwrap(); + assert_eq!(longer.xml.len(), 1, "raw {raw}"); + assert_eq!(first.palette_applied, !raw); + let addresses = |jp2: &Jp2Metadata| -> Vec<*const u8> { + let palette = jp2.palette.as_ref().expect("a palette"); + let cdef = jp2.channel_definitions.as_ref().expect("a cdef"); + let mut out: Vec<*const u8> = vec![ + palette.columns().as_ptr().cast(), + palette.entry(0).unwrap().as_ptr().cast(), + palette.entry(69).unwrap().as_ptr().cast(), + ]; + for at in [0, 69] { + out.push(core::ptr::from_ref(&jp2.file_type.compatibility[at]).cast()); + out.push(core::ptr::from_ref(&cdef[at]).cast()); + for info in jp2.uuid_info.iter().take(2) { + out.push(core::ptr::from_ref(&info.ids[at]).cast()); + } + } + out + }; + assert_eq!(addresses(&first).len(), 11, "raw {raw}"); + assert_eq!(addresses(&again), addresses(&first), "raw {raw}"); + assert_eq!(addresses(&longer), addresses(&first), "raw {raw}"); + assert_eq!(first.file_type.compatibility[69], 69u32.to_be_bytes()); + assert_eq!(first.channel_definitions.as_ref().unwrap().len(), 70); + let palette = first.palette.as_ref().unwrap(); + assert_eq!(palette.entry(69), Some(&[207, 208, 209][..])); + assert_eq!(first.uuid_info[1].ids[69], [69 ^ 0xFF; 16]); + assert_eq!(again, first, "raw {raw}"); + assert_eq!( + read_header_with(&bytes, &options).unwrap().jp2.unwrap(), + first, + "raw {raw}" + ); + } +} diff --git a/tests/rreq_alloc.rs b/tests/rreq_alloc.rs index 72298f8a..325079ed 100644 --- a/tests/rreq_alloc.rs +++ b/tests/rreq_alloc.rs @@ -123,4 +123,19 @@ fn the_first_rreq_is_read_once_and_shared() { }; assert_eq!(entries(&again), entries(&first)); assert_eq!(again, first); + + // A second `rreq`, fed after the codestream once the first is kept, is + // not read at all: the call allocates as one with nothing new does. + let second = [ + ((rreq.len() + 8) as u32).to_be_bytes().to_vec(), + b"rreq".to_vec(), + rreq.clone(), + ] + .concat(); + decoder.feed(&second); + let mut later = None; + let (_, allocated, _) = measure(|| later = Some(decoder.header().unwrap().unwrap())); + eprintln!("header: after a second rreq, {allocated} bytes in all"); + assert!(allocated < 4 << 10, "a second rreq allocated {allocated}"); + assert_eq!(entries(&later), entries(&first)); } diff --git a/tests/srgb_header_alloc.rs b/tests/srgb_header_alloc.rs new file mode 100644 index 00000000..f5c109bd --- /dev/null +++ b/tests/srgb_header_alloc.rs @@ -0,0 +1,82 @@ +//! Under `ColorOutput::Srgb`, `IncrementalDecoder::header` plans the sRGB +//! step on each call, and a plan of an ICC profile reads its curves and +//! builds a transform: up to milliseconds and a few hundred KB. The decoder +//! keeps what it read and built of the profile, so a later call with +//! nothing new fed builds none of it again. This runs every profile in +//! `icc/profiles.json` that OpenJPEG converts, RGB and gray. +//! +//! The bytes are counted with a counting global allocator, so this file holds +//! a single test. The shim is in `tests/support/alloc.rs`. + +#[path = "support/alloc.rs"] +mod alloc; +#[path = "support/synth.rs"] +mod synth; +use alloc::ALLOCATED; +use std::sync::atomic::Ordering; + +use rust_j2k::{ColorOutput, ColorSpace, DecodeOptions, IncrementalDecoder}; + +#[global_allocator] +static ALLOCATOR: alloc::PeakAlloc = alloc::PeakAlloc; + +fn hex(text: &str) -> Vec { + (0..text.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap()) + .collect() +} + +#[test] +fn a_later_srgb_header_builds_no_transform() { + let text = String::from_utf8(synth::read_file(synth::fixtures("icc/profiles.json"))).unwrap(); + let profiles: serde_json::Value = serde_json::from_str(&text).unwrap(); + let options = DecodeOptions::default().with_color(ColorOutput::Srgb); + let (mut most, mut converted) = (0, 0); + for case in profiles["cases"].as_array().unwrap() { + // OpenJPEG's planes are given for the profiles it converts. + if case.get("planes").is_none() { + continue; + } + let name = case["name"].as_str().unwrap(); + let source = case["codestream"].as_str().unwrap(); + let file = profiles["codestreams"][source]["file"].as_str().unwrap(); + let codestream = synth::read_file(synth::fixtures(file)); + let header = vec![ + synth::ihdr_for(&codestream), + synth::bx( + b"colr", + &synth::colr_icc(&hex(case["profile"].as_str().unwrap())), + ), + ]; + let bytes = synth::jp2_file(&header, &[], &codestream, &[]); + + let mut decoder = IncrementalDecoder::new(options.clone()).unwrap(); + decoder.feed(&bytes); + let Ok(Some(first)) = decoder.header() else { + continue; + }; + // Converted, and not left as coded under the profile. + if !matches!( + first.jp2.as_ref().unwrap().color, + ColorSpace::Srgb | ColorSpace::Grayscale + ) { + continue; + } + converted += 1; + let before = ALLOCATED.load(Ordering::SeqCst); + let again = decoder.header().unwrap().unwrap(); + let allocated = ALLOCATED.load(Ordering::SeqCst) - before; + assert_eq!(again, first, "{name}"); + // About 2 KB, the header's own and the tag table each plan reads + // (4.3 KB for a profile of 100 tags); one transform built is 50 to + // 400 KB. + assert!( + allocated < 8 << 10, + "{name}: a later call allocated {allocated}" + ); + most = most.max(allocated); + } + eprintln!("{converted} profiles converted: a later call allocated at most {most} bytes"); + assert!(converted > 100, "{converted}"); +}