use crate::codestream::markers::{Rect, Siz};
use crate::{ColorOutput, DecodeOptions, Error, ReportEntry, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[doc(alias = "decode_area")]
pub struct Window {
pub x0: u32,
pub y0: u32,
pub x1: u32,
pub y1: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
#[doc(alias = "decode_area")]
pub enum Region {
#[default]
Whole,
Window(Window),
Tile(u32),
}
impl Window {
#[must_use]
pub const fn new(x0: u32, y0: u32, x1: u32, y1: u32) -> Self {
Window { x0, y0, x1, y1 }
}
fn rect(self) -> Rect {
Rect {
x0: self.x0,
y0: self.y0,
x1: self.x1,
y1: self.y1,
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct Selection {
pub(crate) area: Siz,
pub(crate) order: Vec<usize>,
pub(crate) subset: bool,
}
impl Selection {
pub(crate) fn needs_tile(&self, siz: &Siz, index: u32) -> bool {
siz.tile_rect(index)
.is_some_and(|tile| !tile.intersect(&self.area.image_rect()).is_empty())
}
pub(crate) fn tiles(&self, siz: &Siz) -> Vec<bool> {
(0..siz.num_tiles())
.map(|index| self.needs_tile(siz, index))
.collect()
}
pub(crate) fn read_rect(&self, siz: &Siz) -> Rect {
let image = siz.image_rect();
let area = self.area.image_rect();
let (across, _) = siz.tile_grid();
if area.is_empty() || area == image || siz.tile_width == 0 || siz.tile_height == 0 {
return image;
}
let column = |x: u32| (x.saturating_sub(siz.tile_x_offset)) / siz.tile_width;
let row = |y: u32| (y.saturating_sub(siz.tile_y_offset)) / siz.tile_height;
let index = |x: u32, y: u32| u64::from(row(y)) * u64::from(across) + u64::from(column(x));
let first = u32::try_from(index(area.x0, area.y0)).ok();
let last = u32::try_from(index(area.x1 - 1, area.y1 - 1)).ok();
match (
first.and_then(|i| siz.tile_rect(i)),
last.and_then(|i| siz.tile_rect(i)),
) {
(Some(first), Some(last)) => Rect {
x0: first.x0,
y0: first.y0,
x1: last.x1,
y1: last.y1,
},
_ => image,
}
}
}
pub(crate) fn check_options(options: &DecodeOptions) -> Result<()> {
if let Region::Window(w) = options.region {
if w.x0 >= w.x1 || w.y0 >= w.y1 {
return Err(Error::invalid_options(format!(
"the window {}..{} by {}..{} is empty",
w.x0, w.x1, w.y0, w.y1
)));
}
}
if let Some(components) = &options.components {
if components.is_empty() {
return Err(Error::invalid_options(
"`DecodeOptions::components` is `Some` of no component; a decode returns \
at least one",
));
}
let mut sorted = components.clone();
sorted.sort_unstable();
if let Some(pair) = sorted.windows(2).find(|pair| pair[0] == pair[1]) {
return Err(Error::invalid_options(format!(
"`DecodeOptions::components` names component {} more than once",
pair[0]
)));
}
if options.color == ColorOutput::Srgb {
return Err(Error::invalid_options(
"`DecodeOptions::components` returns the components as coded, so it cannot \
be combined with `ColorOutput::Srgb`",
));
}
}
Ok(())
}
pub(crate) fn select(siz: &Siz, options: &DecodeOptions) -> Result<Selection> {
let image = siz.image_rect();
let count = siz.components.len();
let order: Vec<usize> = match &options.components {
None => (0..count).collect(),
Some(list) => {
if let Some(&past) = list.iter().find(|&&c| usize::from(c) >= count) {
return Err(Error::invalid_options(format!(
"`DecodeOptions::components` names component {past}, but the image has \
{count}"
)));
}
list.iter().map(|&c| usize::from(c)).collect()
}
};
let area = match options.region {
Region::Whole => None,
Region::Window(window) => {
let area = window.rect().intersect(&image);
if area.is_empty() {
return Err(Error::invalid_options(format!(
"the window {}..{} by {}..{} is outside the image area {}..{} by {}..{}",
window.x0,
window.x1,
window.y0,
window.y1,
image.x0,
image.x1,
image.y0,
image.y1
)));
}
Some(area)
}
Region::Tile(tile) => Some(siz.tile_rect(tile).ok_or_else(|| {
let tiles = siz.num_tiles();
Error::invalid_options(if tiles == 1 {
format!("tile {tile} is past the image's 1 tile (tile 0)")
} else {
format!(
"tile {tile} is past the image's {tiles} tiles (0 to {})",
tiles.saturating_sub(1)
)
})
})?),
};
let Some(area) = area else {
return Ok(Selection {
area: siz.clone(),
order,
subset: options.components.is_some(),
});
};
let area = siz.windowed(area);
let reduction = options.resolution_reduction;
for &comp in &order {
let (width, height) = area.component_extent_at(comp, reduction).unwrap_or((0, 0));
if width == 0 || height == 0 {
return Err(Error::invalid_options(format!(
"the area {}..{} by {}..{} holds no sample of component {comp} at resolution \
reduction {reduction}",
area.x_offset, area.x_size, area.y_offset, area.y_size
)));
}
}
Ok(Selection {
area,
order,
subset: options.components.is_some(),
})
}
pub(crate) fn keep_entries(entries: Vec<ReportEntry>, tiles: &[bool]) -> Vec<ReportEntry> {
let reads = |tile: u32| tiles.get(tile as usize).copied().unwrap_or(false);
let mut kept = Vec::with_capacity(entries.len());
for entry in entries {
match entry {
ReportEntry::MissingTiles { tiles: run } => {
let mut tile = run.start;
while tile < run.end {
if !reads(tile) {
tile += 1;
continue;
}
let start = tile;
while tile < run.end && reads(tile) {
tile += 1;
}
kept.push(ReportEntry::MissingTiles { tiles: start..tile });
}
}
ReportEntry::MissingPackets { tile, .. }
| ReportEntry::TruncatedTilePart { tile, .. }
| ReportEntry::TilePartCountMismatch { tile, .. }
| ReportEntry::LeftoverBytes { tile, .. } => {
if reads(tile) {
kept.push(entry);
}
}
other => kept.push(other),
}
}
kept
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codestream::markers::SizComponent;
#[test]
fn the_read_rect_is_the_union_of_the_tiles_read() {
let siz = Siz {
x_size: 108,
y_size: 72,
x_offset: 7,
y_offset: 5,
tile_width: 16,
tile_height: 14,
tile_x_offset: 2,
tile_y_offset: 3,
components: vec![SizComponent {
bit_depth: 8,
signed: false,
x_sampling: 1,
y_sampling: 1,
}],
};
let image = siz.image_rect();
let mut checked = 0;
for x0 in (0..115).step_by(3) {
for x1 in (x0 + 1..120).step_by(7) {
for (y0, y1) in [(0, 80), (5, 6), (16, 17), (17, 30), (30, 72), (70, 90)] {
let window = Rect { x0, y0, x1, y1 }.intersect(&image);
if window.is_empty() {
continue;
}
let selection = Selection {
area: siz.windowed(window),
order: vec![0],
subset: false,
};
let tiles: Vec<Rect> = selection
.tiles(&siz)
.iter()
.enumerate()
.filter(|(_, read)| **read)
.map(|(index, _)| siz.tile_rect(index as u32).unwrap())
.collect();
let union = tiles.iter().fold(tiles[0], |u, t| Rect {
x0: u.x0.min(t.x0),
y0: u.y0.min(t.y0),
x1: u.x1.max(t.x1),
y1: u.y1.max(t.y1),
});
let area: u64 = tiles
.iter()
.map(|t| u64::from(t.x1 - t.x0) * u64::from(t.y1 - t.y0))
.sum();
let read = selection.read_rect(&siz);
assert_eq!(read, union, "window {window:?}");
assert_eq!(
area,
u64::from(read.x1 - read.x0) * u64::from(read.y1 - read.y0),
"window {window:?}"
);
checked += 1;
}
}
}
assert!(checked > 500, "{checked}");
}
#[test]
fn a_run_of_missing_tiles_is_split_at_the_tiles_not_read() {
let tiles = [false, true, false, true, false, false];
let entries = vec![
ReportEntry::MissingTiles { tiles: 0..5 },
ReportEntry::MissingTiles { tiles: 4..6 },
ReportEntry::TilePartCountMismatch {
tile: 2,
declared: 2,
found: 1,
},
ReportEntry::TilePartCountMismatch {
tile: 3,
declared: 2,
found: 1,
},
ReportEntry::MissingEoc,
];
assert_eq!(
keep_entries(entries, &tiles),
vec![
ReportEntry::MissingTiles { tiles: 1..2 },
ReportEntry::MissingTiles { tiles: 3..4 },
ReportEntry::TilePartCountMismatch {
tile: 3,
declared: 2,
found: 1,
},
ReportEntry::MissingEoc,
]
);
}
}