Skip to content

Decode tiled JPEG TIFFs by splicing JPEGTables (tag 347)#1520

Open
brendancol wants to merge 1 commit intoxarray-contrib:mainfrom
brendancol:fix-1502-jpegtables
Open

Decode tiled JPEG TIFFs by splicing JPEGTables (tag 347)#1520
brendancol wants to merge 1 commit intoxarray-contrib:mainfrom
brendancol:fix-1502-jpegtables

Conversation

@brendancol
Copy link
Copy Markdown
Contributor

Closes #1502.

GDAL-written tiled compress=JPEG TIFFs aren't readable today: each tile is a JPEG fragment that depends on DQT/DHT tables stored once in tag 347, and we never read tag 347. libjpeg sees an SOI immediately followed by SOS and aborts with OSError: broken data stream when reading image file.

Fix:

  • Parse tag 347 in _header.py and surface it as IFD.jpeg_tables.
  • Add _splice_jpeg_tables() in _compression.py: take the tables stream, drop its SOI and trailing EOI, and inject the rest right after the tile's SOI. jpeg_decompress and decompress take a new jpeg_tables= kwarg.
  • Pass ifd.jpeg_tables through _decode_strip_or_tile in the strip, tile, and COG-HTTP paths.
  • Don't second-guess libjpeg on YCbCr: it already converts to RGB on decode, so no extra .convert() call.

Tests in test_jpeg.py: four for the splice helper and two rasterio-backed end-to-end reads (tiled YCbCr 3-band, tiled grayscale) that diff against rasterio and require mean absolute error under 5 for uint8.

Write side is untouched; #1514 already disabled the broken JPEG writer.

GDAL-written tiled compress=JPEG TIFFs aren't readable today: each tile
is a JPEG fragment that depends on DQT/DHT tables stored once in tag
347, and we never read tag 347. libjpeg sees an SOI immediately
followed by SOS and aborts with OSError: broken data stream.

Parse tag 347 in _header.py and surface it as IFD.jpeg_tables. Add
_splice_jpeg_tables() in _compression.py that takes the tables stream,
drops its SOI and trailing EOI, and inserts the rest right after the
tile's SOI. jpeg_decompress and decompress take a new jpeg_tables=
kwarg, and ifd.jpeg_tables flows through _decode_strip_or_tile in the
strip, tile, and COG-HTTP paths.

For YCbCr photometric, libjpeg already converts to RGB on decode, so
the reader uses Pillow's returned mode directly.

Closes xarray-contrib#1502.
@github-actions github-actions Bot added the performance PR touches performance-sensitive code label May 8, 2026
@brendancol brendancol requested a review from Copilot May 8, 2026 02:32
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes interoperability with GDAL-written tiled compress=JPEG TIFFs by parsing the TIFF JPEGTables tag (347) and splicing the shared DQT/DHT tables into each per-tile JPEG fragment before decoding, enabling Pillow/libjpeg to successfully decode those tiles.

Changes:

  • Parse TIFF tag 347 (JPEGTables) in _header.py and expose it as IFD.jpeg_tables.
  • Add JPEG-table splicing support in _compression.py and thread a new jpeg_tables= kwarg through the decode pipeline in _reader.py (strips, tiles, and COG-HTTP).
  • Add unit and end-to-end tests covering table splicing and GDAL-style tiled JPEG reads.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
xrspatial/geotiff/_header.py Adds tag 347 constant and an IFD.jpeg_tables accessor to surface JPEGTables bytes.
xrspatial/geotiff/_compression.py Introduces _splice_jpeg_tables() and plumbs jpeg_tables through jpeg_decompress()/decompress().
xrspatial/geotiff/_reader.py Passes ifd.jpeg_tables into _decode_strip_or_tile() and down into decompress().
xrspatial/geotiff/tests/test_jpeg.py Adds splice-helper tests and rasterio-backed end-to-end tests for GDAL tiled JPEG TIFFs.
Comments suppressed due to low confidence (1)

xrspatial/geotiff/_reader.py:534

  • _decode_strip_or_tile gained a jpeg_tables parameter, but the docstring’s Parameters section doesn’t mention it. Please document what jpeg_tables is (tag 347 payload) and when it is expected to be provided, or remove the partial Parameters section to avoid it getting out of sync.
def _decode_strip_or_tile(data_slice, compression, width, height, samples,
                          bps, bytes_per_sample, is_sub_byte, dtype, pred,
                          byte_order='<', jpeg_tables=None):
    """Decompress, apply predictor, unpack sub-byte, and reshape a strip/tile.

    Parameters
    ----------
    byte_order : str
        '<' for little-endian, '>' for big-endian.  When the file byte
        order differs from the system's native order, pixel data is
        byte-swapped after decompression.

    Returns an array shaped (height, width) or (height, width, samples).
    """

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +215 to +220
rasterio = pytest.importorskip('rasterio')


class TestGdalTiledJpegRead:
"""Read GDAL-style tiled JPEG TIFFs that use the JPEGTables tag."""

Comment on lines +869 to +884
def _splice_jpeg_tables(tile_data: bytes, jpeg_tables: bytes) -> bytes:
"""Splice a JPEGTables stream into a tile's JPEG fragment.

GDAL-style tiled JPEG TIFFs store DQT/DHT tables once in tag 347
(an abbreviated JPEG: SOI + tables + EOI) and each tile is a JPEG
fragment whose own DQT/DHT segments were stripped. To make a tile
self-contained, drop the tables stream's leading SOI and trailing
EOI and insert what remains after the tile's SOI marker.

Both buffers must start with SOI (FF D8). If either does not, the
tile data is returned unchanged so libjpeg sees its original input
and raises a meaningful error.
"""
if not jpeg_tables:
return tile_data
if len(tile_data) < 2 or tile_data[0] != 0xFF or tile_data[1] != 0xD8:
Comment on lines +185 to +188
# BYTE arrays may surface as a tuple of ints
if isinstance(v, tuple):
return bytes(v)
return bytes(v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance PR touches performance-sensitive code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tiled JPEG TIFFs from GDAL fail because reader does not inject JPEGTables (tag 347)

2 participants