M13.24: web app depth (WEB-1) — GPU effects in frame workers, OPFS disk cache, storage manager
- GPU in the browser: each frame worker opens its own WebGPU device (Gpu::request_deferred) and renders the GPU compositor and GPU effects with deferred readbacks (effectcraft-gpu deferred): readbacks keyed by content start with map_async and miss, the pass returns placeholders, the layer cache's gate drops inserts, and FrameServer::resume renders again once the device delivered. Backend Auto times whole frames per comp in the workers. Frames with effects go to GPU workers instead of the page. CPU fallback without WebGPU in workers (?nogpuworkers). - Fix: a WGSL constant (3.40282347e38) that Chrome rejects invalidated every GPU kernel in Chrome (the page's compositor too); a test checks every float literal fits f32. - Disk cache in the Origin Private File System: workers write sealed frame entries with sync access handles (temp file + move), the page keeps the DiskIndex (LRU under the settings' limit, at most half the quota) and reads hits instead of rendering; survives reloads; blue cache bar. - Storage manager: Settings ▸ Disk ▸ Browser Storage (usage/quota, persistent storage, Clear buttons, automation ids) and storage.info / storage.persist / storage.clear (StorageHost). - Docs: web.md (GPU workers, deferred passes, disk cache, storage manager, threading design: one engine instance per worker), architecture, preferences, parity (WEB-1), roadmap. - Tests: deferred passes vs CPU on a real device, placeholder gating, frame server passes and Auto, GPU worker routing + disk cache across a reload, storage commands and widgets, store usage by kind; smoke test: GPU effect frames in workers with pixel parity, disk hits after a reload, storage manager. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
081ce79de3
commit
1b726349ab
@@ -21,6 +21,7 @@ serde_json = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
effectcraft-host = { workspace = true }
|
||||
effectcraft-gpu = { workspace = true }
|
||||
effectcraft-media = { workspace = true }
|
||||
effectcraft-export = { workspace = true }
|
||||
effectcraft-expr = { workspace = true }
|
||||
|
||||
@@ -105,6 +105,14 @@ export async function storeLoadAll() { return backend.loadAll(); }
|
||||
export async function storePut(key, data, modified) { return backend.put(key, data, modified); }
|
||||
export async function storeDelete(key) { return backend.del(key); }
|
||||
|
||||
/// Ask the browser to keep the origin's storage under pressure; resolves with whether it is.
|
||||
export async function storePersist() {
|
||||
try {
|
||||
if (navigator.storage && navigator.storage.persist) return await navigator.storage.persist();
|
||||
} catch {}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// {usage, quota, persisted, backend}.
|
||||
export async function storeEstimate() {
|
||||
const out = { backend: backend ? backend.name : null };
|
||||
@@ -341,8 +349,10 @@ export function workerStats() {
|
||||
const frameWorkers = [];
|
||||
|
||||
/// Start a frame worker; returns its index. `onMessage(index, json, bytes, error)` receives each
|
||||
/// `frameReply` (JSON, pixels as a Uint8Array) or, if the worker dies, the error.
|
||||
export function frameWorkerStart(base, onMessage) {
|
||||
/// `frameReply` (JSON, pixels as a Uint8Array) or, if the worker dies, the error. `gpu`: the
|
||||
/// worker opens its own WebGPU device (when the browser has WebGPU in workers) and renders
|
||||
/// GPU effects on it.
|
||||
export function frameWorkerStart(base, onMessage, gpu) {
|
||||
const index = frameWorkers.length;
|
||||
const worker = new Worker(new URL("worker.js", base), { type: "module", name: `effectcraft-frames-${index}` });
|
||||
worker.onmessage = (e) => {
|
||||
@@ -353,11 +363,105 @@ export function frameWorkerStart(base, onMessage) {
|
||||
onMessage(index, undefined, undefined, String(e.message || "frame worker failed"));
|
||||
worker.terminate();
|
||||
};
|
||||
worker.postMessage({ type: "init", module: self.effectcraftModule ?? null, base });
|
||||
worker.postMessage({ type: "init", module: self.effectcraftModule ?? null, base, frames: true, gpu: !!gpu });
|
||||
frameWorkers.push(worker);
|
||||
return index;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ disk cache (OPFS)
|
||||
|
||||
// The disk cache's frames (src/diskcache.rs): one file per frame under
|
||||
// effectcraft-cache/v1/frames/<32 hex>.ecc in the Origin Private File System. Frame workers write
|
||||
// them with synchronous access handles (a temporary file moved into place, so a reader never
|
||||
// sees a partial entry; every entry also ends in a checksum); the page lists, reads and deletes.
|
||||
const CACHE_ROOT = "effectcraft-cache";
|
||||
const CACHE_PATH = [CACHE_ROOT, "v1", "frames"];
|
||||
let cacheDirHandle = null;
|
||||
|
||||
async function cacheDir() {
|
||||
if (cacheDirHandle) return cacheDirHandle;
|
||||
if (!navigator.storage || !navigator.storage.getDirectory) throw new Error("no Origin Private File System");
|
||||
let d = await navigator.storage.getDirectory();
|
||||
for (const n of CACHE_PATH) d = await d.getDirectoryHandle(n, { create: true });
|
||||
cacheDirHandle = d;
|
||||
return d;
|
||||
}
|
||||
|
||||
/// Every cached entry: [{name, size, modified}]. Temporaries older than ten minutes (a writer
|
||||
/// that died) are removed.
|
||||
export async function cacheList() {
|
||||
const dir = await cacheDir();
|
||||
const out = [];
|
||||
const stale = [];
|
||||
for await (const [name, h] of dir.entries()) {
|
||||
if (h.kind !== "file") continue;
|
||||
const f = await h.getFile();
|
||||
if (name.includes(".tmp")) {
|
||||
if (Date.now() - f.lastModified > 600000) stale.push(name);
|
||||
continue;
|
||||
}
|
||||
out.push({ name, size: f.size, modified: f.lastModified });
|
||||
}
|
||||
for (const n of stale) { try { await dir.removeEntry(n); } catch {} }
|
||||
return out;
|
||||
}
|
||||
|
||||
/// An entry's bytes.
|
||||
export async function cacheRead(name) {
|
||||
const dir = await cacheDir();
|
||||
const f = await (await dir.getFileHandle(name)).getFile();
|
||||
return new Uint8Array(await f.arrayBuffer());
|
||||
}
|
||||
|
||||
/// Write an entry (in a worker: a synchronous access handle; elsewhere a writable stream);
|
||||
/// resolves with its size.
|
||||
export async function cacheWrite(name, bytes) {
|
||||
const dir = await cacheDir();
|
||||
const canMove = typeof FileSystemHandle !== "undefined" && "move" in FileSystemHandle.prototype;
|
||||
const tmp = canMove ? `${name}.tmp.${Math.random().toString(36).slice(2)}` : name;
|
||||
const fh = await dir.getFileHandle(tmp, { create: true });
|
||||
if (fh.createSyncAccessHandle) {
|
||||
const h = await fh.createSyncAccessHandle();
|
||||
try {
|
||||
h.truncate(0);
|
||||
h.write(bytes, { at: 0 });
|
||||
h.flush();
|
||||
} finally {
|
||||
h.close();
|
||||
}
|
||||
} else {
|
||||
const w = await fh.createWritable();
|
||||
await w.write(bytes);
|
||||
await w.close();
|
||||
}
|
||||
if (canMove) {
|
||||
try { await fh.move(dir, name); } catch (e) { try { await dir.removeEntry(tmp); } catch {} throw e; }
|
||||
}
|
||||
return bytes.length;
|
||||
}
|
||||
|
||||
/// Delete entries (names); missing ones are ignored.
|
||||
export async function cacheDelete(names) {
|
||||
const dir = await cacheDir();
|
||||
for (const n of names) { try { await dir.removeEntry(n); } catch {} }
|
||||
}
|
||||
|
||||
/// Delete the whole cache.
|
||||
export async function cacheClear() {
|
||||
cacheDirHandle = null;
|
||||
try {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
await root.removeEntry(CACHE_ROOT, { recursive: true });
|
||||
} catch (e) {
|
||||
if (e.name !== "NotFoundError") throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this thread has WebGPU (`navigator.gpu`).
|
||||
export function hasWebGpu() {
|
||||
return !!(self.navigator && self.navigator.gpu);
|
||||
}
|
||||
|
||||
/// Post a message ({type: "frame", json} or {type: "file", path, bytes}) to frame worker `index`.
|
||||
export function frameWorkerPost(index, msg, transfer) {
|
||||
const w = frameWorkers[index];
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use effectcraft_engine::Session;
|
||||
|
||||
use crate::{api, audio, browse, files, frames, persist, worker};
|
||||
use crate::{api, audio, browse, diskcache, files, frames, persist, storage, worker};
|
||||
use effectcraft_ui_egui::EffectcraftApp;
|
||||
use serde_json::json;
|
||||
use wasm_bindgen::prelude::*;
|
||||
@@ -104,6 +104,10 @@ impl eframe::App for WebApp {
|
||||
}
|
||||
api::set_info("gpu", json!({"compositor": self.app.gpu_adapter(), "viewerOnGpu": self.app.viewer_on_gpu()}));
|
||||
api::set_info("frameWorkers", frames::stats());
|
||||
// Settings ▸ Disk ▸ Disk Cache (frames in the Origin Private File System).
|
||||
let d = &self.app.session.prefs.disk;
|
||||
diskcache::configure(d.disk_cache_enabled, d.disk_cache_max_gb, storage::quota());
|
||||
api::set_info("diskCache", diskcache::stats());
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
@@ -139,6 +143,7 @@ pub fn session() -> Session {
|
||||
config: Some(Arc::new(persist::config())),
|
||||
offload: (!query_flag("noworkers")).then(|| Arc::new(worker::WorkerOffload) as Arc<dyn effectcraft_engine::offload::Offload>),
|
||||
browser: Some(Arc::new(browse::WebBrowser)),
|
||||
storage: Some(Arc::new(storage::WebStorage)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -186,6 +191,8 @@ pub async fn start(canvas_id: String) -> Result<(), JsValue> {
|
||||
api::set_info("storage", json!({"backend": persist::backend(), "entries": stored, "loadMs": js_sys::Date::now() - t0}));
|
||||
audio::install_unlock();
|
||||
browse::restore();
|
||||
diskcache::init();
|
||||
storage::refresh();
|
||||
let runner = eframe::WebRunner::new();
|
||||
runner
|
||||
.start(
|
||||
@@ -210,10 +217,11 @@ pub async fn start(canvas_id: String) -> Result<(), JsValue> {
|
||||
}
|
||||
install_hooks(&mut app);
|
||||
// Viewer frames render in frame workers (`?frameworkers=N`, 0 or `?noworkers`:
|
||||
// on the page's thread).
|
||||
// on the page's thread), each on its own WebGPU device where the browser has
|
||||
// WebGPU in workers (`?nogpuworkers`: their CPU).
|
||||
let n = if query_flag("noworkers") { 0 } else { query_value("frameworkers").and_then(|v| v.parse().ok()).unwrap_or(2usize).min(8) };
|
||||
if n > 0 {
|
||||
app.frames.set_remote(Some(Arc::new(frames::WebFrames::start(n))));
|
||||
app.frames.set_remote(Some(Arc::new(frames::WebFrames::start(n, !query_flag("nogpuworkers")))));
|
||||
}
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
api::set_sender(tx);
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
//! The disk cache (Settings ▸ Disk ▸ Disk Cache) in the browser: viewer frames kept in the
|
||||
//! Origin Private File System between visits, with the size limit from the settings and
|
||||
//! least-recently-used eviction.
|
||||
//!
|
||||
//! - **Writes** happen in the frame workers: a render request carries the frame's disk-cache key
|
||||
//! (`effectcraft_engine::remote::FrameMsg::Render`), the worker posts the frame, then writes
|
||||
//! the sealed entry (`disk_cache::frame_entry`: LZ4, checksum) with a synchronous access
|
||||
//! handle into a temporary file moved into place (`js/host.js` `cacheWrite`), and reports
|
||||
//! `FrameReply::Stored`.
|
||||
//! - **The index** lives here, on the page ([`DiskIndex`], shared with the desktop's cache):
|
||||
//! rebuilt at startup from the folder listing (oldest files first), updated by the workers'
|
||||
//! `Stored` replies and by reads; eviction deletes the least recently used files.
|
||||
//! - **Reads** are asynchronous: a frame whose key is indexed is read and decoded here instead
|
||||
//! of rendering it (`crate::frames`); a damaged or missing file is a miss and is forgotten.
|
||||
//!
|
||||
//! Only frames are cached on disk in the browser (the desktop also keeps slow layer buffers):
|
||||
//! a layer lookup happens in the middle of a synchronous render, where the browser's file
|
||||
//! system can't be read.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use effectcraft_engine::render::disk_cache::{self, DiskIndex, Kind};
|
||||
use serde_json::{Value, json};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
#[wasm_bindgen(module = "/js/host.js")]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_name = cacheList)]
|
||||
fn cache_list() -> js_sys::Promise;
|
||||
#[wasm_bindgen(js_name = cacheRead)]
|
||||
fn cache_read(name: &str) -> js_sys::Promise;
|
||||
#[wasm_bindgen(js_name = cacheWrite)]
|
||||
pub(crate) fn cache_write(name: &str, bytes: js_sys::Uint8Array) -> js_sys::Promise;
|
||||
#[wasm_bindgen(js_name = cacheDelete)]
|
||||
fn cache_delete(names: js_sys::Array) -> js_sys::Promise;
|
||||
#[wasm_bindgen(js_name = cacheClear)]
|
||||
fn cache_clear() -> js_sys::Promise;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
index: DiskIndex,
|
||||
/// The folder was listed (lookups before then miss).
|
||||
loaded: bool,
|
||||
/// The Origin Private File System works here.
|
||||
available: bool,
|
||||
/// Settings ▸ Disk ▸ Enable Disk Cache.
|
||||
enabled: bool,
|
||||
max_bytes: u64,
|
||||
hits: u64,
|
||||
misses: u64,
|
||||
writes: u64,
|
||||
evictions: u64,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ST: RefCell<State> = RefCell::new(State { enabled: true, max_bytes: 1 << 30, ..Default::default() });
|
||||
}
|
||||
|
||||
fn js_err(e: JsValue) -> String {
|
||||
e.as_string().or_else(|| js_sys::Reflect::get(&e, &"message".into()).ok().and_then(|m| m.as_string())).unwrap_or_else(|| format!("{e:?}"))
|
||||
}
|
||||
|
||||
/// List the cache folder and build the index (in the background).
|
||||
pub fn init() {
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
match JsFuture::from(cache_list()).await {
|
||||
Ok(list) => {
|
||||
let mut entries: Vec<(f64, u128, u64)> = js_sys::Array::from(&list)
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let get = |k: &str| js_sys::Reflect::get(&e, &k.into()).ok();
|
||||
let key = disk_cache::parse_entry_name(&get("name")?.as_string()?)?;
|
||||
Some((get("modified")?.as_f64().unwrap_or(0.0), key, get("size")?.as_f64().unwrap_or(0.0) as u64))
|
||||
})
|
||||
.collect();
|
||||
entries.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
for (_, key, bytes) in entries {
|
||||
s.index.insert(Kind::Frame, key, bytes);
|
||||
}
|
||||
s.loaded = true;
|
||||
s.available = true;
|
||||
});
|
||||
evict();
|
||||
}
|
||||
Err(e) => {
|
||||
let e = js_err(e);
|
||||
log::info!("disk cache unavailable: {e}");
|
||||
ST.with(|s| s.borrow_mut().error = Some(e));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Apply the settings: on/off and the limit (`max_gb`, at most half the origin's quota when it
|
||||
/// is known).
|
||||
pub fn configure(enabled: bool, max_gb: u32, quota: Option<u64>) {
|
||||
let mut max = (max_gb.max(1) as u64) << 30;
|
||||
if let Some(q) = quota.filter(|q| *q > 0) {
|
||||
max = max.min(q / 2);
|
||||
}
|
||||
let changed = ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
let changed = s.enabled != enabled || s.max_bytes != max;
|
||||
s.enabled = enabled;
|
||||
s.max_bytes = max;
|
||||
changed
|
||||
});
|
||||
if changed {
|
||||
evict();
|
||||
}
|
||||
}
|
||||
|
||||
/// The cache is usable: listed, available and enabled.
|
||||
pub fn active() -> bool {
|
||||
ST.with(|s| {
|
||||
let s = s.borrow();
|
||||
s.loaded && s.available && s.enabled
|
||||
})
|
||||
}
|
||||
|
||||
/// The frame of `key` is cached.
|
||||
pub fn contains(key: u128) -> bool {
|
||||
active() && ST.with(|s| s.borrow().index.contains(Kind::Frame, key))
|
||||
}
|
||||
|
||||
/// A lookup missed (counted for the statistics).
|
||||
pub fn note_miss() {
|
||||
ST.with(|s| s.borrow_mut().misses += 1);
|
||||
}
|
||||
|
||||
/// Read and decode a cached frame; `None` (forgotten and deleted) when the file is missing or
|
||||
/// damaged.
|
||||
pub async fn read(key: u128) -> Option<disk_cache::Frame8> {
|
||||
let name = disk_cache::entry_name(key);
|
||||
let bytes = JsFuture::from(cache_read(&name)).await.ok().and_then(|b| b.dyn_into::<js_sys::Uint8Array>().ok()).map(|b| b.to_vec());
|
||||
let frame = bytes.as_deref().and_then(disk_cache::read_frame_entry);
|
||||
ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
if frame.is_some() {
|
||||
s.hits += 1;
|
||||
s.index.touch(Kind::Frame, key);
|
||||
} else {
|
||||
s.misses += 1;
|
||||
s.index.remove(Kind::Frame, key);
|
||||
}
|
||||
});
|
||||
if frame.is_none() && bytes.is_some() {
|
||||
delete(vec![name]);
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
/// A worker stored the frame of `key` (`bytes` on disk).
|
||||
pub fn stored(key: u128, bytes: u64) {
|
||||
ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
s.index.insert(Kind::Frame, key, bytes);
|
||||
s.writes += 1;
|
||||
});
|
||||
evict();
|
||||
}
|
||||
|
||||
fn evict() {
|
||||
let victims = ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
let max = if s.enabled { s.max_bytes } else { u64::MAX };
|
||||
let v = s.index.evict(max);
|
||||
s.evictions += v.len() as u64;
|
||||
v
|
||||
});
|
||||
if !victims.is_empty() {
|
||||
delete(victims.into_iter().map(|(_, k)| disk_cache::entry_name(k)).collect());
|
||||
}
|
||||
}
|
||||
|
||||
fn delete(names: Vec<String>) {
|
||||
let arr = js_sys::Array::new();
|
||||
for n in names {
|
||||
arr.push(&JsValue::from_str(&n));
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let _ = JsFuture::from(cache_delete(arr)).await;
|
||||
});
|
||||
}
|
||||
|
||||
/// Delete every cached frame; returns (entries, bytes) removed.
|
||||
pub fn clear() -> (u64, u64) {
|
||||
let r = ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
let r = (s.index.len() as u64, s.index.total());
|
||||
s.index.clear();
|
||||
r
|
||||
});
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
if let Err(e) = JsFuture::from(cache_clear()).await {
|
||||
log::warn!("disk cache: clearing failed: {}", js_err(e));
|
||||
}
|
||||
});
|
||||
r
|
||||
}
|
||||
|
||||
/// `cache.diskStats` / `storage.info().diskCache`.
|
||||
pub fn stats() -> Value {
|
||||
ST.with(|s| {
|
||||
let s = s.borrow();
|
||||
json!({
|
||||
"enabled": s.enabled && s.available,
|
||||
"available": s.available,
|
||||
"loaded": s.loaded,
|
||||
"folder": "Origin Private File System: effectcraft-cache/v1/frames",
|
||||
"entries": s.index.len(),
|
||||
"frames": s.index.len(),
|
||||
"layers": 0,
|
||||
"bytes": s.index.total(),
|
||||
"maxBytes": s.max_bytes,
|
||||
"hits": s.hits,
|
||||
"misses": s.misses,
|
||||
"writes": s.writes,
|
||||
"evictions": s.evictions,
|
||||
"error": s.error,
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -6,27 +6,39 @@
|
||||
//! time, then diffs: [`Mirror`]); the frame comes back as premultiplied RGBA8 in a transferred
|
||||
//! buffer. One frame per worker at a time, so the page always decides what renders next (the
|
||||
//! viewer's frame before prefetch). A worker that fails is dropped; with none left, frames render
|
||||
//! on the page's thread again (`Frames::pump`).
|
||||
//! on the page's thread again (`Frames::pump`). With the disk cache on, a frame whose key is
|
||||
//! cached is read from the Origin Private File System instead ([`crate::diskcache`]); the
|
||||
//! others are stored there by the worker that renders them.
|
||||
//!
|
||||
//! **Worker side** — [`worker_frame`]: the worker's [`FrameServer`] (footage from the worker's
|
||||
//! media pool, expressions) handles each message and posts its replies.
|
||||
//! **Worker side** — [`worker_frame_init`] / [`worker_frame`]: the worker's [`FrameServer`]
|
||||
//! (footage from the worker's media pool, expressions) handles each message and posts its
|
||||
//! replies. Where the browser has WebGPU in workers, the worker opens its own device
|
||||
//! ([`Gpu::request_deferred`]) and renders GPU effects and the GPU compositor on it: a frame
|
||||
//! takes several passes, awaiting the device's readbacks in between (they can't be waited for
|
||||
//! synchronously, even in a worker), and Backend Auto picks CPU or GPU per comp from measured
|
||||
//! frame times. Without WebGPU, frames render on the worker's CPU.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_engine::offload::footage_files;
|
||||
use effectcraft_engine::remote::{FrameMsg, FrameReply, FrameServer, Mirror};
|
||||
use effectcraft_gpu::Gpu;
|
||||
use effectcraft_ui_egui::frames::{RemoteDone, RemoteFrame, RemoteFrames, RemoteJob};
|
||||
use serde_json::{Value, json};
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
#[wasm_bindgen(module = "/js/host.js")]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_name = frameWorkerStart)]
|
||||
fn frame_worker_start(base: &str, on_message: &js_sys::Function) -> u32;
|
||||
fn frame_worker_start(base: &str, on_message: &js_sys::Function, gpu: bool) -> u32;
|
||||
#[wasm_bindgen(js_name = frameWorkerPost)]
|
||||
fn frame_worker_post(index: u32, msg: &JsValue, transfer: &js_sys::Array);
|
||||
#[wasm_bindgen(js_name = hasWebGpu)]
|
||||
fn has_web_gpu() -> bool;
|
||||
}
|
||||
|
||||
/// One frame worker as the page sees it.
|
||||
@@ -36,6 +48,8 @@ struct Fw {
|
||||
files: HashSet<String>,
|
||||
busy: Option<(u64, RemoteDone)>,
|
||||
alive: bool,
|
||||
/// Its GPU adapter (after it reported), or why it has none.
|
||||
gpu: Option<Result<String, String>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -48,6 +62,11 @@ struct State {
|
||||
/// Bytes of project sync messages sent (diffs keep this small).
|
||||
sync_bytes: u64,
|
||||
syncs: u64,
|
||||
/// Frames rendered through a worker's GPU, and the passes of the last one.
|
||||
gpu_frames: u64,
|
||||
last_passes: u32,
|
||||
/// Frames served from the disk cache.
|
||||
disk_hits: u64,
|
||||
}
|
||||
|
||||
type OnMessage = Closure<dyn FnMut(u32, JsValue, JsValue, JsValue)>;
|
||||
@@ -57,6 +76,8 @@ thread_local! {
|
||||
static HANDLER: RefCell<Option<OnMessage>> = const { RefCell::new(None) };
|
||||
/// The worker's frame server (worker side).
|
||||
static SERVER: RefCell<Option<FrameServer>> = const { RefCell::new(None) };
|
||||
/// The worker's GPU device (worker side).
|
||||
static GPU: RefCell<Option<Gpu>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
fn obj(pairs: &[(&str, JsValue)]) -> JsValue {
|
||||
@@ -71,31 +92,22 @@ fn obj(pairs: &[(&str, JsValue)]) -> JsValue {
|
||||
pub struct WebFrames;
|
||||
|
||||
impl WebFrames {
|
||||
/// Start `n` frame workers.
|
||||
pub fn start(n: usize) -> WebFrames {
|
||||
/// Start `n` frame workers; `gpu`: each opens its own WebGPU device where it can.
|
||||
pub fn start(n: usize, gpu: bool) -> WebFrames {
|
||||
let on: OnMessage = Closure::new(|index: u32, json: JsValue, bytes: JsValue, error: JsValue| on_message(index, json, bytes, error));
|
||||
STATE.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
for _ in 0..n {
|
||||
let index = frame_worker_start(&crate::page_url(""), on.as_ref().unchecked_ref());
|
||||
s.workers.push(Fw { index, mirror: Mirror::default(), files: HashSet::new(), busy: None, alive: true });
|
||||
let index = frame_worker_start(&crate::page_url(""), on.as_ref().unchecked_ref(), gpu);
|
||||
s.workers.push(Fw { index, mirror: Mirror::default(), files: HashSet::new(), busy: None, alive: true, gpu: None });
|
||||
}
|
||||
});
|
||||
HANDLER.with(|h| *h.borrow_mut() = Some(on));
|
||||
WebFrames
|
||||
}
|
||||
}
|
||||
|
||||
impl RemoteFrames for WebFrames {
|
||||
fn slots(&self) -> usize {
|
||||
STATE.with(|s| s.borrow().workers.iter().filter(|w| w.alive).count())
|
||||
}
|
||||
|
||||
fn purge(&self) {
|
||||
purge();
|
||||
}
|
||||
|
||||
fn start(&self, job: RemoteJob, done: RemoteDone) {
|
||||
/// Send `job` to an idle worker.
|
||||
fn render(&self, job: RemoteJob, done: RemoteDone) {
|
||||
let r = STATE.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
s.next_id += 1;
|
||||
@@ -121,7 +133,8 @@ impl RemoteFrames for WebFrames {
|
||||
sent = t.len() as u64;
|
||||
frame_worker_post(index, &obj(&[("type", "frame".into()), ("json", t.into())]), &js_sys::Array::new());
|
||||
}
|
||||
let req = FrameMsg::Render { id, revision: job.revision, comp: job.comp, time: job.t, opts: Box::new(job.opts) };
|
||||
let disk = job.disk_key.map(|k| format!("{k:032x}"));
|
||||
let req = FrameMsg::Render { id, revision: job.revision, comp: job.comp, time: job.t, opts: Box::new(job.opts), disk };
|
||||
frame_worker_post(
|
||||
index,
|
||||
&obj(&[("type", "frame".into()), ("json", serde_json::to_string(&req).unwrap_or_default().into())]),
|
||||
@@ -140,6 +153,49 @@ impl RemoteFrames for WebFrames {
|
||||
}
|
||||
}
|
||||
|
||||
impl RemoteFrames for WebFrames {
|
||||
fn slots(&self) -> usize {
|
||||
STATE.with(|s| s.borrow().workers.iter().filter(|w| w.alive).count())
|
||||
}
|
||||
|
||||
fn purge(&self) {
|
||||
purge();
|
||||
}
|
||||
|
||||
fn gpu(&self) -> bool {
|
||||
STATE.with(|s| s.borrow().workers.iter().any(|w| w.alive && matches!(w.gpu, Some(Ok(_)))))
|
||||
}
|
||||
|
||||
fn disk(&self) -> bool {
|
||||
crate::diskcache::active()
|
||||
}
|
||||
|
||||
fn disk_contains(&self, key: u128) -> bool {
|
||||
crate::diskcache::contains(key)
|
||||
}
|
||||
|
||||
fn start(&self, job: RemoteJob, done: RemoteDone) {
|
||||
// A frame in the disk cache is read, not rendered (a failed read renders it).
|
||||
if let Some(k) = job.disk_key {
|
||||
if crate::diskcache::contains(k) {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match crate::diskcache::read(k).await {
|
||||
Some(f) => {
|
||||
STATE.with(|s| s.borrow_mut().disk_hits += 1);
|
||||
done(Ok(RemoteFrame { width: f.width, height: f.height, rgba: f.rgba, ms: 0.0 }));
|
||||
}
|
||||
None => WebFrames.render(job, done),
|
||||
}
|
||||
crate::repaint();
|
||||
});
|
||||
return;
|
||||
}
|
||||
crate::diskcache::note_miss();
|
||||
}
|
||||
self.render(job, done);
|
||||
}
|
||||
}
|
||||
|
||||
/// A message from frame worker `index`: a JSON [`FrameReply`] (with the pixels in `bytes`), or
|
||||
/// `error` when the worker died.
|
||||
fn on_message(index: u32, json: JsValue, bytes: JsValue, error: JsValue) {
|
||||
@@ -154,11 +210,15 @@ fn on_message(index: u32, json: JsValue, bytes: JsValue, error: JsValue) {
|
||||
}
|
||||
let reply: FrameReply = serde_json::from_str(&json.as_string()?).ok()?;
|
||||
match reply {
|
||||
FrameReply::Frame { id, width, height, ms } => {
|
||||
FrameReply::Frame { id, width, height, ms, passes, gpu } => {
|
||||
let (_, d) = w.busy.take_if(|b| b.0 == id)?;
|
||||
let rgba = bytes.dyn_into::<js_sys::Uint8Array>().map(|b| b.to_vec()).unwrap_or_default();
|
||||
st.rendered += 1;
|
||||
st.last_ms = ms;
|
||||
if gpu {
|
||||
st.gpu_frames += 1;
|
||||
st.last_passes = passes;
|
||||
}
|
||||
Some((d, Ok(RemoteFrame { width, height, rgba, ms })))
|
||||
}
|
||||
FrameReply::Failed { id, error, .. } => {
|
||||
@@ -171,6 +231,20 @@ fn on_message(index: u32, json: JsValue, bytes: JsValue, error: JsValue) {
|
||||
w.mirror.reset();
|
||||
None
|
||||
}
|
||||
FrameReply::Stored { key, bytes } => {
|
||||
if let Ok(k) = u128::from_str_radix(&key, 16) {
|
||||
crate::diskcache::stored(k, bytes);
|
||||
}
|
||||
None
|
||||
}
|
||||
FrameReply::Info { gpu, error } => {
|
||||
match (&gpu, &error) {
|
||||
(Some(g), _) => log::info!("frame worker {index}: GPU {g}"),
|
||||
(None, e) => log::info!("frame worker {index}: CPU only ({})", e.as_deref().unwrap_or("no GPU")),
|
||||
}
|
||||
w.gpu = Some(gpu.ok_or_else(|| error.unwrap_or_default()));
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some((d, r)) = done {
|
||||
@@ -207,6 +281,15 @@ pub fn purge() {
|
||||
pub fn stats() -> Value {
|
||||
STATE.with(|s| {
|
||||
let s = s.borrow();
|
||||
let gpu: Vec<Value> = s
|
||||
.workers
|
||||
.iter()
|
||||
.map(|w| match &w.gpu {
|
||||
Some(Ok(name)) => json!(name),
|
||||
Some(Err(e)) => json!({"cpu": e}),
|
||||
None => Value::Null,
|
||||
})
|
||||
.collect();
|
||||
json!({
|
||||
"workers": s.workers.len(),
|
||||
"alive": s.workers.iter().filter(|w| w.alive).count(),
|
||||
@@ -216,16 +299,150 @@ pub fn stats() -> Value {
|
||||
"lastMs": s.last_ms,
|
||||
"syncs": s.syncs,
|
||||
"syncBytes": s.sync_bytes,
|
||||
"gpu": gpu,
|
||||
"gpuFrames": s.gpu_frames,
|
||||
"lastPasses": s.last_passes,
|
||||
"diskHits": s.disk_hits,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// `workerFrameCheck` promises waiting for their frame: id → (resolve, reject, local frame).
|
||||
#[allow(clippy::type_complexity)]
|
||||
static CHECKS: RefCell<std::collections::HashMap<u64, (js_sys::Function, js_sys::Function, (u32, u32, Vec<u8>), f64)>> = RefCell::new(Default::default());
|
||||
}
|
||||
|
||||
/// `effectcraft.workerFrameCheck({time?, scale?, backend?})`: render the active comp's frame in
|
||||
/// a frame worker (backend `gpu` by default: the worker's WebGPU device) and on the page's CPU
|
||||
/// with the same render options, and compare them. Resolves with `{width, height, maxDiff,
|
||||
/// meanDiff, over4, workerMs, gpuFrames}` (differences in 8-bit levels; `over4`: the fraction
|
||||
/// of channels more than 4 levels apart). Rejects when no worker is idle (try again).
|
||||
#[wasm_bindgen(js_name = workerFrameCheck)]
|
||||
pub fn worker_frame_check(params: JsValue) -> js_sys::Promise {
|
||||
let get = |k: &str| js_sys::Reflect::get(¶ms, &k.into()).ok().filter(|v| !v.is_undefined());
|
||||
let time = get("time").and_then(|v| v.as_f64());
|
||||
let scale = get("scale").and_then(|v| v.as_f64()).unwrap_or(0.5);
|
||||
let backend = get("backend").and_then(|v| v.as_string()).unwrap_or_else(|| "gpu".into());
|
||||
js_sys::Promise::new(&mut |resolve, reject| {
|
||||
let backend = backend.clone();
|
||||
crate::post(move |app| {
|
||||
let s = &app.session;
|
||||
let Some(comp) = s.active_comp_id() else {
|
||||
let _ = reject.call1(&JsValue::NULL, &"no active composition".into());
|
||||
return;
|
||||
};
|
||||
let t = time.map(effectcraft_engine::time::Tick::from_seconds_f64).unwrap_or_else(|| s.time());
|
||||
let mut opts = app.frame_opts(comp, scale);
|
||||
opts.backend = match backend.as_str() {
|
||||
"cpu" => effectcraft_engine::render::Backend::Cpu,
|
||||
"auto" => effectcraft_engine::render::Backend::Auto,
|
||||
_ => effectcraft_engine::render::Backend::Gpu,
|
||||
};
|
||||
let local = {
|
||||
let mut r = effectcraft_engine::render::Renderer::new(
|
||||
&s.project,
|
||||
s.footage.as_ref(),
|
||||
effectcraft_engine::render::RenderOpts { backend: effectcraft_engine::render::Backend::Cpu, ..opts },
|
||||
);
|
||||
r.expr = s.expr.as_deref();
|
||||
let img = r.comp_frame(comp, t);
|
||||
(img.width, img.height, effectcraft_engine::remote::rgba8_premultiplied(&img))
|
||||
};
|
||||
let id = STATE.with(|st| {
|
||||
let mut st = st.borrow_mut();
|
||||
st.next_id += 1;
|
||||
st.next_id
|
||||
});
|
||||
CHECKS.with(|c| c.borrow_mut().insert(id, (resolve.clone(), reject.clone(), local, js_sys::Date::now())));
|
||||
let job = RemoteJob { project: s.project.clone(), revision: s.revision, comp, t, opts, disk_key: None };
|
||||
WebFrames.render(
|
||||
job,
|
||||
Box::new(move |r: Result<RemoteFrame, String>| {
|
||||
let Some((resolve, reject, (w, h, want), t0)) = CHECKS.with(|c| c.borrow_mut().remove(&id)) else { return };
|
||||
match r {
|
||||
Ok(f) if (f.width, f.height) == (w, h) && f.rgba.len() == want.len() => {
|
||||
let (mut max, mut sum, mut over) = (0u32, 0u64, 0u64);
|
||||
for (a, b) in f.rgba.iter().zip(&want) {
|
||||
let d = (*a as i32 - *b as i32).unsigned_abs();
|
||||
max = max.max(d);
|
||||
sum += d as u64;
|
||||
over += (d > 4) as u64;
|
||||
}
|
||||
let n = want.len().max(1) as f64;
|
||||
let c = ((h / 2 * w + w / 2) * 4) as usize;
|
||||
let v = json!({"width": w, "height": h, "maxDiff": max, "meanDiff": sum as f64 / n, "over4": over as f64 / n,
|
||||
"workerMs": f.ms, "wallMs": js_sys::Date::now() - t0, "gpuFrames": stats()["gpuFrames"],
|
||||
"center": [&f.rgba[c..c + 4], &want[c..c + 4]]});
|
||||
let _ = resolve.call1(&JsValue::NULL, &JsValue::from_str(&v.to_string()));
|
||||
}
|
||||
Ok(f) => {
|
||||
let _ = reject.call1(&JsValue::NULL, &format!("size {}x{} vs {w}x{h}", f.width, f.height).into());
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = reject.call1(&JsValue::NULL, &e.into());
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- worker side
|
||||
|
||||
/// Handle one frame message (a JSON [`FrameMsg`]) in a frame worker; replies are posted with
|
||||
/// their pixels transferred.
|
||||
fn post_reply(r: &FrameReply, px: Option<&[u8]>) {
|
||||
let scope: web_sys::DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
|
||||
let t = serde_json::to_string(r).unwrap_or_default();
|
||||
let res = match px {
|
||||
Some(px) => {
|
||||
let buf = js_sys::Uint8Array::from(px).buffer();
|
||||
scope.post_message_with_transfer(
|
||||
&obj(&[("type", "frameReply".into()), ("json", t.into()), ("bytes", buf.clone().into())]),
|
||||
&js_sys::Array::of1(&buf),
|
||||
)
|
||||
}
|
||||
None => scope.post_message(&obj(&[("type", "frameReply".into()), ("json", t.into())])),
|
||||
};
|
||||
if let Err(e) = res {
|
||||
log::warn!("frame worker: postMessage: {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn new_server() -> FrameServer {
|
||||
FrameServer::new(crate::worker::pool(), Some(Arc::new(effectcraft_expr::Expressions)))
|
||||
}
|
||||
|
||||
/// Set up a frame worker (called once by `web/worker.js` after `workerInit`): its frame
|
||||
/// server and, with `gpu` and WebGPU in workers, its own GPU device. Reports
|
||||
/// [`FrameReply::Info`].
|
||||
#[wasm_bindgen(js_name = workerFrameInit)]
|
||||
pub async fn worker_frame_init(gpu: bool) {
|
||||
let mut server = new_server();
|
||||
let info = if !gpu {
|
||||
FrameReply::Info { gpu: None, error: Some("GPU frame workers are off (?nogpuworkers)".into()) }
|
||||
} else if !has_web_gpu() {
|
||||
FrameReply::Info { gpu: None, error: Some("no WebGPU in workers".into()) }
|
||||
} else {
|
||||
match Gpu::request_deferred().await {
|
||||
Ok(g) => {
|
||||
let name = effectcraft_engine::render::Accelerator::name(&g);
|
||||
server.set_accel(Some(Arc::new(g.clone())));
|
||||
GPU.with(|c| *c.borrow_mut() = Some(g));
|
||||
FrameReply::Info { gpu: Some(name), error: None }
|
||||
}
|
||||
Err(e) => FrameReply::Info { gpu: None, error: Some(e) },
|
||||
}
|
||||
};
|
||||
SERVER.with(|c| *c.borrow_mut() = Some(server));
|
||||
post_reply(&info, None);
|
||||
}
|
||||
|
||||
/// Handle one frame message (a JSON [`FrameMsg`]) in a frame worker: replies are posted with
|
||||
/// their pixels transferred. A frame rendering in passes awaits the GPU between them; a frame
|
||||
/// with a disk-cache key is then stored ([`FrameReply::Stored`]).
|
||||
#[wasm_bindgen(js_name = workerFrame)]
|
||||
pub fn worker_frame(json: String) {
|
||||
pub async fn worker_frame(json: String) {
|
||||
let msg: FrameMsg = match serde_json::from_str(&json) {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
@@ -233,29 +450,25 @@ pub fn worker_frame(json: String) {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let replies = SERVER.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
let server = c.get_or_insert_with(|| {
|
||||
let pool = crate::worker::pool();
|
||||
FrameServer::new(pool, Some(std::sync::Arc::new(effectcraft_expr::Expressions)))
|
||||
});
|
||||
server.handle(msg)
|
||||
});
|
||||
let scope: web_sys::DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
|
||||
let disk = match &msg {
|
||||
FrameMsg::Render { disk, .. } => disk.clone(),
|
||||
_ => None,
|
||||
};
|
||||
let mut replies = SERVER.with(|c| c.borrow_mut().get_or_insert_with(new_server).handle(msg));
|
||||
while SERVER.with(|c| c.borrow().as_ref().is_some_and(|s| s.waiting())) {
|
||||
let Some(g) = GPU.with(|c| c.borrow().clone()) else { break };
|
||||
g.settled().await;
|
||||
replies = SERVER.with(|c| c.borrow_mut().as_mut().map(|s| s.resume()).unwrap_or_default());
|
||||
}
|
||||
for (r, px) in replies {
|
||||
let t = serde_json::to_string(&r).unwrap_or_default();
|
||||
let res = match px {
|
||||
Some(px) => {
|
||||
let buf = js_sys::Uint8Array::from(&px[..]).buffer();
|
||||
scope.post_message_with_transfer(
|
||||
&obj(&[("type", "frameReply".into()), ("json", t.into()), ("bytes", buf.clone().into())]),
|
||||
&js_sys::Array::of1(&buf),
|
||||
)
|
||||
post_reply(&r, px.as_deref());
|
||||
if let (FrameReply::Frame { width, height, .. }, Some(px), Some(key)) = (&r, &px, &disk) {
|
||||
let entry = effectcraft_engine::render::disk_cache::frame_entry(*width, *height, px);
|
||||
let name = format!("{key}.ecc");
|
||||
match JsFuture::from(crate::diskcache::cache_write(&name, js_sys::Uint8Array::from(&entry[..]))).await {
|
||||
Ok(n) => post_reply(&FrameReply::Stored { key: key.clone(), bytes: n.as_f64().unwrap_or(entry.len() as f64) as u64 }, None),
|
||||
Err(e) => log::warn!("frame worker: disk cache write failed: {e:?}"),
|
||||
}
|
||||
None => scope.post_message(&obj(&[("type", "frameReply".into()), ("json", t.into())])),
|
||||
};
|
||||
if let Err(e) = res {
|
||||
log::warn!("frame worker: postMessage: {e:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
//! | rfd file dialogs | `<input type=file>` pickers; drop files on the page |
|
||||
//! | Media Browser on the file system | browser storage and folders opened with the File System Access API ([`browse`]) |
|
||||
//! | written files (Save, Render Queue) | browser downloads (several render files as one `.zip`) |
|
||||
//! | frame render threads | frame workers, each with a project replica fed by diffs ([`frames`]); `Frames::pump` on the UI thread without workers |
|
||||
//! | frame render threads | frame workers, each with a project replica fed by diffs and its own WebGPU device ([`frames`]); `Frames::pump` on the UI thread without workers |
|
||||
//! | disk cache folder | frames in the Origin Private File System, written by the frame workers ([`diskcache`]) |
|
||||
//! | (none) | the storage manager: usage, quota, persistence, clearing ([`storage`]) |
|
||||
//! | Render Queue / analysis threads | Web Workers running their own engine instance ([`worker`]) |
|
||||
//! | cpal audio output | Web Audio: an AudioWorklet fed from the preview mixdown ([`audio`]) |
|
||||
//! | TCP control channel / MCP | `window.effectcraft` JavaScript API ([`api`]) |
|
||||
@@ -29,12 +31,16 @@ pub mod audio;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod browse;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod diskcache;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod files;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod frames;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod persist;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod storage;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod worker;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The storage manager ([`StorageHost`], `storage.*` commands, Settings ▸ Disk ▸ Browser
|
||||
//! Storage): the origin's usage and quota (`navigator.storage.estimate()`), persistent storage
|
||||
//! (`navigator.storage.persist()`), what the store holds by kind ([`crate::store::FileKind`])
|
||||
//! and the disk cache ([`crate::diskcache`]); clearing each.
|
||||
//!
|
||||
//! The browser answers asynchronously: [`StorageHost::info`] returns the latest estimate and
|
||||
//! asks for a new one at most once a second.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use effectcraft_engine::storage::StorageHost;
|
||||
use serde_json::{Value, json};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use crate::store::FileKind;
|
||||
|
||||
#[wasm_bindgen(module = "/js/host.js")]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_name = storePersist)]
|
||||
fn store_persist() -> js_sys::Promise;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Estimate {
|
||||
usage: u64,
|
||||
quota: u64,
|
||||
persisted: bool,
|
||||
/// When the last refresh started (ms).
|
||||
asked: f64,
|
||||
busy: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static EST: RefCell<Estimate> = RefCell::new(Estimate::default());
|
||||
}
|
||||
|
||||
/// Refresh the estimate in the background (at most once a second).
|
||||
pub fn refresh() {
|
||||
let now = js_sys::Date::now();
|
||||
let go = EST.with(|e| {
|
||||
let mut e = e.borrow_mut();
|
||||
if e.busy || now - e.asked < 1000.0 {
|
||||
return false;
|
||||
}
|
||||
e.busy = true;
|
||||
e.asked = now;
|
||||
true
|
||||
});
|
||||
if !go {
|
||||
return;
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
let v = JsFuture::from(crate::persist::store_estimate()).await.ok();
|
||||
EST.with(|e| {
|
||||
let mut e = e.borrow_mut();
|
||||
e.busy = false;
|
||||
if let Some(v) = v {
|
||||
let get = |k: &str| js_sys::Reflect::get(&v, &k.into()).ok();
|
||||
e.usage = get("usage").and_then(|x| x.as_f64()).unwrap_or(0.0) as u64;
|
||||
e.quota = get("quota").and_then(|x| x.as_f64()).unwrap_or(0.0) as u64;
|
||||
e.persisted = get("persisted").and_then(|x| x.as_bool()).unwrap_or(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The origin's quota in bytes, when known.
|
||||
pub fn quota() -> Option<u64> {
|
||||
EST.with(|e| Some(e.borrow().quota).filter(|q| *q > 0))
|
||||
}
|
||||
|
||||
/// The web app's [`StorageHost`].
|
||||
pub struct WebStorage;
|
||||
|
||||
impl StorageHost for WebStorage {
|
||||
fn info(&self) -> Value {
|
||||
refresh();
|
||||
let (usage, quota, persisted) = EST.with(|e| {
|
||||
let e = e.borrow();
|
||||
(e.usage, e.quota, e.persisted)
|
||||
});
|
||||
json!({
|
||||
"backend": crate::persist::backend(),
|
||||
"usage": usage,
|
||||
"quota": quota,
|
||||
"persisted": persisted,
|
||||
"files": crate::files::STORE.usage(),
|
||||
"diskCache": crate::diskcache::stats(),
|
||||
"error": crate::persist::last_error(),
|
||||
})
|
||||
}
|
||||
|
||||
fn request_persist(&self) -> Value {
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
let granted = JsFuture::from(store_persist()).await.ok().and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
EST.with(|e| e.borrow_mut().persisted = granted);
|
||||
crate::repaint();
|
||||
});
|
||||
json!({"requested": true, "persisted": EST.with(|e| e.borrow().persisted)})
|
||||
}
|
||||
|
||||
fn clear(&self, what: &str) -> Result<Value, String> {
|
||||
let kinds: Vec<FileKind> = match what {
|
||||
"diskCache" => vec![],
|
||||
"all" => vec![FileKind::Media, FileKind::Project, FileKind::AutoSave],
|
||||
k => vec![FileKind::from_name(k).ok_or_else(|| format!("unknown storage kind {k}"))?],
|
||||
};
|
||||
let (mut entries, mut bytes) = (0u64, 0u64);
|
||||
if matches!(what, "diskCache" | "all") {
|
||||
let (n, b) = crate::diskcache::clear();
|
||||
entries += n;
|
||||
bytes += b;
|
||||
}
|
||||
for k in kinds {
|
||||
let (n, b) = crate::files::STORE.clear_kind(k);
|
||||
entries += n;
|
||||
bytes += b;
|
||||
}
|
||||
// The estimate catches up on the next refresh.
|
||||
EST.with(|e| e.borrow_mut().asked = 0.0);
|
||||
Ok(json!({"cleared": what, "entries": entries, "bytes": bytes}))
|
||||
}
|
||||
}
|
||||
@@ -182,6 +182,74 @@ impl Store {
|
||||
pub fn files(&self) -> Vec<(String, usize, f64, bool)> {
|
||||
self.lock().list(FILES).into_iter().filter_map(|(k, n, m, p)| Some((key_path(&k)?.to_string(), n, m, p))).collect()
|
||||
}
|
||||
|
||||
/// Stored (persisted) files by kind: `{projects, media, autoSaves}`, each `{count, bytes}`
|
||||
/// (the storage manager, `storage.info`).
|
||||
pub fn usage(&self) -> serde_json::Value {
|
||||
let mut out = serde_json::Map::new();
|
||||
for k in [FileKind::Project, FileKind::Media, FileKind::AutoSave] {
|
||||
let (mut count, mut bytes) = (0u64, 0u64);
|
||||
for (path, n, _, persisted) in self.files() {
|
||||
if persisted && FileKind::of(&path) == k {
|
||||
count += 1;
|
||||
bytes += n as u64;
|
||||
}
|
||||
}
|
||||
out.insert(k.name().into(), serde_json::json!({"count": count, "bytes": bytes}));
|
||||
}
|
||||
out.into()
|
||||
}
|
||||
|
||||
/// Delete every stored file of a kind; returns (files, bytes) removed.
|
||||
pub fn clear_kind(&self, kind: FileKind) -> (u64, u64) {
|
||||
let (mut count, mut bytes) = (0u64, 0u64);
|
||||
for (path, n, _, persisted) in self.files() {
|
||||
if persisted && FileKind::of(&path) == kind {
|
||||
self.lock().remove(&file_key(&path));
|
||||
count += 1;
|
||||
bytes += n as u64;
|
||||
}
|
||||
}
|
||||
if count > 0 {
|
||||
self.changed();
|
||||
}
|
||||
(count, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a stored file is (Settings ▸ Disk ▸ Browser Storage).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FileKind {
|
||||
/// A saved project (`.ecproj` outside the auto-save folder).
|
||||
Project,
|
||||
/// Imported footage and everything else.
|
||||
Media,
|
||||
/// Auto-saves (`/EffectCraft Auto-Save/…`, or `… auto-save N.ecproj`).
|
||||
AutoSave,
|
||||
}
|
||||
|
||||
impl FileKind {
|
||||
pub fn of(path: &str) -> FileKind {
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if !lower.ends_with(".ecproj") {
|
||||
return FileKind::Media;
|
||||
}
|
||||
let name = lower.rsplit('/').next().unwrap_or(&lower);
|
||||
if lower.contains("/effectcraft auto-save/") || name.contains(" auto-save ") { FileKind::AutoSave } else { FileKind::Project }
|
||||
}
|
||||
|
||||
/// `storage.clear` / `storage.info` name.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
FileKind::Project => "projects",
|
||||
FileKind::Media => "media",
|
||||
FileKind::AutoSave => "autoSaves",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_name(n: &str) -> Option<FileKind> {
|
||||
[FileKind::Project, FileKind::Media, FileKind::AutoSave].into_iter().find(|k| k.name() == n)
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings and friends ([`ConfigStore`]) in the store; auto-saves ([`FileOps`]) in its file
|
||||
@@ -289,6 +357,28 @@ mod tests {
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_by_kind_and_clearing() {
|
||||
let s = store();
|
||||
s.put_file("/a.ecproj", Arc::from(&b"proj"[..]), true);
|
||||
s.put_file("/clip.mp4", Arc::from(&b"0123456789"[..]), true);
|
||||
s.put_file("/still.png", Arc::from(&b"px"[..]), true);
|
||||
s.put_file("/EffectCraft Auto-Save/a auto-save 1.ecproj", Arc::from(&b"auto"[..]), true);
|
||||
s.put_file("/render.gif", Arc::from(&b"out"[..]), false);
|
||||
let u = s.usage();
|
||||
assert_eq!(u["projects"], serde_json::json!({"count": 1, "bytes": 4}));
|
||||
assert_eq!(u["media"], serde_json::json!({"count": 2, "bytes": 12}), "render outputs are not stored");
|
||||
assert_eq!(u["autoSaves"], serde_json::json!({"count": 1, "bytes": 4}));
|
||||
assert_eq!(FileKind::from_name("autoSaves"), Some(FileKind::AutoSave));
|
||||
assert_eq!(FileKind::of("/x/My auto-save 3.ecproj"), FileKind::AutoSave);
|
||||
s.lock().take_pending();
|
||||
assert_eq!(s.clear_kind(FileKind::Media), (2, 12));
|
||||
assert!(s.file("/clip.mp4").is_none() && s.file("/a.ecproj").is_some() && s.file("/render.gif").is_some());
|
||||
let deleted: Vec<String> = s.lock().take_pending().into_iter().filter(|p| p.data.is_none()).map(|p| p.key).collect();
|
||||
assert_eq!(deleted.len(), 2, "the deletions are flushed to browser storage");
|
||||
assert_eq!(s.usage()["media"]["count"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_coalesce_per_key_in_order() {
|
||||
let mut m = Mirror::default();
|
||||
|
||||
@@ -192,6 +192,71 @@ try {
|
||||
check(fwk.after.syncs >= 2, `project synced as diffs: ${JSON.stringify(fwk.after)}`);
|
||||
check(fwk.maxGapMs < 400, `event loop blocked ${fwk.maxGapMs} ms while scrubbing`);
|
||||
|
||||
// GPU effects in the browser (M13.24): each frame worker opens its own WebGPU device; frames
|
||||
// with effects go to the workers, which render them on the GPU in passes (awaiting the
|
||||
// device's readbacks), while the page's event loop stays free.
|
||||
const gw = await js(`(async () => {
|
||||
const t0 = performance.now();
|
||||
while (effectcraft.info().frameWorkers.gpu.some((g) => g === null) && performance.now() - t0 < 30000) await new Promise((r) => setTimeout(r, 200));
|
||||
return {gpu: effectcraft.info().frameWorkers.gpu, workerWebGpu: effectcraft.info().webgpu};
|
||||
})()`);
|
||||
report.steps.gpuWorkers = gw;
|
||||
if (gw.gpu.some((g) => typeof g === "string")) {
|
||||
report.steps.gpuWorkers.effects = await js(`(async () => {
|
||||
const before = effectcraft.info().frameWorkers;
|
||||
let maxGapMs = 0, last = performance.now();
|
||||
const timer = setInterval(() => { const now = performance.now(); maxGapMs = Math.max(maxGapMs, now - last); last = now; }, 10);
|
||||
await effectcraft.execute("layer.newSolid", {name: "GPU Blur Solid", color: "#cc3366", width: 300, height: 200});
|
||||
await effectcraft.execute("effect.apply", {effect: "Gaussian Blur"});
|
||||
await effectcraft.execute("prop.set", {path: "effects/#1/blurriness", value: 25});
|
||||
await effectcraft.execute("effect.apply", {effect: "Glow"});
|
||||
for (let k = 0; k < 6; k++) {
|
||||
await effectcraft.execute("time.set", {time: 0.3 + k / 5});
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
}
|
||||
const t0 = performance.now();
|
||||
while (effectcraft.info().frameWorkers.gpuFrames < before.gpuFrames + 3 && performance.now() - t0 < 120000) await new Promise((r) => setTimeout(r, 100));
|
||||
clearInterval(timer);
|
||||
const after = effectcraft.info().frameWorkers;
|
||||
// The worker's GPU frame against the page's CPU render of the same frame.
|
||||
let parity = null;
|
||||
for (let i = 0; i < 100 && !parity; i++) {
|
||||
parity = await effectcraft.workerFrameCheck({scale: 0.5}).catch(() => null);
|
||||
if (!parity) await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
after.parity = parity;
|
||||
await effectcraft.execute("edit.undo", {});
|
||||
await effectcraft.execute("edit.undo", {});
|
||||
await effectcraft.execute("edit.undo", {});
|
||||
await effectcraft.execute("edit.undo", {});
|
||||
return {before, after, maxGapMs};
|
||||
})()`);
|
||||
const ge = report.steps.gpuWorkers.effects;
|
||||
report.steps.gpuWorkers.screenshot = await shot("01b-gpu-effects");
|
||||
check(ge.after.gpuFrames >= ge.before.gpuFrames + 3, `GPU effect frames rendered in workers: ${JSON.stringify(ge)}`);
|
||||
check(ge.after.lastPasses >= 2, `frames rendered in passes (deferred readbacks): ${ge.after.lastPasses}`);
|
||||
const pa = ge.after.parity;
|
||||
check(pa && pa.meanDiff < 0.5 && pa.over4 < 0.005, `GPU worker frame vs the CPU: ${JSON.stringify(pa)}`);
|
||||
check(ge.maxGapMs < 400, `event loop blocked ${ge.maxGapMs} ms while GPU workers rendered`);
|
||||
} else {
|
||||
report.steps.gpuWorkers.note = "no WebGPU in workers here: frame workers render on their CPU";
|
||||
}
|
||||
|
||||
// The storage manager (Settings ▸ Disk ▸ Browser Storage) and its commands.
|
||||
await js(`effectcraft.execute("storage.persist", {})`);
|
||||
const st = await js(`(async () => { await new Promise((r) => setTimeout(r, 1200)); return effectcraft.execute("storage.info", {}); })()`);
|
||||
report.steps.storage = st;
|
||||
check(st.available && st.quota > 0 && st.usage > 0, `storage.info: ${JSON.stringify(st)}`);
|
||||
check(st.diskCache && st.diskCache.enabled && st.diskCache.writes > 0, `disk cache in OPFS: ${JSON.stringify(st.diskCache)}`);
|
||||
await js(`effectcraft.execute("prefs.open", {page: "disk"})`);
|
||||
await sleep(800);
|
||||
report.steps.storage.screenshot = await shot("01c-storage-manager");
|
||||
const ids = await js(`effectcraft.request("ui.elements", {prefix: "settings.storage."}).then((l) => l.map((e) => e.id))`);
|
||||
report.steps.storage.elements = ids;
|
||||
check(ids.includes("settings.storage.usage") && ids.includes("settings.storage.clear.diskCache"), `storage manager widgets: ${ids}`);
|
||||
await js(`effectcraft.request("ui.click", {id: "settings.cancel"})`);
|
||||
await sleep(300);
|
||||
|
||||
// Render Queue: a short, small GIF → download. `renderQueue.render` waits by default; the
|
||||
// render still runs in a worker and the reply comes when it ends (the page keeps running).
|
||||
const rqT = Date.now();
|
||||
@@ -302,6 +367,25 @@ try {
|
||||
await js(`effectcraft.execute("prefs.set", {key: "general.recentItems", value: 7})`);
|
||||
const saved = await js(`effectcraft.saveToBrowser("/persist-test.ecproj")`);
|
||||
await js(`effectcraft.execute("layer.newSolid", {name: "Unsaved Solid"})`);
|
||||
// Disk cache: frames the workers render now are stored in the Origin Private File System
|
||||
// (the CPU renderer sends every frame to the workers).
|
||||
await js(`effectcraft.execute("render.backend", {backend: "cpu"})`);
|
||||
const diskTimes = [0.4, 0.8, 1.2];
|
||||
const stored = await js(`(async () => {
|
||||
const w0 = (await effectcraft.execute("cache.diskStats", {})).writes;
|
||||
for (const t of ${JSON.stringify(diskTimes)}) {
|
||||
await effectcraft.execute("time.set", {time: t});
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
}
|
||||
const t0 = performance.now();
|
||||
let st;
|
||||
do {
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
st = await effectcraft.execute("cache.diskStats", {});
|
||||
} while (st.writes < w0 + ${diskTimes.length} && performance.now() - t0 < 60000);
|
||||
return {writesBefore: w0, after: st};
|
||||
})()`);
|
||||
check(stored.after.writes >= stored.writesBefore + diskTimes.length, `frames written to the disk cache: ${JSON.stringify(stored)}`);
|
||||
await sleep(1500); // the session snapshot is taken at most every second
|
||||
await js("effectcraft.flush()");
|
||||
const before = await js("effectcraft.listStored()");
|
||||
@@ -321,6 +405,31 @@ try {
|
||||
check(paths.includes("/tone.wav") && paths.includes("/persist-test.ecproj"), `stored files: ${paths}`);
|
||||
check(recentItems === 7, `setting after reload: ${recentItems}`);
|
||||
check(rec.recentProjects[0] === "/persist-test.ecproj", `recent projects: ${rec.recentProjects}`);
|
||||
// The disk cache survived the reload: the same frames come from it, not from a render.
|
||||
report.steps.diskCache = await js(`(async () => {
|
||||
const t0 = performance.now();
|
||||
let st;
|
||||
do {
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
st = await effectcraft.execute("cache.diskStats", {});
|
||||
} while (!st.loaded && performance.now() - t0 < 20000);
|
||||
const listed = st.entries;
|
||||
for (const t of ${JSON.stringify(diskTimes)}) {
|
||||
await effectcraft.execute("time.set", {time: t});
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
}
|
||||
const t1 = performance.now();
|
||||
while (effectcraft.info().frameWorkers.diskHits < ${diskTimes.length} && performance.now() - t1 < 30000) await new Promise((r) => setTimeout(r, 200));
|
||||
return {listed, stats: await effectcraft.execute("cache.diskStats", {}), frameWorkers: effectcraft.info().frameWorkers};
|
||||
})()`);
|
||||
const dcr = report.steps.diskCache;
|
||||
dcr.stored = stored;
|
||||
check(dcr.listed >= diskTimes.length, `disk cache entries after reload: ${JSON.stringify(dcr)}`);
|
||||
check(dcr.frameWorkers.diskHits >= diskTimes.length, `cache hits after reload: ${JSON.stringify(dcr.frameWorkers)}`);
|
||||
const cleared = await js(`effectcraft.execute("storage.clear", {what: "diskCache"})`);
|
||||
const afterClear = await js(`effectcraft.execute("cache.diskStats", {})`);
|
||||
dcr.cleared = { cleared, afterClear };
|
||||
check(cleared.entries >= diskTimes.length && afterClear.entries === 0, `storage.clear diskCache: ${JSON.stringify(dcr.cleared)}`);
|
||||
await js(`effectcraft.execute("file.openRecent", {index: 0})`);
|
||||
const reopened = await js(`effectcraft.execute("comp.info", {}).then(c => c.layers.map(l => l.name))`);
|
||||
check(reopened.includes("Persisted Solid") && !reopened.includes("Unsaved Solid"), `Open Recent: ${reopened}`);
|
||||
|
||||
@@ -62,6 +62,8 @@
|
||||
listStored: () => ec.listStored(),
|
||||
removeStored: (path) => ec.removeStored(path),
|
||||
flush: () => ec.flush(),
|
||||
// A frame rendered in a frame worker (its GPU by default) vs the page's CPU: {maxDiff, meanDiff, over4, …}.
|
||||
workerFrameCheck: (params) => ec.workerFrameCheck(params ?? {}).then(JSON.parse),
|
||||
};
|
||||
// Offline start and install (PWA): the service worker caches the app's files.
|
||||
if ("serviceWorker" in navigator && !new URLSearchParams(location.search).has("nosw")) {
|
||||
|
||||
@@ -2,21 +2,35 @@
|
||||
// crates/engine/src/offload.rs and remote.rs). The page sends the compiled module, then:
|
||||
// - job workers: footage files and jobs (Render Queue, analyses, Roto Brush); the worker replies
|
||||
// with JSON messages and rendered files;
|
||||
// - frame workers: footage files and frame messages (project syncs as diffs, render requests,
|
||||
// Roto Brush segmentations); the worker replies with frames (pixels transferred).
|
||||
// - frame workers (`frames: true`): footage files and frame messages (project syncs as diffs,
|
||||
// render requests, Roto Brush segmentations); the worker replies with frames (pixels
|
||||
// transferred). With `gpu: true` it opens its own WebGPU device and renders GPU effects on
|
||||
// it; a frame then takes several passes, awaiting the device's readbacks in between.
|
||||
// Messages are handled one at a time, in order: a frame awaiting its readbacks finishes before
|
||||
// the next message (a project sync, the next request) is looked at.
|
||||
import init, * as ec from "./effectcraft_web.js";
|
||||
|
||||
let ready = null;
|
||||
self.onmessage = async (e) => {
|
||||
const m = e.data;
|
||||
if (m.type === "init") {
|
||||
ready = init({ module_or_path: m.module ?? new URL("effectcraft_web_bg.wasm", m.base) }).then(() => ec.workerInit());
|
||||
await ready;
|
||||
self.postMessage({ type: "ready" });
|
||||
return;
|
||||
}
|
||||
await ready;
|
||||
let queue = Promise.resolve();
|
||||
|
||||
async function handle(m) {
|
||||
if (m.type === "file") ec.workerFile(m.path, m.bytes);
|
||||
else if (m.type === "job") ec.workerJob(m.json);
|
||||
else if (m.type === "frame") ec.workerFrame(m.json);
|
||||
else if (m.type === "frame") await ec.workerFrame(m.json);
|
||||
}
|
||||
|
||||
self.onmessage = (e) => {
|
||||
const m = e.data;
|
||||
if (m.type === "init") {
|
||||
ready = (async () => {
|
||||
await init({ module_or_path: m.module ?? new URL("effectcraft_web_bg.wasm", m.base) });
|
||||
ec.workerInit();
|
||||
if (m.frames) await ec.workerFrameInit(!!m.gpu);
|
||||
self.postMessage({ type: "ready" });
|
||||
})();
|
||||
return;
|
||||
}
|
||||
// A failure (a panic) is re-raised outside the queue so the page's `onerror` sees it, as
|
||||
// before the queue: the page then drops the worker.
|
||||
queue = queue.then(() => ready).then(() => handle(m)).catch((err) => setTimeout(() => { throw err; }));
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user