rust_j2k/header.rs
1//! What [`read_header`](crate::read_header) returns: an image's shape and
2//! metadata, read without decoding any tile data.
3
4use crate::Window;
5use crate::codestream::markers::Siz;
6use crate::jp2::Jp2Metadata;
7
8/// An image's header: what [`decode`](crate::decode) would return, without
9/// the samples.
10///
11/// The fields describe two things. [`width`](Self::width),
12/// [`height`](Self::height), [`components`](Self::components) and
13/// [`jp2`](Self::jp2) describe the image a decode under the same options
14/// returns, so under [`read_header_with`](crate::read_header_with) they
15/// follow the options: the reduction, window, tile, component subset,
16/// [`raw_channels`](crate::DecodeOptions::raw_channels) and
17/// [`color`](crate::DecodeOptions::color).
18/// [`image_area`](Self::image_area), [`tiles`](Self::tiles),
19/// [`max_reduction`](Self::max_reduction) and
20/// [`quality_layers`](Self::quality_layers) describe the file's main header,
21/// and are the same whatever the options.
22///
23/// The struct is `#[non_exhaustive]`, so more of the header can be added
24/// without a breaking change.
25#[derive(Debug, Clone, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct Header {
28 /// The image area's width, as [`Image::width`](crate::Image::width): on
29 /// the reduced grid under a resolution reduction.
30 pub width: u32,
31 /// The image area's height, as [`Image::height`](crate::Image::height):
32 /// on the reduced grid under a resolution reduction.
33 pub height: u32,
34 /// One entry per [`Image::components`](crate::Image::components) entry,
35 /// in the same order: for a palettized JP2 file, the palette's channels.
36 pub components: Vec<ComponentInfo>,
37 /// The largest
38 /// [`resolution_reduction`](crate::DecodeOptions::resolution_reduction)
39 /// the main header allows: the fewest decomposition levels any component
40 /// has in the main header's `COD` and `COC` markers. A larger reduction is
41 /// [`Error::InvalidOptions`](crate::Error::InvalidOptions). A tile-part
42 /// `COD` or `COC` with fewer levels can still refuse a reduction up to
43 /// this one, but only the decode finds that.
44 pub max_reduction: u8,
45 /// The number of quality layers the main header's `COD` marker declares
46 /// (`SGcod`, at least 1). A
47 /// [`max_quality_layers`](crate::DecodeOptions::max_quality_layers) cap
48 /// (set with
49 /// [`with_max_quality_layers`](crate::DecodeOptions::with_max_quality_layers))
50 /// at or past it decodes every layer of a tile that keeps this `COD`. A
51 /// tile-part `COD` can declare another count for its tile, and only the
52 /// decode reads that.
53 pub quality_layers: u16,
54 /// The image area on the reference grid, as the `SIZ` marker declares
55 /// it: `XOsiz..Xsiz` by `YOsiz..Ysiz`, at full resolution. A
56 /// [`Region::Window`](crate::Region::Window) is in the same coordinates,
57 /// so a window of the image's top-left 64 x 64 samples starts at
58 /// `(image_area.x0, image_area.y0)`, not at `(0, 0)`.
59 pub image_area: Window,
60 /// The tile grid the `SIZ` marker declares. Its
61 /// [`count`](TileGrid::count) is how many tiles
62 /// [`Region::Tile`](crate::Region::Tile) can name: `0` to `count() - 1`.
63 pub tiles: TileGrid,
64 /// What [`decode`](crate::decode) would put on
65 /// [`Image::jp2`](crate::Image::jp2): `None` for a raw codestream.
66 pub jp2: Option<Jp2Metadata>,
67}
68
69/// How an image is cut into tiles: the grid that the `SIZ` marker declares
70/// on the reference grid, the coordinate space of the whole codestream.
71///
72/// Every tile is [`tile_width`](Self::tile_width) by
73/// [`tile_height`](Self::tile_height), and the grid starts at
74/// ([`x_offset`](Self::x_offset), [`y_offset`](Self::y_offset)). Tiles at the
75/// edges are cut to the image area, so they can be smaller. They are
76/// numbered in raster order from 0, as [`Region::Tile`](crate::Region::Tile)
77/// numbers them: tile `n` is in column `n % columns` and row `n / columns`.
78/// An image of one tile has a grid of 1 by 1.
79///
80/// The grid follows ISO/IEC 15444-1 B.3: `columns` is `ceil((Xsiz - XTOsiz)
81/// / XTsiz)` (Eq. B-5), `rows` the same down, and [`tile`](Self::tile) gives
82/// each tile's rectangle (Eq. B-7). On ordinary files the values match what
83/// `opj_dump` prints as `tw`, `th`, `tdx`, `tdy`, `tx0` and `ty0`.
84///
85/// ```
86/// use rust_j2k::{DecodeOptions, Region, decode_with, read_header};
87///
88/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
89/// # let bytes = include_bytes!(concat!(
90/// # env!("CARGO_MANIFEST_DIR"),
91/// # "/tests/fixtures/window/tiled_53.j2k"
92/// # )).to_vec();
93/// # /*
94/// let bytes = std::fs::read("image.j2k")?;
95/// # */
96/// let tiles = read_header(&bytes)?.tiles;
97/// for index in 0..tiles.count() {
98/// let area = tiles.tile(index).expect("the index is below the count");
99/// let options = DecodeOptions::default().with_region(Region::Tile(index));
100/// let tile = decode_with(&bytes, &options)?;
101/// assert_eq!((tile.width, tile.height), (area.x1 - area.x0, area.y1 - area.y0));
102/// println!("tile {index} at ({}, {}): {}x{}", area.x0, area.y0, tile.width, tile.height);
103/// }
104/// # assert_eq!((tiles.columns, tiles.rows), (3, 3));
105/// # Ok(())
106/// # }
107/// ```
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109#[non_exhaustive]
110pub struct TileGrid {
111 /// Tiles across.
112 pub columns: u32,
113 /// Tiles down.
114 pub rows: u32,
115 /// The width of a tile before the cut to the image area (`XTsiz`).
116 pub tile_width: u32,
117 /// The height of a tile before the cut to the image area (`YTsiz`).
118 pub tile_height: u32,
119 /// The left edge of the first column of tiles on the reference grid
120 /// (`XTOsiz`). It is at or left of the image area's left edge.
121 pub x_offset: u32,
122 /// The top edge of the first row of tiles on the reference grid
123 /// (`YTOsiz`). It is at or above the image area's top edge.
124 pub y_offset: u32,
125 /// The image area, which cuts the edge tiles.
126 image: Window,
127}
128
129impl TileGrid {
130 /// How many tiles the image has: `columns * rows`, at most 65535.
131 #[must_use]
132 pub const fn count(&self) -> u32 {
133 self.columns.saturating_mul(self.rows)
134 }
135
136 /// Tile `index`'s rectangle on the reference grid, cut to the image
137 /// area: the area [`Region::Tile`](crate::Region::Tile)`(index)` decodes.
138 /// `None` when `index` is at or past [`count`](Self::count).
139 ///
140 /// Column `p = index % columns` and row `q = index / columns` span
141 /// `max(x_offset + p * tile_width, x0)..min(x_offset + (p + 1) *
142 /// tile_width, x1)` across, for the image area `x0..x1`, and the same
143 /// down (ISO/IEC 15444-1 Eq. B-7).
144 #[must_use]
145 pub fn tile(&self, index: u32) -> Option<Window> {
146 if index >= self.count() {
147 return None;
148 }
149 let (p, q) = (
150 u64::from(index % self.columns),
151 u64::from(index / self.columns),
152 );
153 let (w, h) = (u64::from(self.tile_width), u64::from(self.tile_height));
154 let (xo, yo) = (u64::from(self.x_offset), u64::from(self.y_offset));
155 let image = self.image;
156 // Each end is clamped into the image area, which is u32.
157 let clamp = |v: u64, lo: u32, hi: u32| v.clamp(u64::from(lo), u64::from(hi)) as u32;
158 Some(Window::new(
159 clamp(xo + p * w, image.x0, image.x1),
160 clamp(yo + q * h, image.y0, image.y1),
161 clamp(xo + (p + 1) * w, image.x0, image.x1),
162 clamp(yo + (q + 1) * h, image.y0, image.y1),
163 ))
164 }
165
166 /// The grid `siz` declares.
167 pub(crate) fn of_siz(siz: &Siz) -> Self {
168 let (columns, rows) = siz.tile_grid();
169 TileGrid {
170 columns,
171 rows,
172 tile_width: siz.tile_width,
173 tile_height: siz.tile_height,
174 x_offset: siz.tile_x_offset,
175 y_offset: siz.tile_y_offset,
176 image: image_area(siz),
177 }
178 }
179}
180
181/// The image area `siz` declares.
182pub(crate) fn image_area(siz: &Siz) -> Window {
183 Window::new(siz.x_offset, siz.y_offset, siz.x_size, siz.y_size)
184}
185
186/// One output channel's sample format and size, as on the
187/// [`Component`](crate::Component) that [`decode`](crate::decode) would
188/// return.
189///
190/// The struct is `#[non_exhaustive]`, so more of a channel's description can
191/// be added without a breaking change.
192#[derive(Debug, Clone, PartialEq, Eq)]
193#[non_exhaustive]
194pub struct ComponentInfo {
195 /// Bits per sample: 1 to 31 for unsigned samples, 1 to 32 for signed
196 /// ones, as [`Component::bit_depth`](crate::Component::bit_depth).
197 pub bit_depth: u8,
198 /// Whether the samples are signed.
199 pub signed: bool,
200 /// Horizontal sub-sampling factor on the reference grid; `1` means no
201 /// sub-sampling.
202 pub x_sampling: u8,
203 /// Vertical sub-sampling factor on the reference grid; `1` means no
204 /// sub-sampling.
205 pub y_sampling: u8,
206 /// The channel's width in samples, as
207 /// [`Component::width`](crate::Component::width): `ceil(x1 / dx) -
208 /// ceil(x0 / dx)` for the image area `x0..x1` and the sub-sampling `dx`.
209 /// Under a resolution reduction of `r` levels each end is reduced on its
210 /// own, as OpenJPEG has it: `ceil(ceil(x1 / dx) / 2^r) - ceil(ceil(x0 /
211 /// dx) / 2^r)`. Neither is `ceil(width / dx)`, nor the full width halved:
212 /// those are off by one when the image area starts at an odd offset.
213 pub width: u32,
214 /// The channel's height in samples, as
215 /// [`Component::height`](crate::Component::height); see
216 /// [`width`](Self::width).
217 pub height: u32,
218}
219
220impl ComponentInfo {
221 /// A channel of this format and sub-sampling, sized from `siz` at a
222 /// resolution reduction. A zero sub-sampling factor, which the parser
223 /// rejects, gives an empty channel.
224 pub(crate) fn on_grid(
225 siz: &Siz,
226 bit_depth: u8,
227 signed: bool,
228 x_sampling: u8,
229 y_sampling: u8,
230 reduction: u8,
231 ) -> Self {
232 let (width, height) = siz
233 .sampled_extent_at(x_sampling, y_sampling, reduction)
234 .unwrap_or((0, 0));
235 ComponentInfo {
236 bit_depth,
237 signed,
238 x_sampling,
239 y_sampling,
240 width,
241 height,
242 }
243 }
244
245 /// The codestream's components as coded, sized at a resolution reduction.
246 pub(crate) fn of_siz(siz: &Siz, reduction: u8) -> Vec<Self> {
247 siz.components
248 .iter()
249 .map(|c| {
250 Self::on_grid(
251 siz,
252 c.bit_depth,
253 c.signed,
254 c.x_sampling,
255 c.y_sampling,
256 reduction,
257 )
258 })
259 .collect()
260 }
261}