1use crate::codestream::markers::{Rect, Siz};
12use crate::{ColorOutput, DecodeOptions, Error, ReportEntry, Result};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23#[doc(alias = "decode_area")]
24pub struct Window {
25 pub x0: u32,
27 pub y0: u32,
29 pub x1: u32,
31 pub y1: u32,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, Default)]
52#[non_exhaustive]
53#[doc(alias = "decode_area")]
54pub enum Region {
55 #[default]
57 Whole,
58 Window(Window),
60 Tile(u32),
64}
65
66impl Window {
67 #[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#[derive(Debug, Clone)]
93pub(crate) struct Selection {
94 pub(crate) area: Siz,
98 pub(crate) order: Vec<usize>,
100 pub(crate) subset: bool,
102}
103
104impl Selection {
105 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 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 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 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
155pub(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
190pub(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
267pub(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 #[test]
317 fn the_read_rect_is_the_union_of_the_tiles_read() {
318 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 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}