Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

codecs: PNG export gives the same bytes on any core count (#1932)

ROSSA AI483712655fbc
diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs
index 1afb21a79..22320424a 100644
--- a/crates/codecs/src/codecs/png.rs
+++ b/crates/codecs/src/codecs/png.rs
@@ -363,11 +363,17 @@ fn parallel_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompress
return None;
}
let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 32);
- if threads < 2 {
- return None;
- }
+ banded_idat(data, w, h, bpp, level, threads)
+}
+
+/// Filtered bytes per deflate band. The bands depend only on the image, never on the number of
+/// threads, so the same image and options give the same bytes whatever the machine's core count.
+const BAND_BYTES: usize = 512 << 10;
+
+/// [`parallel_idat`] on `threads` worker threads.
+fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompression, threads: usize) -> Option<Vec<u8>> {
let stride = w * bpp;
- let band_rows = h.div_ceil(threads * 4).max(1);
+ let band_rows = (BAND_BYTES / stride.saturating_add(1)).max(1);
let bands: Vec<(usize, usize)> = (0..h).step_by(band_rows).map(|y| (y, (y + band_rows).min(h))).collect();
let lvl = match level {
PngCompression::Fast => flate2::Compression::fast(),
@@ -377,7 +383,7 @@ fn parallel_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompress
let next = std::sync::atomic::AtomicUsize::new(0);
type Band = (usize, Vec<u8>, u32, usize);
let mut parts: Vec<Band> = std::thread::scope(|sc| {
- let workers: Vec<_> = (0..threads.min(bands.len()))
+ let workers: Vec<_> = (0..threads.min(bands.len()).max(1))
.map(|_| {
sc.spawn(|| {
let mut out: Vec<Band> = Vec::new();
@@ -598,6 +604,28 @@ mod parallel_tests {
}
}
+ /// The bytes depend on the image, not on the machine: one, two, seven and 32 worker threads
+ /// (and the machine's own count, through `encode`) give the same stream.
+ #[test]
+ fn the_parallel_encoder_gives_the_same_bytes_on_any_thread_count() {
+ let (w, h, bpp) = (1201usize, 1013usize, 4usize);
+ let px: Vec<u8> =
+ (0..w * h * bpp).map(|i| ((i / 5) as u32).wrapping_mul(2_654_435_761).rotate_left(i as u32 % 11) as u8 / 5 + (i % 89) as u8).collect();
+ assert!(px.len() >= PARALLEL_MIN_BYTES && px.len() > 2 * BAND_BYTES);
+ for level in [PngCompression::Fast, PngCompression::Default, PngCompression::Best] {
+ let one = banded_idat(&px, w, h, bpp, level, 1).unwrap();
+ for threads in [2, 7, 32] {
+ assert!(banded_idat(&px, w, h, bpp, level, threads).unwrap() == one, "{level:?}: {threads} threads differ from one");
+ }
+ assert!(parallel_idat(&px, w, h, bpp, level).unwrap() == one, "{level:?}: this machine's thread count differs from one");
+ let img = Image::from_raw(w as u32, h as u32, ChannelLayout::Rgba, SampleType::U8, px.clone()).unwrap();
+ let opts = EncodeOptions { png_compression: level, ..Default::default() };
+ let png = crate::encode(&img, Format::Png, &opts).unwrap();
+ assert!(png.windows(one.len()).any(|c| c == one.as_slice()), "{level:?}: the file carries the stream");
+ assert_eq!(decode(&png, &Limits::default()).unwrap().data(), img.data());
+ }
+ }
+
#[test]
fn large_images_roundtrip_through_the_parallel_encoder() {
for (layout, sample, ch, bytes) in [(ChannelLayout::Rgb, SampleType::U8, 3usize, 1usize), (ChannelLayout::Rgba, SampleType::U16, 4, 2)] {