mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Affinity reader: decompress the tiles of a plane on worker threads
After the conversion fix, zstd decoding is about 80 percent of raster time and every tile was decoded one after the other. A plane now walks its tile grid first (flat cells are filled on the way), then extracts all tiles it needs with the new Archive::read_many, which decodes on up to 8 std::thread::scope threads (entries are taken from a shared counter), and copies them in place. Limits are unchanged: read_many charges every entry in order before decoding, exactly as that many read() calls, and returns the first error in that order (a failing tile before a refused or malformed later one wins). Fewer than four tiles, wasm32, or a failed thread start fall back to decoding on the calling thread. Output is byte-identical. Part of #9412 Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
1 parent
ace68fbb14
commit
44fd2ea784
3 files changed
+224
-31
No files matched your search
@@ -287,7 +287,31 @@ impl<'a> Archive<'a> {
|
||||
|
||||
/// Extract an entry by name: decompress, undo the byte predictor and verify the CRC.
|
||||
pub fn read(&mut self, name: &str) -> Result<Vec<u8>, Error> {
|
||||
let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone();
|
||||
self.claim(name)?.decode()
|
||||
}
|
||||
|
||||
/// Extract several entries, decoding them on worker threads. The entries are charged one
|
||||
/// after the other exactly as the same number of [`read`](Self::read) calls would charge
|
||||
/// them, and the first error in that order is the one returned.
|
||||
pub(crate) fn read_many(&mut self, names: &[&str]) -> Result<Vec<Vec<u8>>, Error> {
|
||||
let mut claimed = Vec::with_capacity(names.len());
|
||||
let mut refused = None;
|
||||
for name in names {
|
||||
match self.claim(name) {
|
||||
Ok(c) => claimed.push(c),
|
||||
Err(e) => {
|
||||
refused = Some(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let decoded = decode_all(&claimed).into_iter().collect::<Result<Vec<_>, _>>()?;
|
||||
refused.map_or(Ok(decoded), Err)
|
||||
}
|
||||
|
||||
/// Check an entry against the limits, count it as extracted and locate its stored bytes.
|
||||
fn claim(&mut self, name: &str) -> Result<Claimed<'a>, Error> {
|
||||
let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?;
|
||||
let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?;
|
||||
if size > self.limits.max_entry {
|
||||
return Err(Error::Limit("archive entry too large"));
|
||||
@@ -306,22 +330,79 @@ impl<'a> Archive<'a> {
|
||||
let method = e.compression & 3;
|
||||
let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size };
|
||||
let data = c.take(offset(stored_len)?)?;
|
||||
let mut out = match method {
|
||||
1 => inflate(data, size)?,
|
||||
2 => unzstd(data, size)?,
|
||||
_ => data.to_vec(),
|
||||
Ok(Claimed { data, size, compression: e.compression, crc: e.crc })
|
||||
}
|
||||
}
|
||||
|
||||
/// An entry that is charged and located but not yet decoded.
|
||||
struct Claimed<'a> {
|
||||
data: &'a [u8],
|
||||
size: usize,
|
||||
compression: u8,
|
||||
crc: u32,
|
||||
}
|
||||
|
||||
impl Claimed<'_> {
|
||||
fn decode(&self) -> Result<Vec<u8>, Error> {
|
||||
let mut out = match self.compression & 3 {
|
||||
1 => inflate(self.data, self.size)?,
|
||||
2 => unzstd(self.data, self.size)?,
|
||||
_ => self.data.to_vec(),
|
||||
};
|
||||
if out.len() != size {
|
||||
if out.len() != self.size {
|
||||
return Err(Error::Malformed("archive entry size mismatch"));
|
||||
}
|
||||
unpredict(&mut out, e.compression)?;
|
||||
if crc32fast::hash(&out) != e.crc {
|
||||
unpredict(&mut out, self.compression)?;
|
||||
if crc32fast::hash(&out) != self.crc {
|
||||
return Err(Error::Malformed("archive entry checksum mismatch"));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Most threads decoding entries at once; each zstd frame may reserve its declared window.
|
||||
const MAX_DECODE_THREADS: usize = 8;
|
||||
/// Fewer entries than this are decoded in place: starting a thread costs more than they do.
|
||||
const MIN_PARALLEL_ENTRIES: usize = 4;
|
||||
|
||||
/// Decode every entry, in parallel when there are enough of them. The results are in order.
|
||||
fn decode_all(jobs: &[Claimed<'_>]) -> Vec<Result<Vec<u8>, Error>> {
|
||||
static THREADS: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
|
||||
// The browser build has no threads to start.
|
||||
let threads = if jobs.len() < MIN_PARALLEL_ENTRIES || cfg!(target_arch = "wasm32") {
|
||||
1
|
||||
} else {
|
||||
(*THREADS.get_or_init(|| std::thread::available_parallelism().map_or(1, usize::from).min(MAX_DECODE_THREADS))).min(jobs.len())
|
||||
};
|
||||
if threads <= 1 {
|
||||
return jobs.iter().map(Claimed::decode).collect();
|
||||
}
|
||||
let next = std::sync::atomic::AtomicUsize::new(0);
|
||||
// The workers and this thread take the next undecoded entry until none is left.
|
||||
let work = || {
|
||||
let mut done = Vec::new();
|
||||
loop {
|
||||
let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let Some(job) = jobs.get(i) else { break };
|
||||
done.push((i, job.decode()));
|
||||
}
|
||||
done
|
||||
};
|
||||
let mut slots: Vec<Option<Result<Vec<u8>, Error>>> = jobs.iter().map(|_| None).collect();
|
||||
std::thread::scope(|sc| {
|
||||
// A thread that cannot be started just leaves its share to the others.
|
||||
let workers: Vec<_> = (1..threads).filter_map(|_| std::thread::Builder::new().spawn_scoped(sc, work).ok()).collect();
|
||||
let mut finished = vec![work()];
|
||||
finished.extend(workers.into_iter().map(|w| w.join().unwrap_or_default()));
|
||||
for (i, result) in finished.into_iter().flatten() {
|
||||
if let Some(slot) = slots.get_mut(i) {
|
||||
*slot = Some(result);
|
||||
}
|
||||
}
|
||||
});
|
||||
slots.into_iter().map(|r| r.unwrap_or(Err(Error::Malformed("tile decoder stopped")))).collect()
|
||||
}
|
||||
|
||||
/// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught
|
||||
/// without unbounded allocation.
|
||||
fn read_bounded(mut r: impl Read, size: usize) -> Result<Vec<u8>, Error> {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! (`DyBm.Bckg` → archive entry `c/N`), which is imported as is; other pixels are planar tiles of
|
||||
//! 256 bytes × 256 rows per channel, each its own archive entry.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::Error;
|
||||
use crate::model::{Affine, Image, Pixels, Reader};
|
||||
@@ -123,7 +123,7 @@ fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affi
|
||||
let scratch = pixels.checked_mul(channels * bps).ok_or(Error::Limit("pixel layer size"))?;
|
||||
r.admit_pixels(pixels.checked_mul(4).ok_or(Error::Limit("pixel layer size"))?, scratch)?;
|
||||
let mut planes = Vec::with_capacity(channels);
|
||||
let mut cache = HashMap::new();
|
||||
let mut cache = Cache::new();
|
||||
for c in 1..=channels {
|
||||
planes.push(plane(r, bitmap, c, bps, (x0, y0, w, h), &mut cache)?);
|
||||
}
|
||||
@@ -210,14 +210,24 @@ fn tag(prefix: &[u8; 3], c: usize) -> [u8; 4] {
|
||||
[prefix[0], prefix[1], prefix[2], b'0' + c as u8]
|
||||
}
|
||||
|
||||
/// Decoded tiles by archive entry name: a tile shared by several grid cells or channels is
|
||||
/// extracted (and charged to the archive's budget) once.
|
||||
type Cache<'s> = HashMap<&'s str, Vec<u8>>;
|
||||
|
||||
/// A tile to copy into a plane once its entry is decoded: pixel column and row of its corner.
|
||||
struct Place<'s> {
|
||||
name: &'s str,
|
||||
at: (usize, usize),
|
||||
}
|
||||
|
||||
/// One channel of level 0, cropped to (x0, y0, w, h) pixels; `bps` bytes per sample.
|
||||
fn plane(
|
||||
r: &mut Reader,
|
||||
fn plane<'s>(
|
||||
r: &mut Reader<'s, '_, '_>,
|
||||
bitmap: ObjId,
|
||||
c: usize,
|
||||
bps: usize,
|
||||
(x0, y0, w, h): (u32, u32, u32, u32),
|
||||
cache: &mut HashMap<String, Vec<u8>>,
|
||||
cache: &mut Cache<'s>,
|
||||
) -> Result<Vec<u8>, Error> {
|
||||
let s = r.s;
|
||||
let width = s.int(bitmap, b"BmpW").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
|
||||
@@ -242,6 +252,15 @@ fn plane(
|
||||
let mut out = vec![0u8; row * h as usize];
|
||||
let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps);
|
||||
let (py0, py1) = (y0 as usize, (y0 + h) as usize);
|
||||
let crop = (bx0, py0, bx1, py1);
|
||||
// First walk the grid: flat cells are filled right away (cells never overlap, so the order
|
||||
// of the copies does not matter) and the tiles that show are collected. They are extracted
|
||||
// together below, on several threads, then copied. A walk that fails still extracts the
|
||||
// tiles before the failing cell, as a tile-by-tile walk would have.
|
||||
let mut places: Vec<Place<'s>> = Vec::new();
|
||||
let mut wanted: Vec<&'s str> = Vec::new();
|
||||
let mut queued: HashSet<&'s str> = HashSet::new();
|
||||
let mut failure = None;
|
||||
for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) {
|
||||
let state = &if let Value::UInt(u) = state { u8::try_from(*u).unwrap_or(255) } else { 255 };
|
||||
let (ty, tx) = (t / tw.max(1), t % tw.max(1));
|
||||
@@ -249,25 +268,22 @@ fn plane(
|
||||
0 | 1 => None,
|
||||
2 => Some(0xFF),
|
||||
4 => {
|
||||
let Some(blck) = tiles.next() else { return Err(Error::Malformed("missing pixel tile")) };
|
||||
let Some(blck) = tiles.next() else {
|
||||
failure = Some(Error::Malformed("missing pixel tile"));
|
||||
break;
|
||||
};
|
||||
let (ox, oy) = (tx * TILE, ty * TILE);
|
||||
if ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0 {
|
||||
continue;
|
||||
}
|
||||
let name = s.entry(blck, b"Data").ok_or(Error::Malformed("pixel tile without data"))?.to_string();
|
||||
if !cache.contains_key(&name) {
|
||||
let mut data = r.archive.read(&name)?;
|
||||
// Older files wrap a tile in a one-field stream: header, then a 64 KiB blob.
|
||||
if data.len() == TILE_BYTES + 22 && data.starts_with(b"\x00\xffKS") {
|
||||
data = data.get(21..21 + TILE_BYTES).ok_or(Error::Malformed("pixel tile"))?.to_vec();
|
||||
}
|
||||
if data.len() != TILE_BYTES {
|
||||
return Err(Error::Malformed("pixel tile size"));
|
||||
}
|
||||
cache.insert(name.clone(), data);
|
||||
let Some(name) = s.entry(blck, b"Data") else {
|
||||
failure = Some(Error::Malformed("pixel tile without data"));
|
||||
break;
|
||||
};
|
||||
if !cache.contains_key(name) && queued.insert(name) {
|
||||
wanted.push(name);
|
||||
}
|
||||
let tile = cache.get(&name).ok_or(Error::Malformed("pixel tile"))?;
|
||||
copy(&mut out, row, (bx0, py0, bx1, py1), (ox, oy), Some(tile), 0);
|
||||
places.push(Place { name, at: (ox, oy) });
|
||||
continue;
|
||||
}
|
||||
3 => {
|
||||
@@ -278,12 +294,34 @@ fn plane(
|
||||
r.warn("pixel layers drawn from an embedded image (left empty)");
|
||||
None
|
||||
}
|
||||
_ => return Err(Error::Malformed("unknown pixel tile state")),
|
||||
_ => {
|
||||
failure = Some(Error::Malformed("unknown pixel tile state"));
|
||||
break;
|
||||
}
|
||||
};
|
||||
if let Some(v) = fill {
|
||||
copy(&mut out, row, (bx0, py0, bx1, py1), (tx * TILE, ty * TILE), None, v);
|
||||
copy(&mut out, row, crop, (tx * TILE, ty * TILE), None, v);
|
||||
}
|
||||
}
|
||||
let decoded = r.archive.read_many(&wanted);
|
||||
// A tile that fails to extract is reported before the failure of the walk after it.
|
||||
for (name, mut data) in wanted.into_iter().zip(decoded?) {
|
||||
// Older files wrap a tile in a one-field stream: header, then a 64 KiB blob.
|
||||
if data.len() == TILE_BYTES + 22 && data.starts_with(b"\x00\xffKS") {
|
||||
data = data.get(21..21 + TILE_BYTES).ok_or(Error::Malformed("pixel tile"))?.to_vec();
|
||||
}
|
||||
if data.len() != TILE_BYTES {
|
||||
return Err(Error::Malformed("pixel tile size"));
|
||||
}
|
||||
cache.insert(name, data);
|
||||
}
|
||||
if let Some(e) = failure {
|
||||
return Err(e);
|
||||
}
|
||||
for place in &places {
|
||||
let tile = cache.get(place.name).ok_or(Error::Malformed("pixel tile"))?;
|
||||
copy(&mut out, row, crop, place.at, Some(tile), 0);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
@@ -817,7 +817,13 @@ mod raster_identity {
|
||||
}
|
||||
|
||||
/// The per-byte closure copy `plane` used before the row copies.
|
||||
fn copy_reference(out: &mut [u8], row: usize, (bx0, py0, bx1, py1): (usize, usize, usize, usize), (ox, oy): (usize, usize), at: impl Fn(usize, usize) -> u8) {
|
||||
fn copy_reference(
|
||||
out: &mut [u8],
|
||||
row: usize,
|
||||
(bx0, py0, bx1, py1): (usize, usize, usize, usize),
|
||||
(ox, oy): (usize, usize),
|
||||
at: impl Fn(usize, usize) -> u8,
|
||||
) {
|
||||
for y in oy.max(py0)..(oy + 256).min(py1) {
|
||||
for x in ox.max(bx0)..(ox + 256).min(bx1) {
|
||||
if let Some(b) = out.get_mut((y - py0) * row + (x - bx0)) {
|
||||
@@ -831,7 +837,9 @@ mod raster_identity {
|
||||
fn tile_copy_matches_the_byte_loop_for_every_crop() {
|
||||
let tile = bytes(256 * 256, 77);
|
||||
// Crops that cut the tile on each side, sit inside it, and miss it.
|
||||
for &(bx0, bx1, py0, py1) in &[(0, 600, 0, 600), (10, 300, 20, 200), (100, 150, 100, 130), (256, 512, 0, 256), (0, 256, 300, 400), (255, 257, 255, 257), (300, 301, 0, 1)] {
|
||||
for &(bx0, bx1, py0, py1) in
|
||||
&[(0, 600, 0, 600), (10, 300, 20, 200), (100, 150, 100, 130), (256, 512, 0, 256), (0, 256, 300, 400), (255, 257, 255, 257), (300, 301, 0, 1)]
|
||||
{
|
||||
for &(ox, oy) in &[(0, 0), (256, 0), (0, 256), (256, 256), (512, 256)] {
|
||||
let row = bx1 - bx0;
|
||||
let mut old = vec![0xAAu8; row * (py1 - py0)];
|
||||
@@ -846,3 +854,69 @@ mod raster_identity {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Archive::read_many` against the same reads made one at a time.
|
||||
mod read_many {
|
||||
use crate::synth::{self, Method};
|
||||
use crate::{Archive, Error, Limits};
|
||||
|
||||
fn entry(i: usize) -> Vec<u8> {
|
||||
(0..4096 + i * 37).map(|b| (b * 31 + i * 7) as u8).collect()
|
||||
}
|
||||
|
||||
fn archive(count: usize, method: Method) -> Vec<u8> {
|
||||
let datas: Vec<Vec<u8>> = (0..count).map(entry).collect();
|
||||
let names: Vec<String> = (0..count).map(|i| format!("d/{i}")).collect();
|
||||
let entries: Vec<(&str, &[u8], Method)> = names.iter().zip(&datas).map(|(n, d)| (n.as_str(), d.as_slice(), method)).collect();
|
||||
synth::container(&entries, None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_serial_reads_and_charges_the_same() {
|
||||
for method in [Method::Stored, Method::Zlib, Method::Zstd] {
|
||||
for count in [1, 3, 4, 5, 40] {
|
||||
let file = archive(count, method);
|
||||
let names: Vec<String> = (0..count).map(|i| format!("d/{i}")).collect();
|
||||
let names: Vec<&str> = names.iter().map(String::as_str).collect();
|
||||
let mut one = Archive::open(&file, Limits::default()).unwrap();
|
||||
let serial: Vec<Vec<u8>> = names.iter().map(|n| one.read(n).unwrap()).collect();
|
||||
let mut many = Archive::open(&file, Limits::default()).unwrap();
|
||||
assert_eq!(many.read_many(&names).unwrap(), serial);
|
||||
assert_eq!(many.extracted(), one.extracted());
|
||||
assert_eq!(serial[count - 1], entry(count - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_limit_stops_at_the_same_entry_as_serial_reads() {
|
||||
let file = archive(12, Method::Zstd);
|
||||
let names: Vec<String> = (0..12).map(|i| format!("d/{i}")).collect();
|
||||
let names: Vec<&str> = names.iter().map(String::as_str).collect();
|
||||
let limits = Limits { max_total: (0..7).map(|i| entry(i).len()).sum(), ..Limits::default() };
|
||||
let mut one = Archive::open(&file, limits).unwrap();
|
||||
let failed = names.iter().position(|n| one.read(n).is_err()).unwrap();
|
||||
assert_eq!(failed, 7);
|
||||
let mut many = Archive::open(&file, limits).unwrap();
|
||||
assert!(matches!(many.read_many(&names), Err(Error::Limit(_))));
|
||||
assert_eq!(many.extracted(), one.extracted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_failing_entry_in_order_is_reported() {
|
||||
let mut file = archive(12, Method::Stored);
|
||||
// Flip a data byte of entry 2 (checksum failure); entry 9 is missing from the list.
|
||||
let at = file.windows(4).position(|w| w == b"#Fil").unwrap();
|
||||
let second = at + 4 + entry(0).len();
|
||||
let third = second + 4 + entry(1).len();
|
||||
file[third + 4 + 10] ^= 0xFF;
|
||||
let names: Vec<String> = (0..12).map(|i| if i == 9 { "gone".to_string() } else { format!("d/{i}") }).collect();
|
||||
let names: Vec<&str> = names.iter().map(String::as_str).collect();
|
||||
let mut a = Archive::open(&file, Limits::default()).unwrap();
|
||||
assert_eq!(a.read_many(&names).unwrap_err(), Error::Malformed("archive entry checksum mismatch"));
|
||||
// Without the corrupt entry the missing one is what fails.
|
||||
let intact = archive(12, Method::Stored);
|
||||
let mut a = Archive::open(&intact, Limits::default()).unwrap();
|
||||
assert_eq!(a.read_many(&names).unwrap_err(), Error::Malformed("missing archive entry"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user