合入小壹 P2-G 首开画布与整屏读取提速

This commit is contained in:
WuYongJie 2026-11-28 01:14:55 +08:00
commit 32ebdab2ad
10 changed files with 282 additions and 22 deletions

View File

@ -2606,7 +2606,19 @@ pub(super) fn save_delivery_artifacts(dir: &Path, active: &Document, export_dir:
Ok(count)
}
pub(super) fn read_production_screen(native: &Document, input: &Value) -> R<Value> {
#[path = "jiansun_screen_preview.rs"]
mod screen_preview;
pub(super) use screen_preview::ScreenReader;
#[cfg(test)]
fn read_production_screen(native: &Document, input: &Value) -> R<Value> {
read_production_screen_with(native, input, |area| screen_preview::render(native, area).map(std::sync::Arc::new))
}
fn read_production_screen_with(
native: &Document, input: &Value,
preview: impl FnOnce(photocraft_geom::Rect) -> R<std::sync::Arc<Vec<u8>>>,
) -> R<Value> {
use base64::{Engine as _, engine::general_purpose::STANDARD};
use photocraft_geom::Rect;
let meta = mapping(native).ok_or("工作画布缺少模板映射")?;
@ -2620,28 +2632,18 @@ pub(super) fn read_production_screen(native: &Document, input: &Value) -> R<Valu
return Err("导出范围超出画布".into());
}
let area = Rect::from_xywh(0, top as i32, width as u32, height as u32);
let scale = (1536.0 / f64::from(area.width().max(area.height()))).min(1.0);
let [w, h] = [area.width(), area.height()].map(|size| (f64::from(size) * scale).round().max(1.0) as u32);
let rendered = photocraft_compose::render_reduced_rect(native, area, w, h);
let rgb = rendered.px.into_iter().flat_map(|[r, g, b, alpha]| {
[r, g, b].map(|value| ((value * alpha + 1.0 - alpha).clamp(0.0, 1.0) * 255.0 + 0.5) as u8)
}).collect();
let preview = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, rgb)
.map_err(|_| "实际画面无法读取")?;
let options = photocraft_codecs::EncodeOptions { jpeg_quality: 85, ..Default::default() };
let jpeg = photocraft_codecs::encode(&preview, photocraft_codecs::Format::Jpeg, &options)
.map_err(|error| format!("实际画面无法编码:{error}"))?;
let jpeg = preview(area)?;
let fields: Vec<_> = page["mapping"]["fields"].as_array().into_iter().flatten()
.filter_map(|field| field["fieldId"].as_str()).collect();
let mut receipt = json!({"page":index,"totalPages":pages.len(),"revision":input["revision"],"fields":fields,
"screenStamp":format!("{:x}", Sha256::digest(&jpeg)),"overlayLayers":screen_overlay_layers(native, &meta, area, None)});
"screenStamp":format!("{:x}", Sha256::digest(jpeg.as_slice())),"overlayLayers":screen_overlay_layers(native, &meta, area, None)});
if input["preflight"] == true && fields.is_empty() {
let pixels = photocraft_codecs::decode(&jpeg).map_err(|_| "实际画面无法读取")?
.convert(photocraft_codecs::ChannelLayout::Gray, photocraft_codecs::SampleType::U8);
receipt["blank"] = json!(pixels.data().iter().all(|pixel| *pixel >= 250));
}
if input["signatureOnly"] != true {
receipt["images"] = json!([{"type":"image","data":STANDARD.encode(&jpeg),"mimeType":"image/jpeg"}]);
receipt["images"] = json!([{"type":"image","data":STANDARD.encode(jpeg.as_slice()),"mimeType":"image/jpeg"}]);
}
Ok(receipt)
}
@ -3985,6 +3987,10 @@ impl Backend {
#[path = "jiansun_fidelity_tests.rs"]
mod fidelity_tests;
#[cfg(test)]
#[path = "jiansun_screen_tests.rs"]
mod screen_tests;
#[cfg(test)]
mod tests {
use super::*;

View File

@ -695,6 +695,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
let mut workflow_children = WorkflowChildren::default();
let mut detail_image_reads = None;
let mut canvas_screen_reads = None;
let screen_reader = Arc::new(super::canvas_workspace::ScreenReader::default());
let mut late_workflow_replies = Vec::new();
let start_workflow = |children: &mut WorkflowChildren, delegation: &Value, run: Option<&str>| {
if b.exiting() { return Err("客户端正在退出,未派发工作流".into()); }
@ -822,8 +823,9 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
let transport = daemon.clone();
let run = daemon_run.clone();
let id = value["id"].clone();
let reader = screen_reader.clone();
queue_canvas_screen(pool, cancellation,
move || super::canvas_workspace::read_production_screen(&document, &v),
move || reader.read(&document, &v),
move |reply| { let _ = transport.reply(&run, &id, &reply); })
} else { Err("缺少实际工作画布") };
if let Err(error) = queued {

View File

@ -0,0 +1,49 @@
use photocraft_doc::Document;
use photocraft_geom::Rect;
use serde_json::Value;
use std::sync::{Arc, Mutex, Weak};
use super::{R, read_production_screen_with};
struct Preview {
document: Weak<Document>,
area: Rect,
text_gamma: u32,
jpeg: Arc<Vec<u8>>,
}
/// Reuse the last screen image during a Pi run, keyed by the immutable canvas snapshot.
#[derive(Default)]
pub(in crate::jiansun_backend) struct ScreenReader(Mutex<Option<Preview>>);
impl ScreenReader {
pub(in crate::jiansun_backend) fn read(&self, native: &Arc<Document>, input: &Value) -> R<Value> {
read_production_screen_with(native, input, |area| {
let document = Arc::downgrade(native);
let text_gamma = photocraft_compose::psblend::text_gamma().to_bits();
{
let last = self.0.lock().map_err(|_| "整屏读取缓存状态失效")?;
if let Some(last) = last.as_ref().filter(|last| last.area == area && last.text_gamma == text_gamma && last.document.ptr_eq(&document)) {
return Ok(last.jpeg.clone());
}
}
let jpeg = Arc::new(render(native, area)?);
*self.0.lock().map_err(|_| "整屏读取缓存状态失效")? = Some(Preview { document, area, text_gamma, jpeg: jpeg.clone() });
Ok(jpeg)
})
}
}
pub(super) fn render(native: &Document, area: Rect) -> R<Vec<u8>> {
let scale = (1536.0 / f64::from(area.width().max(area.height()))).min(1.0);
let [w, h] = [area.width(), area.height()].map(|size| (f64::from(size) * scale).round().max(1.0) as u32);
let rendered = photocraft_compose::render_reduced_rect(native, area, w, h);
let rgb = rendered
.px
.into_iter()
.flat_map(|[r, g, b, alpha]| [r, g, b].map(|value| ((value * alpha + 1.0 - alpha).clamp(0.0, 1.0) * 255.0 + 0.5) as u8))
.collect();
let preview = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, rgb).map_err(|_| "实际画面无法读取")?;
let options = photocraft_codecs::EncodeOptions { jpeg_quality: 85, ..Default::default() };
photocraft_codecs::encode(&preview, photocraft_codecs::Format::Jpeg, &options).map_err(|error| format!("实际画面无法编码:{error}"))
}

View File

@ -0,0 +1,68 @@
use super::*;
use std::sync::Arc;
use std::time::Instant;
#[test]
fn jiansun_screen_read_reuses_exact_pixels_until_canvas_or_region_changes() {
let mut doc = Document::new("screen", photocraft_geom::Size::new(32, 48), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);
doc.metadata.text.push((
MAPPING.to_owned(),
json!({
"canvasFirst": true,
"outputs": [
{"mapping":{"fields":[]},"top":0,"width":32,"height":24},
{"mapping":{"fields":[]},"top":24,"width":32,"height":24}
]
})
.to_string(),
));
let mut bottom = photocraft_doc::Layer::raster("blue", photocraft_color::PixelFormat::RGBA8);
bottom.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::from_xywh(0, 24, 32, 24), &[0.0, 0.5, 1.0, 1.0]);
doc.layers.push(bottom);
let doc = Arc::new(doc);
let reader = ScreenReader::default();
for (revision, page) in [0, 0, 1, 1, 0].into_iter().enumerate() {
let args = json!({"page":page,"revision":revision});
assert_eq!(reader.read(&doc, &args).unwrap(), read_production_screen(&doc, &args).unwrap());
}
let mut edited = (*doc).clone();
let mut top = photocraft_doc::Layer::raster("red", photocraft_color::PixelFormat::RGBA8);
top.surface_mut().unwrap().fill_rect(edited.bounds(), &[0.5, 0.0, 0.0, 1.0]);
edited.layers.push(top);
let edited = Arc::new(edited);
let args = json!({"page":0,"revision":7});
let next = reader.read(&edited, &args).unwrap();
assert_eq!(next, read_production_screen(&edited, &args).unwrap());
assert_ne!(next["images"], read_production_screen(&doc, &args).unwrap()["images"]);
}
#[test]
#[ignore = "requires the local XIAOYI_CANVAS_BENCH draft"]
fn jiansun_detail_screen_read() {
let path = std::env::var_os("XIAOYI_CANVAS_BENCH").unwrap();
let start = Instant::now();
let doc = Arc::new(photocraft_format::load_path(Path::new(&path)).unwrap());
println!("open={:?}", start.elapsed());
let start = Instant::now();
let meta = mapping(&doc).unwrap();
println!("mapping={:?}", start.elapsed());
let count = meta["outputs"].as_array().unwrap().len();
let reader = ScreenReader::default();
for _ in 0..3 {
for page in [0, 1, count / 2, count - 1] {
let input = json!({"page":page,"revision":1});
let start = Instant::now();
let previous = read_production_screen(&doc, &input).unwrap();
let baseline = start.elapsed();
let start = Instant::now();
let first = reader.read(&doc, &input).unwrap();
let miss = start.elapsed();
let start = Instant::now();
let second = reader.read(&doc, &input).unwrap();
let hit = start.elapsed();
assert_eq!(first, previous);
assert_eq!(second, previous);
println!("page={page} baseline={baseline:?} miss={miss:?} hit={hit:?}");
}
}
}

View File

@ -0,0 +1,56 @@
use super::*;
use std::time::Instant;
struct CopyingZip<'a>(ZipSource<'a>);
impl ByteSource for CopyingZip<'_> {
fn get(&self, path: &str, max: usize) -> Result<Vec<u8>> {
self.0.get(path, max)
}
}
#[test]
#[ignore = "requires the local XIAOYI_CANVAS_BENCH draft"]
fn jiansun_detail_draft_loading() {
let path = std::env::var_os("XIAOYI_CANVAS_BENCH").unwrap();
let t = Instant::now();
let bytes = crate::read::read_file(Path::new(&path)).unwrap();
println!("file bytes={} read={:?}", bytes.len(), t.elapsed());
let t = Instant::now();
let src = ZipSource::new(&bytes).unwrap();
let index = t.elapsed();
let opts = LoadOptions { preserve_ids: true, ..LoadOptions::default() };
let t = Instant::now();
let manifest = read_manifest(&src, &opts).unwrap();
println!("zip_index={index:?} manifest={:?}", t.elapsed());
println!("embedded_thumbnail={}", manifest.thumbnail.is_some());
let mut hashes = HashSet::new();
for (_, key, hash) in &manifest.document.metadata.psd_global_blocks {
if key != "6c6e6b32" || !hashes.insert(hash) {
continue;
}
let path = blob_path(hash);
let t = Instant::now();
let copied = src.get(&path, usize::MAX).unwrap();
let copy = t.elapsed();
let t = Instant::now();
let payload = src.get_payload(&path, usize::MAX).unwrap();
let borrow = t.elapsed();
assert_eq!(copied, payload.as_ref());
drop(copied);
let t = Instant::now();
let decoded = decompress_bounded(&payload, opts.max_blob_bytes, None, &path).unwrap();
let zstd = t.elapsed();
let t = Instant::now();
assert_eq!(hash_bytes(&decoded), *hash);
println!("lnk2 bytes={} decoded={} zip_copy={copy:?} zip_borrow={borrow:?} zstd={zstd:?} hash={:?}", payload.len(), decoded.len(), t.elapsed());
}
assert!(!hashes.is_empty(), "draft has no lnk2 blob");
let src = CopyingZip(src);
for owned in [true, false, false, true, true, false] {
let source: &dyn ByteSource = if owned { &src } else { &src.0 };
let t = Instant::now();
let doc = load(source, &opts).unwrap();
println!("decode owned={owned} time={:?} size={:?}", t.elapsed(), doc.size);
}
}

