Skip to content

[V4] Backport codec defect fixes - #3294

Merged
JimBobSquarePants merged 33 commits into
release/4.1.xfrom
js/backports-v4
Dec 1, 2026
Merged

JimBobSquarePants merged 33 commits into
release/4.1.xfrom
js/backports-v4

Conversation

@JimBobSquarePants

Copy link
Copy Markdown
Member

Summary

This PR backports codec defect fixes from main to release/4.1.x.

  • JPEG: table, frame and scan parsing checks.
  • GIF: unknown extensions, frames without color tables, and MaxFrames. A frame delay that the delay field cannot hold now saturates.
  • PNG: chunk order, IHDR, fcTL and dispose_op checks. A frame delay that fcTL cannot hold is written as the nearest fraction.
  • BMP: header reads, pixel offset and compression checks.
  • ANI: the header frame count no longer sets the resource count.
  • PBM: zero width or height is rejected. The Bit component type writes 8-bit samples for gray and RGB.
  • TGA: header checks, color map use from the first entry index, index checks, RLE decode, 16-bit gray alpha, and zero size in Identify.
  • TIFF: strip layout, planar strip count, per-directory tag state, and LZW and PackBits data checks.
  • EXR: decoder defects.
  • WebP:
    • Decoder and encoder defects found against libwebp.
    • TransparentColorMode.Clear in both encoders.
    • Alpha from an ALPH chunk without the VP8X alpha flag.
    • Only the chunks before the first image chunk are used.
    • A frame duration that the ANMF field cannot hold now saturates.

The tests use fixture files and image comparisons. They do not assert internal state.

Known difference

The lossy encoder output on this branch is not byte-equal to libwebp. libwebp encodes method 3 and higher with its token loop (VP8EncTokenLoop). This branch has no token loop. main added it as a performance feature, so this PR does not include it.

- Skip the data sub-blocks of an extension with an unknown label (GIF89a section 12).
- Read the LZW minimum code size of a frame without a color table, so the block alignment stays correct.
- Count the frames that the decoder added for MaxFrames. A first frame with RestoreToPrevious disposal no longer lets an extra frame through.
- DHT uses one counter for the bytes left in the segment, so a table cannot read past the segment.
- DHT in an arithmetic-coded image is checked and ignored, not rejected.
- DAC rejects an odd length, a bad table class and a DC value with L > U.
- SOF13 and SOF14 throw NotSupportedException.
- A SOS marker without a frame and a stream without a frame throw InvalidImageContentException from Identify too.
- A scan after the only scan of a sequential frame throws, or stops the parse when image data errors are ignored.
- The arithmetic decoder stores the conditioning tables by table selector, not by component index.
- A sequential frame uses the standard Huffman table for an undefined table 0 or 1. Other undefined tables throw.
Decode threw ArgumentOutOfRangeException from the image constructor and
Identify returned a 0x0 image. The header check now throws
InvalidImageContentException for both.
Gray and RGB output with the Bit component type, for example from black
and white metadata, threw in the binary encoder and wrote 16-bit samples
with maxval 255 in the plain encoder. The encoder now maps Bit to Byte.
- Throw when the stream is shorter than the 18-byte header.
- Reject image type 0 and unknown image types in Decode and Identify.
- Reject a color mapped image type without a color map.
- Decode 15-bit, 16-bit, 24-bit and 32-bit true-color pixels directly
  when the file has a color map, and skip color map entries in whole bytes.
- Read Width and Height as unsigned 16-bit values. The encoder rejects
  sizes over 65535.
- Decode RLE data one row at a time, so the decode does not need one
  buffer for the whole image. A packet past the last pixel throws
  InvalidImageContentException.
- Dispose the image when Decode throws.
- Decode 16-bit gray without alpha bits as opaque.
The decoder set the capacity of the resource list from cFrames in the anih header. A large value
allocated a large array before the decoder read any chunk. The frame list chunks now set the
resource count.
Each header read must fill its buffer, or the decoder throws before it allocates the pixels.
The pixel data offset must be between the end of the headers and the end of the file.
BI_BITFIELDS and BI_ALPHABITFIELDS are valid only at 16 and 32 bits. Compression 100 (RLE24) is
valid only in OS/2 2.x headers. The header checks reject JPEG, PNG and unknown compression values,
so Identify rejects each header that Decode rejects.
IHDR is the first chunk, has 13 data bytes, a width and a height from 1 to 2^31-1, and
compression method 0. A critical chunk that the decoder does not know throws
NotSupportedException. An fcTL chunk before the first IDAT chunk must cover the whole image.
The fcTL region check uses 64-bit sums, so a large offset cannot wrap, and blend_op must be 0 or
1. The encoder writes dispose_op 0 for an unspecified disposal, not 255. The decoder reads a
dispose_op more than 2 as no disposal, so files with 255 decode with the same pixels.
- Reject a tiled IFD without tile or strip byte counts.
- Decode the short last strip when a file holds extra chunky strips.
- Read a one-sample image with PlanarConfiguration 2 as chunky.
- Reject zero YCbCrSubsampling factors and a zero width or height.
- LZW skips repeated Clear codes.
- PackBits writes the part of a run that fits in the strip.
- Identify reports the inclusive data window size.
- Invalid pixel types, compression values and a short version field are invalid image content.
- A row holds every channel. Unknown channels are skipped in the decoded block.
- PXR24 uses the type of each channel. B44 copies non-HALF channels and restores pLinear channels.
- The chunk byte count must fit the block and the stream. NONE blocks must match the row size.
- DWAA, DWAB, HTJ2K and LJ2K use their rows per chunk for the offset table.
- CMapStart is the color map index of the first stored entry, not a byte
  offset. A pixel index maps to the stored entry index minus CMapStart.
