Repository navigation
feat!: read every header box once and share it: ftyp, cdef, pclr and an all-boxes allocation guard - #787
Merged
Conversation
FileType::compatibility, Jp2Metadata::channel_definitions and UuidInfo::ids become MetadataLists, and Palette shares its table. The ftyp is checked without allocating and built once into the kept lists; the pclr, cmap and cdef are read once into a BoxLayout kept there too, which the plans and the metadata share. The checks after the codestream read no palette table. A new allocation test holds a large box of every type the metadata reports or reads and guards the whole class. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
…hared The palette holds 4 bytes for each byte of an 8-bit column, past the 3.2 bound the docs gave for metadata boxes, but at most about 1 MiB, so each citation of the bound names it as the rreq is named. Adds the measured before and after table, pins the entry sizes and the kept walks' size, and lists the new MetadataList types in the auto-trait check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
Clippy's wrong_self_convention on the current stable toolchain. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…at starts again While the codestream's end is not found, the walk after it starts again on each feed, which dropped its lists with it: the ftyp, the box layout, the colr list and the lists of the boxes before the codestream were built again on each call. The walks now keep those apart, for the jp2c start, and a walk that starts again starts from a clone of them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
…ss header calls An IncrementalDecoder now keeps what an sRGB plan read of an ICC profile and the transforms it built, so a later header call builds none again. While the walks hold the lists of the boxes before the codestream, the walk there counts the boxes the metadata reports instead of keeping a record of each, and a box is named only for an error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
…only counted them Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
This was referenced Nov 30, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #786
Every header box is now read once and shared, following the design of #781 and #784 (
jp2::Lists/kept, read once per walk, cloned in O(1)). Before this change:ftyp,pclr,cmapandcdefboxes were read twice by each read of the file, once for the checks and once for the plans and metadata;IncrementalDecoder::headercopied them on every call.The checks now build nothing.
jp2::box_layoutreads the palette,cmapandcdefonce into aBoxLayout, which the plans and the metadata share. Theftypis checked in place and builds itsFileTypeonce. AnIncrementalDecoderkeeps both injp2::Listsfrom the first call that finds thejp2cbox. The boxes before thejp2care fixed from then on, and the lists are reset as before when thejp2cstart changes or the input shrinks.Review round 1: what changed
1. Shares are kept while the codestream arrives (blocking)
AfterWalkresets itsListswhen itsfrommoves, which it does on each call while the codestream's end is not yet fed. So every call rebuilt the lists of the boxes before the codestream.jp2::Walks::beforenow keeps the lists as the boxes before the codestream left them, withfile_type,layoutandcolr. It is keyed on thejp2cstart:Walks::fitdrops it with the rest.Walks::reportedseeds a freshAfterWalk's lists with an O(1) clone ofbefore, so the walk reads only the boxes after the codestream.fromare codestream, not boxes. So that walk still starts again, but from the shared lists.beforeis held, only a count (Kept::count_only), and a walk that finds thejp2cat another start reads them again.Boxes::readno longer builds aStringname for each box; it is formatted only into an error. The records of thejp2hchildren (24 bytes each, for the length of the call) remain; caching them means holding borrowed records apart from the input, so it is documented instead.tests/header_boxes_alloc.rs: the 1 MiB tile-part is fed 4 KiB at a time, each call must allocate under the per-call bound, and each header must share itscompatibility, palette column,cdef,colrpayload,xmlpayload,uinfids andrreqfeatures with the first header (pointer equality). It fails on 2beaa70 (the PR head reviewed).2. The sRGB plan is kept across calls
jp2::IccMemo(crate-internal, inWalks) keeps what the plan read of an ICC profile for each form (gray or RGB, a refusal included), the transform built for each format (at most three), and the gray table. It is keyed on the profile's bytes, and a plan of another profile drops it. The checks that depend on the options still run on each plan. No public API changed.tests/srgb_header_alloc.rs(new) runs every profile inicc/profiles.jsonthat OpenJPEG converts: 179 converted, and a later call allocates at most 4252 bytes (under the 8 KiB bound; one transform built is 50 to 400 KB).Srgbcall3. The docs give the exact costs
The
IncrementalDecoder::headerrustdoc,docs/resource-bounds.md,docs/incremental-decoding.md,SECURITY.md, the CHANGELOG and theHeaderCachedocs no longer say a call "builds nothing of them again" or "8 to 12 bytes per output channel". They now say:ftypor a 65535-entrycdef);jp2hchild costs a 24-byte record for the length of the call, so 50000 unusablecolrchildren (550 KB) cost 0.64 ms and 5.2 MB allocated (3.1 MB peak) a call;size_of::<jp2::Walks>()is now 2448 bytes (was 1824), and the docs and the pin test say so. Theincremental.rsline of 102 columns is re-wrapped.The catch-all now also has the many-small-boxes shape: 200 small
uuidand 200 smalluinfboxes, ares, and anrreqwith ML 255 masks. A later call allocates 1304 bytes with 3 columns and 30536 with 255 (the review measured 58,336 at 255 columns); a header holds 98 and 6650.4. Smaller fixes
jp2::Walks::before(withfile_type,colrandlayout) andjp2::IccMemo, and its Memory list covers both.a_uinf_only_checked_builds_no_uuid(src/jp2/tests/uuid_info.rs).docs/stability.mdneeds nothing: no public type or signature changed in this round, andIccMemoandWalks::beforeare crate-internal.Breaking changes (approved for 0.6.0)
FileType::compatibilityis aMetadataList<[u8; 4]>.UuidInfo::idsis aMetadataList<[u8; 16]>.Jp2Metadata::channel_definitionsis anOption<MetadataList<ChannelDefinitionEntry>>.Palettekeeps its public API. Its tables are behindArc, so a clone shares them.The CHANGELOG "Migrating from 0.5" entry lists these.
Audit: everything
metadata()andheaderbuild or cloneFileType(compatibility)Lists::file_type,MetadataListchannel_definitions(cdef)BoxLayout::cdef, oneMetadataListfor the plans and the metadataPalette(columns,values)ArcinBoxLayoutcmapentriesArc<[_]>inBoxLayoutUuidInfo::idsMetadataList, built only in the pass that keeps itxml,uuid,ipr,uuid_info(location),rreq,colrlist, ICC profileImageHeader,Resolution,color(enum)Copyor fixed sizeJp2Metadata::channels(Vec<ChannelDefinition>, 8 B each)raw_channels, component subset,Srgb)channel_mapping(6 B each)Header::components(12 B each)PalettePlanchannels,ChannelPlanorder/definitions)Jp2File::otherWalks::beforeis held: only countedJp2Headerchildren,colr()/pclr()payloadVecsjp2hchild, for the length of a call; documented with exact figuresjp2::IccMemo, keyed on the profile bytesHeaderpieces inIncrementalDecoder::headerMeasured (docs/resource-bounds.md method)
The base file is
tests/fixtures/jp2_sycc_422_even.jp2with each box added. Each figure comes from a release program with a counting allocator, with resident memory from/usr/bin/time -vless the base file's 2.9 MiB. Heap figures are bytes per byte the boxes add; resident is in MiB. The 1-minute load was about 13.headercall (nothing new), main → nowftyp(4.19 MB)cdef(393 KB)pclr+cmap(262 KB)The first-call incremental peak follows the one-shot peak:
ftyp2.00 → 1.16,cdef3.34 → 1.78,pclr8.00 → 4.03 B/B. A header held after a later call holds 4.2 MB → 68 B (ftyp), 655 KB → 80 B (cdef), and 1.05 MB → 6.6 KB (pclr, the 255 output channels' entries).Bound correction: a palette holds an
i32per entry, which is 4 bytes for each byte of an 8-bit column. That is over the 3.2 B/B the docs gave for metadata boxes, and it was true on main as well (held 4.25 there). The palette is capped at 1024 x 255 entries, about 1 MiB. Every citation of the bound now adds "and about 1 MiB more for a palette", the same way therreq4.6 MiB clause is written. These docs were updated: README, SECURITY (×5),docs/resource-bounds.md(×4 plus a new table),docs/incremental-decoding.md, thesrc/lib.rsrustdoc (×2), theIncrementalDecoder::headerrustdoc and theHeaderCachedocs.size_of::<jp2::Walks>()went from 1424 to 2448 bytes:Listsgainedfile_typeandlayout, andWalksgainedbeforeandicc. The docs now say 2448, and a test pins it on 64-bit targets. A call with nothing new onincremental_header_list_allocnow allocates 688 B (692 before), and its header holds 44 B (48 before). The docs are updated to match.Output identical to main
A release program hashed (128-bit FNV over the
{:#?}text, written as it is formatted, so no dump is kept) each output on main (e8b5b49) and on c57ec70, for all 89.jp2/.jphfixtures undertests/fixtures, in default,Srgband strict-off modes:decode_with,read_header_with, andIncrementalDecoderheadertwice andfinish. That is 1335 hashes, and the two files are identical bycmp. On this branch the twoheadercalls hash the same for every file and mode. No oracle snapshot or fixture changed.Acceptance → tests
Catch-all guard:
tests/header_boxes_alloc.rs(new). One file holds a large box of every type the metadata reports or reads, before and after the codestream. With 3 and with 255 palette columns:It fails on main (4,495,078 B per call with 3 columns).
Shared across calls (pointer equality):
tests/incremental_header_payloads.rs::header_shares_the_header_boxes_across_callschecks palette columns and entries,compatibility,cdefanduinfids acrossfirst,againandlonger, for raw on and off. It fails on main.rreq_seen:tests/rreq_alloc.rsfeeds a second wholerreqafter the codestream. The call allocates < 4 KiB (1048 B) and shares the entries.Sizes the docs give:
a_channel_entry_is_the_size_the_docs_giveandthe_kept_walks_are_the_size_the_docs_give(insrc/jp2/tests/channels.rs).Auto traits:
tests/auto_traits.rscoversMetadataList<ChannelDefinitionEntry>,<[u8; 4]>and<[u8; 16]>.Mutation checks
Each file was backed up and restored after its mutation, each mutation was asserted to apply, and the work was committed first. The suites run were
--lib,header_boxes_alloc,srgb_header_alloc,incremental_header_payloads,rreq_alloc,jp2_palette_metadata,read_header_alloc,incremental_header_list_alloc,incrementalandincremental_header. All 13 were killed.rreq_seen: falserrequnit test,header_boxes_allocheader_boxes_alloc,incremental_header_payloadsftypbuilt on each callpalette::plancdefdeep copy into the plansuinfids also built in the measure passa_uinf_only_checked_builds_no_uuid(new)beforeheader_boxes_alloc, and two incremental unit tests via the new inconsistency guardbeforenever keptheader_boxes_alloc(streaming)srgb_header_allocsrgb_header_allocsrgb_header_allocheader_boxes_allocjp2cmovedthe_walks_kept_past_the_boxes_start_again_for_another_codestream(extended)Gate (stable 1.100.1 after
rustup update stable,nice -n 19 -j 4)cargo fmt --all -- --check: okcargo clippy --all-targets -- -D warnings: okcargo clippy --lib -- -D warnings: okcargo test: 116 suites, 2092 passed, 0 failedcargo deny check: advisories ok, bans ok, licenses ok, sources okRUSTDOCFLAGS=-D warnings cargo doc --no-deps: okwasmtime run --dir=$PWD::$PWD, as CI sets it):--lib856 passed, 6 ignored;jp2_icc30,sample_limit2,limit_32bit18 passedjp2_boxes633,213 runs,header_split117,020,incremental_decode1,044,958 (-max_len=4096); no crashWhat to look at hardest
jp2::box_layoutandLists::layout/file_typerest on one premise: once ajp2cis found, the boxes before it are fixed.Walks::fitalready resetsListswhen thejp2cstart moves or the input shrinks, and nothing new depends on the options (layout::readtakes only the header andjph).color_channels(plans.palette.output_count(siz), …)replacesplans.outputs(siz, 0)?.len(). They are equal:ChannelPlan::applykeeps the length or returns anInconsistenterror that can't occur here, since the plan is built from that count.pclrbound clause above is a correction to a bound that was already exceeded on main.Kept::count_onlyinparse_boxes_kept: the walk before the codestream counts the reported boxes only whileWalks::beforeis held, and walks again keeping them if thejp2cstart is not the one the walks were kept for.read_beforerefuses (Inconsistent) a file whose boxes were only counted.IccMemois keyed on the profile bytes only. The options reach the plan through the format and the checks, which run on each call.🤖 Generated with Claude Code
https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV