Skip to main content

rust_j2k/
window.rs

1//! Decoding part of an image: a window on the reference grid, one tile, or
2//! some of the components ([`DecodeOptions::region`],
3//! [`DecodeOptions::components`]).
4//!
5//! The tiles outside the window are not decoded, and the components left out
6//! are not decoded past the packet walk. Inside a tile the window needs, only
7//! the code-blocks whose wavelet support reaches the window are decoded, and
8//! the wavelet runs over only the samples the window needs
9//! ([`crate::dwt::Footprint`]).
10
11use crate::codestream::markers::{Rect, Siz};
12use crate::{ColorOutput, DecodeOptions, Error, ReportEntry, Result};
13
14/// A rectangle on the image's reference grid, `x0..x1` by `y0..y1`, for
15/// [`Region::Window`]. The bounds are half-open: `x1` and `y1` are one
16/// past the last column and row.
17///
18/// The reference grid is the one SIZ declares, so the image area is
19/// `XOsiz..Xsiz` by `YOsiz..Ysiz`, and `(0, 0)` is the grid's origin, not the
20/// image's top-left when the image has an offset. This is the rectangle
21/// OpenJPEG's `opj_set_decode_area` and `opj_decompress -d x0,y0,x1,y1` take.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23#[doc(alias = "decode_area")]
24pub struct Window {
25    /// The left edge.
26    pub x0: u32,
27    /// The top edge.
28    pub y0: u32,
29    /// One past the right edge.
30    pub x1: u32,
31    /// One past the bottom edge.
32    pub y1: u32,
33}
34
35/// The area of the image a decode returns, for [`DecodeOptions::region`].
36///
37/// It selects the decode area. It is not the JPEG 2000 region of interest
38/// (`RGN`), which the decoder applies on its own.
39///
40/// One value holds the choice, so a window and a tile cannot be asked for
41/// together. The enum is `#[non_exhaustive]`, so a new kind of area is not a
42/// breaking change.
43///
44/// ```
45/// use rust_j2k::{DecodeOptions, Region, Window};
46///
47/// assert_eq!(Region::default(), Region::Whole);
48/// let options = DecodeOptions::default().with_region(Region::Window(Window::new(0, 0, 8, 8)));
49/// assert_eq!(options.region, Region::Window(Window::new(0, 0, 8, 8)));
50/// ```
51#[derive(Debug, Clone, PartialEq, Eq, Default)]
52#[non_exhaustive]
53#[doc(alias = "decode_area")]
54pub enum Region {
55    /// The whole image. This is the default.
56    #[default]
57    Whole,
58    /// A rectangle of the reference grid, cut to the image area.
59    Window(Window),
60    /// One tile, by its index in raster order from 0. The header's
61    /// [`tiles`](crate::Header::tiles) gives the grid, and its
62    /// [`count`](crate::TileGrid::count) how many tiles there are.
63    Tile(u32),
64}
65
66impl Window {
67    /// The window `x0..x1` by `y0..y1`.
68    ///
69    /// ```
70    /// use rust_j2k::Window;
71    ///
72    /// let window = Window::new(16, 8, 48, 40);
73    /// assert_eq!((window.x1 - window.x0, window.y1 - window.y0), (32, 32));
74    /// ```
75    #[must_use]
76    pub const fn new(x0: u32, y0: u32, x1: u32, y1: u32) -> Self {
77        Window { x0, y0, x1, y1 }
78    }
79
80    fn rect(self) -> Rect {
81        Rect {
82            x0: self.x0,
83            y0: self.y0,
84            x1: self.x1,
85            y1: self.y1,
86        }
87    }
88}
89
90/// The part of an image a decode returns: its area on the reference grid and
91/// the components, in output order.
92#[derive(Debug, Clone)]
93pub(crate) struct Selection {
94    /// The codestream's SIZ with its image area cut to what the decode
95    /// returns ([`Siz::windowed`]). Equal to the codestream's when the decode
96    /// returns the whole image.
97    pub(crate) area: Siz,
98    /// The SIZ components the decode returns, in output order.
99    pub(crate) order: Vec<usize>,
100    /// Whether [`DecodeOptions::components`] chose the components.
101    pub(crate) subset: bool,
102}
103
104impl Selection {
105    /// Whether tile `index` of `siz` has any of the reference grid this
106    /// decode returns. A tile that touches the area only where a component
107    /// has no sample is still decoded, as OpenJPEG picks its tiles on the
108    /// reference grid too.
109    pub(crate) fn needs_tile(&self, siz: &Siz, index: u32) -> bool {
110        siz.tile_rect(index)
111            .is_some_and(|tile| !tile.intersect(&self.area.image_rect()).is_empty())
112    }
113
114    /// The tiles of `siz` this decode reads, one flag per tile index.
115    pub(crate) fn tiles(&self, siz: &Siz) -> Vec<bool> {
116        (0..siz.num_tiles())
117            .map(|index| self.needs_tile(siz, index))
118            .collect()
119    }
120
121    /// The part of the image the tiles this decode reads cover, on the
122    /// reference grid: the area grown out to the edges of the tiles it
123    /// reaches, which [`tiles`](Self::tiles) flags. Those tiles are a block
124    /// of whole rows and columns of the grid, so their union is a rectangle.
125    /// It is the image area when the decode returns the whole image, or when
126    /// the area is not inside the tile grid, which SIZ's checks rule out.
127    pub(crate) fn read_rect(&self, siz: &Siz) -> Rect {
128        let image = siz.image_rect();
129        let area = self.area.image_rect();
130        let (across, _) = siz.tile_grid();
131        if area.is_empty() || area == image || siz.tile_width == 0 || siz.tile_height == 0 {
132            return image;
133        }
134        // The grid column of `x`, which is at or past the tile origin (A-9).
135        let column = |x: u32| (x.saturating_sub(siz.tile_x_offset)) / siz.tile_width;
136        let row = |y: u32| (y.saturating_sub(siz.tile_y_offset)) / siz.tile_height;
137        let index = |x: u32, y: u32| u64::from(row(y)) * u64::from(across) + u64::from(column(x));
138        let first = u32::try_from(index(area.x0, area.y0)).ok();
139        let last = u32::try_from(index(area.x1 - 1, area.y1 - 1)).ok();
140        match (
141            first.and_then(|i| siz.tile_rect(i)),
142            last.and_then(|i| siz.tile_rect(i)),
143        ) {
144            (Some(first), Some(last)) => Rect {
145                x0: first.x0,
146                y0: first.y0,
147                x1: last.x1,
148                y1: last.y1,
149            },
150            _ => image,
151        }
152    }
153}
154
155/// The checks of the three options that need no input.
156pub(crate) fn check_options(options: &DecodeOptions) -> Result<()> {
157    if let Region::Window(w) = options.region {
158        if w.x0 >= w.x1 || w.y0 >= w.y1 {
159            return Err(Error::invalid_options(format!(
160                "the window {}..{} by {}..{} is empty",
161                w.x0, w.x1, w.y0, w.y1
162            )));
163        }
164    }
165    if let Some(components) = &options.components {
166        if components.is_empty() {
167            return Err(Error::invalid_options(
168                "`DecodeOptions::components` is `Some` of no component; a decode returns \
169                 at least one",
170            ));
171        }
172        let mut sorted = components.clone();
173        sorted.sort_unstable();
174        if let Some(pair) = sorted.windows(2).find(|pair| pair[0] == pair[1]) {
175            return Err(Error::invalid_options(format!(
176                "`DecodeOptions::components` names component {} more than once",
177                pair[0]
178            )));
179        }
180        if options.color == ColorOutput::Srgb {
181            return Err(Error::invalid_options(
182                "`DecodeOptions::components` returns the components as coded, so it cannot \
183                 be combined with `ColorOutput::Srgb`",
184            ));
185        }
186    }
187    Ok(())
188}
189
190/// What a decode of a codestream of `siz` returns under `options`, at
191/// `options.resolution_reduction`. A window is cut to the image area; one
192/// with no part inside it, a tile index past the grid, a component past
193/// SIZ's, and an area that holds no sample of a returned component at the
194/// reduction are [`Error::InvalidOptions`], as OpenJPEG refuses them.
195pub(crate) fn select(siz: &Siz, options: &DecodeOptions) -> Result<Selection> {
196    let image = siz.image_rect();
197    let count = siz.components.len();
198    let order: Vec<usize> = match &options.components {
199        None => (0..count).collect(),
200        Some(list) => {
201            if let Some(&past) = list.iter().find(|&&c| usize::from(c) >= count) {
202                return Err(Error::invalid_options(format!(
203                    "`DecodeOptions::components` names component {past}, but the image has \
204                     {count}"
205                )));
206            }
207            list.iter().map(|&c| usize::from(c)).collect()
208        }
209    };
210    let area = match options.region {
211        Region::Whole => None,
212        Region::Window(window) => {
213            let area = window.rect().intersect(&image);
214            if area.is_empty() {
215                return Err(Error::invalid_options(format!(
216                    "the window {}..{} by {}..{} is outside the image area {}..{} by {}..{}",
217                    window.x0,
218                    window.x1,
219                    window.y0,
220                    window.y1,
221                    image.x0,
222                    image.x1,
223                    image.y0,
224                    image.y1
225                )));
226            }
227            Some(area)
228        }
229        Region::Tile(tile) => Some(siz.tile_rect(tile).ok_or_else(|| {
230            let tiles = siz.num_tiles();
231            Error::invalid_options(if tiles == 1 {
232                format!("tile {tile} is past the image's 1 tile (tile 0)")
233            } else {
234                format!(
235                    "tile {tile} is past the image's {tiles} tiles (0 to {})",
236                    tiles.saturating_sub(1)
237                )
238            })
239        })?),
240    };
241    let Some(area) = area else {
242        return Ok(Selection {
243            area: siz.clone(),
244            order,
245            subset: options.components.is_some(),
246        });
247    };
248    let area = siz.windowed(area);
249    let reduction = options.resolution_reduction;
250    for &comp in &order {
251        let (width, height) = area.component_extent_at(comp, reduction).unwrap_or((0, 0));
252        if width == 0 || height == 0 {
253            return Err(Error::invalid_options(format!(
254                "the area {}..{} by {}..{} holds no sample of component {comp} at resolution \
255                 reduction {reduction}",
256                area.x_offset, area.x_size, area.y_offset, area.y_size
257            )));
258        }
259    }
260    Ok(Selection {
261        area,
262        order,
263        subset: options.components.is_some(),
264    })
265}
266
267/// Keep the report entries about the tiles a decode reads (`tiles`, one flag
268/// per tile index), so a tile outside the window does not make the image
269/// look incomplete. A run of missing tiles is split into the runs of it the
270/// decode reads.
271///
272/// A window reads a rectangle of tiles, so a run splits into at most one
273/// piece per row of tiles it reads, each of at least one tile read: the
274/// pieces are bounded by the tiles read, which the sample limit bounds.
275pub(crate) fn keep_entries(entries: Vec<ReportEntry>, tiles: &[bool]) -> Vec<ReportEntry> {
276    let reads = |tile: u32| tiles.get(tile as usize).copied().unwrap_or(false);
277    let mut kept = Vec::with_capacity(entries.len());
278    for entry in entries {
279        match entry {
280            ReportEntry::MissingTiles { tiles: run } => {
281                let mut tile = run.start;
282                while tile < run.end {
283                    if !reads(tile) {
284                        tile += 1;
285                        continue;
286                    }
287                    let start = tile;
288                    while tile < run.end && reads(tile) {
289                        tile += 1;
290                    }
291                    kept.push(ReportEntry::MissingTiles { tiles: start..tile });
292                }
293            }
294            ReportEntry::MissingPackets { tile, .. }
295            | ReportEntry::TruncatedTilePart { tile, .. }
296            | ReportEntry::TilePartCountMismatch { tile, .. }
297            | ReportEntry::LeftoverBytes { tile, .. } => {
298                if reads(tile) {
299                    kept.push(entry);
300                }
301            }
302            other => kept.push(other),
303        }
304    }
305    kept
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::codestream::markers::SizComponent;
312
313    /// `read_rect` is the union of the tiles `tiles` flags, for windows
314    /// on and off the tile grid, clipped edge tiles, and an image and tile
315    /// grid with origins of their own.
316    #[test]
317    fn the_read_rect_is_the_union_of_the_tiles_read() {
318        // A 7x5 grid of 16x14 tiles from (2, 3); the image is 101x67 at (7, 5),
319        // so the edge tiles are partial.
320        let siz = Siz {
321            x_size: 108,
322            y_size: 72,
323            x_offset: 7,
324            y_offset: 5,
325            tile_width: 16,
326            tile_height: 14,
327            tile_x_offset: 2,
328            tile_y_offset: 3,
329            components: vec![SizComponent {
330                bit_depth: 8,
331                signed: false,
332                x_sampling: 1,
333                y_sampling: 1,
334            }],
335        };
336        let image = siz.image_rect();
337        let mut checked = 0;
338        for x0 in (0..115).step_by(3) {
339            for x1 in (x0 + 1..120).step_by(7) {
340                for (y0, y1) in [(0, 80), (5, 6), (16, 17), (17, 30), (30, 72), (70, 90)] {
341                    let window = Rect { x0, y0, x1, y1 }.intersect(&image);
342                    if window.is_empty() {
343                        continue;
344                    }
345                    let selection = Selection {
346                        area: siz.windowed(window),
347                        order: vec![0],
348                        subset: false,
349                    };
350                    let tiles: Vec<Rect> = selection
351                        .tiles(&siz)
352                        .iter()
353                        .enumerate()
354                        .filter(|(_, read)| **read)
355                        .map(|(index, _)| siz.tile_rect(index as u32).unwrap())
356                        .collect();
357                    let union = tiles.iter().fold(tiles[0], |u, t| Rect {
358                        x0: u.x0.min(t.x0),
359                        y0: u.y0.min(t.y0),
360                        x1: u.x1.max(t.x1),
361                        y1: u.y1.max(t.y1),
362                    });
363                    let area: u64 = tiles
364                        .iter()
365                        .map(|t| u64::from(t.x1 - t.x0) * u64::from(t.y1 - t.y0))
366                        .sum();
367                    let read = selection.read_rect(&siz);
368                    assert_eq!(read, union, "window {window:?}");
369                    // No gap: the tiles read fill their union.
370                    assert_eq!(
371                        area,
372                        u64::from(read.x1 - read.x0) * u64::from(read.y1 - read.y0),
373                        "window {window:?}"
374                    );
375                    checked += 1;
376                }
377            }
378        }
379        assert!(checked > 500, "{checked}");
380    }
381
382    #[test]
383    fn a_run_of_missing_tiles_is_split_at_the_tiles_not_read() {
384        let tiles = [false, true, false, true, false, false];
385        let entries = vec![
386            ReportEntry::MissingTiles { tiles: 0..5 },
387            ReportEntry::MissingTiles { tiles: 4..6 },
388            ReportEntry::TilePartCountMismatch {
389                tile: 2,
390                declared: 2,
391                found: 1,
392            },
393            ReportEntry::TilePartCountMismatch {
394                tile: 3,
395                declared: 2,
396                found: 1,
397            },
398            ReportEntry::MissingEoc,
399        ];
400        assert_eq!(
401            keep_entries(entries, &tiles),
402            vec![
403                ReportEntry::MissingTiles { tiles: 1..2 },
404                ReportEntry::MissingTiles { tiles: 3..4 },
405                ReportEntry::TilePartCountMismatch {
406                    tile: 3,
407                    declared: 2,
408                    found: 1,
409                },
410                ReportEntry::MissingEoc,
411            ]
412        );
413    }
414}