Merge branch 'main' into worktree-agent-a38a174c36aa9f23a

This commit is contained in:
Brandon Thomas
2026-10-03 19:52:55 -04:00
40 changed files with 2811 additions and 197 deletions
+8 -1
View File
@@ -549,6 +549,9 @@ fn purge_caches(s: &mut Session, p: &Value) -> Result<Value> {
if disk && let Some(dc) = &s.disk_cache {
disk_entries = dc.stats().entries;
dc.clear();
} else if disk && let Some(h) = &s.storage {
// The browser's disk cache (Origin Private File System).
disk_entries = h.clear("diskCache").ok().and_then(|r| r["entries"].as_u64()).unwrap_or(0) as usize;
}
if matches!(what.as_str(), "all" | "image" | "memory" | "memoryAndDisk") {
effectcraft_effects::roto::purge();
@@ -560,7 +563,11 @@ fn purge_caches(s: &mut Session, p: &Value) -> Result<Value> {
/// `cache.diskStats`: the disk cache's folder, limit and contents.
pub(crate) fn disk_stats(s: &mut Session, _: &Value) -> Result<Value> {
let Some(dc) = &s.disk_cache else { return Ok(json!({"enabled": false})) };
let Some(dc) = &s.disk_cache else {
// The browser's disk cache (Origin Private File System), when the web app has one.
let web = s.storage.as_ref().map(|h| h.info()["diskCache"].clone()).filter(|d| d.is_object());
return Ok(web.unwrap_or_else(|| json!({"enabled": false})));
};
let st = dc.stats();
Ok(json!({
"enabled": true,
+1
View File
@@ -198,6 +198,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(align::specs());
v.extend(content_fill::specs());
v.extend(stubs::specs());
v.extend(crate::storage::specs());
v.extend(crate::learn::specs());
v.extend(crate::templates::specs());
v.extend(crate::preview::specs());
+4
View File
@@ -34,6 +34,7 @@ pub mod roto;
pub mod scriptui;
mod session_settings;
pub mod shortcuts;
pub mod storage;
pub mod sysinfo;
pub mod templates;
pub mod tracking;
@@ -363,6 +364,8 @@ pub struct Session {
pub offloaded: Vec<offload::OffloadedJob>,
/// What the Media Browser browses (`None`: the local file system where there is one).
pub browser: Option<Arc<dyn media_browser::Browser>>,
/// The browser's storage (the web app; Settings ▸ Disk ▸ Browser Storage, `storage.*`).
pub storage: Option<Arc<dyn storage::StorageHost>>,
/// Offloaded jobs that ended, newest last (kind, error): how a caller waiting for one
/// (`wait: true` over the control channel in the browser) learns its outcome.
pub offload_log: Vec<(offload::JobKind, Option<String>)>,
@@ -447,6 +450,7 @@ impl Default for Session {
offloaded: vec![],
offload_log: vec![],
browser: None,
storage: None,
tasks: vec![],
job_log: vec![],
next_task_id: 1,
+5
View File
@@ -819,6 +819,9 @@ pub enum Item {
},
/// Read-only information line.
Note(&'static str),
/// The browser's storage manager (web app only, `storage.*`): usage and quota, persistent
/// storage, Clear buttons. Not shown where there is no browser storage.
BrowserStorage,
}
/// One page of the Settings dialog.
@@ -1035,6 +1038,7 @@ pub fn pages() -> Vec<Page> {
s("disk.diskCacheMaxGb", "Maximum Disk Cache Size", Kind::Int(1, 100_000, "GB"), true),
s("disk.diskCacheFolder", "Disk Cache Folder", Kind::Path, true),
Button { label: "Empty Disk Cache", command: "edit.purge", params: r#"{"what":"disk"}"# },
BrowserStorage,
Section("Media Cache"),
s("disk.mediaCacheFolder", "Database and Cache Folder", Kind::Path, true),
s("disk.conformedMediaFolder", "Conformed Audio Folder", Kind::Path, true),
@@ -1143,6 +1147,7 @@ pub fn pages_json() -> Value {
Item::Labels => json!({"labels": "labels.N.name / labels.N.color (N = 0..15)"}),
Item::AudioDevices { key } => json!({"type": "device", "key": key, "label": "Default Output"}),
Item::Note(t) => json!({"note": t}),
Item::BrowserStorage => json!({"browserStorage": "storage.info / storage.persist / storage.clear (web app)"}),
})
.collect();
json!({"id": p.id, "title": p.title, "items": items})
+271 -17
View File
@@ -13,13 +13,23 @@
//! - [`FrameServer`] (worker side): applies syncs, relayed Roto Brush segmentations and render
//! requests, and renders frames as premultiplied RGBA8 ([`rgba8_premultiplied`]).
//!
//! - GPU frames: a worker with its own WebGPU device ([`FrameServer::accel`]) renders through
//! the GPU compositor and GPU effects. Its readbacks can't be waited for, so a frame renders
//! in passes ([`effectcraft_render::Accelerator::frame_begin`]): [`FrameServer::handle`]
//! runs the first, and while [`FrameServer::waiting`] the transport awaits the device and
//! calls [`FrameServer::resume`] for the next. Backend Auto picks CPU or GPU per comp from
//! the frames' total times ([`effectcraft_render::AutoPick`]).
//! - Disk cache: a render request may carry the frame's disk-cache key ([`FrameMsg::Render`]
//! `disk`); the transport stores the finished frame under it (the browser: in the Origin
//! Private File System) and reports [`FrameReply::Stored`].
//!
//! The transport (structured-clone messages, transferable pixel buffers) is the web crate's;
//! everything here is portable and tested natively.
use std::sync::Arc;
use effectcraft_project::{ItemId, Project};
use effectcraft_render::{ExprHost, FootageSource, Image, LayerCache, RenderOpts, Renderer};
use effectcraft_render::{Accelerator, AutoKey, Backend, ExprHost, FootageSource, Image, LayerCache, RenderOpts, Renderer};
use effectcraft_time::Tick;
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -120,8 +130,17 @@ pub enum FrameMsg {
Project { revision: u64, project: String },
/// Changes from the worker's revision `from` to `revision`.
Patch { from: u64, revision: u64, ops: Vec<Op> },
/// Render a frame of the current project.
Render { id: u64, revision: u64, comp: ItemId, time: Tick, opts: Box<RenderOpts> },
/// Render a frame of the current project. `disk`: the frame's disk-cache key (32 hex
/// digits) when the transport should store it.
Render {
id: u64,
revision: u64,
comp: ItemId,
time: Tick,
opts: Box<RenderOpts>,
#[serde(default, skip_serializing_if = "Option::is_none")]
disk: Option<String>,
},
/// Roto Brush segmentations computed elsewhere (a propagation worker).
Segs { segs: Vec<SegData> },
/// Drop cached layer buffers (Edit ▸ Purge).
@@ -133,8 +152,27 @@ pub enum FrameMsg {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum FrameReply {
/// Premultiplied RGBA8 pixels of request `id`, rendered in `ms` milliseconds.
Frame { id: u64, width: u32, height: u32, ms: f64 },
/// Premultiplied RGBA8 pixels of request `id`, rendered in `ms` milliseconds (`passes`
/// render passes, `gpu`: through the GPU accelerator).
Frame {
id: u64,
width: u32,
height: u32,
ms: f64,
#[serde(default)]
passes: u32,
#[serde(default)]
gpu: bool,
},
/// The frame was stored in the disk cache under `key` (`bytes` on disk).
Stored { key: String, bytes: u64 },
/// The worker's renderer: its GPU adapter, or why it has none.
Info {
#[serde(default)]
gpu: Option<String>,
#[serde(default)]
error: Option<String>,
},
/// Request `id` was not rendered (`stale`: the worker holds another revision).
Failed { id: u64, error: String, stale: bool },
/// A sync could not be applied: the page must send the whole project again.
@@ -189,14 +227,45 @@ pub struct FrameServer {
pub footage: Arc<dyn FootageSource>,
pub expr: Option<Arc<dyn ExprHost>>,
pub cache: Arc<LayerCache>,
/// The worker's own accelerator (a GPU device; see [`FrameServer::set_accel`]).
accel: Option<Arc<dyn Accelerator>>,
doc: Value,
project: Option<Arc<Project>>,
revision: Option<u64>,
/// The frame being rendered in passes.
pending: Option<Pending>,
}
/// A frame whose readbacks are in flight.
struct Pending {
id: u64,
project: Arc<Project>,
comp: ItemId,
time: Tick,
opts: RenderOpts,
t0: web_time::Instant,
passes: u32,
/// Backend Auto's choice: (timing key, GPU).
auto: Option<(AutoKey, bool)>,
}
/// Passes before a frame gives up on deferred readbacks and renders on the CPU.
pub const MAX_PASSES: u32 = 24;
impl FrameServer {
pub fn new(footage: Arc<dyn FootageSource>, expr: Option<Arc<dyn ExprHost>>) -> FrameServer {
FrameServer { footage, expr, cache: Arc::new(LayerCache::default()), doc: Value::Null, project: None, revision: None }
FrameServer { footage, expr, cache: Arc::new(LayerCache::default()), accel: None, doc: Value::Null, project: None, revision: None, pending: None }
}
/// Render with `accel` when the request's backend asks for it (the worker's GPU). Its miss
/// gate keeps placeholder buffers of unfinished passes out of the layer cache.
pub fn set_accel(&mut self, accel: Option<Arc<dyn Accelerator>>) {
self.cache.set_gate(accel.as_ref().and_then(|a| a.miss_gate()));
self.accel = accel;
}
pub fn accel(&self) -> Option<&Arc<dyn Accelerator>> {
self.accel.as_ref()
}
pub fn revision(&self) -> Option<u64> {
@@ -207,6 +276,11 @@ impl FrameServer {
self.project.as_ref()
}
/// A frame is waiting for readbacks: await the device, then [`FrameServer::resume`].
pub fn waiting(&self) -> bool {
self.pending.is_some()
}
fn load(&mut self, revision: u64) -> Result<(), String> {
let p = Project::from_json(&self.doc.to_string()).map_err(|e| e.to_string())?;
self.project = Some(Arc::new(p));
@@ -214,7 +288,8 @@ impl FrameServer {
Ok(())
}
/// Handle one message; returns the replies with their pixels.
/// Handle one message; returns the replies with their pixels. A render that needs more
/// passes returns nothing yet ([`FrameServer::waiting`]).
pub fn handle(&mut self, msg: FrameMsg) -> Vec<(FrameReply, Option<Vec<u8>>)> {
match msg {
FrameMsg::Project { revision, project } => {
@@ -246,7 +321,7 @@ impl FrameServer {
self.cache.clear();
vec![]
}
FrameMsg::Render { id, revision, comp, time, opts } => {
FrameMsg::Render { id, revision, comp, time, opts, .. } => {
let fail = |error: String, stale: bool| vec![(FrameReply::Failed { id, error, stale }, None)];
if self.revision != Some(revision) {
return fail(format!("the replica is at {:?}, not {revision}", self.revision), true);
@@ -255,17 +330,60 @@ impl FrameServer {
if p.comp(comp).is_none() {
return fail(format!("no composition {}", comp.0), false);
}
let t0 = web_time::Instant::now();
let mut r = Renderer::new(&p, self.footage.as_ref(), *opts);
r.expr = self.expr.as_deref();
r.cache = Some(&self.cache);
let img = r.comp_frame(comp, time);
let ms = t0.elapsed().as_secs_f64() * 1000.0;
vec![(FrameReply::Frame { id, width: img.width, height: img.height, ms }, Some(rgba8_premultiplied(&img)))]
let mut opts = *opts;
let mut auto = None;
if let Some(a) = &self.accel {
// Auto: CPU or GPU for the whole frame (all its passes), timed as a whole.
if opts.backend == Backend::Auto {
if !p.settings.gpu_acceleration {
opts.backend = Backend::Cpu;
} else if opts.roi.is_none()
&& let Some(pick) = a.auto_pick()
{
let key = AutoKey::new(comp, opts.scale, false);
let gpu = pick.choose(key);
opts.backend = if gpu { Backend::Gpu } else { Backend::Cpu };
auto = Some((key, gpu));
}
}
a.frame_begin();
}
self.pending = Some(Pending { id, project: p, comp, time, opts, t0: web_time::Instant::now(), passes: 0, auto });
self.resume()
}
}
}
/// Run the next pass of the frame in progress; its reply once it is done.
pub fn resume(&mut self) -> Vec<(FrameReply, Option<Vec<u8>>)> {
let Some(mut pr) = self.pending.take() else { return vec![] };
pr.passes += 1;
let accel = self.accel.clone().filter(|_| pr.opts.backend != Backend::Cpu);
let give_up = pr.passes > MAX_PASSES;
let mut r = Renderer::new(&pr.project, self.footage.as_ref(), pr.opts);
r.expr = self.expr.as_deref();
r.cache = Some(&self.cache);
if !give_up {
r.accel = accel.as_deref();
}
if let Some(a) = r.accel {
a.pass_begin();
}
let img = r.comp_frame(pr.comp, pr.time);
if r.accel.is_some_and(|a| a.pass_missed()) {
self.pending = Some(pr);
return vec![];
}
let ms = pr.t0.elapsed().as_secs_f64() * 1000.0;
let gpu = r.accel.is_some() && r.active_accel().is_some();
if let (Some((key, chose)), Some(a)) = (pr.auto, &self.accel)
&& let Some(pick) = a.auto_pick()
{
pick.record(key, chose, ms);
}
vec![(FrameReply::Frame { id: pr.id, width: img.width, height: img.height, ms, passes: pr.passes, gpu }, Some(rgba8_premultiplied(&img)))]
}
fn lost(&mut self, error: String) -> Vec<(FrameReply, Option<Vec<u8>>)> {
self.doc = Value::Null;
self.project = None;
@@ -332,7 +450,8 @@ mod tests {
assert!(send(first, &mut w).is_empty());
assert!(m.sync(s.revision, &s.project).is_none(), "nothing new");
let t = Tick::from_seconds_f64(1.0);
let render = |w: &mut FrameServer, rev: u64, id: u64| w.handle(round(&FrameMsg::Render { id, revision: rev, comp, time: t, opts: Box::new(opts) }));
let render =
|w: &mut FrameServer, rev: u64, id: u64| w.handle(round(&FrameMsg::Render { id, revision: rev, comp, time: t, opts: Box::new(opts), disk: None }));
let out = render(&mut w, s.revision, 1);
let (FrameReply::Frame { id, width, height, .. }, Some(px)) = &out[0] else { panic!("{:?}", out[0].0) };
assert_eq!((*id, *width as usize * *height as usize * 4), (1, px.len()));
@@ -367,6 +486,7 @@ mod tests {
comp: ItemId(2),
time: Tick::from_seconds_f64(0.5),
opts: Box::new(RenderOpts { scale: 0.5, draft: true, roi: Some([1.0, 2.0, 3.0, 4.0]), ..Default::default() }),
disk: Some(format!("{:032x}", 0xabcdu128)),
},
] {
let a = serde_json::to_string(&m).unwrap();
@@ -374,11 +494,145 @@ mod tests {
assert!(a.starts_with("{\"type\":"), "{a}");
}
for r in [
FrameReply::Frame { id: 1, width: 2, height: 3, ms: 4.5 },
FrameReply::Frame { id: 1, width: 2, height: 3, ms: 4.5, passes: 2, gpu: true },
FrameReply::Stored { key: "00ff".into(), bytes: 9 },
FrameReply::Info { gpu: Some("Adapter (BrowserWebGpu)".into()), error: None },
FrameReply::Failed { id: 1, error: "x".into(), stale: true },
FrameReply::Resync { error: "y".into() },
] {
assert_eq!(round(&r), r);
}
}
/// An accelerator with deferred readbacks: a GPU effect chain is "read back" one
/// [`Deferred::settle`] after it was first asked for (computed with the CPU effects, so the
/// finished frame equals the CPU render); until then it misses and returns its input.
#[derive(Default)]
struct Deferred {
ready: std::sync::Mutex<std::collections::HashSet<u64>>,
asked: std::sync::Mutex<std::collections::HashSet<u64>>,
gate: Arc<std::sync::atomic::AtomicBool>,
chains: std::sync::atomic::AtomicUsize,
auto: effectcraft_render::AutoPick,
}
impl Deferred {
fn settle(&self) {
let asked: Vec<u64> = self.asked.lock().unwrap().drain().collect();
self.ready.lock().unwrap().extend(asked);
}
}
impl Accelerator for Deferred {
fn name(&self) -> String {
"deferred".into()
}
fn comp_frame(&self, _: &Renderer, _: ItemId, _: Tick) -> Option<Image> {
None
}
fn supports_effect(&self, id: &str) -> bool {
effectcraft_effects::GPU_EFFECTS.contains(&id)
}
fn effects(&self, chain: &[effectcraft_render::FxStep], buf: &effectcraft_effects::Buf, levels: Option<f32>) -> Option<effectcraft_effects::Buf> {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
for s in chain {
s.spec.id.hash(&mut h);
s.ctx.time.to_bits().hash(&mut h);
}
(buf.img.width, buf.img.height).hash(&mut h);
for p in &buf.img.data {
for c in p {
c.to_bits().hash(&mut h);
}
}
let key = h.finish();
if !self.ready.lock().unwrap().contains(&key) {
self.asked.lock().unwrap().insert(key);
self.gate.store(true, std::sync::atomic::Ordering::Relaxed);
return Some(buf.clone());
}
self.chains.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut b = buf.clone();
for s in chain {
b = effectcraft_effects::apply(s.spec, &s.ctx, b);
if let Some(l) = levels {
effectcraft_render::color::quantize(&mut b.img, l);
}
}
Some(b)
}
fn auto_pick(&self) -> Option<&effectcraft_render::AutoPick> {
Some(&self.auto)
}
fn frame_begin(&self) {
self.ready.lock().unwrap().clear();
}
fn pass_begin(&self) {
self.gate.store(false, std::sync::atomic::Ordering::Relaxed);
}
fn pass_missed(&self) -> bool {
self.gate.load(std::sync::atomic::Ordering::Relaxed)
}
fn miss_gate(&self) -> Option<Arc<std::sync::atomic::AtomicBool>> {
Some(self.gate.clone())
}
}
#[test]
fn deferred_readbacks_render_in_passes() {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
let comp = s.active_comp_id().unwrap();
s.execute("layer.newSolid", json!({"color": "#3388ff", "name": "Blue", "width": 200, "height": 120})).unwrap();
s.execute("effect.apply", json!({"effect": "ec.blur.gaussian"})).unwrap();
s.execute("effect.apply", json!({"effect": "ec.stylize.glow"})).unwrap();
s.execute("layer.newSolid", json!({"color": "#ffcc00", "name": "Yellow", "width": 80, "height": 80})).unwrap();
s.execute("effect.apply", json!({"effect": "ec.color.levels"})).unwrap();
let opts = RenderOpts { scale: 0.25, backend: Backend::Gpu, ..Default::default() };
let t = Tick::from_seconds_f64(1.0);
let mut w = server(&s);
let acc = Arc::new(Deferred::default());
w.set_accel(Some(acc.clone()));
let mut m = Mirror::default();
w.handle(round(&m.sync(s.revision, &s.project).unwrap()));
let req = |id| round(&FrameMsg::Render { id, revision: s.revision, comp, time: t, opts: Box::new(opts), disk: None });
assert!(w.handle(req(1)).is_empty() && w.waiting(), "the first pass misses");
let mut out = vec![];
for _ in 0..10 {
acc.settle();
out = w.resume();
if !w.waiting() {
break;
}
}
let (FrameReply::Frame { id: 1, passes, gpu: true, .. }, Some(px)) = &out[0] else { panic!("{:?}", out.first().map(|o| &o.0)) };
assert!(*passes >= 2, "{passes}");
assert!(acc.chains.load(std::sync::atomic::Ordering::Relaxed) >= 2);
// The same pixels as the CPU: no placeholder survived, in the frame or the layer cache.
assert_eq!(*px, local(&s, comp, t, RenderOpts { backend: Backend::Cpu, ..opts }));
let out = w.handle(req(2));
let out = if out.is_empty() {
acc.settle();
w.resume()
} else {
out
};
assert_eq!(out[0].1.as_deref(), Some(&px[..]));
// CPU requests never touch the accelerator; Auto times whole frames.
let cpu = RenderOpts { backend: Backend::Cpu, ..opts };
let out = w.handle(round(&FrameMsg::Render { id: 3, revision: s.revision, comp, time: t, opts: Box::new(cpu), disk: None }));
assert!(matches!(out[0].0, FrameReply::Frame { id: 3, passes: 1, gpu: false, .. }));
for id in 4..12 {
let auto = RenderOpts { backend: Backend::Auto, ..opts };
let mut out = w.handle(round(&FrameMsg::Render { id, revision: s.revision, comp, time: t, opts: Box::new(auto), disk: None }));
while w.waiting() {
acc.settle();
out = w.resume();
}
assert_eq!(out[0].1.as_deref(), Some(&px[..]), "frame {id}");
}
let st = acc.auto.stats(effectcraft_render::AutoKey::new(comp, opts.scale, false)).unwrap();
assert!(st.cpu_frames > 0 && st.gpu_frames > 0, "{st:?}");
}
}
+133
View File
@@ -0,0 +1,133 @@
//! Browser storage management: what the web app keeps in the browser (projects, imported media,
//! auto-saves and settings in the Origin Private File System or IndexedDB; the disk cache's
//! frames in the Origin Private File System), how much of the origin's quota that uses, whether
//! the browser keeps it under storage pressure, and clearing it.
//!
//! The browser's storage APIs are asynchronous and the engine's commands are not, so a
//! [`StorageHost`] answers from its latest snapshot (refreshing it in the background) and
//! starts requests that finish later; the snapshot reports their outcome.
//!
//! Commands (agents, Settings ▸ Disk ▸ Browser Storage): `storage.info`, `storage.persist`,
//! `storage.clear {what}`. Without a host (the desktop) `storage.info` reports
//! `{available: false}` and the others fail.
use serde_json::{Value, json};
use crate::commands::{CommandSpec, str_p};
use crate::{Result, Session, cmd};
/// What can be cleared ([`StorageHost::clear`]).
pub const CLEARABLE: &[&str] = &["diskCache", "media", "projects", "autoSaves", "all"];
/// The browser's storage, as the web app manages it.
pub trait StorageHost: Send + Sync {
/// The latest snapshot: `{backend, usage, quota, persisted, files: {count, bytes, media,
/// projects, autoSaves}, diskCache: {enabled, entries, bytes, maxBytes, hits, misses, writes,
/// evictions}}` (`usage` / `quota` from `navigator.storage.estimate()`, in bytes). Asks for
/// a fresh one.
fn info(&self) -> Value;
/// Ask the browser to keep the storage under pressure (`navigator.storage.persist()`); the
/// answer arrives in a later [`StorageHost::info`] (`persisted`).
fn request_persist(&self) -> Value;
/// Delete stored data: `diskCache` (cached frames), `media` (imported footage), `projects`
/// (saved projects), `autoSaves`, or `all` of them (settings stay). Returns what was
/// removed: `{cleared, entries, bytes}`.
fn clear(&self, what: &str) -> std::result::Result<Value, String>;
}
fn host(s: &Session, cmd: &str) -> Result<std::sync::Arc<dyn StorageHost>> {
s.storage.clone().ok_or_else(|| crate::commands::bad(cmd, "browser storage is only managed in the web app"))
}
fn info(s: &mut Session, _: &Value) -> Result<Value> {
Ok(match &s.storage {
Some(h) => {
let mut v = h.info();
if let Some(o) = v.as_object_mut() {
o.insert("available".into(), json!(true));
}
v
}
None => json!({"available": false}),
})
}
fn persist(s: &mut Session, _: &Value) -> Result<Value> {
Ok(host(s, "storage.persist")?.request_persist())
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let what = str_p(p, "what").unwrap_or("diskCache");
if !CLEARABLE.contains(&what) {
return Err(crate::commands::bad("storage.clear", format!("what: one of {}", CLEARABLE.join(", "))));
}
let h = host(s, "storage.clear")?;
let r = h.clear(what).map_err(|e| crate::commands::bad("storage.clear", e))?;
s.toast(format!("Cleared browser storage: {what}"));
Ok(r)
}
fn has_host(s: &Session) -> std::result::Result<(), String> {
if s.storage.is_some() { Ok(()) } else { Err("browser storage is only managed in the web app".into()) }
}
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
crate::query!(
"storage.info",
"Browser Storage",
"{} → {available, backend, usage, quota, persisted, files: {count, bytes, media, projects, autoSaves}, diskCache: {enabled, entries, bytes, maxBytes, hits, misses, writes, evictions}}",
info
),
cmd!("storage.persist", "Request Persistent Storage", [], None, "{} → {requested, persisted}", has_host, persist),
cmd!("storage.clear", "Clear Browser Storage", [], None, "{what: diskCache|media|projects|autoSaves|all} → {cleared, entries, bytes}", has_host, clear),
]
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use super::*;
#[derive(Default)]
struct Mock {
cleared: Mutex<Vec<String>>,
persisted: Mutex<bool>,
}
impl StorageHost for Mock {
fn info(&self) -> Value {
json!({"backend": "opfs", "usage": 1000, "quota": 100000, "persisted": *self.persisted.lock().unwrap(),
"diskCache": {"enabled": true, "entries": 3, "bytes": 300, "maxBytes": 1 << 30}})
}
fn request_persist(&self) -> Value {
*self.persisted.lock().unwrap() = true;
json!({"requested": true})
}
fn clear(&self, what: &str) -> std::result::Result<Value, String> {
self.cleared.lock().unwrap().push(what.into());
Ok(json!({"cleared": what, "entries": 3, "bytes": 300}))
}
}
#[test]
fn storage_commands_go_to_the_host() {
let mut s = Session::default();
assert_eq!(s.execute_checked("storage.info", json!({})).unwrap(), json!({"available": false}));
assert!(s.execute_checked("storage.clear", json!({"what": "diskCache"})).is_err());
let m = Arc::new(Mock::default());
s.storage = Some(m.clone());
let i = s.execute_checked("storage.info", json!({})).unwrap();
assert_eq!((i["available"].clone(), i["backend"].clone(), i["persisted"].clone()), (json!(true), json!("opfs"), json!(false)));
assert_eq!(s.execute_checked("storage.persist", json!({})).unwrap()["requested"], json!(true));
assert_eq!(s.execute_checked("storage.info", json!({})).unwrap()["persisted"], json!(true));
assert!(s.execute_checked("storage.clear", json!({"what": "everything"})).is_err());
assert_eq!(s.execute_checked("storage.clear", json!({"what": "media"})).unwrap()["cleared"], json!("media"));
// The disk cache's own commands use the browser's disk cache when there is no folder.
let st = s.execute_checked("cache.diskStats", json!({})).unwrap();
assert_eq!((st["enabled"].clone(), st["entries"].clone()), (json!(true), json!(3)));
assert_eq!(s.execute_checked("edit.purge", json!({"what": "disk"})).unwrap()["diskEntries"], json!(3));
assert_eq!(*m.cleared.lock().unwrap(), vec!["media".to_string(), "diskCache".to_string()]);
}
}
+4 -4
View File
@@ -325,7 +325,7 @@ fn raster_into(e: &mut Enc, s: &Scene) -> Option<(wgpu::Texture, wgpu::Texture)>
/// Rasterise a scene and read it back ([`effectcraft_render::Accelerator::raster_3d`]). `None`
/// when the device can't (no readback, size or buffer limits).
pub(crate) fn render(g: &GpuContext, s: &Scene) -> Option<Target> {
if !g.can_readback() {
if !g.can_wait() {
return None;
}
let mut e = Enc::new(g);
@@ -520,7 +520,7 @@ fn storage_buf(g: &GpuContext, size: u64, label: &str) -> wgpu::Buffer {
/// Read a storage buffer back (submits and waits).
fn read_buffer(e: &mut Enc, buf: &wgpu::Buffer, size: u64) -> Option<Vec<u8>> {
if !e.g.can_readback() {
if !e.g.can_wait() {
return None;
}
let rb = e.g.device.create_buffer(&wgpu::BufferDescriptor {
@@ -560,7 +560,7 @@ const BIG: f32 = 3.0e38;
pub(crate) fn resolve_run(e: &mut Enc, prep: &Prepared) -> Option<Option<Resolved>> {
let (w, h) = prep.out;
let g = e.g;
if !g.fits(w, h) || (prep.dof.is_some() && !g.can_readback()) {
if !g.fits(w, h) || (prep.dof.is_some() && !g.can_wait()) {
return None;
}
let px = w as u64 * h as u64;
@@ -673,7 +673,7 @@ pub(crate) fn finish(e: &mut Enc, r: &Resolved, encode: bool, canvas: Option<&Gp
/// [`effectcraft_render::Accelerator::render_3d`]: the whole prepared run on the GPU, read
/// back.
pub(crate) fn render_prepared(g: &GpuContext, prep: &Prepared) -> Option<Rendered> {
if !g.can_readback() {
if !g.can_wait() {
return None;
}
let mut e = Enc::new(g);
+67 -16
View File
@@ -262,6 +262,8 @@ pub struct GpuContext {
/// GPU particle pipeline (built on first use) and simulation checkpoints.
pub(crate) particles: crate::particles::PipesCell,
pub(crate) particle_states: crate::particles::StatesCell,
/// Deferred readbacks (a browser worker's WebGPU device), see [`crate::deferred`].
pub(crate) deferred: Option<Arc<crate::deferred::Deferred>>,
}
fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
@@ -452,27 +454,43 @@ impl GpuContext {
adv3d: std::sync::OnceLock::new(),
particles: Default::default(),
particle_states: Default::default(),
deferred: None,
})
}
/// A device of its own on the best adapter (CLI, tests, benchmarks). `None` when no
/// adapter qualifies.
#[cfg(not(target_arch = "wasm32"))]
pub fn headless() -> Option<GpuContext> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = pollster::block_on(
instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }),
)
.ok()?;
/// Switch to deferred readbacks (see [`crate::deferred`]): readbacks are never waited for.
pub fn set_deferred(&mut self, on: bool) {
self.deferred = on.then(Default::default);
}
pub fn deferred(&self) -> Option<&Arc<crate::deferred::Deferred>> {
self.deferred.as_ref()
}
/// A device of its own on the best adapter, without blocking (a browser worker: WebGPU
/// only; natively any backend). `Err` says why there is none.
pub async fn request() -> Result<GpuContext, String> {
#[allow(unused_mut)]
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
#[cfg(target_arch = "wasm32")]
{
desc.backends = wgpu::Backends::BROWSER_WEBGPU;
}
let instance = wgpu::Instance::new(desc);
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() })
.await
.map_err(|e| format!("no adapter: {e}"))?;
let limits = adapter.limits();
let required_limits = wgpu::Limits {
max_texture_dimension_2d: limits.max_texture_dimension_2d.min(16384),
max_buffer_size: limits.max_buffer_size,
..wgpu::Limits::default()
};
let (device, queue) =
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("effectcraft gpu"), required_limits, ..Default::default() }))
.ok()?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor { label: Some("effectcraft gpu"), required_limits, ..Default::default() })
.await
.map_err(|e| format!("no device: {e}"))?;
device.on_uncaptured_error(Arc::new(|e| {
// Under test a validation error (a WGSL typo invalidates every kernel) fails loudly.
if cfg!(test) {
@@ -480,12 +498,26 @@ impl GpuContext {
}
log::error!("wgpu: {e}")
}));
GpuContext::new(&adapter, device, queue).map_err(|e| log::info!("gpu: {e}")).ok()
GpuContext::new(&adapter, device, queue)
}
/// Readback (GPU → CPU) waits for the device; impossible on the browser's main thread.
/// A device of its own on the best adapter (CLI, tests, benchmarks). `None` when no
/// adapter qualifies.
#[cfg(not(target_arch = "wasm32"))]
pub fn headless() -> Option<GpuContext> {
pollster::block_on(GpuContext::request()).map_err(|e| log::info!("gpu: {e}")).ok()
}
/// Readbacks (GPU → CPU) are possible: waited for natively, or deferred (a browser
/// worker, [`crate::deferred`]). Impossible on the browser's main thread.
pub fn can_readback(&self) -> bool {
cfg!(not(target_arch = "wasm32"))
self.can_wait() || self.deferred.is_some()
}
/// Readbacks can be waited for (natively, unless deferred). Steps that read back without a
/// key ([`crate::deferred`]) need this.
pub fn can_wait(&self) -> bool {
cfg!(not(target_arch = "wasm32")) && self.deferred.is_none()
}
pub(crate) fn fits(&self, w: u32, h: u32) -> bool {
@@ -802,7 +834,7 @@ impl<'g> Enc<'g> {
/// [`Enc::read_texture`] into `out` (`w × bpp × h` bytes), through a reused staging buffer.
fn read_texture_into(&mut self, texture: &wgpu::Texture, w: u32, h: u32, bpp: u32, out: &mut [u8]) -> Option<()> {
if !self.g.can_readback() {
if !self.g.can_wait() {
return None;
}
self.g.transfers.count(false, out.len());
@@ -889,6 +921,25 @@ impl<'g> Enc<'g> {
let _ = self.g.device.poll(wgpu::PollType::Poll);
}
/// A deferred readback of `img` (RGBA f32) under `key` (see [`crate::deferred`]): the bytes
/// once they arrived (`Some(None)`: the readback failed), else `None` after starting the
/// copy if needed and marking the pass missed.
pub(crate) fn read_keyed(&mut self, img: &GpuImage, key: u128, offset: [f64; 2], scale: f64) -> Option<Option<crate::deferred::Readback>> {
use crate::deferred::Lookup;
let d = self.g.deferred.clone()?;
match d.lookup(key) {
Lookup::Ready(r) => return Some(r),
Lookup::InFlight => {}
Lookup::Absent => {
self.g.transfers.count(false, img.width as usize * img.height as usize * 16);
let done = d.start(key, img.width, img.height, offset, scale);
self.read_texture_async(&img.texture, img.width, img.height, 16, done);
}
}
d.miss();
None
}
/// A data buffer for kernels that read tables (curves).
pub fn data(&self, v: &[f32]) -> wgpu::Buffer {
let mut bytes = Vec::with_capacity(v.len().max(4) * 4);
+293
View File
@@ -0,0 +1,293 @@
//! Deferred readbacks: rendering on a device whose readbacks cannot be waited for (WebGPU in a
//! browser worker: a buffer maps only once the worker returns to its event loop).
//!
//! A frame renders in passes (see [`effectcraft_render::Accelerator::frame_begin`]). Every
//! readback the renderer needs is keyed by what determines its pixels: a GPU effect chain by
//! its input buffer's pixels and the chain's parameters, the top-level frame by comp, time and
//! render options. A key seen for the first time records the GPU work, starts an asynchronous
//! copy (`map_async`) and *misses*: the step returns a placeholder and the pass is marked missed
//! (raising the gate that keeps placeholder-derived buffers out of the layer cache). The caller
//! awaits [`Deferred::settled`] and renders again; keys whose bytes arrived are served from
//! here. A pass without a miss is the finished frame.
//!
//! Correctness: a result is only computed from genuine inputs. Pixels a chain reads are part
//! of its key, and a chain whose kernels read other data through the effect host (other layers,
//! other times) is not started when that data missed while it ran (the miss counter moved).
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use effectcraft_effects::Buf;
use effectcraft_render::FxStep;
/// Bytes read back for one key, with the geometry they describe.
#[derive(Clone, Debug)]
pub(crate) struct Readback {
pub bytes: Vec<u8>,
pub width: u32,
pub height: u32,
/// Layer buffer offset and scale (chains).
pub offset: [f64; 2],
pub scale: f64,
}
/// What [`Deferred::lookup`] knows about a key.
pub(crate) enum Lookup {
/// The bytes arrived (`None`: the readback failed; render this step another way).
Ready(Option<Readback>),
/// Started in this frame, not arrived yet.
InFlight,
/// Never asked for in this frame.
Absent,
}
#[derive(Default)]
struct State {
/// Frame generation: results of an older frame's readbacks are dropped.
generation: u64,
ready: HashMap<u128, Option<Readback>>,
waiting: HashSet<u128>,
in_flight: usize,
/// Misses so far in this frame (a counter, so a chain sees misses during its own work).
misses: u64,
wakers: Vec<Waker>,
}
/// Deferred readback state of a device (see the module docs).
#[derive(Default)]
pub struct Deferred {
st: Mutex<State>,
/// Raised from the pass's first miss to its end.
gate: Arc<AtomicBool>,
/// Passes and readbacks (diagnostics).
pub(crate) passes: std::sync::atomic::AtomicU64,
pub(crate) readbacks: std::sync::atomic::AtomicU64,
}
impl Deferred {
pub fn frame_begin(&self) {
if let Ok(mut s) = self.st.lock() {
s.generation += 1;
s.ready.clear();
s.waiting.clear();
s.misses = 0;
}
self.gate.store(false, Ordering::Relaxed);
}
pub fn pass_begin(&self) {
self.gate.store(false, Ordering::Relaxed);
self.passes.fetch_add(1, Ordering::Relaxed);
}
pub fn missed(&self) -> bool {
self.gate.load(Ordering::Relaxed)
}
pub fn gate(&self) -> Arc<AtomicBool> {
self.gate.clone()
}
/// Misses so far in this frame.
pub(crate) fn misses(&self) -> u64 {
self.st.lock().map(|s| s.misses).unwrap_or(0)
}
/// Mark the pass as missed.
pub(crate) fn miss(&self) {
if let Ok(mut s) = self.st.lock() {
s.misses += 1;
}
self.gate.store(true, Ordering::Relaxed);
}
pub(crate) fn lookup(&self, key: u128) -> Lookup {
let Ok(s) = self.st.lock() else { return Lookup::Ready(None) };
if let Some(r) = s.ready.get(&key) {
return Lookup::Ready(r.clone());
}
if s.waiting.contains(&key) { Lookup::InFlight } else { Lookup::Absent }
}
/// A readback for `key` is being started; returns the callback that stores its bytes.
pub(crate) fn start(self: &Arc<Self>, key: u128, width: u32, height: u32, offset: [f64; 2], scale: f64) -> impl FnOnce(Option<Vec<u8>>) + 'static {
let generation = match self.st.lock() {
Ok(mut s) => {
s.waiting.insert(key);
s.in_flight += 1;
s.generation
}
Err(_) => 0,
};
self.readbacks.fetch_add(1, Ordering::Relaxed);
let me = self.clone();
move |bytes: Option<Vec<u8>>| {
let wakers = match me.st.lock() {
Ok(mut s) => {
s.in_flight = s.in_flight.saturating_sub(1);
if s.generation == generation {
s.waiting.remove(&key);
s.ready.insert(key, bytes.map(|bytes| Readback { bytes, width, height, offset, scale }));
}
if s.in_flight == 0 { std::mem::take(&mut s.wakers) } else { vec![] }
}
Err(_) => vec![],
};
for w in wakers {
w.wake();
}
}
}
/// Readbacks still in flight.
pub fn in_flight(&self) -> usize {
self.st.lock().map(|s| s.in_flight).unwrap_or(0)
}
/// Resolves once no readback is in flight (on the web the browser's event loop delivers
/// them; natively a device poll does).
pub fn settled(self: &Arc<Self>) -> Settled {
Settled(self.clone())
}
}
/// See [`Deferred::settled`].
pub struct Settled(Arc<Deferred>);
impl Future for Settled {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let Ok(mut s) = self.0.st.lock() else { return Poll::Ready(()) };
if s.in_flight == 0 {
return Poll::Ready(());
}
s.wakers.push(cx.waker().clone());
Poll::Pending
}
}
/// 128-bit key from two differently seeded std hashers (deterministic within a process).
pub(crate) struct Key(std::collections::hash_map::DefaultHasher, std::collections::hash_map::DefaultHasher);
impl Key {
pub fn new(tag: u64) -> Key {
let mut a = std::collections::hash_map::DefaultHasher::new();
let mut b = std::collections::hash_map::DefaultHasher::new();
tag.hash(&mut a);
(tag ^ 0x9e37_79b9_7f4a_7c15).hash(&mut b);
0xa5u8.hash(&mut b);
Key(a, b)
}
pub fn bytes(&mut self, v: &[u8]) {
self.0.write(v);
self.1.write(v);
}
pub fn u64(&mut self, v: u64) {
self.bytes(&v.to_le_bytes());
}
pub fn f64(&mut self, v: f64) {
self.u64(v.to_bits());
}
pub fn debug(&mut self, v: &impl std::fmt::Debug) {
self.bytes(format!("{v:?}").as_bytes());
self.bytes(&[0xff]);
}
pub fn finish(&self) -> u128 {
((self.0.finish() as u128) << 64) | self.1.finish() as u128
}
}
/// Key of a GPU effect chain on `buf`: the input pixels and geometry, the bit depth, and every
/// step's effect, parameters (sorted) and context.
pub(crate) fn chain_key(chain: &[FxStep], buf: &Buf, levels: Option<f32>) -> u128 {
let mut k = Key::new(1);
k.u64(buf.img.width as u64);
k.u64(buf.img.height as u64);
k.bytes(bytemuck::cast_slice(&buf.img.data));
k.f64(buf.offset[0]);
k.f64(buf.offset[1]);
k.f64(buf.scale);
k.debug(&levels);
for s in chain {
let c = &s.ctx;
k.bytes(s.spec.id.as_bytes());
let mut names: Vec<&String> = c.params.values.keys().collect();
names.sort();
for n in names {
k.bytes(n.as_bytes());
k.debug(&c.params.values[n]);
}
k.f64(c.time);
k.f64(c.layer_size[0]);
k.f64(c.layer_size[1]);
k.u64(c.seed as u64);
k.u64(c.adjustment as u64);
let e = &c.env;
k.debug(&e.masks);
k.u64(e.host.is_some() as u64);
k.f64(e.comp_time);
k.f64(e.frame_rate);
k.u64(e.effect_index as u64);
k.debug(&e.working_space);
k.u64(e.working_linear as u64);
k.debug(&e.shutter);
}
k.finish()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys_are_stable_and_distinct() {
let mut a = Key::new(1);
a.bytes(b"abc");
let mut b = Key::new(1);
b.bytes(b"abc");
let mut c = Key::new(2);
c.bytes(b"abc");
assert_eq!(a.finish(), b.finish());
assert_ne!(a.finish(), c.finish());
}
#[test]
fn readbacks_resolve_and_old_frames_are_dropped() {
let d = Arc::new(Deferred::default());
d.frame_begin();
d.pass_begin();
assert!(matches!(d.lookup(7), Lookup::Absent));
let done = d.start(7, 2, 1, [1.0, 2.0], 0.5);
d.miss();
assert!(d.missed() && d.gate().load(Ordering::Relaxed));
assert!(matches!(d.lookup(7), Lookup::InFlight));
assert_eq!(d.in_flight(), 1);
// The settle future wakes when the last readback lands.
let mut fut = std::pin::pin!(d.settled());
let waker = Waker::noop();
assert!(fut.as_mut().poll(&mut Context::from_waker(waker)).is_pending());
done(Some(vec![1, 2, 3, 4, 5, 6, 7, 8]));
assert!(fut.as_mut().poll(&mut Context::from_waker(waker)).is_ready());
let Lookup::Ready(Some(r)) = d.lookup(7) else { panic!("not ready") };
assert_eq!((r.width, r.height, r.offset, r.scale, r.bytes.len()), (2, 1, [1.0, 2.0], 0.5, 8));
d.pass_begin();
assert!(!d.missed());
// A readback of the previous frame arriving late is dropped.
let late = d.start(9, 1, 1, [0.0; 2], 1.0);
d.frame_begin();
late(Some(vec![0; 4]));
assert!(matches!(d.lookup(9), Lookup::Absent));
assert!(matches!(d.lookup(7), Lookup::Absent));
assert_eq!(d.in_flight(), 0);
}
}
+34
View File
@@ -51,6 +51,20 @@ pub(crate) fn run_chain(e: &mut Enc, chain: &[FxStep], buf: &Buf, levels: Option
if !e.g.can_readback() || buf.img.is_empty() {
return None;
}
// Deferred readbacks (a browser worker): served by key once the bytes arrived.
let deferred = e.g.deferred.clone();
let key = deferred.as_ref().map(|_| crate::deferred::chain_key(chain, buf, levels));
if let (Some(d), Some(k)) = (&deferred, key) {
match d.lookup(k) {
crate::deferred::Lookup::Ready(r) => return r.and_then(readback_buf),
crate::deferred::Lookup::InFlight => {
d.miss();
return Some(buf.clone());
}
crate::deferred::Lookup::Absent => {}
}
}
let misses = deferred.as_ref().map(|d| d.misses());
let mut b = GBuf { img: e.g.upload_image(&buf.img)?, offset: buf.offset, scale: buf.scale };
for step in chain {
b = apply(e, step.spec.id, &step.ctx, b)?;
@@ -58,10 +72,30 @@ pub(crate) fn run_chain(e: &mut Enc, chain: &[FxStep], buf: &Buf, levels: Option
b.img = ops::quantize(e, &b.img, l);
}
}
if let (Some(d), Some(k)) = (&deferred, key) {
// Data the kernels fetched through the effect host missed meanwhile: not genuine.
if Some(d.misses()) != misses {
d.miss();
return Some(buf.clone());
}
// The placeholder (the input) keeps this pass cheap; the next pass gets the result.
return match e.read_keyed(&b.img, k, b.offset, b.scale) {
Some(r) => r.and_then(readback_buf),
None => Some(buf.clone()),
};
}
let img = e.download(&b.img)?;
Some(Buf { img, offset: b.offset, scale: b.scale })
}
/// A layer buffer from deferred readback bytes (RGBA f32).
fn readback_buf(r: crate::deferred::Readback) -> Option<Buf> {
let mut img = effectcraft_raster::Image::new(r.width, r.height);
let dst: &mut [u8] = bytemuck::cast_slice_mut(&mut img.data);
(dst.len() == r.bytes.len()).then(|| dst.copy_from_slice(&r.bytes))?;
Some(Buf { img, offset: r.offset, scale: r.scale })
}
/// An effect stack running on a GPU-resident image (adjustment layers): GPU chains stay on
/// the device; CPU effects read the image back, run, and upload the result.
pub(crate) struct GpuFx<'e, 'g> {
+101 -1
View File
@@ -49,6 +49,7 @@ mod adv3d;
mod bokeh;
mod classic3d;
mod context;
pub mod deferred;
mod effects;
mod fx_color;
mod fx_distort;
@@ -112,6 +113,44 @@ impl Gpu {
Gpu { ctx: Arc::new(ctx), auto: Default::default() }
}
/// A device of its own without blocking, with deferred readbacks (a browser worker, see
/// [`deferred`]); natively the same device works too (tests). `Err` says why there is none.
pub async fn request_deferred() -> Result<Gpu, String> {
let mut ctx = GpuContext::request().await?;
ctx.set_deferred(true);
Ok(Gpu::from_context(ctx))
}
/// [`Gpu::request_deferred`] blocking (tests of the browser worker's path, natively).
#[cfg(not(target_arch = "wasm32"))]
pub fn headless_deferred() -> Option<Gpu> {
pollster::block_on(Gpu::request_deferred()).map_err(|e| log::info!("gpu: {e}")).ok()
}
/// The deferred readback state, when readbacks are deferred.
pub fn deferred(&self) -> Option<&Arc<deferred::Deferred>> {
self.ctx.deferred()
}
/// Resolves once no deferred readback is in flight (immediately without deferred readbacks).
pub async fn settled(&self) {
if let Some(d) = self.ctx.deferred() {
d.settled().await;
}
}
/// Deliver finished readbacks without blocking (native; the browser delivers them itself).
pub fn poll(&self) {
#[cfg(not(target_arch = "wasm32"))]
let _ = self.ctx.device.poll(wgpu::PollType::Poll);
}
/// `{passes, readbacks, inFlight}` of deferred rendering (diagnostics).
pub fn deferred_stats(&self) -> Option<(u64, u64, usize)> {
let d = self.ctx.deferred()?;
Some((d.passes.load(std::sync::atomic::Ordering::Relaxed), d.readbacks.load(std::sync::atomic::Ordering::Relaxed), d.in_flight()))
}
pub fn context(&self) -> &GpuContext {
&self.ctx
}
@@ -146,11 +185,50 @@ impl Gpu {
if !self.ctx.can_readback() {
return None;
}
if let Some(d) = self.ctx.deferred.clone() {
return self.render_deferred(&d, r, comp, t);
}
let mut e = Enc::new(&self.ctx);
let img = walk::render(&mut e, r, comp, t)?;
e.download(&img)
}
/// [`Gpu::render`] with deferred readbacks: the frame's readback is keyed by comp, time and
/// render options; until it arrives (or while layer steps still miss) the pass gets a
/// placeholder.
fn render_deferred(&self, d: &Arc<deferred::Deferred>, r: &Renderer, comp: ItemId, t: Tick) -> Option<Image> {
let mut k = deferred::Key::new(2);
k.u64(comp.0);
k.u64(t.0 as u64);
k.debug(&r.opts);
let key = k.finish();
let image = |rb: deferred::Readback| -> Option<Image> {
let mut img = Image::new(rb.width, rb.height);
let dst: &mut [u8] = bytemuck::cast_slice_mut(&mut img.data);
(dst.len() == rb.bytes.len()).then(|| dst.copy_from_slice(&rb.bytes))?;
Some(img)
};
match d.lookup(key) {
deferred::Lookup::Ready(rb) => return rb.and_then(image),
deferred::Lookup::InFlight => {
d.miss();
return Some(Image::new(1, 1));
}
deferred::Lookup::Absent => {}
}
let misses = d.misses();
let mut e = Enc::new(&self.ctx);
let img = walk::render(&mut e, r, comp, t)?;
if d.misses() != misses {
// Layer steps are still in flight: this pass's canvas is not the frame.
return Some(Image::new(1, 1));
}
match e.read_keyed(&img, key, [0.0; 2], 1.0) {
Some(rb) => rb.and_then(image),
None => Some(Image::new(1, 1)),
}
}
/// Wait for all submitted GPU work (benchmarks).
pub fn wait(&self) {
let _ = self.ctx.device.poll(wgpu::PollType::wait_indefinitely());
@@ -183,12 +261,32 @@ impl Accelerator for Gpu {
}
fn particles(&self) -> Option<&dyn effectcraft_effects::psim::ParticleSim> {
self.ctx.can_readback().then_some(self as &dyn effectcraft_effects::psim::ParticleSim)
self.ctx.can_wait().then_some(self as &dyn effectcraft_effects::psim::ParticleSim)
}
fn auto_pick(&self) -> Option<&effectcraft_render::AutoPick> {
Some(&self.auto)
}
fn frame_begin(&self) {
if let Some(d) = self.ctx.deferred() {
d.frame_begin();
}
}
fn pass_begin(&self) {
if let Some(d) = self.ctx.deferred() {
d.pass_begin();
}
}
fn pass_missed(&self) -> bool {
self.ctx.deferred().is_some_and(|d| d.missed())
}
fn miss_gate(&self) -> Option<Arc<std::sync::atomic::AtomicBool>> {
self.ctx.deferred().map(|d| d.gate())
}
}
impl effectcraft_effects::psim::ParticleSim for Gpu {
@@ -206,6 +304,8 @@ mod tests_adjust;
#[cfg(test)]
mod tests_adv3d;
#[cfg(test)]
mod tests_deferred;
#[cfg(test)]
mod tests_fx_color;
#[cfg(test)]
mod tests_fx_distort;
+1 -1
View File
@@ -109,7 +109,7 @@ fn uniforms(req: &SimRequest, n: u32, s0: u64, prev_n: u32) -> Vec<u8> {
/// Simulate `req` (see [`effectcraft_effects::psim::ParticleSim`]).
pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimParticle>> {
if !g.can_readback() || req.steps > u32::MAX as u64 {
if !g.can_wait() || req.steps > u32::MAX as u64 {
return None;
}
let n = req.births.len() as u32;
+2 -1
View File
@@ -2,7 +2,8 @@
// effectcraft-effects operation for operation. Every name here is prefixed `fxn_` (the
// family files share one module).
const FXN_MAX: f32 = 3.40282347e38;
// f32::MAX exactly (a decimal that rounds above it is rejected by browsers' WGSL compilers).
const FXN_MAX: f32 = 3.4028234663852886e38;
fn fxn_pixel(gid: vec3<u32>) -> vec2<i32> {
let dims = out_dims();
+42
View File
@@ -562,3 +562,45 @@ fn backend_selection_and_display_frames() {
}
}
}
/// Browsers' WGSL compilers reject an f32 literal whose exact decimal value lies outside the f32
/// range (`3.40282347e38` rounds to f32::MAX in Rust but exceeds it), which invalidates the whole
/// module (every kernel); naga accepts it, so native runs can't catch it. Every float literal
/// with an exponent must be within the f32 range exactly.
#[test]
fn wgsl_float_literals_fit_f32() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/shaders");
let mut checked = 0;
for entry in std::fs::read_dir(&dir).unwrap() {
let path = entry.unwrap().path();
let src = std::fs::read_to_string(&path).unwrap();
for (n, line) in src.lines().enumerate() {
let code = line.split("//").next().unwrap_or("");
let bytes = code.as_bytes();
let mut i = 0;
while i < bytes.len() {
let starts = bytes[i].is_ascii_digit() && (i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_' || bytes[i - 1] == b'.'));
if !starts {
i += 1;
continue;
}
let mut j = i;
while j < bytes.len()
&& (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'.' || ((bytes[j] == b'-' || bytes[j] == b'+') && matches!(bytes[j - 1], b'e' | b'E')))
{
j += 1;
}
let lit = code[i..j].trim_end_matches('f');
if !lit.starts_with("0x")
&& lit.contains(['e', 'E'])
&& let Ok(v) = lit.parse::<f64>()
{
checked += 1;
assert!(v.abs() <= f32::MAX as f64, "{}:{}: {lit} is outside the f32 range", path.display(), n + 1);
}
i = j;
}
}
}
assert!(checked > 0);
}
+140
View File
@@ -0,0 +1,140 @@
//! Deferred readbacks (the browser worker's WebGPU path) vs the CPU: a frame renders in passes
//! until no readback is missing, and the result matches the CPU render. Natively the same
//! device works with readbacks deferred; a device poll delivers them, as the browser's event
//! loop does.
use std::sync::OnceLock;
use effectcraft_keyframe::Value;
use effectcraft_project::build;
use effectcraft_project::{BitDepth, Comp, ItemKind, LayerSource};
use effectcraft_render::{Accelerator, Backend, LayerCache, RenderOpts, Renderer};
use effectcraft_time::{FrameRate, Tick};
use crate::Gpu;
use crate::tests::{Pattern, Scene, diff, n, set, tolerance, v3};
/// The device, held exclusively: deferred state is per device and a frame renders at a time
/// (a frame worker renders one frame at a time too).
fn deferred_gpu() -> Option<(&'static Gpu, std::sync::MutexGuard<'static, ()>)> {
static G: OnceLock<Option<Gpu>> = OnceLock::new();
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
let g = G.get_or_init(|| pollster::block_on(Gpu::request_deferred()).map_err(|e| eprintln!("deferred gpu tests skipped: {e}")).ok()).as_ref()?;
Some((g, LOCK.lock().unwrap_or_else(|e| e.into_inner())))
}
/// Footage with GPU effects around a CPU-only one, a solid with Glow, and a precomp whose
/// layer is blurred inside and outside (a chain whose input is another chain's result).
fn scene() -> Scene {
let cpu_only = "ec.blur.ccradial";
assert!(!effectcraft_effects::GPU_EFFECTS.contains(&cpu_only));
let mut s = Scene::new(BitDepth::Bpc32);
let mut bg = s.footage(97, 61);
s.effect(&mut bg, "ec.blur.gaussian", &[("blurriness", n(5.0))]);
s.effect(&mut bg, cpu_only, &[]);
s.effect(&mut bg, "ec.color.levels", &[("gamma", n(1.3))]);
s.push(bg);
let mut solid = s.solid([0.9, 0.4, 0.1], 30, 20);
s.effect(&mut solid, "ec.stylize.glow", &[("threshold", n(20.0)), ("radius", n(6.0))]);
set(&mut solid, "transform/position", v3(30.0, 20.0));
s.push(solid);
// Precomp: a footage layer blurred inside; the precomp layer blurred again outside.
let inner = Comp::new(60, 40, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
let inner_id = s.p.add_item("Inner", effectcraft_color::Label::Blue, None, ItemKind::Comp(inner.clone().into()));
{
let mut ins = Scene { p: std::mem::take(&mut s.p), cid: inner_id, comp: inner };
let mut l = ins.footage(50, 30);
ins.effect(&mut l, "ec.blur.fastbox", &[("radius", n(3.0))]);
ins.push(l);
s.p = ins.p;
}
let mut pre = build::layer(&mut s.p, &s.comp, "Inner", LayerSource::Comp { item: inner_id }, (60, 40), None);
s.effect(&mut pre, "ec.blur.directional", &[("length", n(6.0)), ("direction", Value::Scalar(30.0))]);
set(&mut pre, "transform/position", v3(60.0, 35.0));
s.push(pre);
s
}
/// Render in passes with deferred readbacks; returns the frame and the number of passes.
fn render_passes(g: &Gpu, s: &Scene, opts: RenderOpts, cache: &LayerCache, t: Tick) -> (effectcraft_raster::Image, usize) {
cache.set_gate(g.miss_gate());
let mut r = Renderer::new(&s.p, &Pattern, opts);
r.accel = Some(g);
r.cache = Some(cache);
g.frame_begin();
for pass in 1..=12 {
g.pass_begin();
let img = r.comp_frame(s.cid, t);
if !g.pass_missed() {
assert_eq!(g.deferred().unwrap().in_flight(), 0);
return (img, pass);
}
// The browser awaits `Gpu::settled`; natively a blocking poll delivers the readbacks.
g.wait();
pollster::block_on(g.settled());
}
panic!("the frame never completed");
}
#[test]
fn deferred_passes_match_the_cpu() {
let Some((g, _lock)) = deferred_gpu() else { return };
assert!(g.context().can_readback() && !g.context().can_wait());
let s = scene();
let t = Tick::from_seconds_f64(0.5);
let cpu = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Cpu, ..Default::default() }).comp_frame_cpu(s.cid, t);
let tol = tolerance(BitDepth::Bpc32) * 2.0;
// The whole frame on the GPU (GPU compositor + chains + the frame's readback).
let cache = LayerCache::default();
let (img, passes) = render_passes(g, &s, RenderOpts { backend: Backend::Gpu, ..Default::default() }, &cache, t);
let d = diff(&cpu, &img, tol);
assert!(d.over == 0, "whole-frame GPU: {d:?}");
assert!(passes >= 3, "chains, the nested chain, then the frame readback: {passes} passes");
// Again (a new frame: results are per frame; the layer cache holds the genuine buffers of
// the cacheable layers): the same pixels.
let (img2, passes2) = render_passes(g, &s, RenderOpts { backend: Backend::Gpu, ..Default::default() }, &cache, t);
assert_eq!(img2.data, img.data);
assert!(passes2 <= passes, "{passes2} <= {passes}");
// CPU compositing with GPU chains (a region of interest keeps the frame off the GPU
// compositor): every placeholder is gone by the last pass.
let roi = Some([0.0, 0.0, 97.0, 61.0]);
let cpu_roi = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Cpu, roi, ..Default::default() }).comp_frame_cpu(s.cid, t);
let (img3, passes3) = render_passes(g, &s, RenderOpts { backend: Backend::Gpu, roi, ..Default::default() }, &LayerCache::default(), t);
let d = diff(&cpu_roi, &img3, tol);
assert!(d.over == 0, "CPU composite, GPU chains: {d:?}");
assert!(passes3 >= 2);
let (p, rb, inflight) = g.deferred_stats().unwrap();
assert!(p >= (passes + passes2 + passes3) as u64 && rb > 0 && inflight == 0);
}
#[test]
fn placeholders_never_reach_the_layer_cache() {
let Some((g, _lock)) = deferred_gpu() else { return };
let s = scene();
let t = Tick::from_seconds_f64(1.0);
let cache = LayerCache::default();
cache.set_gate(g.miss_gate());
let mut r = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Gpu, roi: Some([0.0, 0.0, 97.0, 61.0]), ..Default::default() });
r.accel = Some(g);
r.cache = Some(&cache);
g.frame_begin();
g.pass_begin();
let _ = r.comp_frame(s.cid, t);
assert!(g.pass_missed());
// Only buffers computed before the first miss were kept (the first layer's input up to its
// first chain: nothing with an effect result).
let first_pass_entries = cache.stats().entries;
g.wait();
pollster::block_on(g.settled());
let (img, _) = render_passes(g, &s, RenderOpts { backend: Backend::Gpu, roi: Some([0.0, 0.0, 97.0, 61.0]), ..Default::default() }, &cache, t);
assert!(cache.stats().entries > first_pass_entries, "{first_pass_entries} → {:?}", cache.stats());
// A fresh CPU render through the same cache (served from it) agrees with the CPU.
let mut cr = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Cpu, roi: Some([0.0, 0.0, 97.0, 61.0]), ..Default::default() });
cr.cache = Some(&cache);
let cached = cr.comp_frame_cpu(s.cid, t);
let fresh =
Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Cpu, roi: Some([0.0, 0.0, 97.0, 61.0]), ..Default::default() }).comp_frame_cpu(s.cid, t);
let tol = tolerance(BitDepth::Bpc32) * 2.0;
assert_eq!(diff(&fresh, &cached, tol).over, 0);
assert_eq!(diff(&fresh, &img, tol).over, 0);
}
+20
View File
@@ -32,6 +32,8 @@ use crate::eval::EvalCtx;
pub struct LayerCache {
inner: Mutex<Inner>,
disk: Mutex<Option<(Arc<crate::disk_cache::DiskCache>, u64)>>,
/// While set, inserts are dropped (see [`LayerCache::set_gate`]).
gate: Mutex<Option<Arc<std::sync::atomic::AtomicBool>>>,
}
struct Entry {
@@ -72,9 +74,24 @@ impl LayerCache {
LayerCache {
inner: Mutex::new(Inner { map: HashMap::new(), bytes: 0, budget, clock: 0, hits: 0, misses: 0, missed_at: HashMap::new() }),
disk: Mutex::new(None),
gate: Mutex::new(None),
}
}
/// Drop inserts while `gate` is set. A render whose GPU readbacks are still in flight (the
/// browser's deferred readbacks, see [`crate::Accelerator::pass_missed`]) computes some
/// buffers from placeholders; the accelerator raises the gate from its first missing
/// readback to the end of the pass, so none of them is kept (in memory or on disk).
pub fn set_gate(&self, gate: Option<Arc<std::sync::atomic::AtomicBool>>) {
if let Ok(mut g) = self.gate.lock() {
*g = gate;
}
}
fn gated(&self) -> bool {
self.gate.lock().ok().and_then(|g| g.as_ref().map(|g| g.load(std::sync::atomic::Ordering::Relaxed))).unwrap_or(false)
}
/// Attach (or detach) the disk cache. `salt` separates projects and footage versions (see
/// `footage_salt`); keys on disk are `(salt, key)`.
pub fn set_disk(&self, disk: Option<(Arc<crate::disk_cache::DiskCache>, u64)>) {
@@ -130,6 +147,9 @@ impl LayerCache {
}
pub fn insert(&self, key: u64, buf: Arc<Buf>) {
if self.gated() {
return;
}
let started = self.inner.lock().ok().and_then(|mut g| g.missed_at.remove(&key));
if let Some((dc, dk)) = self.disk_key(key) {
let slow = started.is_some_and(|t| t.elapsed().as_secs_f64() * 1e3 >= dc.min_layer_ms() as f64);
+172 -53
View File
@@ -40,7 +40,8 @@ pub enum Kind {
}
impl Kind {
fn dir(self) -> &'static str {
/// The kind's folder name.
pub fn dir(self) -> &'static str {
match self {
Kind::Frame => "frames",
Kind::Layer => "layers",
@@ -80,13 +81,98 @@ struct Meta {
last_use: u64,
}
/// The cache's index: entry sizes and least-recently-used order under a size limit. Portable
/// (no file system): [`DiskCache`] keeps one over its folder, and the browser keeps one over the
/// Origin Private File System (`apps/effectcraft-web`, where the files are written by workers).
#[derive(Default)]
struct Index {
pub struct DiskIndex {
map: HashMap<(Kind, u128), Meta>,
total: u64,
clock: u64,
}
impl DiskIndex {
/// Record an entry (`bytes` on disk) as the most recently used; replaces an older record.
pub fn insert(&mut self, kind: Kind, key: u128, bytes: u64) {
self.clock += 1;
let c = self.clock;
if let Some(old) = self.map.insert((kind, key), Meta { bytes, last_use: c }) {
self.total -= old.bytes;
}
self.total += bytes;
}
/// Mark an entry as just used (a read). `false` when it is not indexed.
pub fn touch(&mut self, kind: Kind, key: u128) -> bool {
self.clock += 1;
let c = self.clock;
match self.map.get_mut(&(kind, key)) {
Some(m) => {
m.last_use = c;
true
}
None => false,
}
}
/// Forget an entry; its size, if it was indexed.
pub fn remove(&mut self, kind: Kind, key: u128) -> Option<u64> {
let m = self.map.remove(&(kind, key))?;
self.total -= m.bytes;
Some(m.bytes)
}
pub fn contains(&self, kind: Kind, key: u128) -> bool {
self.map.contains_key(&(kind, key))
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
/// Bytes of every indexed entry.
pub fn total(&self) -> u64 {
self.total
}
/// Keys of one kind (unordered).
pub fn keys(&self, kind: Kind) -> Vec<u128> {
self.map.keys().filter(|k| k.0 == kind).map(|k| k.1).collect()
}
/// Entries from least to most recently used.
pub fn lru_order(&self) -> Vec<(Kind, u128)> {
let mut v: Vec<(u64, (Kind, u128))> = self.map.iter().map(|(k, m)| (m.last_use, *k)).collect();
v.sort_unstable_by_key(|e| e.0);
v.into_iter().map(|e| e.1).collect()
}
/// Remove least recently used entries until the total fits `max` bytes; returns them (the
/// caller deletes their files).
pub fn evict(&mut self, max: u64) -> Vec<(Kind, u128)> {
if self.total <= max {
return vec![];
}
let mut out = vec![];
for k in self.lru_order() {
if self.total <= max {
break;
}
self.remove(k.0, k.1);
out.push(k);
}
out
}
pub fn clear(&mut self) {
*self = DiskIndex::default();
}
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
enum Job {
Write(Kind, u128, Vec<u8>),
@@ -99,7 +185,7 @@ struct Queue {
pub struct DiskCache {
dir: PathBuf,
index: Mutex<Index>,
index: Mutex<DiskIndex>,
max_bytes: AtomicU64,
hits: AtomicU64,
misses: AtomicU64,
@@ -172,7 +258,7 @@ impl DiskCache {
std::fs::create_dir_all(&dir)?;
let dc = Arc::new(DiskCache {
dir,
index: Mutex::new(Index::default()),
index: Mutex::new(DiskIndex::default()),
max_bytes: AtomicU64::new(max_bytes),
hits: AtomicU64::new(0),
misses: AtomicU64::new(0),
@@ -223,12 +309,9 @@ impl DiskCache {
}
}
found.sort_by_key(|e| e.0);
let mut idx = Index::default();
let mut idx = DiskIndex::default();
for (_, kind, key, bytes) in found {
idx.clock += 1;
let clock = idx.clock;
idx.total += bytes;
idx.map.insert((kind, key), Meta { bytes, last_use: clock });
idx.insert(kind, key, bytes);
}
if let Ok(mut g) = self.index.lock() {
*g = idx;
@@ -260,16 +343,16 @@ impl DiskCache {
}
pub fn contains(&self, kind: Kind, key: u128) -> bool {
self.index.lock().is_ok_and(|g| g.map.contains_key(&(kind, key)))
self.index.lock().is_ok_and(|g| g.contains(kind, key))
}
/// Keys of one kind (unordered).
pub fn keys(&self, kind: Kind) -> Vec<u128> {
self.index.lock().map(|g| g.map.keys().filter(|k| k.0 == kind).map(|k| k.1).collect()).unwrap_or_default()
self.index.lock().map(|g| g.keys(kind)).unwrap_or_default()
}
pub fn stats(&self) -> DiskStats {
let (entries, bytes) = self.index.lock().map(|g| (g.map.len(), g.total)).unwrap_or_default();
let (entries, bytes) = self.index.lock().map(|g| (g.len(), g.total())).unwrap_or_default();
DiskStats {
entries,
bytes,
@@ -286,7 +369,7 @@ impl DiskCache {
pub fn clear(&self) {
self.flush();
if let Ok(mut g) = self.index.lock() {
*g = Index::default();
g.clear();
}
for kind in [Kind::Frame, Kind::Layer] {
let _ = std::fs::remove_dir_all(self.dir.join(kind.dir()));
@@ -322,11 +405,7 @@ impl DiskCache {
let payload = payload.to_vec();
self.hits.fetch_add(1, Ordering::Relaxed);
if let Ok(mut g) = self.index.lock() {
g.clock += 1;
let c = g.clock;
if let Some(m) = g.map.get_mut(&(kind, key)) {
m.last_use = c;
}
g.touch(kind, key);
}
// Persist the recency for the next session (best effort).
if let Ok(f) = std::fs::File::options().append(true).open(&path) {
@@ -347,10 +426,8 @@ impl DiskCache {
}
fn forget(&self, kind: Kind, key: u128) {
if let Ok(mut g) = self.index.lock()
&& let Some(m) = g.map.remove(&(kind, key))
{
g.total -= m.bytes;
if let Ok(mut g) = self.index.lock() {
g.remove(kind, key);
}
}
@@ -382,13 +459,7 @@ impl DiskCache {
if std::fs::create_dir_all(parent).is_err() {
return;
}
let mut data = Vec::with_capacity(payload.len() + 16);
data.extend_from_slice(MAGIC);
data.push(kind.tag());
data.extend_from_slice(&[0, 0, 0]);
data.extend_from_slice(payload);
let sum = checksum(&data);
data.extend_from_slice(&sum.to_le_bytes());
let data = seal(kind, payload);
let n = self.tmp_counter.fetch_add(1, Ordering::Relaxed);
let tmp = parent.join(format!("{key:032x}.tmp.{}.{n}", std::process::id()));
if std::fs::write(&tmp, &data).is_err() {
@@ -401,13 +472,7 @@ impl DiskCache {
}
self.writes.fetch_add(1, Ordering::Relaxed);
if let Ok(mut g) = self.index.lock() {
g.clock += 1;
let c = g.clock;
let bytes = data.len() as u64;
if let Some(old) = g.map.insert((kind, key), Meta { bytes, last_use: c }) {
g.total -= old.bytes;
}
g.total += bytes;
g.insert(kind, key, data.len() as u64);
}
self.evict();
}
@@ -415,23 +480,9 @@ impl DiskCache {
/// Remove least recently used entries until the cache fits its limit.
fn evict(&self) {
let max = self.max_bytes();
let victims: Vec<(Kind, u128)> = {
let Ok(mut g) = self.index.lock() else { return };
if g.total <= max {
return;
}
let mut by_age: Vec<(u64, (Kind, u128), u64)> = g.map.iter().map(|(k, m)| (m.last_use, *k, m.bytes)).collect();
by_age.sort_unstable_by_key(|e| e.0);
let mut out = vec![];
for (_, k, bytes) in by_age {
if g.total <= max {
break;
}
g.map.remove(&k);
g.total -= bytes;
out.push(k);
}
out
let victims = match self.index.lock() {
Ok(mut g) => g.evict(max),
Err(_) => return,
};
for (kind, key) in victims {
let _ = std::fs::remove_file(self.path(kind, key));
@@ -510,6 +561,40 @@ fn writer(dc: std::sync::Weak<DiskCache>, q: Arc<(Mutex<Queue>, Condvar)>) {
}
}
/// An entry file's bytes: header (magic, kind), payload, checksum.
pub fn seal(kind: Kind, payload: &[u8]) -> Vec<u8> {
let mut data = Vec::with_capacity(payload.len() + 16);
data.extend_from_slice(MAGIC);
data.push(kind.tag());
data.extend_from_slice(&[0, 0, 0]);
data.extend_from_slice(payload);
let sum = checksum(&data);
data.extend_from_slice(&sum.to_le_bytes());
data
}
/// A sealed frame entry ([`seal`] of the encoded frame): what the browser's frame workers
/// write to the Origin Private File System.
pub fn frame_entry(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
seal(Kind::Frame, &encode_frame(width, height, rgba))
}
/// A frame from a sealed entry's bytes (`None` when damaged).
pub fn read_frame_entry(data: &[u8]) -> Option<Frame8> {
decode_frame(verify(data, Kind::Frame)?)
}
/// An entry's file name in its kind's folder (`<32 hex>.ecc`).
pub fn entry_name(key: u128) -> String {
format!("{key:032x}.ecc")
}
/// The key of an entry file name (`None` for temporaries and other files).
pub fn parse_entry_name(name: &str) -> Option<u128> {
let hex = name.strip_suffix(".ecc")?;
(hex.len() == 32).then(|| u128::from_str_radix(hex, 16).ok()).flatten()
}
/// Check magic, kind and checksum; returns the payload.
fn verify(d: &[u8], kind: Kind) -> Option<&[u8]> {
if d.len() < 16 || &d[..4] != MAGIC || d[4] != kind.tag() {
@@ -707,6 +792,40 @@ mod tests {
Buf { img, offset: [1.5, -2.25], scale: 0.5 }
}
#[test]
fn index_evicts_least_recently_used() {
let mut ix = DiskIndex::default();
ix.insert(Kind::Frame, 1, 100);
ix.insert(Kind::Frame, 2, 100);
ix.insert(Kind::Layer, 3, 100);
assert_eq!((ix.len(), ix.total()), (3, 300));
assert!(ix.touch(Kind::Frame, 1));
assert!(!ix.touch(Kind::Frame, 3));
assert_eq!(ix.lru_order(), vec![(Kind::Frame, 2), (Kind::Layer, 3), (Kind::Frame, 1)]);
assert_eq!(ix.evict(250), vec![(Kind::Frame, 2)]);
assert!(ix.evict(250).is_empty());
ix.insert(Kind::Frame, 1, 50);
assert_eq!(ix.total(), 150);
assert_eq!(ix.remove(Kind::Layer, 3), Some(100));
assert_eq!(ix.keys(Kind::Frame), vec![1]);
ix.clear();
assert!(ix.is_empty() && ix.total() == 0);
}
#[test]
fn frame_entries_round_trip_and_names_parse() {
let rgba: Vec<u8> = (0..4 * 6 * 3).map(|i| (i * 7 % 256) as u8).collect();
let e = frame_entry(6, 3, &rgba);
assert_eq!(read_frame_entry(&e), Some(Frame8 { width: 6, height: 3, rgba: rgba.clone() }));
let mut bad = e.clone();
bad[20] ^= 1;
assert!(read_frame_entry(&bad).is_none());
let key = 0x0123_4567_89ab_cdef_0011_2233_4455_6677u128;
assert_eq!(parse_entry_name(&entry_name(key)), Some(key));
assert_eq!(parse_entry_name("abc.ecc"), None);
assert_eq!(parse_entry_name(&format!("{key:032x}.tmp.1")), None);
}
#[test]
fn hit_miss_and_exact_round_trip() {
let dir = tmpdir("hit");
+17
View File
@@ -296,6 +296,23 @@ pub trait Accelerator: Send + Sync {
fn auto_pick(&self) -> Option<&AutoPick> {
None
}
/// Deferred readbacks: where a GPU readback cannot be waited for (WebGPU in a browser
/// worker), a frame renders in *passes*. A readback the accelerator does not have yet is
/// started, the step returns a cheap placeholder and the pass is marked missed
/// ([`Self::pass_missed`]); the caller waits for the readbacks in flight (asynchronously)
/// and renders the frame again, and the steps whose results arrived are served from them.
/// The frame is done after a pass with no miss. `frame_begin` forgets the previous frame's
/// results, `pass_begin` clears the miss. Synchronous accelerators never miss.
fn frame_begin(&self) {}
fn pass_begin(&self) {}
fn pass_missed(&self) -> bool {
false
}
/// Raised from a pass's first miss to its end (results computed meanwhile may hold
/// placeholders): give it to [`LayerCache::set_gate`] so they are not cached.
fn miss_gate(&self) -> Option<Arc<std::sync::atomic::AtomicBool>> {
None
}
}
/// Where an effect stack runs (see [`Renderer::run_effects_on`]): a CPU buffer, or an image
+50 -4
View File
@@ -172,6 +172,9 @@ pub struct RemoteJob {
pub comp: ItemId,
pub t: Tick,
pub opts: RenderOpts,
/// The frame's disk-cache key, when the renderer keeps a disk cache
/// ([`RemoteFrames::disk`]): served from it on a hit, stored there after a render.
pub disk_key: Option<u128>,
}
/// Premultiplied RGBA8 pixels from a [`RemoteFrames`] renderer.
@@ -195,6 +198,31 @@ pub trait RemoteFrames: Send + Sync {
fn start(&self, job: RemoteJob, done: RemoteDone);
/// Drop cached intermediate results (Edit ▸ Purge).
fn purge(&self) {}
/// It renders GPU effects (its own GPU device): frames with effects go to it rather than
/// the UI thread's GPU compositor, which would run their effects on the CPU.
fn gpu(&self) -> bool {
false
}
/// It keeps a disk cache of frames (the browser's Origin Private File System).
fn disk(&self) -> bool {
false
}
/// The disk cache holds the frame of this key (the blue cache bar).
fn disk_contains(&self, _key: u128) -> bool {
false
}
}
/// Whether a comp (or a comp it nests) has a layer with enabled effects.
pub fn comp_has_effects(project: &Project, comp: ItemId) -> bool {
fn walk(p: &Project, comp: ItemId, depth: usize) -> bool {
let Some(c) = p.comp(comp) else { return false };
c.layers.iter().any(|l| {
l.switches.effects && l.effects().is_some_and(|fx| fx.groups().any(|g| g.enabled))
|| depth < 16 && matches!(l.source, effectcraft_engine::project::LayerSource::Comp { item } if walk(p, item, depth + 1))
})
}
walk(project, comp, 0)
}
pub struct Frames {
@@ -283,14 +311,22 @@ impl Frames {
/// Frames of (revision, comp, scale) in the disk cache but not in RAM — the blue cache bar.
/// `opts` are the viewer's render options (part of the disk key).
pub fn disk_frames(&self, src: &RenderSource, revision: u64, comp: u64, scale: u32, view: u64, frames: i64, opts: &RenderOpts) -> Vec<i64> {
let Some(dc) = &src.disk else { return vec![] };
let remote = self.remote.as_ref().filter(|r| r.disk());
let contains = |k: u128| match (&src.disk, remote) {
(Some(dc), _) => dc.contains(disk_cache::Kind::Frame, k),
(None, Some(r)) => r.disk_contains(k),
(None, None) => false,
};
if src.disk.is_none() && remote.is_none() {
return vec![];
}
let ram: HashSet<i64> = self.cached_frames(revision, comp, scale).into_iter().collect();
let oh = opts_hash(opts);
(0..frames.clamp(0, 100_000))
.filter(|f| !ram.contains(f))
.filter(|f| {
let key = FrameKey { revision, comp, frame: *f, scale, view };
dc.contains(disk_cache::Kind::Frame, frame_disk_key(&self.content_keys, &src.project, &key, oh))
contains(frame_disk_key(&self.content_keys, &src.project, &key, oh))
})
.collect()
}
@@ -396,6 +432,11 @@ impl Frames {
self.remote = remote;
}
/// The remote renderer keeps a disk cache (the browser's).
pub fn remote_disk(&self) -> bool {
self.remote.as_ref().is_some_and(|r| r.disk())
}
/// Whether frames go to a usable [`RemoteFrames`].
pub fn remote_active(&self) -> bool {
self.remote.as_ref().is_some_and(|r| r.slots() > 0)
@@ -435,7 +476,11 @@ impl Frames {
}
job
};
if job.src.gpu.is_some() && job.src.gpu_display {
// The GPU compositor here keeps the frame on the GPU, but runs layer effects on the
// CPU (this thread can't wait for readbacks): frames with effects go to workers
// that render them on their own GPU.
let gpu_here = job.src.gpu.is_some() && job.src.gpu_display && !(remote.gpu() && comp_has_effects(&job.src.project, job.comp));
if gpu_here {
let t0 = web_time::Instant::now();
if let Some(img) = w.render_gpu(&job) {
w.finish(&job, img, t0);
@@ -450,7 +495,8 @@ impl Frames {
let fw = self.worker();
let busy = self.remote_busy.clone();
let t0 = web_time::Instant::now();
let rj = RemoteJob { project: job.src.project.clone(), revision: key.revision, comp: job.comp, t: job.t, opts: job.opts };
let disk_key = remote.disk().then(|| frame_disk_key(&w.content_keys, &job.src.project, &key, opts_hash(&job.opts)));
let rj = RemoteJob { project: job.src.project.clone(), revision: key.revision, comp: job.comp, t: job.t, opts: job.opts, disk_key };
remote.start(
rj,
Box::new(move |r: Result<RemoteFrame, String>| {
+88
View File
@@ -60,6 +60,7 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value
}
}
Item::Labels => labels_ui(app, ui, cur, acts),
Item::BrowserStorage => browser_storage_ui(app, ui, t, acts),
Item::AudioDevices { key } => {
let devices: Vec<String> = app.hooks.audio_devices.as_ref().map(|f| f()).unwrap_or_default();
let sel = get(key).as_str().unwrap_or("").to_string();
@@ -193,6 +194,93 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value
}
}
/// Bytes as "12.3 MB".
pub fn human_bytes(b: u64) -> String {
let units = ["bytes", "KB", "MB", "GB", "TB"];
let mut v = b as f64;
let mut u = 0;
while v >= 1000.0 && u + 1 < units.len() {
v /= 1000.0;
u += 1;
}
if u == 0 { format!("{b} bytes") } else { format!("{v:.1} {}", units[u]) }
}
/// Settings ▸ Disk ▸ Browser Storage (the web app's storage manager, `storage.*`): where the
/// data lives, the origin's usage and quota, persistent storage, and Clear buttons.
fn browser_storage_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, t: &Tokens, acts: &mut Vec<Act>) {
let Some(host) = app.session.storage.clone() else { return };
let info = host.info();
let u = |v: &Value| v.as_u64().unwrap_or(0);
ui.add_space(6.0);
ui.label(RichText::new("Browser Storage").font(Tokens::semibold(12.5)).color(t.tab_text_active));
ui.separator();
let backend = match info["backend"].as_str().unwrap_or("") {
"opfs" => "Origin Private File System",
"indexeddb" => "IndexedDB",
"memory" => "Memory only: nothing is kept after a reload",
"" => "Unknown",
other => other,
};
let r = ui.label(format!("Stored in: {backend}"));
reg(app, "settings.storage.backend", &r, backend);
let (usage, quota) = (u(&info["usage"]), u(&info["quota"]));
let frac = if quota > 0 { usage as f32 / quota as f32 } else { 0.0 };
let text = if quota > 0 { format!("{} of {} used ({:.1} %)", human_bytes(usage), human_bytes(quota), frac * 100.0) } else { "Usage unknown".into() };
let r = ui
.horizontal(|ui| {
ui.add(egui::ProgressBar::new(frac.clamp(0.0, 1.0)).desired_width(220.0).desired_height(8.0));
ui.label(&text);
})
.response;
reg(app, "settings.storage.usage", &r, &text);
let f = &info["files"];
let row = |what: &str, k: &str| format!("{what}: {} ({})", u(&f[k]["count"]), human_bytes(u(&f[k]["bytes"])));
ui.label(
RichText::new(format!("{} · {} · {}", row("Projects", "projects"), row("Imported media", "media"), row("Auto-saves", "autoSaves"))).color(t.text_dim),
);
let d = &info["diskCache"];
let dc = if d["enabled"].as_bool().unwrap_or(false) {
format!(
"Disk cache: {} frames, {} of {} (hits {}, misses {})",
u(&d["entries"]),
human_bytes(u(&d["bytes"])),
human_bytes(u(&d["maxBytes"])),
u(&d["hits"]),
u(&d["misses"])
)
} else {
"Disk cache: off".into()
};
let r = ui.label(RichText::new(&dc).color(t.text_dim));
reg(app, "settings.storage.diskCache", &r, &dc);
ui.horizontal(|ui| {
let persisted = info["persisted"].as_bool().unwrap_or(false);
let state = if persisted { "Persistent storage: granted" } else { "Persistent storage: not granted (the browser may clear it when space runs low)" };
ui.label(state);
if !persisted {
let r = ui.button("Request Persistent Storage");
reg(app, "settings.storage.persist", &r, "Request Persistent Storage");
if r.clicked() {
acts.push(Act::Run("storage.persist".into(), json!({})));
}
}
});
ui.horizontal_wrapped(|ui| {
for (what, label) in
[("diskCache", "Clear Disk Cache"), ("media", "Clear Imported Media"), ("autoSaves", "Clear Auto-Saves"), ("projects", "Clear Saved Projects")]
{
let r = ui.button(label);
reg(app, &format!("settings.storage.clear.{what}"), &r, label);
if r.clicked() {
acts.push(Act::Run("storage.clear".into(), json!({"what": what})));
}
}
});
// The numbers refresh in the background.
ui.ctx().request_repaint_after(std::time::Duration::from_secs(1));
}
fn labels_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, cur: &Value, acts: &mut Vec<Act>) {
ui.label("Label Colors and Names:");
ui.add_space(4.0);
+1 -1
View File
@@ -957,7 +957,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
draw_run(a, b);
}
// Disk-cached frames not in RAM (blue), like After Effects.
if app.session.disk_cache.is_some() {
if app.session.disk_cache.is_some() || app.frames.remote_disk() {
let frames = comp.frame_rate.frame_at(comp.duration);
let opts = app.frame_opts(cid, scale_key as f64 / 1000.0);
let disk = app.frames.disk_frames(&app.render_source(), app.session.revision, cid.0, scale_key, app.view_hash(cid), frames, &opts);
+237
View File
@@ -0,0 +1,237 @@
//! Headless checks for M13.24 (web app depth: GPU frame workers, the browser's disk cache, the
//! storage manager), run natively with stand-ins for the browser:
//!
//! - a frame worker with its own GPU device and deferred readbacks (the browser worker's
//! WebGPU path) renders frames with GPU effects in passes; the page's own GPU compositor
//! keeps frames without effects, and frames with effects go to the worker;
//! - frames the worker rendered are stored under their disk-cache keys (an in-memory stand-in
//! for the Origin Private File System) and served from there after a "reload" (a new frame
//! cache), without rendering; the blue cache bar sees them;
//! - Settings ▸ Disk shows the browser storage manager when the session has a storage host,
//! and its buttons run `storage.*` commands.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use effectcraft_engine::Session;
use effectcraft_engine::remote::{FrameMsg, FrameReply, FrameServer, Mirror};
use effectcraft_engine::render::RenderOpts;
use effectcraft_engine::render::disk_cache;
use effectcraft_engine::storage::StorageHost;
use effectcraft_gpu::Gpu;
use effectcraft_ui_egui::EffectcraftApp;
use effectcraft_ui_egui::control::{self, ControlRequest, Outcome};
use effectcraft_ui_egui::frames::{FrameImage, FrameKey, Frames, RemoteDone, RemoteFrame, RemoteFrames, RemoteJob, RenderSource};
use egui_kittest::Harness;
use serde_json::{Value, json};
fn rt<T: serde::Serialize + for<'de> serde::Deserialize<'de>>(v: &T) -> T {
serde_json::from_str(&serde_json::to_string(v).unwrap()).unwrap()
}
/// A GPU frame worker in this process, with a "disk" shared across reloads.
struct GpuWorker {
gpu: Gpu,
state: Mutex<(Mirror, FrameServer, u64)>,
disk: Arc<Mutex<HashMap<u128, Vec<u8>>>>,
rendered: Mutex<Vec<(u32, bool)>>,
}
impl GpuWorker {
fn new(s: &Session, gpu: Gpu, disk: Arc<Mutex<HashMap<u128, Vec<u8>>>>) -> GpuWorker {
let mut server = FrameServer::new(s.footage.clone(), s.expr.clone());
server.set_accel(Some(Arc::new(gpu.clone())));
GpuWorker { gpu, state: Mutex::new((Mirror::default(), server, 0)), disk, rendered: Mutex::default() }
}
}
impl RemoteFrames for GpuWorker {
fn slots(&self) -> usize {
1
}
fn gpu(&self) -> bool {
true
}
fn disk(&self) -> bool {
true
}
fn disk_contains(&self, key: u128) -> bool {
self.disk.lock().unwrap().contains_key(&key)
}
fn start(&self, job: RemoteJob, done: RemoteDone) {
// The page reads a hit from the disk cache instead of asking the worker.
if let Some(k) = job.disk_key
&& let Some(f) = self.disk.lock().unwrap().get(&k).and_then(|e| disk_cache::read_frame_entry(e))
{
return done(Ok(RemoteFrame { width: f.width, height: f.height, rgba: f.rgba, ms: 0.0 }));
}
let mut st = self.state.lock().unwrap();
let (mirror, server, next) = &mut *st;
if let Some(m) = mirror.sync(job.revision, &job.project) {
assert!(server.handle(rt(&m)).is_empty());
}
*next += 1;
let disk = job.disk_key.map(|k| format!("{k:032x}"));
let mut out = server.handle(rt(&FrameMsg::Render {
id: *next,
revision: job.revision,
comp: job.comp,
time: job.t,
opts: Box::new(job.opts),
disk: disk.clone(),
}));
// The worker awaits its device between passes (`Gpu::settled`); natively a poll.
while server.waiting() {
self.gpu.wait();
pollster::block_on(self.gpu.settled());
out = server.resume();
}
match out.into_iter().next() {
Some((FrameReply::Frame { width, height, ms, passes, gpu, .. }, Some(rgba))) => {
self.rendered.lock().unwrap().push((passes, gpu));
if let Some(k) = job.disk_key {
self.disk.lock().unwrap().insert(k, disk_cache::frame_entry(width, height, &rgba));
}
done(Ok(RemoteFrame { width, height, rgba, ms }))
}
other => done(Err(format!("{:?}", other.map(|o| o.0)))),
}
}
}
fn source(s: &Session, gpu: Option<Gpu>) -> RenderSource {
RenderSource {
project: s.project.clone(),
footage: s.footage.clone(),
expr: s.expr.clone(),
layer_cache: s.layer_cache.clone(),
gpu,
gpu_display: true,
disk: None,
}
}
fn cpu_pixels(f: &FrameImage) -> Vec<egui::Color32> {
match f {
FrameImage::Cpu(c) => c.pixels.clone(),
FrameImage::Gpu(_) => panic!("expected a CPU frame"),
}
}
#[test]
fn gpu_worker_renders_effect_frames_and_the_disk_cache_survives_a_reload() {
let (Some(page_gpu), Some(worker_gpu)) = (Gpu::headless(), Gpu::headless_deferred()) else {
eprintln!("no GPU adapter: skipped");
return;
};
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Fx", "width": 160, "height": 90, "frameRate": 30, "duration": 1})).unwrap();
let plain = s.active_comp_id().unwrap();
s.execute("layer.newSolid", json!({"color": "#3080ff", "width": 80, "height": 40})).unwrap();
s.execute("comp.new", json!({"name": "Blurred", "width": 160, "height": 90, "frameRate": 30, "duration": 1})).unwrap();
let fx = s.active_comp_id().unwrap();
s.execute("layer.newSolid", json!({"color": "#ff8030", "width": 80, "height": 40})).unwrap();
s.execute("effect.apply", json!({"layer": "#1", "effect": "Gaussian Blur"})).unwrap();
s.execute("prop.set", json!({"layer": "#1", "path": "effects/#1/blurriness", "value": 12})).unwrap();
let opts = RenderOpts { backend: effectcraft_engine::render::Backend::Gpu, ..Default::default() };
let t = effectcraft_engine::time::Tick::ZERO;
let key = |comp: effectcraft_engine::project::ItemId| FrameKey { revision: s.revision, comp: comp.0, frame: 0, scale: 1000, view: 0 };
let disk = Arc::new(Mutex::new(HashMap::new()));
let worker = Arc::new(GpuWorker::new(&s, worker_gpu.clone(), disk.clone()));
let mut frames = Frames::default();
frames.set_remote(Some(worker.clone()));
// No effects: the page's GPU compositor keeps the frame on the GPU.
frames.request_urgent(&source(&s, Some(page_gpu.clone())), key(plain), plain, t, opts);
frames.dispatch_remote();
assert!(matches!(frames.get(&key(plain)), Some(FrameImage::Gpu(_))));
assert!(worker.rendered.lock().unwrap().is_empty());
// GPU effects: the worker renders the frame on its GPU, in passes.
frames.request_urgent(&source(&s, Some(page_gpu.clone())), key(fx), fx, t, opts);
frames.dispatch_remote();
let got = cpu_pixels(&frames.get(&key(fx)).expect("rendered by the worker"));
let (passes, on_gpu) = worker.rendered.lock().unwrap()[0];
assert!(on_gpu && passes >= 2, "passes {passes}");
let want = effectcraft_ui_egui::frames::to_color_image(&s.render(fx, t, RenderOpts { backend: effectcraft_engine::render::Backend::Cpu, ..opts }));
let worst = got.iter().zip(&want.pixels).map(|(a, b)| (0..4).map(|c| (a[c] as i32 - b[c] as i32).abs()).max().unwrap()).max().unwrap();
assert!(worst <= 2, "GPU vs CPU: {worst}/255");
assert_eq!(disk.lock().unwrap().len(), 1, "stored under its disk key");
// "Reload": a new frame cache and worker; the frame comes from the disk cache.
let worker2 = Arc::new(GpuWorker::new(&s, worker_gpu, disk.clone()));
let mut frames2 = Frames::default();
frames2.set_remote(Some(worker2.clone()));
assert!(frames2.remote_disk());
let bar = frames2.disk_frames(&source(&s, None), s.revision, fx.0, 1000, 0, 30, &opts);
assert_eq!(bar, vec![0], "the blue cache bar shows the stored frame");
frames2.request_urgent(&source(&s, Some(page_gpu)), key(fx), fx, t, opts);
frames2.dispatch_remote();
assert_eq!(cpu_pixels(&frames2.get(&key(fx)).unwrap()), got);
assert!(worker2.rendered.lock().unwrap().is_empty(), "a hit is not rendered again");
}
#[derive(Default)]
struct Storage {
cleared: Mutex<Vec<String>>,
persist_asked: Mutex<bool>,
}
impl StorageHost for Storage {
fn info(&self) -> Value {
json!({"backend": "opfs", "usage": 52_000_000u64, "quota": 2_000_000_000u64, "persisted": false,
"files": {"projects": {"count": 2, "bytes": 40000}, "media": {"count": 3, "bytes": 50_000_000u64}, "autoSaves": {"count": 1, "bytes": 20000}},
"diskCache": {"enabled": true, "entries": 12, "bytes": 1_500_000, "maxBytes": 1_000_000_000u64, "hits": 4, "misses": 12}})
}
fn request_persist(&self) -> Value {
*self.persist_asked.lock().unwrap() = true;
json!({"requested": true})
}
fn clear(&self, what: &str) -> Result<Value, String> {
self.cleared.lock().unwrap().push(what.into());
Ok(json!({"cleared": what, "entries": 1, "bytes": 1}))
}
}
fn send(h: &mut Harness<'_, EffectcraftApp>, method: &str, params: Value) {
let ctx = h.ctx.clone();
let (req, _rx) = ControlRequest::new(method, params);
if let Outcome::Done(v) = control::handle(h.state_mut(), &ctx, &req) {
assert!(v["ok"] != false, "{method}: {v}");
}
// kittest doesn't call `raw_input_hook`: feed the synthetic click in.
for e in h.state_mut().take_synthetic_input() {
h.event(e);
}
h.run_steps(3);
}
#[test]
fn settings_disk_page_shows_the_browser_storage_manager() {
let mut s = Session::default();
let host = Arc::new(Storage::default());
s.storage = Some(host.clone());
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(2);
effectcraft_ui_egui::panels::settings::open(h.state_mut(), "disk");
h.run_steps(3);
for id in [
"settings.storage.backend",
"settings.storage.usage",
"settings.storage.diskCache",
"settings.storage.persist",
"settings.storage.clear.diskCache",
"settings.storage.clear.media",
] {
assert!(h.state().auto.find(id).is_some(), "{id} is registered");
}
let usage = h.state().auto.find("settings.storage.usage").unwrap().label.clone();
assert!(usage.contains("52.0 MB of 2.0 GB"), "{usage}");
send(&mut h, "ui.click", json!({"id": "settings.storage.clear.diskCache"}));
send(&mut h, "ui.click", json!({"id": "settings.storage.persist"}));
assert_eq!(*host.cleared.lock().unwrap(), vec!["diskCache".to_string()]);
assert!(*host.persist_asked.lock().unwrap());
// Without a host (the desktop) the section is not there.
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(Session::default()));
h.run_steps(2);
effectcraft_ui_egui::panels::settings::open(h.state_mut(), "disk");
h.run_steps(3);
assert!(h.state().auto.find("settings.storage.usage").is_none());
}
+1 -1
View File
@@ -69,7 +69,7 @@ impl RemoteFrames for FakeWorker {
assert!(server.handle(rt(&m)).is_empty());
}
*next += 1;
let out = server.handle(rt(&FrameMsg::Render { id: *next, revision: job.revision, comp: job.comp, time: job.t, opts: Box::new(job.opts) }));
let out = server.handle(rt(&FrameMsg::Render { id: *next, revision: job.revision, comp: job.comp, time: job.t, opts: Box::new(job.opts), disk: None }));
match out.into_iter().next() {
Some((FrameReply::Frame { width, height, ms, .. }, Some(rgba))) => pending.push((done, RemoteFrame { width, height, rgba, ms })),
other => done(Err(format!("{:?}", other.map(|o| o.0)))),