Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion crates/data/src/raster/cog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,11 @@ fn read_layout(r: Sparse) -> Result<Parse> {
ColorType::Gray(_) => (1, ColorHint::Gray),
ColorType::GrayA(_) => (2, ColorHint::GrayAlpha),
ColorType::RGB(_) => (3, ColorHint::Rgb { alpha: false }),
ColorType::YCbCr(_) if dec.find_tag_unsigned::<u16>(Tag::Compression).ok().flatten() == Some(7) => {
// A chunk's three bands are turned into colours together, so they are read together.
ColorType::YCbCr(_)
if super::geotiff::is_ycbcr_jpeg(&mut dec)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Consequence to check: a large planar YCbCr JPEG GeoTIFF (for example, a big orthophoto written with separate bands) used to open in place, so a window or tile read stayed cheap. With this guard it is read whole, so its memory and time now scale with the whole file, and the in-place path that the PR's title describes doesn't apply to it. The PR says it "isn't read in place" but doesn't say what that costs or how big a file it covers. Please give its size as a multiple of the layer (AGENTS.md, Size for real data), and confirm that the whole read is refused past memory::planned with a notice, not left to run out of memory.

Confidence: medium-low (I did not trace the whole-read limit for this path).

Category: performance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Checked. The whole-file read is bounded: past max_samples() it reads an overview, or every k-th pixel where there is none, and says so, so memory doesn't grow with the file. Such a file should be rare: gdal_translate refuses to write one (PHOTOMETRIC=YCBCR requires INTERLEAVE=PIXEL). No change.

&& dec.find_tag_unsigned::<u16>(Tag::PlanarConfiguration).ok().flatten() != Some(2) =>
Comment on lines +369 to +371

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The new PlanarConfiguration != 2 guard changes what a planar YCbCr JPEG does: before, it was read in place (and drawn with wrong colours, since each chunk holds one band and ycbcr_to_rgb skips a single band). Now it falls through to NotTiled. That fix is right, but no test covers the planar branch, so nothing checks that a planar YCbCr JPEG is read whole and converted, rather than read in place. A small case in geotiff.rs's tests (planar, compression 7, YCbCr photometric) asserting Parse::NotTiled in cog::layout, and the whole-file read shown in colour, would pin it.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, a hand-built planar file would pin the guard. Left for the release quality pass.

{
(3, ColorHint::Rgb { alpha: false })
}
ColorType::RGBA(_) => (4, ColorHint::Rgb { alpha: true }),
Expand Down Expand Up @@ -761,6 +765,10 @@ pub fn decode_tile_counted(header: &Sparse, layout: &Layout, level: usize, index
}
}
}
// Each level by its own header, as the whole-file reader reads the level it picks (#2761).
if super::geotiff::is_ycbcr_jpeg(&mut dec) {
super::geotiff::ycbcr_to_rgb(&mut out);
}
if let Some(nd) = layout.nodata {
let nd = nd as f32;
for band in &mut out {
Expand Down
48 changes: 46 additions & 2 deletions crates/data/src/raster/geotiff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -749,7 +749,7 @@ pub(crate) fn read_chunk<R: Read + Seek>(

/// Turns a JPEG-compressed image's three YCbCr bands into red, green and blue in place, with the
/// JFIF (full-range) coefficients JPEG-in-TIFF files use.
fn ycbcr_to_rgb(bands: &mut [Vec<f32>]) {
pub(super) fn ycbcr_to_rgb(bands: &mut [Vec<f32>]) {
let [y, cb, cr] = bands else { return };
for ((y, cb), cr) in y.iter_mut().zip(cb.iter_mut()).zip(cr.iter_mut()) {
let (luma, blue, red) = (*y, *cb - 128.0, *cr - 128.0);
Expand All @@ -759,6 +759,12 @@ fn ycbcr_to_rgb(bands: &mut [Vec<f32>]) {
}
}

/// Whether the current image is JPEG-compressed YCbCr, which the decoder leaves as it is: its bands
/// are turned into colours with [`ycbcr_to_rgb`] (#692).
pub(super) fn is_ycbcr_jpeg<R: Read + Seek>(dec: &mut Decoder<R>) -> bool {
matches!(dec.colortype(), Ok(ColorType::YCbCr(_))) && dec.find_tag_unsigned::<u16>(Tag::Compression).ok().flatten() == Some(7)
}

/// Bits per sample of the current image (the most of any sample).
fn bits<R: Read + Seek>(dec: &mut Decoder<R>) -> u16 {
dec.find_tag_unsigned_vec::<u16>(Tag::BitsPerSample).ok().flatten().and_then(|v| v.into_iter().max()).unwrap_or(8)
Expand Down Expand Up @@ -1866,7 +1872,7 @@ fn read_image(
// From here on, tags (colour type, planar layout) are those of the chosen image.
let ct = dec.colortype().map_err(err)?;
// JPEG-compressed YCbCr, the only YCbCr read (the colour match below rejects the rest).
let ycbcr = matches!(ct, ColorType::YCbCr(_)) && dec.find_tag_unsigned::<u16>(Tag::Compression).ok().flatten() == Some(7);
let ycbcr = is_ycbcr_jpeg(&mut dec);
// A palette image (shown to the decoder as grey) is coloured by its table. One whose table
// doesn't decode, or is too short, is drawn grey, and says so (`Raster::lost`).
let (colour_map, map_why) = if palette {
Expand Down Expand Up @@ -5427,6 +5433,44 @@ mod tests {
check(&r, 32, 32);
}

/// Read in place, a chunk at a time, every level is turned into colours as the whole file is
/// (#2761), and no-data is matched with the colours, not with the stored luma.
#[test]
fn ycbcr_jpeg_is_shown_as_rgb_read_in_place() {
use super::super::cog;
let colors = [[200, 30, 30], [30, 160, 40], [20, 40, 220], [230, 230, 60]];
let file = ycbcr_jpeg_tiff(&[(128, 128, 64), (64, 64, 64)], colors, true);
let header = Sparse::default().with(0, file.clone());
let cog::Parse::Done(mut layout) = cog::layout(&header).unwrap() else { panic!("not read in place") };
assert_eq!(layout.levels.len(), 2);
let chunk = |layout: &cog::Layout, level: usize, c: usize| {
let l = &layout.levels[level];
let (at, n) = (l.offsets[c] as usize, l.counts[c] as usize);
cog::decode_tile(&header, layout, level, c as u32, file[at..at + n].to_vec()).unwrap()
};
for (level, size) in [(0, 128usize), (1, 64)] {
for (i, rgb) in colors.iter().enumerate() {
let (x, y) = (size / 4 + size / 2 * (i % 2), size / 4 + size / 2 * (i / 2));
let bands = chunk(&layout, level, y / 64);
for (band, want) in bands.iter().zip(rgb) {
let got = band[(y % 64) * size + x];
assert!((got - f32::from(*want)).abs() <= 4.0, "level {level}, quarter {i}: {got} for {want}");
}
}
}
// The first quarter's red as it decodes, then its luma, as the file's no-data value.
let red = chunk(&layout, 1, 0)[0][16 * 64 + 16];
layout.nodata = Some(f64::from(red));
assert!(chunk(&layout, 1, 0)[0][16 * 64 + 16].is_nan());
let mut dec = Decoder::new(std::io::Cursor::new(&file)).unwrap();
dec.seek_to_image(1).unwrap();
let DecodingResult::U8(stored) = dec.read_chunk(0).unwrap() else { panic!("not bytes") };
let luma = stored[(16 * 64 + 16) * 3];
assert_ne!(f32::from(luma), red);
layout.nodata = Some(f64::from(luma));
assert_eq!(chunk(&layout, 1, 0)[0][16 * 64 + 16], red);
}

#[test]
fn lzw_chunks_decoded_here_match_the_tiff_crate() {
// Every predictor, padded edge tiles on the right and at the bottom.
Expand Down
Loading