View File

@ -1,5 +1,6 @@
//! Object storage (ZIP or directory), incremental writer and loader.
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
@ -111,6 +112,11 @@ fn beside<A: Send, B>(parallel: bool, a: impl FnOnce() -> Result<A> + Send, b: i
pub trait ByteSource {
fn get(&self, path: &str, max: usize) -> Result<Vec<u8>>;
/// Read an entry, borrowing its bytes when the source already holds them.
fn get_payload(&self, path: &str, max: usize) -> Result<Cow<'_, [u8]>> {
self.get(path, max).map(Cow::Owned)
}
}
pub(crate) struct ZipSource<'a> {
@ -125,7 +131,12 @@ impl<'a> ZipSource<'a> {
impl ByteSource for ZipSource<'_> {
fn get(&self, path: &str, max: usize) -> Result<Vec<u8>> {
self.zip.read_by_name(path, max)
self.get_payload(path, max).map(Cow::into_owned)
}
fn get_payload(&self, path: &str, max: usize) -> Result<Cow<'_, [u8]>> {
let entry = self.zip.find(path).ok_or_else(|| FormatError::corrupt(format!("missing `{path}`")))?;
self.zip.read_payload(entry, max)
}
}
@ -282,7 +293,7 @@ fn check_manifest_depth(json: &[u8]) -> Result<()> {
}
pub(crate) fn read_manifest(src: &dyn ByteSource, opts: &LoadOptions) -> Result<Manifest> {
let raw = src.get(MANIFEST, opts.max_manifest_bytes)?;
let raw = src.get_payload(MANIFEST, opts.max_manifest_bytes)?;
// serde_json stops at 128 levels (about 40 nested groups); the bounded check replaces that limit.
check_manifest_depth(&raw)?;
let mut de = serde_json::Deserializer::from_slice(&raw);
@ -353,7 +364,7 @@ impl Fetch for LoadFetch<'_> {
}
self.account(len)?;
let path = tile_path(hash);
let z = self.src.get(&path, len + len / 8 + 4096)?;
let z = self.src.get_payload(&path, len + len / 8 + 4096)?;
let data = decompress(&z, len, &path)?;
if hash_bytes(&data) != hash {
return Err(FormatError::corrupt(format!("{path}: content does not match its hash")));
@ -379,7 +390,7 @@ impl Fetch for LoadFetch<'_> {
let path = blob_path(hash);
// The stored zstd frame of incompressible data is a little larger than the data, so a
// blob right at `limit` must still be read; `decompress_bounded` enforces `limit`.
let z = self.src.get(&path, limit.saturating_add(limit / 8).saturating_add(4096))?;
let z = self.src.get_payload(&path, limit.saturating_add(limit / 8).saturating_add(4096))?;
// Blob length is not in the manifest; the frame header bounds it and
// we cap at max_blob_bytes.
let data = decompress_bounded(&z, limit, None, &path)?;
@ -423,6 +434,10 @@ pub(crate) fn load(src: &dyn ByteSource, opts: &LoadOptions) -> Result<Document>
loader.document(&m.document)
}
#[cfg(test)]
#[path = "jiansun_load_tests.rs"]
mod jiansun_load_tests;
// ---------------------------------------------------------------------------
// Saving
// ---------------------------------------------------------------------------

