M15.1: web build (eframe wasm) + xtask web

- apps/effectcraft-web (L6): eframe web runner booting the shared EffectcraftApp with a browser
  session: in-memory file table, <input type=file> pickers and drag-and-drop for open/import,
  downloads for Save and Render Queue outputs (several files as one stored .zip), and the
  window.effectcraft promise API over the control channel. Demo project on start.
- wasm32 runtime fixes: web-time for Instant/SystemTime (render, engine, export, ui-egui);
  Frames renders queued jobs on the UI thread (Frames::pump) instead of a thread pool;
  Render Queue runs inline; relative outputs resolve under / ; control PNGs inline.
- effectcraft-export: per-job output Sink (files to memory instead of disk); host FileExporter
  carries it; test that sink exports touch no file.
- xtask web [--dev] [--serve PORT] (wasm-bindgen 0.2.129, optional wasm-opt, COOP/COEP server);
  effectcraft-web in WEB_CRATES. docs/web.md, headless Chrome smoke test, favicon (+attribution).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-02 00:19:35 -04:00
co-authored by Claude Opus 5.5
parent c925ac8ae8
commit 31f192e2a9
30 changed files with 1361 additions and 92 deletions
+1
View File
@@ -24,3 +24,4 @@ serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
web-time = { workspace = true }
+7 -4
View File
@@ -125,11 +125,11 @@ struct Work {
}
fn unix_now() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
fn run_work(w: Work, shared: &JobShared) {
let t0 = std::time::Instant::now();
let t0 = web_time::Instant::now();
{
let mut s = lock(&shared.state);
s.items_total = w.items.len();
@@ -139,7 +139,7 @@ fn run_work(w: Work, shared: &JobShared) {
lock(&shared.updates).push(ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds: 0.0, output: None });
continue;
}
let t1 = std::time::Instant::now();
let t1 = web_time::Instant::now();
lock(&shared.updates).push(ItemUpdate::Started { id: item.id, unix: unix_now() });
{
let mut s = lock(&shared.state);
@@ -211,7 +211,8 @@ impl Session {
return Some(p);
}
let base = self.path.as_deref().and_then(|s| std::path::Path::new(s).parent().map(|d| d.to_path_buf())).filter(|d| !d.as_os_str().is_empty());
let base = base.or_else(|| std::env::current_dir().ok())?;
// (the web has no working directory: relative outputs land in its virtual root)
let base = base.or_else(|| std::env::current_dir().ok()).or_else(|| cfg!(target_arch = "wasm32").then(|| "/".into()))?;
Some(base.join(path).to_string_lossy().to_string())
}
@@ -227,7 +228,9 @@ impl Session {
/// Start rendering every queued item. `wait`: block until done (otherwise a background thread
/// renders; call [`Session::poll_render`] regularly). Returns the ids being rendered.
/// wasm32 has no threads: the render always runs to completion before this returns.
pub fn start_render(&mut self, wait: bool) -> Result<Vec<u64>, String> {
let wait = wait || cfg!(target_arch = "wasm32");
if self.is_rendering() {
return Err("a render is already in progress".into());
}
+1
View File
@@ -21,6 +21,7 @@ filmcraft-isobmff = { workspace = true }
image = { workspace = true, features = ["png", "jpeg", "tiff", "exr"] }
gif = { workspace = true }
rayon = { workspace = true }
web-time = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
+6 -7
View File
@@ -1,7 +1,7 @@
//! Movie export: FilmCraft H.264 → MP4 (+ AAC) and ProRes → MOV (+ PCM), muxed by
//! FilmCraft's ISO BMFF / QuickTime writer.
use std::io::{BufWriter, Write};
use std::io::Write;
use effectcraft_project::Comp;
use effectcraft_project::render_queue::{Channels, OutputFormat, ProResProfile};
@@ -218,7 +218,7 @@ fn deinterleave(buf: &[f32]) -> [Vec<f32>; 2] {
// ---------------------------------------------------------------- the movie
type Writer = Mp4Writer<BufWriter<std::fs::File>>;
type Writer<'f, 's> = Mp4Writer<&'f mut crate::out::Out<'s>>;
pub(crate) fn movie(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
let rate = job.settings.rate(comp);
@@ -242,10 +242,10 @@ pub(crate) fn movie(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> R
drop(first);
st.advance(first_end)?;
let file = std::fs::File::create(job.path).map_err(mux_err)?;
let mut file = crate::out::create(job.sink, job.path)?;
let opts = WriterOptions::new(brand);
let movie_ts = opts.movie_timescale.max(1) as i128;
let mut mux: Writer = Mp4Writer::new(BufWriter::new(file), opts).map_err(mux_err)?;
let mut mux: Writer = Mp4Writer::new(&mut file, opts).map_err(mux_err)?;
let mut vcfg = TrackConfig::new(venc.sample_entry(), rate.num as u32);
if let Some(start) = venc.media_start() {
// An explicit edit: the convenience `media_start` edit would subtract the B-frame delay
@@ -333,10 +333,9 @@ pub(crate) fn movie(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> R
mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?;
}
}
let mut out = mux.finish().map_err(mux_err)?;
let out = mux.finish().map_err(mux_err)?;
out.flush().map_err(mux_err)?;
drop(out);
let bytes = std::fs::metadata(job.path).map(|m| m.len()).unwrap_or(0);
let bytes = file.finish()?;
Ok(Report { path: job.path.to_string(), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio })
}
+18 -19
View File
@@ -17,9 +17,9 @@
//! output is a single pixel wide/high).
mod encode;
mod out;
use std::path::Path;
use std::time::Instant;
use web_time::Instant;
use effectcraft_project::render_queue::{AudioOutput, Channels, OutputFormat, OutputModule, RenderQuality, RenderSettings, sequence_path};
use effectcraft_project::{Comp, ItemId, Project};
@@ -29,6 +29,7 @@ use effectcraft_time::Tick;
use rayon::prelude::*;
pub use effectcraft_project::render_queue;
pub use out::Sink;
#[derive(Debug, thiserror::Error)]
pub enum ExportError {
@@ -61,6 +62,8 @@ pub struct Job<'a> {
/// Output file. For image sequences a run of `#` (or `[#####]`) becomes the frame number; a
/// path without one gets `_NNNNN` before the extension.
pub path: &'a str,
/// Hand finished files to this instead of writing them to disk (web downloads, tests).
pub sink: Option<&'a Sink>,
}
/// Progress after a batch of frames.
@@ -122,9 +125,6 @@ pub fn export(job: &Job, progress: &mut dyn FnMut(&Progress) -> bool) -> Result<
let total = job.settings.frame_count(comp);
let mut st = State { t0, total, done: 0, progress };
st.advance(0)?;
if let Some(dir) = Path::new(job.path).parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(dir).map_err(io)?;
}
let (w, h) = output_size(comp, job.settings, job.output);
let mut report = match job.output.format {
OutputFormat::H264 | OutputFormat::ProRes => encode::movie(job, comp, w, h, &mut st)?,
@@ -218,12 +218,13 @@ fn sequence(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Re
.into_par_iter()
.map(|k| {
let path = sequence_path(job.path, f0 + k as i64);
if job.settings.skip_existing && Path::new(&path).exists() {
if job.settings.skip_existing && out::exists(job.sink, &path) {
return Ok(0);
}
let img = render_frame(job, comp, k);
write_still(&path, fmt, &img, comp, channels, w, h, job.output.quality)?;
Ok(std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0))
let mut f = out::create(job.sink, &path)?;
write_still(&mut f, fmt, &img, comp, channels, w, h, job.output.quality)?;
f.finish()
})
.collect();
for r in written {
@@ -236,9 +237,8 @@ fn sequence(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Re
}
#[allow(clippy::too_many_arguments)]
fn write_still(path: &str, fmt: OutputFormat, img: &Image, comp: &Comp, channels: Channels, w: u32, h: u32, quality: u8) -> Result<()> {
fn write_still(file: &mut out::Out, fmt: OutputFormat, img: &Image, comp: &Comp, channels: Channels, w: u32, h: u32, quality: u8) -> Result<()> {
use image::{ExtendedColorType, ImageEncoder, ImageFormat};
let file = || std::fs::File::create(path).map(std::io::BufWriter::new).map_err(io);
match fmt {
OutputFormat::ExrSequence => {
// Linear light, premultiplied (the EXR convention); RGB keeps alpha = 1 over the background.
@@ -263,12 +263,12 @@ fn write_still(path: &str, fmt: OutputFormat, img: &Image, comp: &Comp, channels
}
}
let buf = image::Rgba32FImage::from_raw(w, h, data).ok_or_else(|| ExportError::Encode("exr buffer".into()))?;
image::DynamicImage::ImageRgba32F(buf).save_with_format(path, ImageFormat::OpenExr).map_err(|e| ExportError::Encode(e.to_string()))
image::DynamicImage::ImageRgba32F(buf).write_to(file, ImageFormat::OpenExr).map_err(|e| ExportError::Encode(e.to_string()))
}
OutputFormat::JpegSequence => {
let px = rgba8(img, comp, Channels::Rgb, w, h);
let rgb: Vec<u8> = px.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect();
image::codecs::jpeg::JpegEncoder::new_with_quality(file()?, quality.clamp(1, 100))
image::codecs::jpeg::JpegEncoder::new_with_quality(file, quality.clamp(1, 100))
.write_image(&rgb, w, h, ExtendedColorType::Rgb8)
.map_err(|e| ExportError::Encode(e.to_string()))
}
@@ -279,11 +279,10 @@ fn write_still(path: &str, fmt: OutputFormat, img: &Image, comp: &Comp, channels
Channels::Rgb => (px.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect(), ExtendedColorType::Rgb8),
};
if fmt == OutputFormat::PngSequence {
image::codecs::png::PngEncoder::new(file()?).write_image(&data, w, h, ct).map_err(|e| ExportError::Encode(e.to_string()))
image::codecs::png::PngEncoder::new(file).write_image(&data, w, h, ct).map_err(|e| ExportError::Encode(e.to_string()))
} else {
// The TIFF encoder needs Seek.
let f = std::fs::File::create(path).map_err(io)?;
image::codecs::tiff::TiffEncoder::new(std::io::BufWriter::new(f)).write_image(&data, w, h, ct).map_err(|e| ExportError::Encode(e.to_string()))
// (the TIFF encoder needs Seek)
image::codecs::tiff::TiffEncoder::new(file).write_image(&data, w, h, ct).map_err(|e| ExportError::Encode(e.to_string()))
}
}
f => Err(ExportError::Unsupported(format!("{} is not a still format", f.label()))),
@@ -294,8 +293,8 @@ fn gif_export(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<
if w > u16::MAX as u32 || h > u16::MAX as u32 {
return Err(ExportError::Unsupported("GIF frames are limited to 65535 px".into()));
}
let file = std::fs::File::create(job.path).map_err(io)?;
let mut enc = gif::Encoder::new(std::io::BufWriter::new(file), w as u16, h as u16, &[]).map_err(|e| ExportError::Encode(e.to_string()))?;
let mut file = out::create(job.sink, job.path)?;
let mut enc = gif::Encoder::new(&mut file, w as u16, h as u16, &[]).map_err(|e| ExportError::Encode(e.to_string()))?;
enc.set_repeat(if job.output.gif_loop { gif::Repeat::Infinite } else { gif::Repeat::Finite(0) }).map_err(|e| ExportError::Encode(e.to_string()))?;
let rate = job.settings.rate(comp);
// GIF delays are in 1/100 s: carry the rounding error so long animations keep their timing.
@@ -328,7 +327,7 @@ fn gif_export(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<
i = end;
}
drop(enc);
let bytes = std::fs::metadata(job.path).map(|m| m.len()).unwrap_or(0);
let bytes = file.finish()?;
Ok(Report { path: job.path.to_string(), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false })
}
+77
View File
@@ -0,0 +1,77 @@
//! Output files: the file system, or an in-memory [`Sink`] chosen per job (the web app, which
//! offers every written file as a download; tests).
use std::io::{BufWriter, Cursor, Seek, SeekFrom, Write};
use crate::{ExportError, Result, io};
/// Receives each finished output file (path as resolved, complete contents) instead of the file
/// system. Called once per file; image sequences call it from the render threads.
pub type Sink = dyn Fn(&str, Vec<u8>) + Send + Sync;
/// One output file being written.
pub(crate) enum Out<'a> {
File(BufWriter<std::fs::File>),
Mem { path: String, cur: Cursor<Vec<u8>>, sink: &'a Sink },
}
/// Create `path` (parent directories included) or an in-memory file for `sink`.
pub(crate) fn create<'a>(sink: Option<&'a Sink>, path: &str) -> Result<Out<'a>> {
match sink {
Some(sink) => Ok(Out::Mem { path: path.to_string(), cur: Cursor::new(Vec::new()), sink }),
None => {
if let Some(dir) = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(dir).map_err(io)?;
}
Ok(Out::File(BufWriter::new(std::fs::File::create(path).map_err(io)?)))
}
}
}
/// Whether `path` already exists (never for a sink: it has no memory of earlier jobs).
pub(crate) fn exists(sink: Option<&Sink>, path: &str) -> bool {
sink.is_none() && std::path::Path::new(path).exists()
}
impl Out<'_> {
/// Flush and close; a sink receives the contents now. Returns the file size.
pub(crate) fn finish(self) -> Result<u64> {
match self {
Out::File(mut w) => {
w.flush().map_err(io)?;
let f = w.into_inner().map_err(|e| ExportError::Io(e.to_string()))?;
Ok(f.metadata().map(|m| m.len()).unwrap_or(0))
}
Out::Mem { path, cur, sink } => {
let data = cur.into_inner();
let n = data.len() as u64;
sink(&path, data);
Ok(n)
}
}
}
}
impl Write for Out<'_> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
match self {
Out::File(w) => w.write(buf),
Out::Mem { cur, .. } => cur.write(buf),
}
}
fn flush(&mut self) -> std::io::Result<()> {
match self {
Out::File(w) => w.flush(),
Out::Mem { .. } => Ok(()),
}
}
}
impl Seek for Out<'_> {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
match self {
Out::File(w) => w.seek(pos),
Out::Mem { cur, .. } => cur.seek(pos),
}
}
}
+3 -3
View File
@@ -55,7 +55,7 @@ fn settings() -> RenderSettings {
fn run(p: &Project, cid: ItemId, footage: &dyn FootageSource, om: &OutputModule, path: &Path) -> effectcraft_export::Report {
let s = settings();
let path = path.to_string_lossy().to_string();
let job = Job { project: p, footage, expr: None, comp: cid, settings: &s, output: om, path: &path };
let job = Job { project: p, footage, expr: None, comp: cid, settings: &s, output: om, path: &path, sink: None };
let mut last = Progress::default();
let mut calls = 0;
let r = export(&job, &mut |pr| {
@@ -167,7 +167,7 @@ fn h264_odd_size_is_cropped_even() {
let comp = p.comp(cid).expect("comp");
assert_eq!(s.output_size(comp).0 % 2, 1);
let path = d.join("odd.mp4").to_string_lossy().to_string();
let job = Job { project: &p, footage: &NoFootage, expr: None, comp: cid, settings: &s, output: &om, path: &path };
let job = Job { project: &p, footage: &NoFootage, expr: None, comp: cid, settings: &s, output: &om, path: &path, sink: None };
let r = export(&job, &mut |_| true).expect("export");
assert_eq!((r.width % 2, r.height % 2), (0, 0));
}
@@ -287,7 +287,7 @@ fn cancel_stops_early() {
let om = OutputModule::for_format(OutputFormat::PngSequence);
let s = settings();
let path = d.join("c_[#####].png").to_string_lossy().to_string();
let job = Job { project: &p, footage: &NoFootage, expr: None, comp: cid, settings: &s, output: &om, path: &path };
let job = Job { project: &p, footage: &NoFootage, expr: None, comp: cid, settings: &s, output: &om, path: &path, sink: None };
let r = export(&job, &mut |_| false);
assert!(matches!(r, Err(effectcraft_export::ExportError::Cancelled)));
let written = std::fs::read_dir(&d).map(|r| r.count()).unwrap_or(0);
+39 -3
View File
@@ -16,8 +16,12 @@ impl Importer for MediaImporter {
}
}
/// Render Queue export via `effectcraft-export`.
pub struct FileExporter;
/// Render Queue export via `effectcraft-export`: to the file system, or to `sink` (the web app
/// turns written files into downloads).
#[derive(Default)]
pub struct FileExporter {
pub sink: Option<Arc<effectcraft_export::Sink>>,
}
impl Exporter for FileExporter {
fn formats(&self) -> Vec<OutputFormat> {
@@ -32,6 +36,7 @@ impl Exporter for FileExporter {
settings: &job.item.settings,
output: &job.item.output,
path: job.path,
sink: self.sink.as_deref(),
};
match effectcraft_export::export(&j, &mut |p| progress(p.done, p.total)) {
Ok(r) => Ok(ExportResult { path: r.path, frames: r.frames, width: r.width, height: r.height, bytes: r.bytes, seconds: r.seconds, audio: r.audio }),
@@ -44,7 +49,7 @@ impl Exporter for FileExporter {
/// A new session with media, import, expressions and export enabled.
pub fn session() -> Session {
Session {
exporter: Some(Arc::new(FileExporter)),
exporter: Some(Arc::new(FileExporter::default())),
footage: Arc::new(effectcraft_media::MediaPool::new()),
importer: Some(Arc::new(MediaImporter)),
expr: Some(Arc::new(effectcraft_expr::Expressions)),
@@ -68,6 +73,37 @@ mod tests {
assert!(img.data.iter().any(|p| p[3] > 0.5));
}
/// The web app's path: outputs go to a sink (downloads), never to the file system.
#[test]
fn render_queue_exports_to_a_sink() {
use std::sync::{Arc, Mutex};
let got: Arc<Mutex<Vec<(String, Vec<u8>)>>> = Arc::default();
let g = got.clone();
let mut s = super::session();
s.exporter = Some(Arc::new(super::FileExporter { sink: Some(Arc::new(move |p: &str, d: Vec<u8>| g.lock().unwrap().push((p.to_string(), d)))) }));
s.execute("file.openDemoProject", json!({})).unwrap();
let dir = "/no-such-dir-effectcraft-sink-test";
s.execute(
"renderQueue.add",
json!({"format": "gif", "output": format!("{dir}/a.gif"), "resolution": 0.0625, "timeSpan": "custom", "start": 0.0, "end": 0.2}),
)
.unwrap();
s.execute(
"renderQueue.add",
json!({"format": "png", "output": format!("{dir}/seq_[##].png"), "resolution": 0.0625, "timeSpan": "custom", "start": 0.0, "end": 0.1}),
)
.unwrap();
s.execute("renderQueue.render", json!({"wait": true})).unwrap();
s.poll_render();
let mut got = got.lock().unwrap().clone();
got.sort_by(|a, b| a.0.cmp(&b.0));
let names: Vec<&str> = got.iter().map(|(p, _)| p.as_str()).collect();
assert_eq!(names, [format!("{dir}/a.gif"), format!("{dir}/seq_00.png"), format!("{dir}/seq_01.png"), format!("{dir}/seq_02.png")]);
assert!(got[0].1.starts_with(b"GIF89a"));
assert!(got[1].1.starts_with(b"\x89PNG"));
assert!(!std::path::Path::new(dir).exists());
}
#[test]
fn render_queue_exports_demo_comp() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out/host-rq");
+1
View File
@@ -21,5 +21,6 @@ effectcraft-text = { workspace = true }
effectcraft-effects = { workspace = true }
kurbo = { workspace = true }
rayon = { workspace = true }
web-time = { workspace = true }
serde = { workspace = true }
log = { workspace = true }
+3 -3
View File
@@ -208,7 +208,7 @@ impl<'a> Renderer<'a> {
let Some(spec) = effectcraft_effects::find(effect) else { continue };
let params = self.effect_params(ctx, layer, g);
let ectx = EffectCtx { params: &params, time: lt.seconds(), layer_size, seed: g.uid as u32, adjustment, env };
let t0 = std::time::Instant::now();
let t0 = web_time::Instant::now();
buf = effectcraft_effects::apply(spec, &ectx, buf);
if let Some(v) = timing.as_deref_mut() {
v.push((spec.id.to_string(), t0.elapsed().as_secs_f64() * 1e3));
@@ -348,9 +348,9 @@ impl<'a> Renderer<'a> {
return;
};
let mut timing = LayerTiming { depth: self.depth, layer: layer.name.clone(), ..Default::default() };
let t0 = std::time::Instant::now();
let t0 = web_time::Instant::now();
let Some(buf) = self.layer_buf_timed(ctx, layer, Some(&mut timing)) else { return };
let t1 = std::time::Instant::now();
let t1 = web_time::Instant::now();
self.composite_layer(ctx, layer, &buf, canvas, opacity);
timing.process_ms = (t1 - t0).as_secs_f64() * 1e3;
timing.composite_ms = t1.elapsed().as_secs_f64() * 1e3;
+1
View File
@@ -25,6 +25,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
rayon = { workspace = true }
web-time = { workspace = true }
kurbo = { workspace = true }
[dev-dependencies]
+10 -1
View File
@@ -355,7 +355,9 @@ fn render_frame(app: &EffectcraftApp, p: &Value) -> Outcome {
Err(e) => return err(e),
};
let mut out = json!({"comp": cid.0, "time": t.seconds(), "width": w, "height": h});
if p.get("base64").and_then(Value::as_bool) == Some(true) {
// (the web has no file system: inline unless a path is given)
let inline = p.get("base64").and_then(Value::as_bool).unwrap_or(cfg!(target_arch = "wasm32") && p.get("path").is_none());
if inline {
out["png"] = json!(base64(&png));
return ok(out);
}
@@ -427,6 +429,13 @@ pub fn save_screenshot(ctx: &egui::Context, image: &egui::ColorImage, path: Opti
rgba.extend_from_slice(&[c.r(), c.g(), c.b(), 255]);
}
}
if path.is_none() && cfg!(target_arch = "wasm32") {
// no file system on the web: inline PNG
return match encode_png(&rgba, cw as u32, ch as u32) {
Ok(png) => json!({"ok": true, "result": {"png": base64(&png), "width": cw, "height": ch}}),
Err(e) => json!({"ok": false, "error": e}),
};
}
let path = path.map(str::to_string).unwrap_or_else(|| std::env::temp_dir().join("effectcraft-screenshot.png").to_string_lossy().to_string());
match encode_png(&rgba, cw as u32, ch as u32) {
Ok(png) => match std::fs::write(&path, png) {
+92 -43
View File
@@ -3,6 +3,9 @@
//! Frames render on a dedicated thread pool from immutable `Arc<Project>` snapshots, so the UI
//! never waits for the compositor. Results land in a memory-budgeted cache keyed by (project
//! revision, comp, frame, scale); the timeline draws the cached range as the green cache bar.
//!
//! wasm32 has no threads: jobs wait in the same priority queue and [`Frames::pump`] renders them
//! on the UI thread between egui frames, within a time budget.
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex};
@@ -61,6 +64,7 @@ pub struct Frames {
inflight: Arc<Mutex<HashSet<FrameKey>>>,
/// Pending jobs, picked by priority when a pool thread frees up (the viewer's frame first).
queue: Arc<Mutex<Queue>>,
#[cfg(not(target_arch = "wasm32"))]
pool: rayon::ThreadPool,
ctx: Option<egui::Context>,
/// Render time of the last viewer (urgent) frame in ms, for the Info panel / perf readout.
@@ -69,11 +73,13 @@ pub struct Frames {
impl Default for Frames {
fn default() -> Self {
#[cfg(not(target_arch = "wasm32"))]
let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(2, 16);
Frames {
cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, budget: 3 << 30 })),
inflight: Arc::new(Mutex::new(HashSet::new())),
queue: Arc::new(Mutex::new(Queue::default())),
#[cfg(not(target_arch = "wasm32"))]
pool: rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("ec-frame-{i}")).build().expect("frame pool"),
ctx: None,
last_ms: Arc::new(Mutex::new(0.0)),
@@ -176,52 +182,95 @@ impl Frames {
let seq = q.seq;
q.jobs.push(Job { key, src: src.clone(), comp, t, opts, urgent, seq });
drop(q);
let queue = self.queue.clone();
let cache = self.cache.clone();
let inflight = self.inflight.clone();
let ctx = self.ctx.clone();
let last = self.last_ms.clone();
// One spawn per job; each spawn renders whichever queued job matters most right now.
self.pool.spawn(move || {
let job = {
let Ok(mut q) = queue.lock() else { return };
// Urgent first (newest), then prefetch in request order.
let best = q.jobs.iter().enumerate().max_by_key(|(_, j)| (j.urgent, if j.urgent { j.seq as i64 } else { -(j.seq as i64) })).map(|(i, _)| i);
let Some(i) = best else { return };
let job = q.jobs.swap_remove(i);
q.running.insert(job.key);
if job.urgent {
q.urgent_running += 1;
}
job
};
let t0 = std::time::Instant::now();
let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts);
r.expr = job.src.expr.as_deref();
r.cache = Some(&job.src.layer_cache);
let img = r.comp_frame(job.comp, job.t);
let ci = Arc::new(to_color_image(&img));
if job.urgent
&& let Ok(mut l) = last.lock()
{
*l = t0.elapsed().as_secs_f64() * 1000.0;
#[cfg(not(target_arch = "wasm32"))]
{
let w = self.worker();
// One spawn per job; each spawn renders whichever queued job matters most right now.
self.pool.spawn(move || {
w.run_next();
});
}
#[cfg(target_arch = "wasm32")]
if let Some(ctx) = &self.ctx {
// rendered by `pump` after this UI frame
ctx.request_repaint();
}
}
fn worker(&self) -> Worker {
Worker { queue: self.queue.clone(), cache: self.cache.clone(), inflight: self.inflight.clone(), ctx: self.ctx.clone(), last: self.last_ms.clone() }
}
/// Render queued frames on this thread, most important first, until the queue is empty or
/// `budget` has passed (at least one frame). Returns whether frames are still queued. Only
/// wasm32 needs this (native frames render on the pool); elsewhere it does nothing.
pub fn pump(&self, budget: std::time::Duration) -> bool {
if cfg!(not(target_arch = "wasm32")) {
return false;
}
let t0 = web_time::Instant::now();
let w = self.worker();
while w.run_next() {
if t0.elapsed() >= budget {
break;
}
if let Ok(mut c) = cache.lock() {
c.insert(job.key, ci);
}
self.queue.lock().map(|q| !q.jobs.is_empty()).unwrap_or(false)
}
}
/// Renders queued jobs (on a pool thread, or the UI thread on wasm32).
struct Worker {
queue: Arc<Mutex<Queue>>,
cache: Arc<Mutex<Cache>>,
inflight: Arc<Mutex<HashSet<FrameKey>>>,
ctx: Option<egui::Context>,
last: Arc<Mutex<f64>>,
}
impl Worker {
/// Render the queued job that matters most right now. `false` when the queue was empty.
fn run_next(&self) -> bool {
let Worker { queue, cache, inflight, ctx, last } = self;
let job = {
let Ok(mut q) = queue.lock() else { return false };
// Urgent first (newest), then prefetch in request order.
let best = q.jobs.iter().enumerate().max_by_key(|(_, j)| (j.urgent, if j.urgent { j.seq as i64 } else { -(j.seq as i64) })).map(|(i, _)| i);
let Some(i) = best else { return false };
let job = q.jobs.swap_remove(i);
q.running.insert(job.key);
if job.urgent {
q.urgent_running += 1;
}
if let Ok(mut inf) = inflight.lock() {
inf.remove(&job.key);
job
};
let t0 = web_time::Instant::now();
let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts);
r.expr = job.src.expr.as_deref();
r.cache = Some(&job.src.layer_cache);
let img = r.comp_frame(job.comp, job.t);
let ci = Arc::new(to_color_image(&img));
if job.urgent
&& let Ok(mut l) = last.lock()
{
*l = t0.elapsed().as_secs_f64() * 1000.0;
}
if let Ok(mut c) = cache.lock() {
c.insert(job.key, ci);
}
if let Ok(mut inf) = inflight.lock() {
inf.remove(&job.key);
}
if let Ok(mut q) = queue.lock() {
q.running.remove(&job.key);
if job.urgent {
q.urgent_running -= 1;
}
if let Ok(mut q) = queue.lock() {
q.running.remove(&job.key);
if job.urgent {
q.urgent_running -= 1;
}
}
if let Some(ctx) = ctx {
ctx.request_repaint();
}
});
}
if let Some(ctx) = ctx {
ctx.request_repaint();
}
true
}
}
+8
View File
@@ -327,6 +327,10 @@ impl EffectcraftApp {
}
fn frames_parallelism(&self) -> usize {
if cfg!(target_arch = "wasm32") {
// frames render one at a time on the UI thread (`Frames::pump`)
return 1;
}
std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4)
}
@@ -625,6 +629,10 @@ impl eframe::App for EffectcraftApp {
}
self.frame(ui);
let ctx = ui.ctx().clone();
// wasm32: no frame threads; render queued frames now, between UI frames.
if cfg!(target_arch = "wasm32") && self.frames.pump(std::time::Duration::from_millis(if self.playback.playing { 24 } else { 40 })) {
ctx.request_repaint();
}
self.last_ui_time = ctx.input(|i| i.time);
if !self.synthetic.is_empty() {
ctx.request_repaint();