Phase 3a-1: lazy fault-in of raster keyframe pixels

Raster keyframes are no longer eagerly decoded at load — `raw_pixels` stays empty
and is paged in on demand from the project container, so a big paint project opens
instantly and only touched frames hit RAM.

- core: `read_packed_media_readonly` (fresh read-only connection, can't conflict
  with an in-place save) + `RasterStore` (holds the container path; `load_pixels`
  reads+decodes a keyframe's PNG by id). `load_beam_sqlite` stops eager-decoding and
  instead marks every raster keyframe `needs_fault_in` (recursively, incl. nested);
  a freshly-created keyframe stays false (blank-resident, nothing to page). Added
  `Document::all_layers_mut`.
- editor: the canvas records a fault-in request when it needs a paged-out keyframe
  (empty pixels && needs_fault_in); the App drains the sink at the top of update(),
  pages the pixels in via the store, clears the flag, and repaints. Store path is set
  on load and after save. Export faults in synchronously per frame.

Cold-scrub still shows a 1-frame gap and the page-in is synchronous; the image proxy
(3a-2) and async load (3a-3) remove those next.
This commit is contained in:
Skyler Lehmkuhl
2026-06-19 16:59:46 -04:00
parent 6d386a884e
commit 4228864259
11 changed files with 244 additions and 14 deletions
@@ -766,6 +766,32 @@ fn set_meta_conn(conn: &Connection, key: &str, value: &str) -> Result<(), String
Ok(())
}
/// Read a packed media item's full bytes via a fresh **read-only** connection,
/// without an open [`BeamArchive`] handle. Returns `Ok(None)` if the item has no
/// chunk rows. Used for on-demand raster fault-in: a read-only connection can't
/// conflict with an in-place save and needs no long-lived handle.
pub fn read_packed_media_readonly(db_path: &Path, id: Uuid) -> Result<Option<Vec<u8>>, String> {
let conn = Connection::open_with_flags(
db_path,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
.map_err(map_sql)?;
let id_bytes = id.as_bytes().to_vec();
let mut stmt = conn
.prepare("SELECT bytes FROM media_chunk WHERE media_id = ?1 ORDER BY chunk_index")
.map_err(map_sql)?;
let rows = stmt
.query_map([&id_bytes], |r| r.get::<_, Vec<u8>>(0))
.map_err(map_sql)?;
let mut out = Vec::new();
let mut any = false;
for row in rows {
out.extend_from_slice(&row.map_err(map_sql)?);
any = true;
}
Ok(if any { Some(out) } else { None })
}
fn map_sql(e: rusqlite::Error) -> String {
format!("SQLite error: {}", e)
}
@@ -650,6 +650,29 @@ impl Document {
layers
}
/// Get mutable references to all layers across the entire document
/// (root + nested groups + inside all vector clips). Mirrors [`all_layers`].
pub fn all_layers_mut(&mut self) -> Vec<&mut AnyLayer> {
let mut layers: Vec<&mut AnyLayer> = Vec::new();
// Iterative walk with an explicit stack of child slices. Group layers are
// descended into but not themselves collected (they hold no keyframes).
let mut stack: Vec<&mut [AnyLayer]> = vec![&mut self.root.children];
while let Some(list) = stack.pop() {
for layer in list {
match layer {
AnyLayer::Group(g) => {
stack.push(&mut g.children);
}
other => layers.push(other),
}
}
}
for clip in self.vector_clips.values_mut() {
layers.extend(clip.layers.root_data_mut());
}
layers
}
// === CLIP LIBRARY METHODS ===
/// Add a vector clip to the library
@@ -561,23 +561,18 @@ fn load_beam_sqlite(path: &Path) -> Result<LoadedProject, String> {
restored_entries.push(e);
}
// Raster keyframes: load PNG bytes from media rows into raw_pixels.
// Raster keyframes are NOT eagerly decoded (Phase 3 paging): `raw_pixels` stays
// empty and is faulted in on demand from the container's `Raster` rows via the
// editor's `RasterStore` (keyed by `kf.id`). Loading a big paint project is now
// instant and only the resident window lives in RAM. Mark every keyframe
// `needs_fault_in` (recursively, incl. nested layers) so the renderer requests a
// page-in; a freshly-created keyframe stays `false` (blank-resident, nothing to load).
let mut raster_load_count = 0usize;
for layer in document.root.children.iter_mut() {
for layer in document.all_layers_mut() {
if let crate::layer::AnyLayer::Raster(rl) = layer {
for kf in &mut rl.keyframes {
if let Ok(Some(_)) = archive.media_info(kf.id) {
match archive.read_media_full(kf.id) {
Ok(png_bytes) => match crate::brush_engine::decode_png(&png_bytes) {
Ok(rgba) => {
kf.raw_pixels = rgba.into_raw();
raster_load_count += 1;
}
Err(e) => eprintln!("⚠️ [LOAD_BEAM] Failed to decode raster {}: {}", kf.id, e),
},
Err(e) => eprintln!("⚠️ [LOAD_BEAM] Failed to read raster {}: {}", kf.id, e),
}
}
kf.needs_fault_in = true;
raster_load_count += 1;
}
}
}
@@ -54,6 +54,7 @@ pub mod svg_export;
pub mod snap;
pub mod webcam;
pub mod raster_layer;
pub mod raster_store;
pub mod brush_settings;
pub mod brush_engine;
pub mod raster_draw;
@@ -117,6 +117,12 @@ pub struct RasterKeyframe {
/// Always `true` after load; cleared by the renderer after uploading.
#[serde(skip, default = "default_true")]
pub texture_dirty: bool,
/// Phase 3 paging: the keyframe's pixels live in the container and must be
/// faulted in (`raw_pixels` empty *and* this true ⇒ page in from the store).
/// A *new* keyframe is `false` (intentionally blank/resident, nothing to load);
/// set true on load and again when evicted. Never serialized.
#[serde(skip)]
pub needs_fault_in: bool,
}
fn default_true() -> bool { true }
@@ -140,6 +146,7 @@ impl RasterKeyframe {
tween_after: TweenType::Hold,
raw_pixels: Vec::new(),
texture_dirty: true,
needs_fault_in: false,
}
}
}
@@ -0,0 +1,56 @@
//! On-demand loader for raster keyframe pixels backed by the project `.beam`
//! container (Phase 3 paging).
//!
//! Raster keyframes are no longer eagerly decoded at load; `raw_pixels` stays
//! empty until something needs the frame, then it is faulted in from the
//! container's `Raster` media row (keyed by the keyframe id). The store holds only
//! the container path and reads through a fresh **read-only** connection per call,
//! so it never conflicts with an in-place save and keeps no long-lived handle.
//! `None` path = an unsaved document (nothing to fault in).
use std::path::PathBuf;
use uuid::Uuid;
/// Faults in raster keyframe pixels from the project container on demand.
#[derive(Default, Clone)]
pub struct RasterStore {
path: Option<PathBuf>,
}
impl RasterStore {
pub fn new(path: Option<PathBuf>) -> Self {
Self { path }
}
/// Point the store at a (possibly new) container path, or `None` for an
/// unsaved document. Call on load and on save-as.
pub fn set_path(&mut self, path: Option<PathBuf>) {
self.path = path;
}
pub fn has_path(&self) -> bool {
self.path.is_some()
}
/// Decode the keyframe's full RGBA pixels from the container, or `None` if the
/// container has no row for it (or decoding fails). The returned buffer is the
/// working `raw_pixels` representation (`width*height*4` sRGB-premultiplied RGBA).
pub fn load_pixels(&self, kf_id: Uuid) -> Option<Vec<u8>> {
let path = self.path.as_ref()?;
let png = match crate::beam_archive::read_packed_media_readonly(path, kf_id) {
Ok(Some(bytes)) => bytes,
Ok(None) => return None,
Err(e) => {
eprintln!("[RasterStore] read {} failed: {}", kf_id, e);
return None;
}
};
match crate::brush_engine::decode_png(&png) {
Ok(img) => Some(img.into_raw()),
Err(e) => {
eprintln!("[RasterStore] decode {} failed: {}", kf_id, e);
None
}
}
}
}