mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
PNG import in steps: stream the rows into tiles, turn upright in bands
PngImport decoded the whole image and then copied it into a second, tile surface (about +400 MB for a 100 MP RGBA8 file, enough to kill a browser tab). A PNG whose rows come in final order now streams: PngDecodeRows::step_stream hands each group of rows on, they become tiles at once (the PngStream the one-shot streamed import also uses) and are dropped, then the prune scan runs in batches. decode_rows is the same step_stream driven to the end, so there is one path. Interlaced, animated and early-eXIf-oriented files are decoded whole as before; a late eXIf sends a streamed import back to a whole decode. The turn upright of an EXIF orientation 2-8 was one whole-buffer pass in the poll of the last rows; OrientSteps (photocraft-codecs) does it in bands of 64 rows through the same band writer as Image::oriented, and PngImport runs it as a stage of its own. Memory-budget errors keep their type and text: the stream is checked as the one-shot streamed import is, and, like the whole-image path, a layer under 32 MiB is not. Docs for the stepped place updated.
This commit is contained in:
1 parent
6ebc4c96f8
commit
7c2127b6bc
11 files changed
+710
-117
No files matched your search
+105
-40
@@ -7,7 +7,7 @@ use crate::Format;
|
||||
use crate::error::CodecError;
|
||||
use crate::fidelity::Plan;
|
||||
use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType};
|
||||
use crate::options::{EncodeOptions, Limits, PngCompression, PngStereo, alloc_zeroed};
|
||||
use crate::options::{EncodeOptions, Limits, PngCompression, PngStereo};
|
||||
|
||||
const F: Format = Format::Png;
|
||||
pub(crate) const XMP_KEYWORD: &str = "XML:com.adobe.xmp";
|
||||
@@ -26,6 +26,7 @@ pub(crate) fn dpi_of_ppm(ppm: u32) -> f32 {
|
||||
if (whole / f64::from(METERS_PER_INCH)).round() == f64::from(ppm) { whole as f32 } else { dpi as f32 }
|
||||
}
|
||||
|
||||
/// Decodes a whole PNG, by driving a [`PngDecodeRows`] to its end.
|
||||
pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
|
||||
PngDecodeRows::new(bytes, limits)?.step(&mut || true)?.ok_or_else(|| err("the decoder stopped before the image ended"))
|
||||
}
|
||||
@@ -119,6 +120,8 @@ pub struct PngDecodeRows<B: AsRef<[u8]>> {
|
||||
/// The decoder's whole output size, for an interlaced image's single frame decode.
|
||||
size: usize,
|
||||
rows: usize,
|
||||
/// For [`PngDecodeRows::step_stream`]: the first row of the group held in `buf`.
|
||||
group_start: usize,
|
||||
interlaced: bool,
|
||||
images: u64,
|
||||
/// The chunks after the pixels: scanned from `text_at` up to `text_end`, a batch at a time,
|
||||
@@ -213,6 +216,7 @@ impl<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
line,
|
||||
size,
|
||||
rows: 0,
|
||||
group_start: 0,
|
||||
interlaced,
|
||||
images,
|
||||
text_at: 8,
|
||||
@@ -225,6 +229,35 @@ impl<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
})
|
||||
}
|
||||
|
||||
/// [`PngDecodeRows::new`] without reserving the whole image, for a caller that streams the rows
|
||||
/// ([`PngDecodeRows::step_stream`]) and so never holds them all. A caller that finds it must
|
||||
/// decode the whole image after all (an interlaced file) calls
|
||||
/// [`PngDecodeRows::reserve_output`] before [`PngDecodeRows::step`].
|
||||
pub fn new_streaming(bytes: B, limits: &Limits) -> Result<Self, CodecError> {
|
||||
Self::open(bytes, limits, false)
|
||||
}
|
||||
|
||||
/// Reserves the buffer [`PngDecodeRows::step`] decodes the whole image into.
|
||||
pub fn reserve_output(&mut self) -> Result<(), CodecError> {
|
||||
let size = self.size;
|
||||
self.buf.try_reserve_exact(size).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {size} bytes for the image")))
|
||||
}
|
||||
|
||||
/// Whether the rows come in final order, so [`PngDecodeRows::step_stream`] can hand them on:
|
||||
/// not an interlaced file, not an APNG (its first frame may be a sub-rectangle), and not one
|
||||
/// whose `eXIf` before the image data asks for another orientation. (An `eXIf` after the image
|
||||
/// data shows only in [`PngExtras::orientation`] at the end.)
|
||||
pub fn streamable(&self) -> bool {
|
||||
let info = self.reader.info();
|
||||
let upright = info.exif_metadata.as_deref().is_none_or(|e| crate::orientation::exif_orientation(e) == 1);
|
||||
!self.interlaced && info.animation_control.is_none() && upright
|
||||
}
|
||||
|
||||
/// The size and pixel format the rows of [`PngDecodeRows::step_stream`] come in.
|
||||
pub fn header(&self) -> PngHeader {
|
||||
PngHeader { width: self.width, height: u32::try_from(self.height).unwrap_or(u32::MAX), layout: self.layout, sample: self.sample }
|
||||
}
|
||||
|
||||
/// The image's width and height in pixels.
|
||||
pub fn size(&self) -> (u32, u32) {
|
||||
(self.width, u32::try_from(self.height).unwrap_or(u32::MAX))
|
||||
@@ -298,6 +331,71 @@ impl<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
self.finish().map(Some)
|
||||
}
|
||||
|
||||
/// Decodes the rows of a [`streamable`](PngDecodeRows::streamable) file a group at a time:
|
||||
/// `sink(y0, data)` gets whole rows `y0..` in final order, `group` of them at a time (the last
|
||||
/// group may be shorter; 0 counts as 1), native-endian, exactly the samples [`decode`] would
|
||||
/// return, and the decoder keeps only that group. Decodes at least one row, then goes on while
|
||||
/// `more()` returns true; `Some` with the extras once the file is read to its end, with the
|
||||
/// resolution a format that lacks one takes from its EXIF or XMP. A damaged file fails with
|
||||
/// the error [`decode`] gives, after however many rows were delivered. An orientation (an
|
||||
/// `eXIf` after the image data may set one) is for the caller to apply.
|
||||
pub fn step_stream<E: From<CodecError>>(
|
||||
&mut self,
|
||||
group: u32,
|
||||
more: &mut dyn FnMut() -> bool,
|
||||
sink: &mut PngRowSink<'_, E>,
|
||||
) -> Result<Option<PngExtras>, E> {
|
||||
if self.done {
|
||||
return Err(err("the image was already decoded").into());
|
||||
}
|
||||
let group = usize::try_from(group.max(1)).unwrap_or(usize::MAX);
|
||||
if !self.tail {
|
||||
while self.rows < self.height {
|
||||
let held = self.rows - self.group_start;
|
||||
let at = held.checked_mul(self.line).ok_or_else(|| err("image too large"))?;
|
||||
let end = at.checked_add(self.line).ok_or_else(|| err("image too large"))?;
|
||||
if self.buf.len() < end {
|
||||
self.buf.try_reserve_exact(end - self.buf.len()).map_err(|_| CodecError::LimitExceeded("cannot allocate a group of rows".into()))?;
|
||||
self.buf.resize(end, 0);
|
||||
}
|
||||
let row = self.buf.get_mut(at..end).ok_or_else(|| err("invalid PNG row group"))?;
|
||||
if self.reader.read_row(row).map_err(map_png_err)?.is_none() {
|
||||
return Err(err("the image data ends before the last row").into());
|
||||
}
|
||||
if self.sample == SampleType::U16 {
|
||||
to_native_endian(row);
|
||||
}
|
||||
self.rows += 1;
|
||||
if self.rows - self.group_start == group || self.rows == self.height {
|
||||
let data = self.buf.get(..end).ok_or_else(|| err("invalid PNG row group"))?;
|
||||
sink(u32::try_from(self.group_start).map_err(|_| err("image too large"))?, data)?;
|
||||
self.group_start = self.rows;
|
||||
}
|
||||
if self.rows < self.height && !more() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
// Past the last row: trailing damage fails the same way it does in `decode`.
|
||||
if self.reader.read_row(&mut []).map_err(map_png_err)?.is_some() {
|
||||
return Err(err("the image has more rows than its header declares").into());
|
||||
}
|
||||
self.begin_tail()?;
|
||||
}
|
||||
while !self.text.done {
|
||||
self.text_batch()?;
|
||||
if !self.text.done && !more() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
self.done = true;
|
||||
let mut extras = self.extras();
|
||||
// As `decode_as_with` does for every format: a resolution the format lacks comes from EXIF or XMP.
|
||||
if extras.meta.dpi.is_none() {
|
||||
extras.meta.dpi = crate::resolution::from_metadata(extras.meta.exif.as_deref(), extras.meta.xmp.as_deref());
|
||||
}
|
||||
Ok(Some(extras))
|
||||
}
|
||||
|
||||
/// Finishes the pixel reader and fixes where the metadata scan ends. Tolerate malformed
|
||||
/// tails once pixels are complete, but never swallow an allocation-limit failure.
|
||||
fn begin_tail(&mut self) -> Result<(), CodecError> {
|
||||
@@ -568,48 +666,13 @@ pub(crate) fn decode_rows<E: From<CodecError>>(
|
||||
begin: &mut dyn FnMut(&PngHeader) -> Result<bool, E>,
|
||||
rows: &mut PngRowSink<'_, E>,
|
||||
) -> Result<Option<PngExtras>, E> {
|
||||
let group = group.max(1);
|
||||
// The limits and plausibility checks are made here, before any row; the output is not reserved.
|
||||
let mut dec = PngDecodeRows::open(bytes, limits, false)?;
|
||||
let upright = dec.reader.info().exif_metadata.as_deref().is_none_or(|e| crate::orientation::exif_orientation(e) == 1);
|
||||
if dec.interlaced || dec.reader.info().animation_control.is_some() || !upright {
|
||||
let mut dec = PngDecodeRows::new_streaming(bytes, limits)?;
|
||||
if !dec.streamable() || !begin(&dec.header())? {
|
||||
return Ok(None);
|
||||
}
|
||||
let height = u32::try_from(dec.height).map_err(|_| err("image too large"))?;
|
||||
if !begin(&PngHeader { width: dec.width, height, layout: dec.layout, sample: dec.sample })? {
|
||||
return Ok(None);
|
||||
}
|
||||
let line = dec.line;
|
||||
let mut buf = alloc_zeroed::<u8>(line.checked_mul(group.min(height) as usize).ok_or_else(|| err("image too large"))?)?;
|
||||
let mut y0 = 0;
|
||||
while y0 < height {
|
||||
let n = group.min(height - y0) as usize;
|
||||
for row in buf.chunks_exact_mut(line.max(1)).take(n) {
|
||||
if dec.reader.read_row(row).map_err(map_png_err)?.is_none() {
|
||||
return Err(err("the image data ends before the last row").into());
|
||||
}
|
||||
}
|
||||
let rows_data = buf.get_mut(..line.saturating_mul(n)).ok_or_else(|| err("invalid PNG row group"))?;
|
||||
if dec.sample == SampleType::U16 {
|
||||
to_native_endian(rows_data);
|
||||
}
|
||||
rows(y0, rows_data)?;
|
||||
y0 += n as u32;
|
||||
}
|
||||
// Past the last row: trailing damage fails the same way it does in `decode`.
|
||||
if dec.reader.read_row(&mut []).map_err(map_png_err)?.is_some() {
|
||||
return Err(err("the image has more rows than its header declares").into());
|
||||
}
|
||||
dec.begin_tail()?;
|
||||
while !dec.text.done {
|
||||
dec.text_batch()?;
|
||||
}
|
||||
let mut extras = dec.extras();
|
||||
// As `decode_as_with` does for every format: a resolution the format lacks comes from EXIF or XMP.
|
||||
if extras.meta.dpi.is_none() {
|
||||
extras.meta.dpi = crate::resolution::from_metadata(extras.meta.exif.as_deref(), extras.meta.xmp.as_deref());
|
||||
}
|
||||
Ok(Some(extras))
|
||||
// With a `more` that always says go on, the first call decodes the whole file.
|
||||
dec.step_stream(group, &mut || true, rows)
|
||||
}
|
||||
|
||||
/// The colour table of a palette PNG (`PLTE`) and the one entry its `tRNS` makes transparent.
|
||||
@@ -797,6 +860,7 @@ struct Utf8Check {
|
||||
}
|
||||
|
||||
impl Utf8Check {
|
||||
/// Feeds the next bytes of the value; false at the first one that isn't valid UTF-8.
|
||||
fn feed(&mut self, bytes: &[u8]) -> bool {
|
||||
for &b in bytes {
|
||||
if self.need > 0 {
|
||||
@@ -843,6 +907,7 @@ impl Utf8Check {
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether the bytes so far end on a whole character.
|
||||
fn complete(&self) -> bool {
|
||||
self.need == 0
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ pub use crate::options::{
|
||||
DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, Limits, PngCompression, PngStereo, TIFF_PYRAMID_MIN,
|
||||
TiffCompression,
|
||||
};
|
||||
pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp};
|
||||
pub use crate::orientation::{OrientSteps, exif_orientation, upright_exif, upright_xmp};
|
||||
pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};
|
||||
pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding};
|
||||
pub use half::f16;
|
||||
@@ -103,11 +103,46 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res
|
||||
finish_format(format, bytes, img, opts)
|
||||
}
|
||||
|
||||
/// What [`decode_as_with`] does with a PNG decoded in steps by [`PngRows`] (`img` is its output):
|
||||
/// the resolution from the metadata, the upright orientation and the final limit check, so the
|
||||
/// result equals [`decode_as_with`]'s on the same file.
|
||||
/// What [`decode_as_with`] does with a PNG decoded in steps by [`PngDecodeRows`] (`img` is its
|
||||
/// output): the resolution from the metadata, the upright orientation and the final limit check,
|
||||
/// so the result equals [`decode_as_with`]'s on the same file.
|
||||
pub fn finish_png_decode(img: Image, opts: &DecodeOptions) -> Result<Image, CodecError> {
|
||||
finish_format(Format::Png, &[], img, opts)
|
||||
match begin_png_finish(img, opts)? {
|
||||
PngFinish::Done(img) => Ok(*img),
|
||||
PngFinish::Orient(mut steps) => loop {
|
||||
if let Some(img) = steps.step(&mut || true)? {
|
||||
return Ok(img);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Where [`begin_png_finish`] leaves a decoded PNG.
|
||||
pub enum PngFinish {
|
||||
/// Finished: it was already upright (or the options keep the orientation).
|
||||
Done(Box<Image>),
|
||||
/// To be turned upright, a band of rows at a time, by driving these steps.
|
||||
Orient(Box<OrientSteps>),
|
||||
}
|
||||
|
||||
/// [`finish_png_decode`] with the turning upright (orientations 2-8) left to the caller, in
|
||||
/// bands it can pace: the resolution from the metadata and the limit checks are made here, and the
|
||||
/// result of the steps equals what [`finish_png_decode`] returns.
|
||||
pub fn begin_png_finish(mut img: Image, opts: &DecodeOptions) -> Result<PngFinish, CodecError> {
|
||||
if img.meta.dpi.is_none() {
|
||||
img.meta.dpi = resolution::from_metadata(img.meta.exif.as_deref(), img.meta.xmp.as_deref());
|
||||
}
|
||||
let o = img.meta.exif.as_deref().map_or(1, exif_orientation);
|
||||
let l = &opts.limits;
|
||||
// As `finish_decode` does: the final guard, then (turning 5-8 swaps the sides) the upright size.
|
||||
l.check(img.width(), img.height(), img.layout(), img.sample_type())?;
|
||||
if opts.keep_orientation || !(2..=8).contains(&o) {
|
||||
return Ok(PngFinish::Done(Box::new(img)));
|
||||
}
|
||||
if (5..=8).contains(&o) {
|
||||
l.check(img.height(), img.width(), img.layout(), img.sample_type())?;
|
||||
}
|
||||
Ok(PngFinish::Orient(Box::new(OrientSteps::new(img, o)?)))
|
||||
}
|
||||
|
||||
/// The steps after a decoder of `format` has produced `img` from `bytes`.
|
||||
|
||||
@@ -311,6 +311,95 @@ fn orient_bytes(src: &[u8], bpp: usize, o: u16, (w, h): (usize, usize), ow: usiz
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the oriented output rows `y0..` that fit in `dst` (whole rows of `ow` pixels), `bpp`
|
||||
/// bytes per pixel: one band of [`orient_bytes`], the same pixels it writes.
|
||||
fn orient_band(src: &[u8], dst: &mut [u8], bpp: usize, o: u16, (w, h): (usize, usize), ow: usize, y0: usize) {
|
||||
macro_rules! go {
|
||||
($n:literal) => {{
|
||||
let (s, _) = src.as_chunks::<$n>();
|
||||
let (d, _) = dst.as_chunks_mut::<$n>();
|
||||
band(s, d, o, (w, h), ow, y0)
|
||||
}};
|
||||
}
|
||||
match bpp {
|
||||
1 => go!(1),
|
||||
2 => go!(2),
|
||||
3 => go!(3),
|
||||
4 => go!(4),
|
||||
5 => go!(5),
|
||||
6 => go!(6),
|
||||
8 => go!(8),
|
||||
10 => go!(10),
|
||||
12 => go!(12),
|
||||
16 => go!(16),
|
||||
_ => go!(20),
|
||||
}
|
||||
}
|
||||
|
||||
/// An image turned upright a band of rows at a time, for a caller that must not block for the
|
||||
/// whole image (the web build has no threads): [`OrientSteps::step`] gives the [`Image`]
|
||||
/// [`Image::oriented`] gives, once every band is written.
|
||||
pub struct OrientSteps {
|
||||
src: Image,
|
||||
o: u16,
|
||||
bpp: usize,
|
||||
/// The oriented size.
|
||||
ow: usize,
|
||||
oh: usize,
|
||||
out: Vec<u8>,
|
||||
/// Output rows written so far.
|
||||
done: usize,
|
||||
}
|
||||
|
||||
impl OrientSteps {
|
||||
/// Sets up turning `img` upright for orientation `o` (2–8; anything else leaves it as it is).
|
||||
/// Allocates the output, which the image is turned into beside the original.
|
||||
pub fn new(img: Image, o: u16) -> Result<Self, CodecError> {
|
||||
let (w, h) = (img.width() as usize, img.height() as usize);
|
||||
let (ow, oh) = if o >= 5 { (h, w) } else { (w, h) };
|
||||
let (layout, sample) = (img.layout(), img.sample_type());
|
||||
let bpp = layout.channels() * sample.bytes();
|
||||
let turns = (2..=8).contains(&o);
|
||||
if turns && (!matches!(bpp, 1..=6 | 8 | 10 | 12 | 16 | 20) || w == 0 || h == 0) {
|
||||
return Err(CodecError::InvalidImage(format!("cannot orient {layout:?} {sample:?} {w}x{h}")));
|
||||
}
|
||||
let out = if turns { alloc_zeroed(img.data().len())? } else { Vec::new() };
|
||||
Ok(Self { src: img, o, bpp, ow, oh, out, done: 0 })
|
||||
}
|
||||
|
||||
/// How much of the image is turned, `0.0..=1.0`.
|
||||
pub fn progress(&self) -> f32 {
|
||||
if self.oh == 0 { 1.0 } else { self.done as f32 / self.oh as f32 }
|
||||
}
|
||||
|
||||
/// Writes bands of [`BAND`] output rows, at least one, then goes on while `more()` returns
|
||||
/// true; `Some` with the upright image once the last band is written.
|
||||
pub fn step(&mut self, more: &mut dyn FnMut() -> bool) -> Result<Option<Image>, CodecError> {
|
||||
if !(2..=8).contains(&self.o) {
|
||||
let placeholder = Image::from_raw(0, 0, self.src.layout(), self.src.sample_type(), Vec::new())?;
|
||||
return Ok(Some(std::mem::replace(&mut self.src, placeholder)));
|
||||
}
|
||||
let (w, h) = (self.src.width() as usize, self.src.height() as usize);
|
||||
while self.done < self.oh {
|
||||
let rows = BAND.min(self.oh - self.done);
|
||||
let row_bytes = self.ow.checked_mul(self.bpp).ok_or_else(|| CodecError::InvalidImage("image too large".into()))?;
|
||||
let at = self.done.saturating_mul(row_bytes);
|
||||
let end = at.saturating_add(rows.saturating_mul(row_bytes));
|
||||
let dst = self.out.get_mut(at..end).ok_or_else(|| CodecError::InvalidImage("the oriented rows are out of range".into()))?;
|
||||
orient_band(self.src.data(), dst, self.bpp, self.o, (w, h), self.ow, self.done);
|
||||
self.done += rows;
|
||||
if self.done < self.oh && !more() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let (layout, sample) = (self.src.layout(), self.src.sample_type());
|
||||
let placeholder = Image::from_raw(0, 0, layout, sample, Vec::new())?;
|
||||
let src = std::mem::replace(&mut self.src, placeholder);
|
||||
let data = std::mem::take(&mut self.out);
|
||||
src.oriented_with(self.o, data).map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
impl Image {
|
||||
/// The image turned upright for orientation `o` (1–8; anything else is
|
||||
/// treated as 1 and returns the image unchanged). Width and height swap
|
||||
@@ -321,8 +410,7 @@ impl Image {
|
||||
return Ok(self);
|
||||
}
|
||||
let (w, h) = (self.width() as usize, self.height() as usize);
|
||||
let swap = o >= 5;
|
||||
let (ow, oh) = if swap { (h, w) } else { (w, h) };
|
||||
let ow = if o >= 5 { h } else { w };
|
||||
let (layout, sample) = (self.layout(), self.sample_type());
|
||||
let bpp = layout.channels() * sample.bytes();
|
||||
// Every layout/sample pair is 1–20 bytes per pixel and has a fixed-size path.
|
||||
@@ -330,6 +418,16 @@ impl Image {
|
||||
return Err(CodecError::InvalidImage(format!("cannot orient {layout:?} {sample:?} {w}x{h}")));
|
||||
}
|
||||
let data = orient_bytes(self.data(), bpp, o, (w, h), ow)?;
|
||||
self.oriented_with(o, data)
|
||||
}
|
||||
|
||||
/// The upright image of orientation `o` (2–8) whose turned pixels are `data`: the size,
|
||||
/// metadata and extra samples of [`Image::oriented`].
|
||||
fn oriented_with(self, o: u16, data: Vec<u8>) -> Result<Image, CodecError> {
|
||||
let (w, h) = (self.width() as usize, self.height() as usize);
|
||||
let swap = o >= 5;
|
||||
let (ow, oh) = if swap { (h, w) } else { (w, h) };
|
||||
let (layout, sample) = (self.layout(), self.sample_type());
|
||||
let mut meta = self.meta.clone();
|
||||
// Extra samples (a TIFF's alpha and spot planes, one sample a pixel) turn with the image.
|
||||
// A plane of the wrong size is left as it is: importers drop it with a warning.
|
||||
|
||||
@@ -214,6 +214,76 @@ fn png_opens_upright_for_every_orientation() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An image turned upright a band of rows at a time is the image `oriented` gives, for every
|
||||
/// orientation, pixel size and shape, and takes a call per band.
|
||||
#[test]
|
||||
fn orient_steps_equal_oriented() {
|
||||
for o in 1..=8u16 {
|
||||
for (layout, sample) in [
|
||||
(ChannelLayout::Gray, SampleType::U8),
|
||||
(ChannelLayout::GrayA, SampleType::U16),
|
||||
(ChannelLayout::Rgb, SampleType::U8),
|
||||
(ChannelLayout::Rgba, SampleType::U16),
|
||||
(ChannelLayout::Rgba, SampleType::F32),
|
||||
] {
|
||||
for (w, h) in [(1u32, 1u32), (7, 5), (130, 66), (65, 200)] {
|
||||
let len = w as usize * h as usize * layout.channels() * sample.bytes();
|
||||
let data: Vec<u8> = (0..len).map(|i| (i.wrapping_mul(2_654_435_761) >> 11) as u8).collect();
|
||||
let mut img = Image::from_raw(w, h, layout, sample, data).unwrap();
|
||||
img.meta.dpi = Some((100.0, 200.0));
|
||||
img.meta.exif = Some(exif(u32::from(o), false, false));
|
||||
let want = img.clone().oriented(o).unwrap();
|
||||
let mut steps = OrientSteps::new(img, o).unwrap();
|
||||
let mut calls = 0;
|
||||
let got = loop {
|
||||
calls += 1;
|
||||
assert!(steps.progress() <= 1.0);
|
||||
if let Some(img) = steps.step(&mut || false).unwrap() {
|
||||
break img;
|
||||
}
|
||||
};
|
||||
assert_eq!(got, want, "o={o} {layout:?} {sample:?} {w}x{h}");
|
||||
let rows = if o >= 5 { w } else { h } as usize;
|
||||
let expected = if (2..=8).contains(&o) { rows.div_ceil(64) } else { 1 };
|
||||
assert_eq!(calls, expected, "o={o} {w}x{h}: one call per band of 64 rows");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A PNG turned upright in bands by `begin_png_finish` is the image `decode` gives, for every
|
||||
/// orientation, and a band of a tall image is not the whole of it.
|
||||
#[test]
|
||||
fn png_finishes_upright_in_bands_for_every_orientation() {
|
||||
let (w, h) = (70, 150);
|
||||
let up = upright(w, h, |x, y| (x * 7 + y * 13) as u8);
|
||||
for o in 1..=8u16 {
|
||||
let (s, sw, sh) = stored(&up, w, h, o);
|
||||
let png = encode(&gray(sw, sh, s), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let file = png_with_exif(&png, &exif(u32::from(o), o % 2 == 0, false));
|
||||
let want = decode(&file).unwrap();
|
||||
let img = PngDecodeRows::new(file.as_slice(), &Limits::default()).unwrap().step(&mut || true).unwrap().unwrap();
|
||||
let got = match begin_png_finish(img, &DecodeOptions::default()).unwrap() {
|
||||
PngFinish::Done(img) => {
|
||||
assert_eq!(o, 1);
|
||||
*img
|
||||
}
|
||||
PngFinish::Orient(mut steps) => {
|
||||
assert!(o > 1);
|
||||
let mut calls = 0;
|
||||
loop {
|
||||
calls += 1;
|
||||
if let Some(img) = steps.step(&mut || false).unwrap() {
|
||||
assert!(calls > 1, "o={o}: more than one band");
|
||||
break img;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
assert_eq!(got, want, "o={o}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Extra samples (a TIFF's alpha and spot planes) turn with the image, so a channel stays
|
||||
/// aligned with the pixels for every orientation.
|
||||
#[test]
|
||||
|
||||
@@ -594,3 +594,53 @@ fn pngsuite_corpus_rows_match_the_whole_decode() {
|
||||
eprintln!("pngsuite: {streamed} streamed, {refused} refused (interlaced), {skipped} skipped (not detected as PNG)");
|
||||
assert!(streamed > 100, "only {streamed} PNGs streamed: run `cargo xtask corpus --all`");
|
||||
}
|
||||
|
||||
/// Streaming a PNG's rows a group at a time gives the pixels and metadata `decode` gives, holds
|
||||
/// only a group at a time, and stops between rows when asked.
|
||||
#[test]
|
||||
fn step_stream_gives_the_pixels_and_extras_of_decode() {
|
||||
for (layout, sample) in [(ChannelLayout::Gray, SampleType::U8), (ChannelLayout::Rgb, SampleType::U16), (ChannelLayout::Rgba, SampleType::U8)] {
|
||||
let (w, h) = (23u32, 19u32);
|
||||
let len = w as usize * h as usize * layout.channels() * sample.bytes();
|
||||
let mut img = Image::from_raw(w, h, layout, sample, (0..len).map(|i| (i.wrapping_mul(2_654_435_761) >> 11) as u8).collect()).unwrap();
|
||||
img.meta.dpi = Some((144.0, 144.0));
|
||||
img.meta.text.push(("Comment".into(), "streamed".into()));
|
||||
img.icc = Some(vec![7; 40]);
|
||||
let bytes = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let want = decode(&bytes).unwrap();
|
||||
for group in [0u32, 1, 4, 19, 64] {
|
||||
let mut dec = PngDecodeRows::new_streaming(bytes.as_slice(), &Limits::default()).unwrap();
|
||||
assert!(dec.streamable());
|
||||
assert_eq!(dec.header(), PngHeader { width: w, height: h, layout, sample });
|
||||
let (mut data, mut next, mut calls) = (Vec::new(), 0u32, 0);
|
||||
let extras = loop {
|
||||
calls += 1;
|
||||
let mut sink = |y0: u32, rows: &[u8]| -> Result<(), CodecError> {
|
||||
assert_eq!(y0, next, "{layout:?} group {group}");
|
||||
assert!(rows.len() <= group.max(1) as usize * dec_line(w, layout, sample), "a group at most");
|
||||
next += (rows.len() / dec_line(w, layout, sample)) as u32;
|
||||
data.extend_from_slice(rows);
|
||||
Ok(())
|
||||
};
|
||||
if let Some(extras) = dec.step_stream(group, &mut || false, &mut sink).unwrap() {
|
||||
break extras;
|
||||
}
|
||||
assert!(calls < 10_000);
|
||||
};
|
||||
assert!(calls > 1, "{layout:?}: stopped between rows");
|
||||
assert_eq!(data, want.data(), "{layout:?} group {group}: pixels");
|
||||
assert_eq!((extras.icc.as_deref(), extras.meta.dpi, &extras.meta.text), (want.icc.as_deref(), want.meta.dpi, &want.meta.text));
|
||||
assert_eq!(extras.orientation, 1);
|
||||
assert!(dec.step_stream::<CodecError>(group, &mut || true, &mut |_, _| Ok(())).is_err(), "spent");
|
||||
}
|
||||
}
|
||||
// An interlaced file doesn't stream.
|
||||
let img = Image::from_raw(9, 9, ChannelLayout::Gray, SampleType::U8, vec![1; 81]).unwrap();
|
||||
let bytes = encode(&img, Format::Png, &EncodeOptions { png_interlaced: true, ..Default::default() }).unwrap();
|
||||
assert!(!PngDecodeRows::new_streaming(bytes.as_slice(), &Limits::default()).unwrap().streamable());
|
||||
}
|
||||
|
||||
/// Bytes per row of `w` pixels.
|
||||
fn dec_line(w: u32, layout: ChannelLayout, sample: SampleType) -> usize {
|
||||
w as usize * layout.channels() * sample.bytes()
|
||||
}
|
||||
@@ -630,6 +630,7 @@ pub struct Jobs {
|
||||
// Derivable on a desktop, where `cooperative` starts off; wasm starts it on.
|
||||
#[allow(clippy::derivable_impls)]
|
||||
impl Default for Jobs {
|
||||
/// No jobs, spawning off; a session steps its jobs itself (cooperative) on wasm only.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
next: 0,
|
||||
|
||||
+120
-52
@@ -259,7 +259,7 @@ impl FlatBuilder {
|
||||
/// What every flat format does to the document of its pixels: the palette mode, the save
|
||||
/// settings, a Targa's alpha channel and the profile an untagged image needs. `img` is the
|
||||
/// decoded image, when the document was built from one (a streamed PNG has none).
|
||||
fn apply_flat_format(r: &mut ImportResult, bytes: &[u8], format: Option<Format>, img: Option<&Image>) -> Result<(), IoError> {
|
||||
pub(crate) fn apply_flat_format(r: &mut ImportResult, bytes: &[u8], format: Option<Format>, img: Option<&Image>) -> Result<(), IoError> {
|
||||
// A palette BMP, PNG or GIF opens in Indexed Color mode with its colour table, as in
|
||||
// Photoshop (#3802, #4804, #7886). A GIF is always palette-based: the first frame's table.
|
||||
let palette = match format {
|
||||
@@ -883,58 +883,48 @@ fn import_png_streamed(name: &str, bytes: &[u8], opts: &crate::ImportOptions, ct
|
||||
import_png_streamed_with(name, bytes, opts, ctl, min_bytes, crate::memory::available)
|
||||
}
|
||||
|
||||
/// [`import_png_streamed`], with the memory the machine can still use given (see
|
||||
/// [`crate::memory::available`]): `None` when it isn't known.
|
||||
fn import_png_streamed_with(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
opts: &crate::ImportOptions,
|
||||
ctl: &Interrupt,
|
||||
min_bytes: u64,
|
||||
available: impl FnOnce() -> Option<u64>,
|
||||
) -> Result<Option<ImportResult>, IoError> {
|
||||
struct Stream {
|
||||
surface: Surface,
|
||||
header: codecs::PngHeader,
|
||||
convert: RowConverter,
|
||||
}
|
||||
// Rows are worked off 0.02..0.55 so a fallback to the whole-image path, which reports 0.6
|
||||
// after its decode, never takes progress backwards.
|
||||
let state = std::cell::RefCell::new(None::<Stream>);
|
||||
let mut available = Some(available);
|
||||
let busy = || IoError::Unsupported("the PNG reader re-entered itself".into());
|
||||
let mut begin = |header: &codecs::PngHeader| -> Result<bool, IoError> {
|
||||
// Decoded size, from the header; a size that overflows is certainly large enough.
|
||||
let bytes = u64::from(header.width)
|
||||
.checked_mul(u64::from(header.height))
|
||||
.and_then(|px| px.checked_mul((header.layout.channels() * header.sample.bytes()) as u64));
|
||||
if bytes.is_some_and(|b| b < min_bytes) {
|
||||
return Ok(false);
|
||||
}
|
||||
// A cancelled import is reported as such, not as the memory it would have needed.
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
/// A PNG's rows becoming the tiles of its layer as they are decoded: the surface, and what turns a
|
||||
/// decoded row into its pixels. Shared by [`import_png_streamed`] (all at once) and the stepped
|
||||
/// import ([`crate::PngImport`], a bounded piece at a time), which give the same document.
|
||||
pub(crate) struct PngStream {
|
||||
surface: Surface,
|
||||
header: codecs::PngHeader,
|
||||
convert: RowConverter,
|
||||
}
|
||||
|
||||
impl PngStream {
|
||||
/// Sets up the surface for rows of `header`, after checking the layer's tiles and a group of
|
||||
/// rows as decoded and as converted against `available` (the memory the machine can still use,
|
||||
/// when known): Linux overcommits, so the tiles would be allocated even when they can't be
|
||||
/// backed, and writing them would have the process killed.
|
||||
pub(crate) fn new(header: &codecs::PngHeader, available: Option<u64>) -> Result<Self, IoError> {
|
||||
let (_, target_layout, _, csample) = flat_target(header.layout, header.sample);
|
||||
// The layer's tiles, plus one group of rows as decoded and as converted into them.
|
||||
// Linux overcommits, so the tiles would be allocated even when they can't be backed, and
|
||||
// writing them would have the process killed: refuse first, as `tiff_to_document` does.
|
||||
let bpp = surface_format(target_layout, csample).bytes_per_pixel() as u64;
|
||||
let src_px = (header.layout.channels() * header.sample.bytes()) as u64;
|
||||
let group = u64::from(header.width).saturating_mul(u64::from(header.height.min(TILE_SIZE as u32)));
|
||||
let needed = tile_bytes(header.width, header.height, bpp).saturating_add(group.saturating_mul(src_px)).saturating_add(group.saturating_mul(bpp));
|
||||
crate::memory::check_fits(header.width, header.height, needed, available.take().and_then(|f| f()))?;
|
||||
*state.try_borrow_mut().map_err(|_| busy())? = Some(Stream {
|
||||
crate::memory::check_fits(header.width, header.height, needed, available)?;
|
||||
Ok(Self {
|
||||
surface: Surface::new(surface_format(target_layout, csample)),
|
||||
header: *header,
|
||||
convert: RowConverter::new((header.layout, header.sample), (target_layout, csample)),
|
||||
});
|
||||
ctl.progress(0.02);
|
||||
Ok(true)
|
||||
};
|
||||
let mut rows = |y0: u32, data: &[u8]| -> Result<(), IoError> {
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let mut guard = state.try_borrow_mut().map_err(|_| busy())?;
|
||||
let Some(Stream { surface, header, convert }) = guard.as_mut() else { return Err(busy()) };
|
||||
let (w, h) = (header.width, header.height);
|
||||
})
|
||||
}
|
||||
|
||||
/// [`PngStream::new`] for a stepped import, which streams every PNG whose rows come in order
|
||||
/// and not only the big ones: a layer under [`STREAM_MIN_BYTES`] of tiles is not checked
|
||||
/// against free memory, as the whole-image path leaves it unchecked ([`check_layer_fits`]).
|
||||
pub(crate) fn for_steps(header: &codecs::PngHeader) -> Result<Self, IoError> {
|
||||
let (_, target_layout, _, csample) = flat_target(header.layout, header.sample);
|
||||
let tiles = tile_bytes(header.width, header.height, surface_format(target_layout, csample).bytes_per_pixel() as u64);
|
||||
Self::new(header, if tiles < STREAM_MIN_BYTES { None } else { crate::memory::available() })
|
||||
}
|
||||
|
||||
/// Converts the whole rows `y0..` in `data` into the tiles, checking `ctl` as it goes.
|
||||
pub(crate) fn write_rows(&mut self, y0: u32, data: &[u8], ctl: &Interrupt) -> Result<(), IoError> {
|
||||
let (w, h) = (self.header.width, self.header.height);
|
||||
let convert = &self.convert;
|
||||
let row_bytes = (w as usize).checked_mul(convert.src_px).filter(|&b| b > 0).ok_or_else(|| IoError::Unsupported("image too large".into()))?;
|
||||
let n = u32::try_from(data.len() / row_bytes).unwrap_or(0);
|
||||
if n == 0 || !data.len().is_multiple_of(row_bytes) {
|
||||
@@ -943,7 +933,7 @@ fn import_png_streamed_with(
|
||||
let to_i32 = |v: u32| i32::try_from(v).map_err(|_| IoError::Unsupported("image too large".into()));
|
||||
let rect = Rect::new(0, to_i32(y0)?, to_i32(w)?, to_i32(y0.saturating_add(n))?);
|
||||
let failed = std::sync::atomic::AtomicBool::new(false);
|
||||
surface
|
||||
self.surface
|
||||
.try_write_rows_with_interrupt(rect, ctl, |y, x0, dst| {
|
||||
if !convert.fill(data, w as usize, y - rect.y0, x0, dst) {
|
||||
failed.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
@@ -956,6 +946,76 @@ fn import_png_streamed_with(
|
||||
if failed.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
return Err(IoError::Unsupported("the decoded image does not match its size".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the layer is scanned for tiles of only the default pixel: only a source with alpha
|
||||
/// has any.
|
||||
pub(crate) fn scans(&self) -> bool {
|
||||
self.header.layout.has_alpha()
|
||||
}
|
||||
|
||||
/// Drops the tiles that hold only the default pixel, all at once.
|
||||
pub(crate) fn prune(&mut self) {
|
||||
if self.scans() {
|
||||
self.surface.prune();
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops one bounded batch of those tiles from where `cursor` left off; true when done.
|
||||
pub(crate) fn prune_step(&mut self, cursor: &mut photocraft_raster::PruneCursor) -> bool {
|
||||
!self.scans() || self.surface.prune_batch(cursor, PRUNE_BATCH)
|
||||
}
|
||||
|
||||
/// A cursor for [`PngStream::prune_step`].
|
||||
pub(crate) fn prune_cursor(&self) -> photocraft_raster::PruneCursor {
|
||||
self.surface.prune_cursor()
|
||||
}
|
||||
|
||||
/// The document of the layer, with the profile and metadata the file ended with.
|
||||
pub(crate) fn into_document(self, name: &str, extras: codecs::PngExtras) -> Result<ImportResult, IoError> {
|
||||
let Self { surface, header, .. } = self;
|
||||
let (mode, _, depth, _) = flat_target(header.layout, header.sample);
|
||||
let warnings = extras.warnings.iter().map(ToString::to_string).collect();
|
||||
flat_document(name, (header.width, header.height, header.layout, mode, depth), surface, extras.icc, &extras.meta, warnings, None)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`import_png_streamed`], with the memory the machine can still use given (see
|
||||
/// [`crate::memory::available`]): `None` when it isn't known.
|
||||
fn import_png_streamed_with(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
opts: &crate::ImportOptions,
|
||||
ctl: &Interrupt,
|
||||
min_bytes: u64,
|
||||
available: impl FnOnce() -> Option<u64>,
|
||||
) -> Result<Option<ImportResult>, IoError> {
|
||||
// Rows are worked off 0.02..0.55 so a fallback to the whole-image path, which reports 0.6
|
||||
// after its decode, never takes progress backwards.
|
||||
let state = std::cell::RefCell::new(None::<PngStream>);
|
||||
let mut available = Some(available);
|
||||
let busy = || IoError::Unsupported("the PNG reader re-entered itself".into());
|
||||
let mut begin = |header: &codecs::PngHeader| -> Result<bool, IoError> {
|
||||
// Decoded size, from the header; a size that overflows is certainly large enough.
|
||||
let bytes = u64::from(header.width)
|
||||
.checked_mul(u64::from(header.height))
|
||||
.and_then(|px| px.checked_mul((header.layout.channels() * header.sample.bytes()) as u64));
|
||||
if bytes.is_some_and(|b| b < min_bytes) {
|
||||
return Ok(false);
|
||||
}
|
||||
// A cancelled import is reported as such, not as the memory it would have needed.
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
*state.try_borrow_mut().map_err(|_| busy())? = Some(PngStream::new(header, available.take().and_then(|f| f()))?);
|
||||
ctl.progress(0.02);
|
||||
Ok(true)
|
||||
};
|
||||
let mut rows = |y0: u32, data: &[u8]| -> Result<(), IoError> {
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let mut guard = state.try_borrow_mut().map_err(|_| busy())?;
|
||||
let Some(stream) = guard.as_mut() else { return Err(busy()) };
|
||||
stream.write_rows(y0, data, ctl)?;
|
||||
let (h, n) = (stream.header.height, u32::try_from(data.len() / (stream.header.width as usize * stream.convert.src_px).max(1)).unwrap_or(0));
|
||||
ctl.progress(0.02 + 0.53 * (y0 + n) as f32 / h.max(1) as f32);
|
||||
Ok(())
|
||||
};
|
||||
@@ -970,17 +1030,13 @@ fn import_png_streamed_with(
|
||||
return Ok(None);
|
||||
};
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let Some(Stream { mut surface, header, .. }) = state.into_inner() else { return Ok(None) };
|
||||
let Some(mut stream) = state.into_inner() else { return Ok(None) };
|
||||
if extras.orientation != 1 {
|
||||
return Ok(None);
|
||||
}
|
||||
ctl.progress(0.95);
|
||||
let (mode, _, depth, _) = flat_target(header.layout, header.sample);
|
||||
if header.layout.has_alpha() {
|
||||
surface.prune();
|
||||
}
|
||||
let warnings = extras.warnings.iter().map(ToString::to_string).collect();
|
||||
flat_document(name, (header.width, header.height, header.layout, mode, depth), surface, extras.icc, &extras.meta, warnings, None).map(Some)
|
||||
stream.prune();
|
||||
stream.into_document(name, extras).map(Some)
|
||||
}
|
||||
|
||||
/// The pixels of a decoded image as a surface of the target layout and sample type, converted
|
||||
@@ -2606,6 +2662,18 @@ mod streamed_png_tests {
|
||||
assert!(matches!(r, Err(IoError::Cancelled)), "{:?}", r.map(|_| ()));
|
||||
}
|
||||
|
||||
/// The stream a stepped import builds refuses a layer that won't fit with the error the
|
||||
/// one-shot streamed import gives, and leaves a small one unchecked, as the whole-image path does.
|
||||
#[test]
|
||||
fn a_stream_for_steps_keeps_the_memory_errors() {
|
||||
let big = codecs::PngHeader { width: 20_000, height: 20_000, layout: ChannelLayout::Rgba, sample: CSample::U8 };
|
||||
let e = PngStream::new(&big, Some(1 << 20)).err().expect("refused");
|
||||
assert!(matches!(&e, IoError::Unsupported(m) if m.contains("not enough memory to open this 20000 × 20000 px image")), "{e}");
|
||||
let small = codecs::PngHeader { width: 64, height: 64, layout: ChannelLayout::Rgba, sample: CSample::U8 };
|
||||
assert!(PngStream::for_steps(&small).is_ok(), "a small layer is not checked");
|
||||
assert!(PngStream::new(&small, Some(1 << 20)).is_err(), "though the check itself would refuse it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_large_documents_stream() {
|
||||
let doc = |w, h, depth| Document::new("size", Size::new(w, h), ColorMode::Rgb, depth);
|
||||
|
||||
+103
-10
@@ -1,15 +1,43 @@
|
||||
//! A PNG import in resumable steps, for a caller that must not block for the whole file (the web
|
||||
//! build has no threads): the same document [`crate::import_with_options_and_interrupt`] gives.
|
||||
//!
|
||||
//! A PNG whose rows come in final order is streamed: each decoded group of rows becomes tiles at
|
||||
//! once and is dropped, as [`crate::import_with_options_and_interrupt`] does, so the image never
|
||||
//! exists next to the layer built from it (a 100 MP RGBA8 file would need about 400 MB more, which
|
||||
//! a browser tab does not have). Any other PNG (interlaced, animated, or stored in another
|
||||
//! orientation) is decoded whole, turned upright and copied into tiles, each in bounded steps.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_codecs::{self as codecs, DecodeOptions, Format, Limits, PngDecodeRows, SharedBytes};
|
||||
use photocraft_codecs::{self as codecs, DecodeOptions, Format, Limits, OrientSteps, PngDecodeRows, PngExtras, PngFinish, SharedBytes, begin_png_finish};
|
||||
use photocraft_geom::TILE_SIZE;
|
||||
use photocraft_raster::{Interrupt, PruneCursor};
|
||||
|
||||
use crate::flat::FlatBuilder;
|
||||
use crate::flat::{FlatBuilder, PngStream, apply_flat_format};
|
||||
use crate::{ImportResult, IoError, Route};
|
||||
|
||||
/// The rows of a file being streamed into the tiles of its layer.
|
||||
struct Streaming {
|
||||
rows: PngDecodeRows<SharedBytes>,
|
||||
stream: PngStream,
|
||||
}
|
||||
|
||||
/// A streamed layer being scanned for tiles that hold only the default pixel.
|
||||
struct Pruning {
|
||||
stream: PngStream,
|
||||
cursor: PruneCursor,
|
||||
extras: PngExtras,
|
||||
}
|
||||
|
||||
enum Stage {
|
||||
/// The rows becoming tiles as they are decoded.
|
||||
Stream(Box<Streaming>),
|
||||
/// The streamed layer's prune scan.
|
||||
Prune(Box<Pruning>),
|
||||
/// The whole image, decoded a row at a time: a file whose rows can't be streamed.
|
||||
Rows(Box<PngDecodeRows<SharedBytes>>),
|
||||
/// The decoded image turned upright (an EXIF orientation 2-8), a band of rows at a time.
|
||||
Orient(Box<OrientSteps>),
|
||||
/// The decoded image becoming the document, a band of rows and a batch of tiles at a time.
|
||||
Build(Box<FlatBuilder>),
|
||||
Spent,
|
||||
@@ -30,34 +58,99 @@ impl PngImport {
|
||||
if crate::route(name, bytes) != Route::Flat || codecs::detect(bytes) != Some(Format::Png) {
|
||||
return Ok(None);
|
||||
}
|
||||
let rows = PngDecodeRows::new(SharedBytes(Arc::clone(bytes)), &Limits::default())?;
|
||||
Ok(Some(Self { name: name.to_string(), bytes: Arc::clone(bytes), stage: Stage::Rows(Box::new(rows)) }))
|
||||
let rows = PngDecodeRows::new_streaming(SharedBytes(Arc::clone(bytes)), &Limits::default())?;
|
||||
let stage = if rows.streamable() {
|
||||
let stream = PngStream::for_steps(&rows.header())?;
|
||||
Stage::Stream(Box::new(Streaming { rows, stream }))
|
||||
} else {
|
||||
Stage::Rows(Box::new(Self::buffered(rows)?))
|
||||
};
|
||||
Ok(Some(Self { name: name.to_string(), bytes: Arc::clone(bytes), stage }))
|
||||
}
|
||||
|
||||
/// A decoder that holds the whole image: its output is reserved up front.
|
||||
fn buffered(mut rows: PngDecodeRows<SharedBytes>) -> Result<PngDecodeRows<SharedBytes>, IoError> {
|
||||
rows.reserve_output()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Whether the rows are streamed into the layer's tiles as they are decoded, so the decoded
|
||||
/// image never exists whole. False for a file whose rows can't come in final order, and from
|
||||
/// the moment a late `eXIf` sends a streamed one back to a whole decode.
|
||||
pub fn streams(&self) -> bool {
|
||||
matches!(self.stage, Stage::Stream(_) | Stage::Prune(_))
|
||||
}
|
||||
|
||||
/// How much of the import is done, `0.0..=1.0`.
|
||||
pub fn progress(&self) -> f32 {
|
||||
match &self.stage {
|
||||
Stage::Stream(s) => s.rows.progress(),
|
||||
Stage::Rows(rows) => rows.progress(),
|
||||
Stage::Build(_) | Stage::Spent => 1.0,
|
||||
Stage::Orient(steps) => steps.progress(),
|
||||
Stage::Prune(_) | Stage::Build(_) | Stage::Spent => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Works while `more()` returns true (at least one bounded piece per call): rows, then the
|
||||
/// image's rows into the document's tiles, then the prune scan. `Some` once the document is
|
||||
/// built, after which the import is spent.
|
||||
/// Works while `more()` returns true (at least one bounded piece per call): rows (into tiles
|
||||
/// as they come, or into the whole image), the turn upright, the copy into tiles, then the
|
||||
/// prune scan. `Some` once the document is built, after which the import is spent.
|
||||
pub fn step(&mut self, more: &mut dyn FnMut() -> bool) -> Result<Option<ImportResult>, IoError> {
|
||||
match std::mem::replace(&mut self.stage, Stage::Spent) {
|
||||
Stage::Stream(mut s) => {
|
||||
let result = {
|
||||
let Streaming { rows, stream } = &mut *s;
|
||||
let mut sink = |y0: u32, data: &[u8]| stream.write_rows(y0, data, &Interrupt::NONE);
|
||||
rows.step_stream::<IoError>(TILE_SIZE as u32, more, &mut sink)?
|
||||
};
|
||||
self.stage = match result {
|
||||
None => Stage::Stream(s),
|
||||
// An `eXIf` after the image data turns the image: decode it whole instead, as
|
||||
// the one-shot import does, with the streamed layer released first.
|
||||
Some(extras) if extras.orientation != 1 => {
|
||||
drop(s);
|
||||
let rows = PngDecodeRows::new_streaming(SharedBytes(Arc::clone(&self.bytes)), &Limits::default())?;
|
||||
Stage::Rows(Box::new(Self::buffered(rows)?))
|
||||
}
|
||||
Some(extras) => {
|
||||
let stream = s.stream;
|
||||
let cursor = stream.prune_cursor();
|
||||
Stage::Prune(Box::new(Pruning { stream, cursor, extras }))
|
||||
}
|
||||
};
|
||||
Ok(None)
|
||||
}
|
||||
Stage::Prune(mut p) => loop {
|
||||
if p.stream.prune_step(&mut p.cursor) {
|
||||
let Pruning { stream, extras, .. } = *p;
|
||||
let mut r = stream.into_document(&self.name, extras)?;
|
||||
apply_flat_format(&mut r, &self.bytes, Some(Format::Png), None)?;
|
||||
return Ok(Some(r));
|
||||
}
|
||||
if !more() {
|
||||
self.stage = Stage::Prune(p);
|
||||
return Ok(None);
|
||||
}
|
||||
},
|
||||
Stage::Rows(mut rows) => {
|
||||
self.stage = match rows.step(more)? {
|
||||
Some(img) => {
|
||||
// The resolution, upright orientation and final limit checks `decode` does.
|
||||
let img = codecs::finish_png_decode(img, &DecodeOptions::default())?;
|
||||
Stage::Build(Box::new(FlatBuilder::new(&self.name, img)?))
|
||||
match begin_png_finish(img, &DecodeOptions::default())? {
|
||||
PngFinish::Done(img) => Stage::Build(Box::new(FlatBuilder::new(&self.name, *img)?)),
|
||||
PngFinish::Orient(steps) => Stage::Orient(steps),
|
||||
}
|
||||
}
|
||||
None => Stage::Rows(rows),
|
||||
};
|
||||
Ok(None)
|
||||
}
|
||||
Stage::Orient(mut steps) => {
|
||||
self.stage = match steps.step(more)? {
|
||||
Some(img) => Stage::Build(Box::new(FlatBuilder::new(&self.name, img)?)),
|
||||
None => Stage::Orient(steps),
|
||||
};
|
||||
Ok(None)
|
||||
}
|
||||
Stage::Build(mut build) => loop {
|
||||
if !build.copy_done() {
|
||||
build.copy_step()?;
|
||||
|
||||
@@ -87,9 +87,9 @@ fn stepped_png_import_keeps_a_palette_as_indexed_colour() {
|
||||
fn stepped_png_import_takes_a_step_per_row_and_bounded_steps_to_build_the_document() {
|
||||
let bytes = encode(&noise(8, 20, ChannelLayout::Rgba, SampleType::U8), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let (_, calls) = stepped("a.png", &bytes, 1);
|
||||
// 19 calls that each decode a row, one that decodes the last and finishes the file, one that
|
||||
// copies its rows into the surface, one that prunes it, and one that builds the document.
|
||||
assert_eq!(calls, 23);
|
||||
// 19 calls that each decode a row (its rows become tiles as they come), one that decodes the
|
||||
// last row and reads to the end of the file, then the prune scan of the tiles and the document.
|
||||
assert_eq!(calls, 21);
|
||||
let arc = Arc::new(bytes);
|
||||
let mut import = PngImport::new("a.png", &arc).unwrap().unwrap();
|
||||
assert_eq!(import.progress(), 0.0);
|
||||
@@ -203,3 +203,108 @@ fn a_damaged_png_fails_in_steps_as_it_does_whole() {
|
||||
assert!(whole.is_err() && stepped.is_err(), "cut at {}", cut.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// An `eXIf` chunk (little-endian) holding only the orientation `o`.
|
||||
fn exif_chunk(o: u16) -> Vec<u8> {
|
||||
let mut t = b"II*\0".to_vec();
|
||||
t.extend_from_slice(&8u32.to_le_bytes());
|
||||
t.extend_from_slice(&1u16.to_le_bytes());
|
||||
for v in [0x0112u16, 3] {
|
||||
t.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
t.extend_from_slice(&1u32.to_le_bytes());
|
||||
t.extend_from_slice(&o.to_le_bytes());
|
||||
t.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
|
||||
png_chunk(b"eXIf", &t)
|
||||
}
|
||||
|
||||
/// `png` with `chunk` just before its image data.
|
||||
fn with_chunk_before_idat(png: &[u8], chunk: &[u8]) -> Vec<u8> {
|
||||
let at = png.windows(4).position(|w| w == b"IDAT").unwrap() - 4;
|
||||
let mut out = png[..at].to_vec();
|
||||
out.extend_from_slice(chunk);
|
||||
out.extend_from_slice(&png[at..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Drives `bytes` to the end a row at a time; true if the import streamed at the start.
|
||||
fn streams_at_start(bytes: &[u8]) -> bool {
|
||||
let bytes = Arc::new(bytes.to_vec());
|
||||
PngImport::new("a.png", &bytes).unwrap().unwrap().streams()
|
||||
}
|
||||
|
||||
/// A plain PNG streams its rows into the layer; a file that can't (interlaced, or stored in
|
||||
/// another orientation) is decoded whole.
|
||||
#[test]
|
||||
fn a_plain_png_streams_and_other_files_are_decoded_whole() {
|
||||
let img = noise(40, 30, ChannelLayout::Rgb, SampleType::U8);
|
||||
let plain = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert!(streams_at_start(&plain));
|
||||
let interlaced = encode(&img, Format::Png, &EncodeOptions { png_interlaced: true, ..Default::default() }).unwrap();
|
||||
assert!(!streams_at_start(&interlaced));
|
||||
assert!(!streams_at_start(&with_chunk_before_idat(&plain, &exif_chunk(6))));
|
||||
// An upright eXIf streams; one after the image data is only seen at the end.
|
||||
assert!(streams_at_start(&with_chunk_before_idat(&plain, &exif_chunk(1))));
|
||||
assert!(streams_at_start(&with_chunks_before_iend(&plain, &[exif_chunk(6)])));
|
||||
}
|
||||
|
||||
/// A file with an orientation turns upright in bands and gives the document the one-shot import
|
||||
/// gives, whether the `eXIf` comes before the image data (decoded whole from the start) or after
|
||||
/// it (streamed, then decoded whole), for every orientation, and a tall file takes many calls.
|
||||
#[test]
|
||||
fn an_oriented_png_is_turned_upright_in_steps_like_import() {
|
||||
for (layout, sample) in [(ChannelLayout::Gray, SampleType::U8), (ChannelLayout::Rgba, SampleType::U16)] {
|
||||
let mut img = noise(70, 150, layout, sample);
|
||||
img.meta.dpi = Some((120.0, 120.0));
|
||||
img.icc = Some(vec![7; 40]);
|
||||
let base = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
for o in 2..=8u16 {
|
||||
for late in [false, true] {
|
||||
let bytes = if late { with_chunks_before_iend(&base, &[exif_chunk(o)]) } else { with_chunk_before_idat(&base, &exif_chunk(o)) };
|
||||
let what = format!("{layout:?} {sample:?} orientation {o}, eXIf {}", if late { "after" } else { "before" });
|
||||
let expected = whole("o.png", &bytes);
|
||||
assert_eq!(expected.document.size.width, if o >= 5 { 150 } else { 70 }, "{what}: upright");
|
||||
let (got, calls) = stepped_zero_budget("o.png", &bytes);
|
||||
assert_same(&got.document, &expected.document, &what);
|
||||
assert_eq!(got.warnings, expected.warnings, "{what}");
|
||||
// 150 rows decoded one call each, the turn in bands of 64 output rows, the copy.
|
||||
assert!(calls > 150 + 2, "{what}: {calls} calls");
|
||||
assert_stepped_equals_import("o.png", &bytes, &what);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A late `eXIf` sends a streamed import back to a whole decode, and the import says so.
|
||||
#[test]
|
||||
fn a_late_exif_ends_the_streaming() {
|
||||
let base = encode(&noise(20, 20, ChannelLayout::Rgb, SampleType::U8), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let bytes = Arc::new(with_chunks_before_iend(&base, &[exif_chunk(3)]));
|
||||
let mut import = PngImport::new("a.png", &bytes).unwrap().unwrap();
|
||||
assert!(import.streams());
|
||||
while import.streams() {
|
||||
assert!(import.step(&mut || false).unwrap().is_none());
|
||||
}
|
||||
// From here the whole image is decoded.
|
||||
assert!(import.step(&mut || false).unwrap().is_none());
|
||||
assert!(!import.streams());
|
||||
}
|
||||
|
||||
/// A streamed import with an ICC profile, text and a resolution is the one-shot import, at every
|
||||
/// depth and layout, 16-bit included.
|
||||
#[test]
|
||||
fn a_streamed_png_with_a_profile_and_text_equals_import() {
|
||||
for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba] {
|
||||
for sample in [SampleType::U8, SampleType::U16] {
|
||||
let mut img = noise(300, 270, layout, sample);
|
||||
img.icc = Some(vec![9; 60]);
|
||||
img.meta.dpi = Some((200.0, 200.0));
|
||||
img.meta.text.push(("Title".into(), "streamed".into()));
|
||||
let bytes = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert!(streams_at_start(&bytes));
|
||||
assert_stepped_equals_import("s.png", &bytes, &format!("{layout:?} {sample:?} with a profile"));
|
||||
let (got, _) = stepped("s.png", &bytes, 0);
|
||||
assert_eq!(got.document.icc_profile.as_deref().map(Vec::as_slice), Some(&[9u8; 60][..]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -510,6 +510,8 @@ impl PhotocraftApp {
|
||||
self.place_bytes_with(name, bytes, linked, &serde_json::json!({}))
|
||||
}
|
||||
|
||||
/// [`PhotocraftApp::place_bytes`] with the command's `params` (a frame to fill): a job where
|
||||
/// places run in the background, else synchronously.
|
||||
fn place_bytes_with(&mut self, name: &str, bytes: Vec<u8>, linked: Option<String>, params: &serde_json::Value) -> Result<serde_json::Value, String> {
|
||||
let r = if crate::jobs_ui::place_in_background(self) {
|
||||
crate::jobs_ui::start_place_bytes(self, name, bytes, linked, params)
|
||||
|
||||
+11
-5
@@ -635,11 +635,17 @@ except Place, which is a job that `poll_jobs` steps on the UI thread (a *coopera
|
||||
without depending on the machine). Elsewhere the same work runs to the end on a worker thread,
|
||||
or inline under `execute`, and gives the same result.
|
||||
- `file_cmds::PlaceSteps` cuts a place into units: a plain PNG decodes a row at a time
|
||||
(`photocraft_codecs::PngRows`, through `photocraft_io::PngImport`; an interlaced PNG and any other
|
||||
format decode in one unit), the flatten runs in bands of four tiles
|
||||
(`composite_to_surface`, the tiles moved into the result), the resize in bands of 64 output rows
|
||||
(`photocraft_algo::resample::ResizeSteps`, the code `resize_surface` runs). Without a cooperative
|
||||
session each stage is one unit and a desktop keeps its parallel flatten and resize.
|
||||
(`photocraft_codecs::PngDecodeRows`, through `photocraft_io::PngImport`) and, when its rows come
|
||||
in final order, each group of 256 rows becomes tiles at once and is dropped, as the one-shot import
|
||||
does, so the decoded image never exists beside the layer (a 100 MP RGBA8 file would cost about 400 MB
|
||||
more, too much for a browser tab). An interlaced, animated or oriented PNG is decoded whole, turned
|
||||
upright in bands of 64 rows (`photocraft_codecs::OrientSteps`) and copied into tiles in bands; any
|
||||
other format decodes in one unit. The flatten runs in bands of four tiles (`composite_to_surface`,
|
||||
the tiles moved into the result), the resize in bands of 64 output rows
|
||||
(`photocraft_algo::resample::ResizeSteps`, the code `resize_surface` runs), and moving the pixels to
|
||||
where they land a tile at a time (`photocraft_raster::TranslateSteps`, the code
|
||||
`Surface::translated` runs). Without a cooperative session each stage is one unit and a desktop
|
||||
keeps its parallel flatten, resize and translate.
|
||||
- The UI places through a job when `background_jobs || session.cooperative_jobs()`
|
||||
(`jobs_ui::place_in_background`); `background_jobs` stays off on the web, since save, print and
|
||||
the other commands gated on it need threads. The status bar shows the progress and Esc cancels.
|
||||
|
||||
Reference in new issue
Block a user