Repository navigation
fix(j2k-jpeg): judge JPEG scan ends consistently - #384
Merged
Merged
Conversation
…t lies
After the last MCU, finish_scan accepted EOI, rejected any other marker,
and reported a missing EOI when the bit reader held no marker. But the
reader only sees a marker inside its prefetch, so a bogus marker a few
bytes after the last MCU was an UnexpectedMarker error, while the same
marker further on went unseen: the decode reported MissingEoi and
returned the image although the stream does end with EOI. Which bytes a
route prefetched decided acceptance. This is how the malformed-input
harness case jpeg/gen-420-64x48/file-bitflip/10654 (a bogus FF2B 13
bytes before EOI) decoded on the CPU while fast-packet validation, which
checks every marker after SOS, rejected it. T.81 allows only EOI there,
and libjpeg-turbo fails such a stream ("Unsupported marker type").
BitReader::take_next_marker returns the marker a refill paused at, else
the next marker in the unread input, and finish_scan and the fast-packet
checkpoint walk both use it. Bytes between the last MCU and EOI are still
ignored; a stream that ends without a marker still warns MissingEoi.
Test: the_marker_after_the_last_mcu_must_be_eoi_however_far_it_lies
(j2k-jpeg, including case 10654) fails before this change.
After the last MCU of a single-scan frame, finish_scan ignored any bytes before EOI and rejected any marker other than EOI under both policies; EOI after junk decoded even under strict decoding, with no warning. libjpeg-turbo 3.2.1 reads such bytes as "extraneous bytes before marker" (a warning) and accepts RSTn, APPn, COM and DNL there. The end of the scan is now judged once, by scan_end_warnings, from where the reader's data ends (BitReader::data_end, independent of prefetch): - EOI after any 0xFF fill bytes: no warning. The input ending first: MissingEoi, as before. - Other bytes before the marker, or RSTn, APPn, COM or DNL in place of EOI: the new Warning::ExtraneousData, a recovery. Strict decoding returns RecoveryRequired; lenient decoding decodes the image and marks it recovered. A marker straight after the last MCU used to be an UnexpectedMarker error under both policies; it is now the same recovery, so adding junk before it never makes a stream more acceptable. - Any other marker: UnexpectedMarker under both policies. The host checkpoint walk behind device plans and fast packets reads the bytes CPU decode reads and returns the same warnings instead of judging them, since a cached plan is shared by strict and lenient decoders of the same bytes. validate_scan_bytes ends a scan at a marker that may follow the last MCU (and at restart markers past the scan's count) rather than rejecting it. A packet whose scan end needs recovery is cached as the new JpegFastPacketState::NeedsRecovery: fast_packet() is None, so Metal decodes the image on its hybrid route, which runs CPU entropy decode, and JpegCachedPlan::packet_for_decoder hands the packet only to a decoder whose policy accepts the recovery. build_device_plan applies the decoder's policy too. Three test fixtures padded their scans before EOI and now need recovery: baseline_grayscale_jpeg writes exactly its MCUs' bits, padded with 1-bits; the dc_only_420_jpeg unit fixture drops its 8 padding bytes; and the malformed-input harness seed lossless-ycbcr16-422-3x3, a 4:4:4 stream relabelled 4:2:2 with five coded bytes left over, is replaced by the valid 16-bit 4:2:2 lossless fixture. Tests: what_follows_the_last_mcu_is_judged_alike_on_every_request (tails from j2k-test-support's jpeg_scan_tail_cases on 4:2:0, restart-coded, grayscale, 12-bit and lossless seeds, strict and lenient, full, scaled and region requests), scan_end_recovery_keeps_the_packet_for_lenient_decoders_only, extraneous_data_after_the_last_mcu_needs_recovery and the updated the_marker_after_the_last_mcu_must_be_eoi_however_far_it_lies fail before this change.
…y when lenient CUDA decodes JPEGs only through fast packets. Its packet resolution returned the error of a plan with malformed entropy data and otherwise took plan.fast_packet(), which is None for the new NeedsRecovery state, so an image with extraneous data after its last MCU would fail with an unsupported-sampling error even for a lenient decoder that CPU decode lets recover. Resolution now goes through JpegCachedPlan::packet_for_decoder with the decoder that asked: a strict decoder gets RecoveryRequired, as CPU full decode returns, and a lenient one decodes the packet. The bytes-only path used by tests and benchmarks judges by the default, strict options. Test: explicit_cuda_judges_what_follows_the_last_mcu_as_cpu_decode_does (needs a CUDA device) compares strict and lenient explicit CUDA RGB8 decodes and strict tile batches with CPU decode for every scan tail.
Explicit Metal decodes of every scan tail from jpeg_scan_tail_cases, on 4:2:0, 4:2:2 and 4:4:4 fast-packet seeds with and without restart intervals and on a grayscale hybrid seed, under the strict and lenient policies, for full, region and scaled requests, the session decode and the RGB8 tile batch, must accept what CPU decode with the same policy accepts and return its bytes. Images whose scan end needs recovery decode on the hybrid route, so regions above the last MCU row still decode. Inputs that end straight after a restart-coded scan's data without EOI are skipped: CPU decode fails there because a Huffman code's lookahead passes the end of the input, while Metal walks the scan with EOI appended and decodes. That difference predates the end-of-scan rule.
The strict clippy gate's too_long_first_doc_paragraph lint flagged its four-line opening paragraph.
…ackets T.81 B.1.1.2 lets any marker be preceded by any number of 0xFF fill bytes, and CPU decode reads them so: EOI after fill decodes without a warning, an input that ends in fill decodes with MissingEoi, and junk before fill and EOI is ExtraneousData for the bytes before the fill. The fast-packet entropy cursor read the first two bytes of a fill run as the marker 0xFFFF, a capability mismatch, so the plan of every such image was JpegFastPacketState::Unsupported: explicit CUDA declined these valid files as an unsupported request, and Metal decoded them on its hybrid route. The entropy cursor now skips the fill run before a marker's code, so fill never reaches the packet's entropy bytes and FF.. 00 is one stuffed 0xFF, as for CPU decode, and the cursor that maps checkpoint offsets counts fill bytes as no data. It now maps them over the scan's source rather than its payload: a reader parked on the marker that ends a scan sits on its last fill byte, past a payload that stops at the first one when that marker isn't EOI, so a flat image whose last checkpoint parks there got MalformedEntropy for fill before RST3 where CPU decode recovers. A scan tail with fill now gets the plan state and the packet of the same tail without it: fill-eoi and fill-end are Ready with the clean image's packet, and junkN-fill-eoi and stuffed-fill-eoi are NeedsRecovery with the ExtraneousData byte count CPU decode reports. Fill before restart markers inside a scan leaves the clean packet too. The CUDA and Metal kernels get the same entropy bytes, restart offsets and checkpoints as for the tail without fill, so they need no change. Tests: fill_after_the_last_mcu_leaves_the_packet_of_the_tail_without_it, fill_before_restart_markers_leaves_the_clean_packet, entropy_extraction_skips_fill_before_markers and packet_checkpoint_conversion_skips_fill_before_markers fail before this change. The Metal scan-end test now also checks that, on the fast-packet seeds, EOI and the end of the input, with or without fill, take the GPU-only route and every other tail the hybrid one; before this change it fails for fill-eoi and fill-end on all four seeds.
… warnings
Since 5e3445cd the end of a scan can leave two warnings, ExtraneousData
and MissingEoi, but the warning merge still budgeted for one
(MAX_DECODE_SCAN_WARNINGS). A lenient decode of a file with extraneous
bytes after its last MCU, no EOI, and a header warning vector without two
spare slots failed with MemoryCapExceeded ("decode size 176 bytes exceeds
cap 160 bytes"): for example a baseline file with three or four APP
segments the decoder doesn't know.
The budget is now two warnings. The decode workspace cap, which reserves
room for the merge, shrinks by two Warning sizes.
Tests: extraneous_data_and_a_missing_eoi_join_any_number_of_header_warnings
(0 to 9 unknown APP segments; fails at 3 before this change) and
warning_merge_fits_a_full_header_vector_and_every_scan_end_warning.
runtime_metadata_and_context_reserve_reduce_progressive_scratch_cap now
derives its expected cap from the constant.
A baseline, 12-bit or lossless file that holds all its entropy-coded data and ends there, without EOI, failed on the CPU with HuffmanDecode TableExhausted whenever the last Huffman codes' lookahead ran past the end of the input, which it does for most files. Metal and CUDA decode such a file: their host walk appends EOI to the scan first. The scan-end rule already says the input ending after the last MCU decodes with MissingEoi under both policies. BitReader now pads Huffman lookahead with ones at the end of the input as it does at a marker, for every reader of a scan (new, from_snapshot, from_data_position), and also when only the 0xFF fill bytes of a marker that was cut off remain. Value bits are still never padded. So an input that ends without a marker decodes exactly as the same input with EOI appended, which is what the GPU host walk decodes: the same pixels plus MissingEoi when the data is all there, and an error when it is not. Progressive scans keep their explicit choice: padding only when the header walk recorded the end of the input as the scan's end. The scan-tail tests no longer skip the case: the j2k-jpeg, j2k-jpeg-metal and j2k-jpeg-cuda scan_end tests now check "end" and "fill-end" on every seed and request. Tests: what_follows_the_last_mcu_is_judged_alike_on_every_request without its skip fails before this change (420-restart2 "end": TableExhausted); an_input_that_ends_early_decodes_as_it_does_with_eoi_appended cuts each seed at every byte of its last 96 and a spread of earlier ones; huffman_lookahead_is_padded_at_the_end_of_the_input; exact_header_template_decodes_a_tile_that_lacks_only_eoi_with_a_warning. exact_header_template_keeps_truncated_tail_errors_input_specific used a tile that lacked only EOI as its failing input and now cuts into the entropy-coded data; reports_huffman_failure_on_truncated_bit_stream keeps its TableExhausted check on a reader without padding. The CUDA scan_end test is un-skipped but not run here: it needs the PC.
A lossless frame coded in several scans judged what follows a scan's last MCU only when the header walk found EOI straight after the frame's last scan. So under strict decoding, without a warning: - bytes before an APPn, COM, DHT, DQT, DRI or TEM marker after the last scan, and those markers themselves, were accepted, as were extraneous bytes before the end of an input without EOI; - bytes after an earlier scan, before the next scan's markers, were ignored, and so was a restart marker past that scan's last MCU. LosslessScanEnd replaces the validate_eoi flag of the lossless scan view. The frame's last scan is judged by scan_end_warnings whatever marker the walk found after it; when the walk found the end of the input instead and warned of the missing EOI, the scan's own MissingEoi is dropped. An earlier scan is judged by the new scan_end_before_next_scan_warnings: bytes other than fill before the next marker, or a restart marker there, are ExtraneousData. The walk already judged the marker itself. Each scan's warnings are kept (they were overwritten by the next scan's), so MAX_DECODE_SCAN_WARNINGS is five: one for each of up to four scans, and a missing EOI. Metal's lossless decode takes its differences from the same host entropy pass and returns the same warnings. Two outcomes still differ from a single scan's because the header walk reads the markers between scans before any scan decodes: DNL after the last scan is InvalidMarker under both policies, and an input that ends inside a marker's fill bytes is Truncated. Tests: what_follows_a_split_lossless_frames_last_scan_is_judged_as_a_single_scans_end_is (jpeg_scan_tail_cases on every split case of the lossless matrix; fails before this change), extraneous_data_after_an_earlier_scan_of_a_split_lossless_frame_needs_recovery, and explicit_metal_judges_the_scan_ends_of_split_lossless_frames_as_cpu_decode_does.
After the last MCU of a single-scan or split lossless frame, an APPn or COM segment in front of EOI was extraneous data: strict decoding returned RecoveryRequired. A multi-scan sequential or progressive file accepts the same segment without a warning, libjpeg-turbo accepts it everywhere, and metadata that doesn't affect samples is not a recovery. scan_end_warnings now skips APPn and COM segments that lie straight after the scan's data (after any 0xFF fill bytes) and judges what follows them as if it followed the data: EOI leaves no warning, the end of the input leaves MissingEoi, other bytes or RSTn or DNL are ExtraneousData, and any other marker is UnexpectedMarker. Bytes before a segment are still ExtraneousData with that segment's marker, and a segment the input cuts off is still ExtraneousData. Every route (CPU decode, the host walk behind device plans and fast packets, Metal's lossless differences) judges the end through this one function, so they change together; a packet whose scan ends in such a segment is no longer NeedsRecovery. A lossless frame's header walk also treats an input that ends inside a marker's fill bytes as an input without EOI, as a single scan's end does, instead of Truncated. Multi-scan sequential and progressive files are unchanged. The last scan of a split lossless frame drops its own MissingEoi whenever the walk warned of one, not only when the scan ran to the end of the input, so an APPn or COM segment before the end leaves one warning. PreparedLosslessScan's terminal_code is no longer read and is removed. jpeg_scan_tail_cases: "e1" and "fe" are Accepted, and ten tails that start with a COM or APP1 segment cover fill, a second segment, the end of the input, extraneous bytes, RST3, DHT and a cut-off segment after it. The j2k-jpeg, j2k-jpeg-metal and j2k-jpeg-cuda scan_end tests read that table, and so does the fast-packet test of fill after the last MCU, which now counts nine tails with fill. On Metal the ten tails that end in EOI or the end of the input keep the GPU-only route (40 route checks, up from 16). The CHANGELOG entry and book/jpeg.md say the same.
jcwal1516
force-pushed
the
review/jpeg-scan-tail
branch
from
December 2, 2026 19:24
e46ed2c to
5f596a7
Compare
4 of 5 tasks
jcwal1516
marked this pull request as ready for review
December 2, 2026 23:35
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.
What and why
Judge the bytes and markers after every JPEG scan from the reader's actual
data end, independent of prefetch. Strict decoding now rejects extraneous
tail data with
RecoveryRequired; lenient decoding reportsWarning::ExtraneousData. CPU, Metal, CUDA, device plans, and cached packetsshare the same decision.
The complete policy also keeps valid
0xFFfill, APPn, and COM metadata ontheir packet/GPU routes; accepts complete scans that end without EOI with a
MissingEoiwarning; and applies the same rules after every scan of a splitlossless frame. Warning ownership and allocation budgeting cover both scan-end
warnings beside existing header warnings.
Impact
!to the title)data, source noted in a README and NOTICES.md)
Warning::ExtraneousDatais an additive variant of a non-exhaustive publicenum. Implementation API impact: rustdoc-hidden
JpegFastPacketStateisexhaustive, so downstream code that deliberately matches this unsupported
helper must add an arm for
NeedsRecovery.Testing
cargo test --release --locked -p j2k-jpeg --test scan_end -- --nocapture: 5 passed.cargo test --release --locked -p j2k-jpeg exact_header_template -- --nocapture: 4 passed.Focused fill and warning-ownership filters: 14 fill-related tests and 1 warning-merge test passed.
J2K_REQUIRE_METAL_RUNTIME=1 cargo test --release --locked -p j2k-jpeg-metal --test scan_end -- --nocapture: 2 passed on Metal hardware.j2k-jpeg-cuda --features cuda-runtime --test scan_end: 1 passed, 0 skipped on RTX CUDA hardware with the mandatory CUDA-Oxide kernel build.cargo xtask stable-api: passed on the exact PR tip.cargo xtask semver: passed against the v0.13.1 baseline after the public and hidden inventory update.Full CUDA or Metal quick validation: not run.
Bug fix: added a test that fails without the fix
User-visible change: added a
CHANGELOG.mdentry underUnreleased