PhotoCraft: An open-source, photo editor written by scratch in pure Rust
perf(codecs): Avoid redundant PNG filter passes (#7690)
Rene Leonhardt98d3ebc1f5d8
diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rsindex ede70d296..f894b3a30 100644--- a/crates/codecs/src/codecs/png.rs+++ b/crates/codecs/src/codecs/png.rs@@ -541,8 +541,15 @@ fn filter_row(row: &[u8], prev: Option<&[u8]>, bpp: usize, scratch: &mut [u8], o}};let cost = |v: &[u8]| v.iter().map(|&b| u64::from((b as i8).unsigned_abs())).sum::<u64>();- let mut best = (cost(row), 0u8);+ let mut best = cost(row);+ let start = out.len();+ out.push(0);+ out.extend_from_slice(row);for kind in 1u8..=4 {+ if best == 0 {+ break;+ }+ let mut c = 0u64;for i in 0..n {let x = row[i];scratch[i] = match kind {@@ -551,27 +558,17 @@ fn filter_row(row: &[u8], prev: Option<&[u8]>, bpp: usize, scratch: &mut [u8], o3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8),_ => x.wrapping_sub(paeth(left(i), up(i), ul(i))),};+ c += u64::from((scratch[i] as i8).unsigned_abs());+ if c >= best {+ break;+ }}- let c = cost(&scratch[..n]);- if c < best.0 {- best = (c, kind);+ if c < best {+ best = c;+ out[start] = kind;+ out[start + 1..].copy_from_slice(&scratch[..n]);}}- out.push(best.1);- if best.1 == 0 {- out.extend_from_slice(row);- return;- }- for i in 0..n {- let x = row[i];- scratch[i] = match best.1 {- 1 => x.wrapping_sub(left(i)),- 2 => x.wrapping_sub(up(i)),- 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8),- _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))),- };- }- out.extend_from_slice(&scratch[..n]);}const ADLER_MOD: u32 = 65_521;@@ -779,6 +776,109 @@ mod indexed_tests {mod parallel_tests {use super::*;+ #[test]+ #[ignore = "manual 24 MP release benchmark"]+ fn benchmark_filter_selection() {+ use std::{hint::black_box, time::Instant};+ for pattern in ["zero", "identical", "varied"] {+ let row: Vec<u8> = (0..6000 * 4).map(|i| if pattern == "zero" { 0 } else { (i * 17 + i / 13) as u8 }).collect();+ let prev: Vec<_> = row.iter().map(|v| if pattern == "identical" { *v } else { v.wrapping_add(3) }).collect();+ let mut scratch = vec![0; row.len()];+ let mut out = Vec::with_capacity(row.len() + 1);+ for trial in 0..6 {+ type Filter = fn(&[u8], Option<&[u8]>, usize, &mut [u8], &mut Vec<u8>);+ let mut paths: [(&str, Filter); 2] = [("main", previous_filter_row), ("split", filter_row)];+ if trial % 2 == 1 {+ paths.reverse();+ }+ for (name, path) in paths {+ let t = Instant::now();+ for _ in 0..4000 {+ out.clear();+ black_box(path)(black_box(&row), Some(black_box(&prev)), 4, &mut scratch, &mut out);+ black_box(&out);+ }+ println!("filter,{pattern},{trial},{name},{:.6}", t.elapsed().as_secs_f64() * 1000.0);+ }+ }+ }+ }++ // The main-branch implementation before this refactor.+ fn previous_filter_row(row: &[u8], prev: Option<&[u8]>, bpp: usize, scratch: &mut [u8], out: &mut Vec<u8>) {+ let n = row.len();+ let up = |i: usize| prev.map_or(0, |p| p[i]);+ let left = |i: usize| if i >= bpp { row[i - bpp] } else { 0 };+ let ul = |i: usize| if i >= bpp { prev.map_or(0, |p| p[i - bpp]) } else { 0 };+ let paeth = |a: u8, b: u8, c: u8| {+ let p = i16::from(a) + i16::from(b) - i16::from(c);+ let (pa, pb, pc) = ((p - i16::from(a)).abs(), (p - i16::from(b)).abs(), (p - i16::from(c)).abs());+ if pa <= pb && pa <= pc {+ a+ } else if pb <= pc {+ b+ } else {+ c+ }+ };+ let cost = |v: &[u8]| v.iter().map(|&b| u64::from((b as i8).unsigned_abs())).sum::<u64>();+ let mut best = (cost(row), 0u8);+ for kind in 1u8..=4 {+ for i in 0..n {+ let x = row[i];+ scratch[i] = match kind {+ 1 => x.wrapping_sub(left(i)),+ 2 => x.wrapping_sub(up(i)),+ 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8),+ _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))),+ };+ }+ let c = cost(&scratch[..n]);+ if c < best.0 {+ best = (c, kind);+ }+ }+ out.push(best.1);+ if best.1 == 0 {+ out.extend_from_slice(row);+ return;+ }+ for i in 0..n {+ let x = row[i];+ scratch[i] = match best.1 {+ 1 => x.wrapping_sub(left(i)),+ 2 => x.wrapping_sub(up(i)),+ 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8),+ _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))),+ };+ }+ out.extend_from_slice(&scratch[..n]);+ }++ #[test]+ fn adaptive_filter_preserves_minimum_cost_and_ties() {+ for bpp in [1, 2, 3, 4, 6, 8] {+ for seed in 0..32usize {+ let row: Vec<u8> = (0..137).map(|i| (i * seed + i / 5) as u8).collect();+ let shifted: Vec<_> = row.iter().map(|v| v.wrapping_add(seed as u8)).collect();+ for prev in [None, Some(row.as_slice()), Some(shifted.as_slice())] {+ let mut expected = vec![99];+ let mut actual = expected.clone();+ let mut scratch = vec![0; row.len()];+ previous_filter_row(&row, prev, bpp, &mut scratch, &mut expected);+ filter_row(&row, prev, bpp, &mut scratch, &mut actual);+ assert_eq!(actual, expected, "bpp={bpp}, seed={seed}");+ }+ }+ }+ let mut out = Vec::new();+ filter_row(&[0; 16], None, 4, &mut [0; 16], &mut out);+ assert_eq!(out, vec![0; 17]);+ out.clear();+ filter_row(&[1; 16], Some(&[0; 16]), 1, &mut [0; 16], &mut out);+ assert_eq!(out, [vec![1, 1], vec![0; 15]].concat());+ }+#[test]fn adler_combine_matches_one_pass() {let a: Vec<u8> = (0..100_000u32).map(|i| (i * 7 + i / 13) as u8).collect();