Keep inpaint boundary arithmetic and allocation sizes representable

This commit is contained in:
Dylan M. Taylor
2026-11-18 13:27:31 -05:00
parent dcb3fcf603
commit aa3dc9e2b0
4 changed files with 143 additions and 18 deletions
+9 -1
View File
@@ -20,12 +20,20 @@ Each module comes with a test that its output is LightCraft's at the base commit
[`craft-render-parity`](../render-parity/README.md) at `Tolerance::BASELINE`. The expected pictures in
`tests/fixtures/` were written by LightCraft's own crate at that commit, on the scene the test builds.
Where the code differs from LightCraft's, the output for every input LightCraft handled is the same:
Differences from LightCraft (ordinary-range output is covered by the baseline fixtures):
- `inpaint::complete_with` returns `None` for a patch radius wider than the image before computing with it (LightCraft
reaches the same `None`, or overflows on a huge radius), returns an image with no pixels at once, and reports
`Cancelled` when any one poll said so, including a poll made on a worker thread.
- `membrane_fill` scales extreme finite boundaries for the harmonic solve and bounds the result by those
boundaries, avoiding overflow in means and neighbour sums. Known pixels remain unchanged; ordinary
values take the original arithmetic path. This does not promise arbitrary extreme-value safety for
PatchMatch completion, which also computes squared costs and downsamples its input.
- Membrane cell indices retain `usize` width. PatchMatch rejects grids whose signed search offsets,
summed-area counts or padded table cannot be represented; patch-area arithmetic no longer overflows
`i32`. An already-cancelled oversized-patch request returns `Cancelled`, not an unavailable-patch result.
## Not here yet
The rest of the pipeline: colour, raster, the sensor stage, raw loading and the render stages. No app uses this crate
+27
View File
@@ -37,6 +37,33 @@ impl std::error::Error for Cancelled {}
mod tests {
use super::*;
#[test]
fn finite_extreme_membrane_boundaries_stay_finite() {
let img = [f32::MAX, 0.0, f32::MAX];
let out = membrane_fill(3, 1, 1, &img, &[false, true, false]);
assert_eq!(out, vec![f32::MAX; 3]);
assert_eq!(membrane_fill(3, 1, 1, &[-f32::MAX, 0.0, f32::MAX], &[false, true, false]), vec![-f32::MAX, 0.0, f32::MAX]);
// Also exercise the multigrid restriction and prolongation at extreme scale.
let hole: Vec<bool> = (0..256).map(|i| i % 16 > 0 && i % 16 < 15 && i / 16 > 0 && i / 16 < 15).collect();
assert_eq!(membrane_fill(16, 16, 1, &[f32::MAX; 256], &hole), vec![f32::MAX; 256]);
let img: Vec<f32> = (0..256).map(|i| if i % 16 < 8 { -f32::MAX } else { f32::MAX }).collect();
let out = membrane_fill(16, 16, 1, &img, &hole);
for ((&actual, &original), &unknown) in out.iter().zip(&img).zip(&hole) {
assert!(actual.is_finite() && actual >= -f32::MAX && actual <= f32::MAX);
if !unknown {
assert_eq!(actual.to_bits(), original.to_bits());
}
}
}
#[test]
fn cancellation_precedes_an_oversized_patch_result() {
let mut hole = vec![false; 32 * 32];
hole[16 * 32 + 16] = true;
let p = CompleteParams { patch_radius: 16, ..CompleteParams::default() };
assert_eq!(complete_with(32, 32, 1, &[0.5; 32 * 32], &hole, &p, &|| true), Err(Cancelled));
}
#[test]
fn hostile_sizes_do_not_panic() {
assert_eq!(complete(4, 4, 3, &[0.0; 5], &[true; 16], &CompleteParams::default()), None);
+60 -12
View File
@@ -6,6 +6,10 @@
//! cascadically (solve on a half-resolution grid, prolong bilinearly, a few SOR sweeps per level).
//! Ported from PhotoCraft's `algo::poisson` (MIT OR Apache-2.0).
fn allocation_fits<T>(len: usize) -> bool {
len.checked_mul(std::mem::size_of::<T>()).is_some_and(|bytes| bytes <= isize::MAX as usize)
}
/// Convergence threshold (max per-sweep update) for the SOR sweeps.
const TOL: f32 = 2e-5;
/// SOR sweeps (cap) and relaxation factor on every level above the coarsest: tuned so a 96×72 disc
@@ -17,10 +21,41 @@ const FINE_OMEGA: f32 = 1.7;
/// (out-of-grid neighbours are ignored, i.e. a Neumann boundary). `v` holds the known values on
/// entry and the solution on exit. Cascadic multigrid + SOR.
pub(crate) fn solve_membrane(w: usize, h: usize, unknown: &[bool], v: &mut [f32]) {
if unknown.len() != w * h || v.len() != w * h {
if Some(unknown.len()) != w.checked_mul(h) || v.len() != unknown.len() {
return;
}
solve_rec(w, h, unknown, v, 0, &|| false);
if !allocation_fits::<(usize, u8)>(unknown.iter().filter(|&&hole| hole).count()) {
return;
}
// Keep the ordinary path bit-for-bit unchanged. Extremely large finite boundaries can
// overflow even their mean or a four-neighbour sum; harmonic interpolation is linear,
// so solve those channels at unit scale instead. The final clamp enforces the harmonic
// maximum principle if the finite-iteration relaxation overshoots a boundary extremum.
let mut low = f32::INFINITY;
let mut high = f32::NEG_INFINITY;
for (&value, &hole) in v.iter().zip(unknown) {
if !hole {
if !value.is_finite() {
solve_rec(w, h, unknown, v, 0, &|| false);
return;
}
low = low.min(value);
high = high.max(value);
}
}
let scale = low.abs().max(high.abs());
let needs_scale = scale.is_finite() && f64::from(scale) > f64::from(f32::MAX) / v.len().max(16) as f64;
if needs_scale {
let mut normalized: Vec<f32> = v.iter().map(|&value| value / scale).collect();
solve_rec(w, h, unknown, &mut normalized, 0, &|| false);
for ((value, solved), &hole) in v.iter_mut().zip(normalized).zip(unknown) {
if hole {
*value = (f64::from(solved) * f64::from(scale)).clamp(f64::from(low), f64::from(high)) as f32;
}
}
} else {
solve_rec(w, h, unknown, v, 0, &|| false);
}
}
fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize, stop: &(dyn Fn() -> bool + Sync)) {
@@ -31,7 +66,9 @@ fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize,
if n_unknown == 0 {
return;
}
let known: Vec<f32> = v.iter().zip(unknown).filter(|(_, u)| !**u).map(|(x, _)| *x).collect();
// Like the cell list below, this filtered collection must not grow geometrically.
let mut known = Vec::with_capacity(v.len() - n_unknown);
known.extend(v.iter().zip(unknown).filter(|(_, u)| !**u).map(|(x, _)| *x));
if known.is_empty() {
return; // nothing to interpolate from
}
@@ -91,21 +128,20 @@ fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize,
/// SOR sweeps over the unknown pixels until the largest update drops below [`TOL`].
fn sor(w: usize, h: usize, unknown: &[bool], v: &mut [f32], max_iter: usize, omega: f32, stop: &(dyn Fn() -> bool + Sync)) {
// Precompute the unknown pixels and which neighbours exist.
let cells: Vec<(u32, u8)> = (0..w * h)
.filter(|&i| unknown[i])
.map(|i| {
let (x, y) = (i % w, i / w);
let m = u8::from(x > 0) | (u8::from(x + 1 < w) << 1) | (u8::from(y > 0) << 2) | (u8::from(y + 1 < h) << 3);
(i as u32, m)
})
.collect();
// The caller validated this exact count; reserve it before extend so geometric growth
// cannot round the allocation above the target's capacity limit.
let mut cells = Vec::with_capacity(unknown.iter().filter(|&&hole| hole).count());
cells.extend((0..w * h).filter(|&i| unknown[i]).map(|i| {
let (x, y) = (i % w, i / w);
let m = u8::from(x > 0) | (u8::from(x + 1 < w) << 1) | (u8::from(y > 0) << 2) | (u8::from(y + 1 < h) << 3);
(i, m)
}));
for _ in 0..max_iter {
if stop() {
return;
}
let mut max_d = 0.0f32;
for &(i, m) in &cells {
let i = i as usize;
let (s, n) = if m == 0b1111 {
(v[i - 1] + v[i + 1] + v[i - w] + v[i + w], 4.0)
} else {
@@ -173,6 +209,10 @@ pub fn membrane_fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool])
if hole.is_empty() {
return img.to_vec();
}
// A valid input slice does not prove the wider index/plane vectors fit the target.
if !allocation_fits::<Vec<f32>>(ch) || !allocation_fits::<(usize, u8)>(hole.iter().filter(|&&hole| hole).count()) {
return img.to_vec();
}
per_channel(w, h, ch, |c| {
let mut v: Vec<f32> = (0..w * h).map(|i| if hole[i] { 0.0 } else { img[i * ch + c] }).collect();
solve_membrane(w, h, hole, &mut v);
@@ -187,6 +227,14 @@ mod tests {
(0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect()
}
#[test]
fn auxiliary_vector_limits_are_checked_without_allocating() {
let max_cells = isize::MAX as usize / std::mem::size_of::<(usize, u8)>();
assert!(allocation_fits::<(usize, u8)>(max_cells));
assert!(!allocation_fits::<(usize, u8)>(max_cells + 1));
assert!(!allocation_fits::<Vec<f32>>(usize::MAX));
}
#[test]
fn a_zero_area_image_comes_back_unchanged_whatever_its_channel_count() {
assert!(membrane_fill(0, 5, usize::MAX, &[], &[]).is_empty());
+47 -5
View File
@@ -117,6 +117,21 @@ fn downsample(l: &Level, ch: usize) -> Level {
Level { w, h, img, hole }
}
// Search offsets add/subtract a full image dimension in i32. Summed-area queries
// add two u32 entries before subtracting. Both the padded table and the larger
// per-pixel nearest-neighbour/valid-coordinate arrays must fit a Vec.
fn supported_grid(w: usize, h: usize) -> bool {
let max_dimension = (i32::MAX / 2) as usize;
w <= max_dimension
&& h <= max_dimension
&& w.checked_mul(h).is_some_and(|n| n <= (u32::MAX / 2) as usize)
&& w.checked_mul(h).and_then(|n| n.checked_mul(std::mem::size_of::<(i32, i32)>())).is_some_and(|bytes| bytes <= isize::MAX as usize)
&& w.checked_add(1)
.and_then(|pw| h.checked_add(1).and_then(|ph| pw.checked_mul(ph)))
.and_then(|n| n.checked_mul(std::mem::size_of::<u32>()))
.is_some_and(|bytes| bytes <= isize::MAX as usize)
}
/// Summed-area table of a boolean grid (`(w+1) × (h+1)`).
fn integral(w: usize, h: usize, m: &[bool]) -> Vec<u32> {
let mut s = vec![0u32; (w + 1) * (h + 1)];
@@ -182,7 +197,8 @@ impl Solver<'_> {
/// SSD between the (clipped) target patch at `t` and the source patch at `s`, per sample.
fn dist(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 {
let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r);
let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32;
let diameter = f64::from(2 * r + 1);
let full = (diameter * diameter) as f32 * ch as f32;
let mut sum = 0.0f32;
let mut n = 0usize;
for dy in -r..=r {
@@ -396,11 +412,16 @@ pub fn complete_with(
if hole.is_empty() {
return Ok(Some(img.to_vec()));
}
if !supported_grid(w, h) {
check()?;
return Ok(None);
}
let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return Ok(Some(img.to_vec())) };
let r = p.patch_radius.max(1);
// A patch wider than the image has no place to be copied from, which is the `None` the search below
// would reach anyway. Said here, before `2 * r + 1` and `r as i32` can overflow on an absurd radius.
if r > (w.min(h) - 1) / 2 {
check()?;
return Ok(None);
}
let psz = 2 * r + 1;
@@ -442,7 +463,7 @@ pub fn complete_with(
let ri = r as i32;
let hs = integral(lw, lh, &lhole);
let mut valid = vec![false; lw * lh];
let mut valid_list = Vec::new();
let mut valid_count = 0;
let mut targets = vec![false; lw * lh];
for y in 0..lh as i32 {
if y % 32 == 0 {
@@ -454,12 +475,12 @@ pub fn complete_with(
let i = y as usize * lw + x as usize;
if inside && cnt == 0 {
valid[i] = true;
valid_list.push((x, y));
valid_count += 1;
}
targets[i] = cnt > 0;
}
}
if valid_list.is_empty() {
if valid_count == 0 {
if li == 0 {
return Ok(None);
}
@@ -467,6 +488,17 @@ pub fn complete_with(
nnf.clear();
continue;
}
// Count first and reserve exactly, avoiding both geometric capacity overflow and
// allocating coordinates for pixels that cannot be source centres.
let mut valid_list = Vec::with_capacity(valid_count);
for (i, &is_valid) in valid.iter().enumerate() {
if i % (lw * 32) == 0 {
check()?;
}
if is_valid {
valid_list.push(((i % lw) as i32, (i / lw) as i32));
}
}
let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, hole: &lhole, valid, valid_list, targets, ctl: cancelled };
// NNF init: upsampled from the coarser level where possible, random otherwise.
let mut rng = Rng::new(p.seed ^ (li as u64) << 20);
@@ -522,7 +554,7 @@ pub fn complete_with(
} else if li + 1 == nlev || it == 0 {
full_search
} else {
(4 * psz as i32).min(full_search)
(4 * psz).min(full_search as usize) as i32
};
for pass in 0..pm_iters {
check()?;
@@ -572,6 +604,16 @@ mod tests {
(e / n as f32).sqrt()
}
#[test]
fn grid_limits_reject_narrowing_and_integral_overflow_without_allocating() {
assert!(supported_grid(32, 32));
assert!(supported_grid(16_384, 8_192));
assert_eq!(supported_grid(20_000, 20_000), usize::BITS > 32);
assert!(!supported_grid(i32::MAX as usize, 1));
assert!(!supported_grid(65_536, 65_536));
assert!(!supported_grid(usize::MAX, usize::MAX));
}
#[test]
fn completion_fills_blemish_from_texture() {
let (w, h, ch) = (96, 96, 3);