View File

@ -236,6 +236,11 @@ impl<'a> ZipReader<'a> {
/// Entry payload (decompressed), at most `max` bytes, CRC-checked.
pub fn read(&self, e: &Entry, max: usize) -> Result<Vec<u8>, FormatError> {
self.read_payload(e, max).map(Cow::into_owned)
}
/// STORE entries already hold the payload in the archive.
pub(crate) fn read_payload(&self, e: &Entry, max: usize) -> Result<Cow<'a, [u8]>, FormatError> {
if e.uncompressed > max {
return Err(FormatError::LimitExceeded(format!("zip entry `{}` is {} bytes (max {max})", e.name, e.uncompressed)));
}
@ -246,7 +251,7 @@ impl<'a> ZipReader<'a> {
.and_then(|end| self.bytes.get(e.data_offset..end))
.ok_or_else(|| FormatError::corrupt(format!("zip entry `{}` out of range", e.name)))?;
let data = match e.method {
0 => raw.to_vec(),
0 => Cow::Borrowed(raw),
8 => {
// The uncompressed length comes from an untrusted ZIP header: a
// small forged archive must not reserve gigabytes up front, so the
@ -257,7 +262,7 @@ impl<'a> ZipReader<'a> {
.take((e.uncompressed as u64).saturating_add(1))
.read_to_end(&mut out)
.map_err(|err| FormatError::corrupt(format!("zip entry `{}`: {err}", e.name)))?;
out
Cow::Owned(out)
}
m => {
return Err(FormatError::Unsupported(format!("zip compression method {m} for `{}`", e.name)));
@ -266,7 +271,7 @@ impl<'a> ZipReader<'a> {
if data.len() != e.uncompressed || data.len() > max {
return Err(FormatError::corrupt(format!("zip entry `{}` has wrong size", e.name)));
}
if crc32(&data) != e.crc {
if crc32(data.as_ref()) != e.crc {
return Err(FormatError::corrupt(format!("zip entry `{}` failed its CRC check", e.name)));
}
Ok(data)

View File

@ -115,6 +115,14 @@ pub(crate) fn convert_tiles(
}
}
}
// The raster tile is already laid out like the texture. Hand its bytes to the queue
// directly instead of allocating and copying every tile during a cold canvas refresh.
if matches!(kind, TexKind::Rgba8Direct | TexKind::R8Direct) {
for (tile, coordinates) in &groups {
put(tile, coordinates, tile.bytes());
}
return groups.len();
}
// CMYK and Lab tiles convert pixel by pixel through a colour transform (a CMYK tile took
// ~5 ms on one thread, the whole of a brush dab's refresh on an A4 CMYK page, #5108): those
// go in bands of rows, so even the one tile a dab touches spreads over the threads. Workers

View File

@ -1100,3 +1100,6 @@ mod fade_tests;
#[cfg(test)]
mod tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod jiansun_open_tests;

View File

@ -0,0 +1,48 @@
use super::*;
use std::time::Instant;
#[test]
fn jiansun_first_gpu_refresh_preserves_pixels_across_tiles() {
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_doc::{Document, Layer};
use photocraft_geom::{Rect, Size};
let _guard = photocraft_testkit::gpu_lock();
let rs = egui_kittest::wgpu::create_render_state(wgpu_setup(), Default::default());
let mut doc = Document::new("detail", Size::new(300, 400), ColorMode::Rgb, SampleType::U8);
let mut layer = Layer::raster("detail", PixelFormat::RGBA8);
let surface = layer.surface_mut().unwrap();
surface.fill_rect(Rect::new(50, 30, 295, 385), &[1.0, 0.0, 0.0, 1.0]);
surface.fill_rect(Rect::new(200, 190, 270, 380), &[0.0, 1.0, 1.0, 1.0]);
doc.layers.push(layer);
let canvas = GpuCanvas::new(&rs);
let refresh = canvas.refresh(doc.id.0, &doc, None, None);
assert_eq!(refresh.kind, "gpu-full", "{:?}", refresh.fallback);
let (format, size, pixels) = canvas.read_texels(doc.id.0).unwrap();
assert_eq!(size, [300, 400]);
let expected = photocraft_compose::render(&doc, doc.bounds());
let expected = display_texels(format, None, &expected);
for (index, (actual, expected)) in pixels.iter().zip(expected.chunks_exact(texel_bytes(format) as usize)).enumerate() {
assert_eq!(*actual, texel_to_f32(format, expected), "pixel {index}");
}
}
#[test]
#[ignore = "requires the local XIAOYI_CANVAS_BENCH draft and a GPU adapter"]
fn jiansun_detail_first_gpu_refresh() {
let _guard = photocraft_testkit::gpu_lock();
let path = std::env::var_os("XIAOYI_CANVAS_BENCH").unwrap();
let doc = photocraft_format::load_path(std::path::Path::new(&path)).unwrap();
let rs = egui_kittest::wgpu::create_render_state(wgpu_setup(), Default::default());
println!("adapter={:?} bounds={:?}", rs.adapter.get_info(), doc.bounds());
for _ in 0..3 {
let canvas = GpuCanvas::new(&rs);
let start = Instant::now();
let refresh = canvas.refresh(doc.id.0, &doc, None, None);
assert_eq!(refresh.kind, "gpu-full", "{:?}", refresh.fallback);
let submit = start.elapsed();
assert!(canvas.health.wait(&rs.device, None));
println!("submit={submit:?} complete={:?} uploads={}", start.elapsed(), refresh.uploads);
}
}