diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs index a5dd8e8f1b9..614c0ef20e3 100644 --- a/crates/engine/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -1,5 +1,5 @@ use super::filters::smart; -use super::source::{SourceImage, cache_get, cache_key, cache_put, source_bytes, source_image, source_surface, svg_source_image, vector_scale}; +use super::source::{SourceImage, cache_get, cache_key, cache_put, source_bytes, source_image, source_surface_from_buffer, svg_source_image, vector_scale}; use super::{ Affine, Arc, BlendMode, Document, EngineError, Homography, JobCtx, Layer, LayerContent, LayerId, PixelFormat, Rect, Result, SmartFilter, SmartObject, SmartSource, Stage, StageKey, Surface, Value, decode_source, other, stack_cache, @@ -47,7 +47,7 @@ pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photoc photocraft_doc::StackMode::Variance => Stat::Variance, }; let buf = photocraft_compose::Buffer { rect: bounds, px: photocraft_algo::stack::combine(&frames, stat) }; - let img = SourceImage { surface: Arc::new(source_surface(&doc, &buf, fmt)?), bounds }; + let img = SourceImage { surface: Arc::new(source_surface_from_buffer(&doc, &buf, fmt)?), bounds }; cache_put(key, img.clone()); Ok(img) } diff --git a/crates/engine/src/cmd/smart_cmds/source.rs b/crates/engine/src/cmd/smart_cmds/source.rs index d7d895b28d7..0c67be84beb 100644 --- a/crates/engine/src/cmd/smart_cmds/source.rs +++ b/crates/engine/src/cmd/smart_cmds/source.rs @@ -155,15 +155,60 @@ pub(super) fn buffer_to_surface(buf: &photocraft_compose::Buffer, fmt: PixelForm s } -pub(super) fn source_surface(src: &Document, buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Result { +/// A source's pixels in `fmt` from a flattened `buf` (the stack-mode combine, which has no +/// document to composite). +pub(super) fn source_surface_from_buffer(src: &Document, buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Result { + let raster = |f| buffer_to_surface(buf, f); + convert_source(src, fmt, raster) +} + +/// `src` composited straight into `fmt` in strips, without the full-size RGBA buffer +/// [`photocraft_compose::flatten`] allocates (16 bytes a pixel on top of the surface). +pub(super) fn flattened_source(src: &Document, fmt: PixelFormat) -> Result { + let b = src.bounds(); + if u64::from(b.width()) * u64::from(b.height()) > photocraft_compose::MAX_RENDER_PIXELS { + return Err(other(format!("the smart object's {}×{} contents are too large to render", b.width(), b.height()))); + } + // The banded compositor composites CMYK in inks and Lab in L, a and b: not the same pixels as + // the RGBA buffer, so those modes keep the buffer path. + let native = |m| matches!(m, ColorMode::Cmyk | ColorMode::Lab); + if native(src.mode) || native(fmt.mode) { + return source_surface_from_buffer(src, &photocraft_compose::flatten(src), fmt); + } + convert_source(src, fmt, |f| composite_in_strips(src, f)) +} + +/// Pixels per strip of [`composite_in_strips`]: the compositor's own bands are 8 Mpx, which for +/// most sources is the whole image again (a band and its f32 conversion are 32 bytes a pixel). +const STRIP_PIXELS: u64 = 1 << 20; + +/// [`photocraft_compose::flatten_to_surface`] of `src`, composited a strip of rows at a time +/// so the float composite and its conversion never cover more than [`STRIP_PIXELS`]. +fn composite_in_strips(src: &Document, fmt: PixelFormat) -> Surface { + let b = src.bounds(); + let rows = photocraft_compose::band_rows_for(b.width(), i32::try_from(STRIP_PIXELS / u64::from(b.width().max(1))).unwrap_or(i32::MAX)); + let mut out = Surface::new(fmt); + let mut y = b.y0; + while y < b.y1 { + let strip = Rect::new(b.x0, y, b.x1, y.saturating_add(rows).min(b.y1)); + out.write_region(strip, &photocraft_compose::composite_to_surface(src, strip, fmt, None).read_region(strip)); + y = strip.y1; + } + out.prune(); + out +} + +/// Runs the gray and 32-bit conversions a source needs to reach `fmt`; `raster` yields the +/// source's composite at a pixel format. +fn convert_source(src: &Document, fmt: PixelFormat, raster: impl FnOnce(PixelFormat) -> Surface) -> Result { let gray = fmt.mode == ColorMode::Grayscale && src.pixel_format().mode != ColorMode::Grayscale; let linear = fmt.sample == SampleType::F32 && src.depth != SampleType::F32; if !gray && !linear { - return Ok(buffer_to_surface(buf, fmt)); + return Ok(raster(fmt)); } let mut doc = Document::new(src.name.clone(), src.size, src.mode, src.depth); doc.icc_profile = src.icc_profile.clone(); - doc.layers = vec![Layer::new("source", LayerContent::Raster(buffer_to_surface(buf, src.pixel_format())))]; + doc.layers = vec![Layer::new("source", LayerContent::Raster(raster(src.pixel_format())))]; if gray { let gray_profile = crate::color_cmds::working_profile(ColorMode::Grayscale); crate::color_cmds::convert_document(&mut doc, &gray_profile, photocraft_cms::Intent::RelativeColorimetric, true)?; @@ -213,8 +258,7 @@ pub fn source_image(file_name: &str, bytes: &[u8], fmt: PixelFormat) -> Result Document { + let mut doc = Document::new("source", Size::new(W as u32, H as u32), mode, depth); + doc.layers = vec![Layer::new("block", LayerContent::Raster(block(&doc.pixel_format(), Rect::new(4, 3, 50, 40))))]; + doc +} + +fn block(fmt: &PixelFormat, r: Rect) -> Surface { + let mut s = Surface::new(*fmt); + let mut data = Vec::new(); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let v = ((x * 7 + y * 13) % 23) as f32 / 22.0; + let a = if (x + y) % 5 == 0 { 0.5 } else { 1.0 }; + data.extend(photocraft_raster::from_rgba(fmt, [v, 1.0 - v, ((x * y) % 7) as f32 / 6.0, a])); + } + } + s.write_region(r, &data); + s +} + +/// Everything the smart object cache would hold, bit for bit. +fn pixels(s: &Surface, bounds: Rect) -> Vec { + s.read_region(bounds).iter().map(|v| v.to_bits()).collect() +} + +/// The composite through the full-size RGBA buffer, the way sources were rendered before. +fn through_buffer(doc: &Document, fmt: PixelFormat) -> Surface { + source_surface_from_buffer(doc, &photocraft_compose::flatten(doc), fmt).unwrap() +} + +fn same(label: &str, doc: &Document, fmt: PixelFormat) { + let (old, new) = (through_buffer(doc, fmt), flattened_source(doc, fmt).unwrap()); + assert_eq!(new.format(), old.format(), "{label}: format"); + assert!(pixels(&old, doc.bounds()) == pixels(&new, doc.bounds()), "{label}: pixels differ"); +} + +#[test] +fn rgb_sources_match_at_every_depth() { + for depth in SampleType::ALL { + let doc = source(ColorMode::Rgb, depth); + same(&format!("rgb {depth:?}"), &doc, doc.pixel_format()); + } +} + +#[test] +fn a_gray_source_in_an_rgb_document_and_back_matches() { + let gray = source(ColorMode::Grayscale, SampleType::U8); + same("gray into rgb", &gray, PixelFormat { mode: ColorMode::Rgb, sample: SampleType::U8, alpha: true }); + let rgb = source(ColorMode::Rgb, SampleType::U8); + same("rgb into gray", &rgb, PixelFormat { mode: ColorMode::Grayscale, sample: SampleType::U8, alpha: true }); +} + +#[test] +fn an_8_bit_source_in_a_32_bit_document_matches() { + let doc = source(ColorMode::Rgb, SampleType::U8); + same("8 into 32", &doc, PixelFormat { mode: ColorMode::Rgb, sample: SampleType::F32, alpha: true }); +} + +/// The banded compositor composites CMYK in inks and Lab in L, a and b, and lands up to 16 and 1 +/// steps (8-bit) off the RGBA buffer on visible pixels, so these sources keep the buffer path. +#[test] +fn a_cmyk_source_matches() { + let doc = source(ColorMode::Cmyk, SampleType::U8); + same("cmyk", &doc, doc.pixel_format()); +} + +#[test] +fn a_lab_source_matches() { + let doc = source(ColorMode::Lab, SampleType::U8); + same("lab", &doc, doc.pixel_format()); +} + +#[test] +fn a_layered_source_with_a_mask_blend_mode_and_effect_matches() { + for depth in [SampleType::U8, SampleType::F32] { + let mut doc = source(ColorMode::Rgb, depth); + let fmt = doc.pixel_format(); + let mut top = Layer::new("top", LayerContent::Raster(block(&fmt, Rect::new(20, 10, 60, 46)))); + top.blend = BlendMode::Multiply; + top.opacity = 0.7; + let mut mask = LayerMask::reveal_all(); + mask.surface.fill_rect(Rect::new(30, 0, 64, 48), &[0.25]); + top.mask = Some(mask); + doc.layers.push(top); + let mut shadowed = Layer::new("shadowed", LayerContent::Raster(block(&fmt, Rect::new(8, 20, 24, 36)))); + shadowed.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + shadowed.effects.enabled = true; + doc.layers.push(shadowed); + same(&format!("layered {depth:?}"), &doc, fmt); + } +} + +#[test] +fn a_source_past_the_render_limit_is_refused_not_emptied() { + let doc = Document::new("huge", Size::new(60_000, 60_000), ColorMode::Rgb, SampleType::U8); + assert!(flattened_source(&doc, doc.pixel_format()).is_err()); +} + +#[test] +fn an_rgb_source_in_a_cmyk_or_lab_document_matches() { + let doc = source(ColorMode::Rgb, SampleType::U8); + for mode in [ColorMode::Cmyk, ColorMode::Lab] { + same(&format!("rgb into {mode:?}"), &doc, PixelFormat { mode, sample: SampleType::U8, alpha: true }); + } +} diff --git a/crates/engine/tests/smart_source_peak.rs b/crates/engine/tests/smart_source_peak.rs new file mode 100644 index 00000000000..5cd957c2e37 --- /dev/null +++ b/crates/engine/tests/smart_source_peak.rs @@ -0,0 +1,50 @@ +//! #10030: decoding a smart object's source (what its first re-render does) composites it in +//! strips, so the peak memory growth stays a small multiple of the source's pixels, not the 32 +//! bytes a pixel the full-size RGBA buffer and its f32 copy took on top of the decoded document. +//! +//! The one test here runs in its own process: it reads the process's peak RSS (`VmHWM`, Linux +//! only) and nothing else may allocate meanwhile. + +#![cfg(target_os = "linux")] + +use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; +use photocraft_engine::{Session, smart_cmds}; +use serde_json::json; + +fn peak_rss_bytes() -> Option { + let status = std::fs::read_to_string("/proc/self/status").ok()?; + let line = status.lines().find(|l| l.starts_with("VmHWM:"))?; + let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; + Some(kib * 1024) +} + +const SIDE: u32 = 4096; + +fn png() -> Vec { + let px = (0..SIDE * SIDE).flat_map(|i| { + let (x, y) = (i % SIDE, i / SIDE); + [(x * 5 + y) as u8, ((y * 7) ^ x) as u8, ((x * y) % 251) as u8, 255 - ((x / 64 + y / 64) % 4 * 40) as u8] + }); + let img = Image::from_raw(SIDE, SIDE, ChannelLayout::Rgba, SampleType::U8, px.collect()).unwrap(); + photocraft_codecs::encode(&img, Format::Png, &EncodeOptions::default()).unwrap() +} + +#[test] +fn decoding_a_smart_object_source_stays_within_16_bytes_a_source_pixel() { + let bytes = png(); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let fmt = s.active().unwrap().doc.pixel_format(); + // Writing 5 resets the peak RSS to the current RSS; skip where the kernel doesn't allow it. + if std::fs::write("/proc/self/clear_refs", "5").is_err() { + return; + } + let Some(before) = peak_rss_bytes() else { return }; + let img = smart_cmds::source_image("big.png", &bytes, fmt).unwrap(); + let grown = peak_rss_bytes().unwrap().saturating_sub(before); + assert_eq!(img.bounds.width(), SIDE); + + let limit = 16 * u64::from(SIDE) * u64::from(SIDE); + eprintln!("peak RSS growth {} MiB for {} px ({:.1} B/px)", grown >> 20, SIDE * SIDE, grown as f64 / f64::from(SIDE * SIDE)); + assert!(grown < limit, "peak RSS grew by {grown} bytes, over {limit} (16 B/px)"); +}