diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index fa703b2bb42..862dbb2ad6d 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -426,9 +426,10 @@ const GRAD_EPS: f32 = 1.0 / 256.0; /// Regularizes the green-similarity weights of the colour differences. const DIFF_EPS: f32 = 1.0 / 64.0; -/// CIE f(t) for L*a*b*, tabulated on 0..2 with linear interpolation. +/// CIE f(t) for L*a*b*, tabulated on 0..2 with linear interpolation. Each entry holds the +/// sample and the step to the next one (one load per lookup; the same `a + (b - a) * f`). struct LabF { - table: Vec, + pairs: Vec<[f32; 2]>, } const LABF_STEPS: usize = 1 << 14; @@ -436,7 +437,8 @@ const LABF_RANGE: f32 = 2.0; impl LabF { fn new() -> Self { - LabF { table: (0..=LABF_STEPS + 1).map(|i| Self::exact(i as f32 * LABF_RANGE / LABF_STEPS as f32)).collect() } + let table: Vec = (0..=LABF_STEPS + 1).map(|i| Self::exact(i as f32 * LABF_RANGE / LABF_STEPS as f32)).collect(); + LabF { pairs: table.windows(2).map(|p| [p[0], p[1] - p[0]]).collect() } } fn exact(t: f32) -> f32 { @@ -450,8 +452,8 @@ impl LabF { } let x = t * (LABF_STEPS as f32 / LABF_RANGE); let i = (x as usize).min(LABF_STEPS); - let a = self.table[i]; - a + (self.table[i + 1] - a) * (x - i as f32) + let [a, step] = self.pairs[i]; + a + step * (x - i as f32) } } @@ -460,17 +462,34 @@ const AHD_BAND: usize = 32; /// Extra band rows above and below the output rows. const M: usize = 3; -/// Maximum scratch allocation of one AHD band: two green, RGB and Lab float -/// planes and two byte homogeneity planes, including their border rows. +/// Scratch rows one AHD worker allocates: the output rows of the tallest band +/// this image has, plus their border rows. +fn ahd_scratch_rows(h: usize) -> usize { + h.min(AHD_BAND) + 2 * M +} + +/// Scratch allocation of one AHD worker ([`AhdScratch::for_image`]): two green, +/// RGB and Lab float planes and two byte homogeneity planes over +/// [`ahd_scratch_rows`], plus the two `u32` rows of vertical sums. pub(crate) fn ahd_scratch(w: u64, h: u64) -> u64 { - w.saturating_add(2 * PAD as u64).saturating_mul(h.min(AHD_BAND as u64).saturating_add(2 * M as u64)).saturating_mul(58) + let s = w.saturating_add(2 * PAD as u64); + let rows = h.min(AHD_BAND as u64).saturating_add(2 * M as u64); + s.saturating_mul(rows.saturating_mul(58).saturating_add(8)) +} + +/// Bands one scratch serves: the bands are split into one group per worker (at most `jobs`), so +/// the scratch is allocated and zeroed once per worker however many workers there are. More +/// groups than workers would allocate a fresh scratch for every band on a many-core machine. +fn ahd_bands_per_group(bands: usize, jobs: usize) -> usize { + let groups = par::workers().min(jobs.max(1)).clamp(1, bands.max(1)); + bands.div_ceil(groups).max(1) } pub(crate) fn ahd_bands(h: usize) -> usize { h.div_ceil(AHD_BAND) } -pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 2) * 4; +pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 1) * 8; /// `v` limited to `lo..=hi` like `f32::clamp`, without its panic on NaN bounds (hostile black /// levels can put NaN in the plane): same result for every non-NaN bound. @@ -480,7 +499,207 @@ fn clampf(v: f32, lo: f32, hi: f32) -> f32 { if v > hi { hi } else { v } } +/// One AHD band's working planes, reused for every band a worker runs (sized for the tallest band). +struct AhdScratch { + /// Green interpolated horizontally (0) and vertically (1). + g: [Vec; 2], + /// Per direction, the RGB candidate (planar). + rgb: [[Vec; 3]; 2], + /// Per direction, its CIELAB (planar). + lab: [[Vec; 3]; 2], + hom: [Vec; 2], + /// Vertical 3-row sums of `hom`, one output row. + vs: [Vec; 2], +} + +impl AhdScratch { + fn new(len: usize, s: usize) -> Self { + let f = || vec![0.0f32; len]; + AhdScratch { + g: [f(), f()], + rgb: [[f(), f(), f()], [f(), f(), f()]], + lab: [[f(), f(), f()], [f(), f(), f()]], + hom: [vec![0u8; len], vec![0u8; len]], + vs: [vec![0u32; s], vec![0u32; s]], + } + } + + /// The scratch for an image `h` rows tall with stride `s`: the size [`ahd_scratch`] budgets. + fn for_image(h: usize, s: usize) -> Self { + AhdScratch::new(ahd_scratch_rows(h) * s, s) + } +} + +/// AHD (see [`ahd_ref`] for the plain statement): the same arithmetic in the same order, per +/// row on slices, planar scratch reused across a worker's bands. Every scratch cell a stage +/// reads was written earlier in the same band, so the planes are never cleared between bands. fn ahd(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usize) { + let (w, h, s) = (p.w, p.h, p.stride); + let d = &p.data; + let white = [0.9642f32, 1.0, 0.8249]; + let m: [[f32; 3]; 3] = std::array::from_fn(|i| std::array::from_fn(|j| to_xyz[i][j] as f32 / white[i])); + let labf = LabF::new(); + let bands = ahd_bands(h); + let per_group = ahd_bands_per_group(bands, jobs); + par::chunks_mut_limited(out, per_group * AHD_BAND * w * 3, jobs, |group, gchunk| { + let mut sc = AhdScratch::for_image(h, s); + for (j, chunk) in gchunk.chunks_mut(AHD_BAND * w * 3).enumerate() { + ahd_band(d, w, s, phase, &m, &labf, group * per_group + j, chunk, &mut sc); + } + }); +} + +#[allow(clippy::too_many_arguments)] +fn ahd_band(d: &[f32], w: usize, s: usize, phase: [u8; 4], m: &[[f32; 3]; 3], labf: &LabF, band: usize, chunk: &mut [f32], sc: &mut AhdScratch) { + let rows = chunk.len() / (w * 3); + let n = rows + 2 * M; + let py = |b: usize| band * AHD_BAND + PAD - M + b; + let drow = |y: usize| &d[y * s..(y + 1) * s]; + // 1. Green interpolated horizontally (0) and vertically (1), columns 2..s-2. + { + let [g0, g1] = &mut sc.g; + for b in 0..n { + let y = py(b); + let (rm2, rm1, r0, rp1, rp2) = (drow(y - 2), drow(y - 1), drow(y), drow(y + 1), drow(y + 2)); + let gh_row = &mut g0[b * s..(b + 1) * s]; + let gv_row = &mut g1[b * s..(b + 1) * s]; + let green = [phase[(y & 1) * 2] == 1, phase[(y & 1) * 2 + 1] == 1]; + for x in 2..s - 2 { + let c = r0[x]; + if green[x & 1] { + gh_row[x] = c; + gv_row[x] = c; + continue; + } + let (l, r) = (r0[x - 1], r0[x + 1]); + let gh = (l + r) * 0.5 + (2.0 * c - r0[x - 2] - r0[x + 2]) * 0.25; + gh_row[x] = clampf(gh, l.min(r), l.max(r)); + let (u, dn) = (rm1[x], rp1[x]); + let gv = (u + dn) * 0.5 + (2.0 * c - rm2[x] - rp2[x]) * 0.25; + gv_row[x] = clampf(gv, u.min(dn), u.max(dn)); + } + } + } + // 2. RGB candidates and their Lab, band rows 1..n-1, columns 3..s-3. + for dir in 0..2 { + let gd = &sc.g[dir]; + let [cr, cg, cb] = &mut sc.rgb[dir]; + let [ll, la, lb] = &mut sc.lab[dir]; + for b in 1..n - 1 { + let y = py(b); + let (dm1, d0, dp1) = (drow(y - 1), drow(y), drow(y + 1)); + let (gm1, g0, gp1) = (&gd[(b - 1) * s..b * s], &gd[b * s..(b + 1) * s], &gd[(b + 1) * s..(b + 2) * s]); + let at = b * s; + let (orr, org, orb) = (&mut cr[at..at + s], &mut cg[at..at + s], &mut cb[at..at + s]); + let (ol, oa, ob) = (&mut ll[at..at + s], &mut la[at..at + s], &mut lb[at..at + s]); + let pr = (y & 1) * 2; + for x in 3..s - 3 { + let own = phase[pr + (x & 1)]; + let gv = g0[x]; + // `va` goes to channel `ch`, `vb` to `2 - ch` (as `px[ch] = va; px[2 - ch] = vb`, + // built from values: an indexed store into `px` stalls store forwarding). + let (ch, va, vb) = if own == 1 { + ( + phase[pr + ((x + 1) & 1)].min(2), + gv + 0.5 * ((d0[x - 1] - g0[x - 1]) + (d0[x + 1] - g0[x + 1])), + gv + 0.5 * ((dm1[x] - gm1[x]) + (dp1[x] - gp1[x])), + ) + } else { + ( + own.min(2), + d0[x], + gv + 0.25 * ((dm1[x - 1] - gm1[x - 1]) + (dm1[x + 1] - gm1[x + 1]) + (dp1[x - 1] - gp1[x - 1]) + (dp1[x + 1] - gp1[x + 1])), + ) + }; + let px = match ch { + 0 => [va, gv, vb], + 2 => [vb, gv, va], + _ => [gv, vb, gv], + }; + let px = px.map(|v| v.clamp(0.0, 1.0)); + orr[x] = px[0]; + org[x] = px[1]; + orb[x] = px[2]; + let xyz: [f32; 3] = std::array::from_fn(|k| m[k][0] * px[0] + m[k][1] * px[1] + m[k][2] * px[2]); + let (fx, fy, fz) = (labf.f(xyz[0]), labf.f(xyz[1]), labf.f(xyz[2])); + ol[x] = 116.0 * fy - 16.0; + oa[x] = 500.0 * (fx - fy); + ob[x] = 200.0 * (fy - fz); + } + } + } + // 3. Homogeneity maps, band rows 2..n-2, columns 4..s-4. + { + let [l0, a0, b0] = &sc.lab[0]; + let [l1, a1, b1] = &sc.lab[1]; + let [h0, h1] = &mut sc.hom; + for b in 2..n - 2 { + fn row(pl: &[f32], bb: usize, s: usize) -> &[f32] { + &pl[bb * s..(bb + 1) * s] + } + let (l0u, l0c, l0d) = (row(l0, b - 1, s), row(l0, b, s), row(l0, b + 1, s)); + let (a0u, a0c, a0d) = (row(a0, b - 1, s), row(a0, b, s), row(a0, b + 1, s)); + let (b0u, b0c, b0d) = (row(b0, b - 1, s), row(b0, b, s), row(b0, b + 1, s)); + let (l1u, l1c, l1d) = (row(l1, b - 1, s), row(l1, b, s), row(l1, b + 1, s)); + let (a1u, a1c, a1d) = (row(a1, b - 1, s), row(a1, b, s), row(a1, b + 1, s)); + let (b1u, b1c, b1d) = (row(b1, b - 1, s), row(b1, b, s), row(b1, b + 1, s)); + let (h0r, h1r) = (&mut h0[b * s..(b + 1) * s], &mut h1[b * s..(b + 1) * s]); + for x in 4..s - 4 { + // Neighbours left, right, up, down; (|ΔL|, Δa² + Δb²) from the centre. + let dist = |lc: f32, ac: f32, bc: f32, ln: f32, an: f32, bn: f32| ((lc - ln).abs(), (ac - an) * (ac - an) + (bc - bn) * (bc - bn)); + let (lc, ac, bc) = (l0c[x], a0c[x], b0c[x]); + let dh = [ + dist(lc, ac, bc, l0c[x - 1], a0c[x - 1], b0c[x - 1]), + dist(lc, ac, bc, l0c[x + 1], a0c[x + 1], b0c[x + 1]), + dist(lc, ac, bc, l0u[x], a0u[x], b0u[x]), + dist(lc, ac, bc, l0d[x], a0d[x], b0d[x]), + ]; + let (lc, ac, bc) = (l1c[x], a1c[x], b1c[x]); + let dv = [ + dist(lc, ac, bc, l1c[x - 1], a1c[x - 1], b1c[x - 1]), + dist(lc, ac, bc, l1c[x + 1], a1c[x + 1], b1c[x + 1]), + dist(lc, ac, bc, l1u[x], a1u[x], b1u[x]), + dist(lc, ac, bc, l1d[x], a1d[x], b1d[x]), + ]; + let eps_l = dh[0].0.max(dh[1].0).min(dv[2].0.max(dv[3].0)); + let eps_c = dh[0].1.max(dh[1].1).min(dv[2].1.max(dv[3].1)); + let count = |v: &[(f32, f32); 4]| v.iter().map(|(l, c)| u8::from(*l <= eps_l && *c <= eps_c)).sum::(); + h0r[x] = count(&dh); + h1r[x] = count(&dv); + } + } + } + // 4. Per pixel, the candidate with the larger 3×3 homogeneity sum. + let [vs0, vs1] = &mut sc.vs; + for r in 0..rows { + let b = r + M; + for (hm, vs) in [(&sc.hom[0], &mut *vs0), (&sc.hom[1], &mut *vs1)] { + let (u, c, dn) = (&hm[(b - 1) * s..b * s], &hm[b * s..(b + 1) * s], &hm[(b + 1) * s..(b + 2) * s]); + for x in PAD - 1..PAD + w + 1 { + vs[x] = u32::from(u[x]) + u32::from(c[x]) + u32::from(dn[x]); + } + } + let at = b * s; + let (r0, g0, b0) = (&sc.rgb[0][0][at..at + s], &sc.rgb[0][1][at..at + s], &sc.rgb[0][2][at..at + s]); + let (r1, g1, b1) = (&sc.rgb[1][0][at..at + s], &sc.rgb[1][1][at..at + s], &sc.rgb[1][2][at..at + s]); + let orow = &mut chunk[r * w * 3..(r + 1) * w * 3]; + for (x, o) in orow.as_chunks_mut::<3>().0.iter_mut().enumerate() { + let px = x + PAD; + let sh = vs0[px - 1] + vs0[px] + vs0[px + 1]; + let sv = vs1[px - 1] + vs1[px] + vs1[px + 1]; + let (c0, c1) = ([r0[px], g0[px], b0[px]], [r1[px], g1[px], b1[px]]); + *o = match sh.cmp(&sv) { + std::cmp::Ordering::Greater => c0, + std::cmp::Ordering::Less => c1, + std::cmp::Ordering::Equal => [0.5 * (c0[0] + c1[0]), 0.5 * (c0[1] + c1[1]), 0.5 * (c0[2] + c1[2])], + }; + } + } +} + +/// The plain AHD statement the optimized [`ahd`] must match bit for bit. +#[cfg(test)] +fn ahd_ref(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usize) { let (w, s) = (p.w, p.stride); let d = &p.data; // Colour at padded coordinates (PAD is even, so the phase is unchanged). @@ -608,6 +827,97 @@ mod tests { } } + #[test] + fn ahd_matches_reference_bit_for_bit() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + for (w, h) in [(1, 1), (2, 3), (7, 5), (53, 103), (64, 70), (33, 31)] { + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + for phase in [[0, 1, 1, 2], [2, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1]] { + for jobs in [1, 3, 64] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, jobs); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); + assert_eq!( + want.iter().map(|v| v.to_bits()).collect::>(), + got.iter().map(|v| v.to_bits()).collect::>(), + "{w}x{h} {phase:?} {jobs}" + ); + } + } + } + } + + /// Bytes the scratch planes actually hold. + fn scratch_bytes(sc: &AhdScratch) -> u64 { + let f = sc.g.iter().chain(sc.rgb.iter().flatten()).chain(sc.lab.iter().flatten()).map(|v| v.capacity() * 4).sum::(); + let b = sc.hom.iter().map(Vec::capacity).sum::(); + let u = sc.vs.iter().map(|v| v.capacity() * 4).sum::(); + (f + b + u) as u64 + } + + /// The memory check in `develop` admits a file on [`ahd_scratch`] per worker; the scratch + /// `ahd` allocates must not exceed it. A short wide strip used to allocate the 38 rows of a + /// full band against a budget of `h + 6` rows (5.4x at `h = 1`). + #[test] + fn ahd_scratch_fits_its_budget() { + for w in [1usize, 2, 33, 4000] { + for h in [1usize, 2, 7, 31, 32, 33, 100, 5000] { + let s = w + 2 * PAD; + let sc = AhdScratch::for_image(h, s); + let budget = ahd_scratch(w as u64, h as u64); + assert_eq!(scratch_bytes(&sc), budget, "{w}x{h}: allocated vs budgeted bytes"); + // The tallest band `ahd` hands out (at most 32 rows, plus 3 above and below) fits. + assert!(sc.g[0].len() >= (h.min(32) + 6) * s, "{w}x{h}"); + } + } + } + + /// One scratch serves many bands (1100 rows are 35 bands, the last one short, over 4 scratches + /// with jobs 1 and at most 8 with jobs 2), so a stage reading a cell left over from an earlier band would show. + #[test] + fn ahd_matches_reference_with_reused_scratch() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + let (w, h) = (37, 1100); + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + for jobs in [1, 2] { + assert!(ahd_bands_per_group(ahd_bands(h), jobs) >= 2, "jobs {jobs}: each scratch must serve several bands"); + for phase in [[0, 1, 1, 2], [2, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1]] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, jobs); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); + assert_eq!(want.len(), got.len()); + assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{w}x{h} {phase:?} jobs {jobs}"); + } + } + } + + /// A 4-worker pool splits 35 bands into groups of 9 (the last of 8), so groups after the first + /// start at band `group * 9` and every scratch is reused for several bands: a wrong band index + /// or a stale scratch cell would change pixels. The group size does not depend on the machine. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn ahd_groups_of_several_bands_match_reference() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + let (w, h) = (37, 1100); + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + pool.install(|| { + assert_eq!(par::workers(), 4); + assert_eq!(ahd_bands_per_group(ahd_bands(h), 4), 9); + // One worker per group, never more groups than workers, however many bands there are. + assert_eq!(ahd_bands_per_group(126, 1000), 32); + for phase in [[0, 1, 1, 2], [1, 2, 0, 1]] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, 4); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, 4); + assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{phase:?}"); + } + }); + } + #[test] fn ahd_survives_nan_planes() { let p = Padded::from_plane(&[f32::NAN; 64], 8, 8);