- CMapStart and CMapLength are unsigned 16-bit values.
- Uncompressed color mapped images now decode 8-bit color map entries.
  Both readers use one row conversion.
- A 15-bit entry uses two bytes, and its 16th bit is not alpha. Other
  entry depths throw NotSupportedException.
The check was only in Decode, so Identify returned a 0x0 image. The
header reader now throws InvalidImageContentException for both.
An index before CMapStart or after the last stored entry threw
IndexOutOfRangeException, which Decode reported as ImageFormatException.
The shared row conversion now compares the stored entry index as an
unsigned value with the entry count and throws InvalidImageContentException.
- Planar strips per plane come from the image height. Extra offsets are ignored.
- Reset the optional coding tags for each IFD. YCbCrSubSampling defaults to 2, 2.
- The JPEG path does not write into the YCbCrSubSampling tag array.
- PackBits reads only the bytes of the byte count.
- LZW rejects a code that is not in the current table.
- VP8 segment header: read the segment map probabilities whenever
  update_map is set, also without new segment data. Segment quantizer
  and filter values are signed. A frame without segment data keeps the
  absolute mode (RFC 6386, section 9.3).
- VP8L code lengths: reject a max_symbol larger than the alphabet, a
  repeat past the alphabet, and an incomplete prefix code, as libwebp
  does.
- ALPH header: reject undefined pre-processing values and set reserved
  bits.
- VP8L meta prefix codes: remap a large or sparse group index range to
  the used groups, so that the decoder does not allocate tables for
  unused groups.
The lossy encoder ignored TransparentColorMode.Clear. The lossless
encoder set the color of a transparent pixel to its prediction, not to
zero, and it tested alpha after the conversion to 8 bits.

Both encoders now set all components of each pixel with zero alpha to
zero in the straight RGBA row vectors, before the conversion to Bgra32.
The source pixels do not change. The lossless predictor keeps the
exact residual of each pixel with zero alpha, also with near-lossless
quantization, so the decoded pixel stays zero.

The Issue2801 encoder test now compares with the cleared source, as the
default Clear mode requires.
Lossy:
- The analysis divides the susceptibility sums by Mbw * Mbh, not
  Mbw * Mbw. The chroma quantizer delta of a non-square image was wrong.
- IsFlat counts the non-zero AC levels. It read the first level of each
  block 15 times.
- The chroma DC error diffusion uses the layout [x][channel][2]. The V
  errors overwrote the U errors.

Lossless:
- Near-lossless preprocessing writes the working copy that the encoder
  reads. It wrote the source after the copy, so it had no effect, and
  it changed the source for the next config.
- Each config and sub-config restarts at a saved write position. The
  saved writer swapped with the best writer, so only the first config
  and sub-config could win.
- The histogram image uses its own hash chain. It overwrote the hash
  chain of the image that the next sub-config reads.
- Each sub-config starts from the same maximum color cache size.
- The brute force configs do not include NumEntropyIx.
- The near-lossless context width of a predictor tile with startX > 0
  is correct.
- The hash chain marks skipped pixels of a long run with -1, so pixel 0
  is not a false match candidate.
Use positional arguments, braces and one-line parameter lists in the EXR security tests, and add the blank lines that SA1515 needs in the PNG and WebP tests.
- Decode alpha only when the ALPH data exists. A VP8X alpha flag without an ALPH chunk threw a NullReferenceException.
- Reject a VP8L stream with fewer than 20 bits left for each Huffman group before the table allocation.
- Reject a VP8X still image whose canvas size is not the image size, and a canvas area of 2^32 or more.
- Reject a VP8 partition that starts with a value larger than the range (RFC 6386, section 7.2).
As in libwebp, ALPH data alone decides if a lossy image has alpha. Each animation frame uses only its own ALPH data.
As in libwebp, a VP8X still image uses the first VP8 or VP8L chunk. After it, the decoder reads only the ICCP, EXIF and XMP chunks, so an ALPH chunk after the image chunk does not add alpha.
The graphic control extension delay has 16 bits. The encoder clamps the frame delay to 0..65535 instead of wrapping it.
…not hold

The fcTL delay parts have 16 bits. A delay whose parts fit is written as it is. Otherwise the encoder writes 65535/1 for 65535 seconds or more, or the largest denominator for which the rounded numerator fits, instead of wrapping each part.
The ANMF duration has 24 bits. The encoder clamps the duration to 2^24 - 1 instead of throwing InvalidDataException. WriteUInt24LittleEndian no longer checks its value: each caller limits it.
- Replace the hand-written VP8 and VP8L bitstream builders with crafted fixtures.
- Replace pixel loops with image comparisons in the WebP, TGA and EXR tests.
- Remove the tests that assert internal encoder state.
- Split the near-lossless Clear case: with near-lossless, the decoded transparent pixels stay zero.
@JimBobSquarePants
JimBobSquarePants merged commit a770e76 into release/4.1.x Dec 1, 2026
11 checks passed
@JimBobSquarePants
JimBobSquarePants deleted the js/backports-v4 branch December 1, 2026 08:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant