M13.10: web frame workers fed by project diffs, offloaded Roto Brush propagation, non-blocking wait jobs, browser Media Browser
Viewer frames render in long-lived Web Workers holding a project replica (engine::remote: structural JSON diff/patch, Mirror, FrameServer); the frame cache hands jobs to a RemoteFrames renderer (UI-thread fallback). Roto Brush propagation runs in a job worker and streams segmentations back (FrameSeg binary form), relayed to frame workers. Control-channel wait:true commands whose job is offloaded reply when it ends. The Media Browser browses a pluggable Browser: the file system on the desktop; browser storage and File System Access folders on the web. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
0f591e0856
commit
5bb6768766
@@ -55,6 +55,87 @@ pub enum Outcome {
|
||||
path: Option<String>,
|
||||
crop: Option<[f32; 4]>,
|
||||
},
|
||||
/// Reply once background jobs end (a `wait: true` command whose job runs in a worker).
|
||||
AwaitJobs(JobWaiter),
|
||||
}
|
||||
|
||||
/// A `wait: true` engine command whose job was sent to the session's offload (the browser's
|
||||
/// Web Workers) instead of blocking the UI thread: the reply goes out when the job ends.
|
||||
pub struct JobWaiter {
|
||||
pub command: String,
|
||||
pub params: Value,
|
||||
/// The command's own result (with `wait: false`).
|
||||
pub result: Value,
|
||||
/// Ids of the jobs it started (`jobs.list` ids: `render`, `track`, `roto`…).
|
||||
pub jobs: Vec<String>,
|
||||
/// Length of [`effectcraft_engine::Session::offload_log`] when it started.
|
||||
pub log_len: usize,
|
||||
}
|
||||
|
||||
/// Commands that block with `wait` (and its default).
|
||||
fn waits(command: &str, params: &Value) -> bool {
|
||||
let default = command == "renderQueue.render";
|
||||
params.get("wait").and_then(Value::as_bool).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Run an engine command. A waiting command (`wait: true`) whose job the session offloads
|
||||
/// runs with `wait: false` instead, and the reply waits for the job ([`Outcome::AwaitJobs`]),
|
||||
/// so the browser's UI keeps drawing while it runs.
|
||||
fn execute_engine(app: &mut EffectcraftApp, id: &str, params: Value) -> Result<Outcome, String> {
|
||||
if !app.session.offloads() || !waits(id, ¶ms) {
|
||||
return app.session.execute_checked(id, params).map(ok).map_err(|e| e.to_string());
|
||||
}
|
||||
let before: Vec<String> = app.session.jobs().into_iter().map(|j| j.id).collect();
|
||||
let log_len = app.session.offload_log.len();
|
||||
let mut p = params.clone();
|
||||
p["wait"] = json!(false);
|
||||
let result = app.session.execute_checked(id, p).map_err(|e| e.to_string())?;
|
||||
let jobs: Vec<String> = app.session.jobs().into_iter().map(|j| j.id).filter(|j| !before.contains(j)).collect();
|
||||
if jobs.is_empty() {
|
||||
return Ok(ok(result));
|
||||
}
|
||||
Ok(Outcome::AwaitJobs(JobWaiter { command: id.to_string(), params, result, jobs, log_len }))
|
||||
}
|
||||
|
||||
impl JobWaiter {
|
||||
/// Whether its jobs are still running.
|
||||
pub fn pending(&self, app: &EffectcraftApp) -> bool {
|
||||
app.session.jobs().iter().any(|j| self.jobs.contains(&j.id))
|
||||
}
|
||||
|
||||
/// The reply: what the blocking command would have returned (`running: false`, the final
|
||||
/// progress, render items and analysis status), or the job's error.
|
||||
pub fn finish(self, app: &mut EffectcraftApp) -> Value {
|
||||
let s = &mut app.session;
|
||||
s.poll_render();
|
||||
let errors: Vec<String> = s.offload_log.iter().skip(self.log_len).filter_map(|(_, e)| e.clone()).collect();
|
||||
if let Some(e) = errors.first() {
|
||||
return json!({"ok": false, "error": e});
|
||||
}
|
||||
let mut r = self.result;
|
||||
if r.get("running").is_some() {
|
||||
r["running"] = json!(false);
|
||||
}
|
||||
if self.command == "renderQueue.render" {
|
||||
let ids: Vec<Value> = r["items"].as_array().map(|a| a.iter().map(|i| i["id"].clone()).collect()).unwrap_or_default();
|
||||
if let Ok(list) = s.execute("renderQueue.list", json!({})) {
|
||||
r["items"] =
|
||||
json!(list["items"].as_array().map(|a| a.iter().filter(|i| ids.contains(&i["id"])).cloned().collect::<Vec<_>>()).unwrap_or_default());
|
||||
}
|
||||
r["rendering"] = json!(s.is_rendering());
|
||||
}
|
||||
let prefix = self.command.split('.').next().unwrap_or("");
|
||||
if matches!(prefix, "warp" | "camera" | "roto")
|
||||
&& r.get("layer").is_some()
|
||||
&& let Ok(st) = s.execute(&format!("{prefix}.status"), json!({"layer": r["layer"], "effect": r["effect"]}))
|
||||
{
|
||||
r["status"] = st;
|
||||
}
|
||||
if r.get("progress").is_some() {
|
||||
r["progress"] = Value::Null;
|
||||
}
|
||||
json!({"ok": true, "result": r})
|
||||
}
|
||||
}
|
||||
|
||||
fn ok(v: Value) -> Outcome {
|
||||
@@ -94,12 +175,12 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
// `comp.new {}` creates a default comp); UI-only ids (`tool.*`, `view.*`, `window.*`,
|
||||
// `playback.*` …) and `ui.menu.invoke` go through the menu dispatcher like a click.
|
||||
let r = if req.method == "engine.execute" && effectcraft_engine::find_command(id).is_some() {
|
||||
app.session.execute_checked(id, params).map_err(|e| e.to_string())
|
||||
execute_engine(app, id, params)
|
||||
} else {
|
||||
crate::menus::invoke(app, ctx, id, params)
|
||||
crate::menus::invoke(app, ctx, id, params).map(ok)
|
||||
};
|
||||
match r {
|
||||
Ok(v) => ok(v),
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
app.ui.status = e.clone();
|
||||
err(e)
|
||||
|
||||
+182
-23
@@ -4,8 +4,10 @@
|
||||
//! 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.
|
||||
//! wasm32 has no threads: jobs wait in the same priority queue and [`Frames::pump`] hands them
|
||||
//! to a [`RemoteFrames`] (the browser's frame worker, a second engine instance fed with project
|
||||
//! diffs, `effectcraft_engine::remote`) or, without one, renders them on the UI thread between
|
||||
//! egui frames, within a time budget.
|
||||
//!
|
||||
//! With the disk cache on (Settings ▸ Media & Disk Cache), every CPU-rendered frame is also
|
||||
//! written to disk under a content key (the comp's content hash, frame, scale, view and render
|
||||
@@ -163,6 +165,38 @@ fn frame_disk_key(keys: &ContentKeys, project: &Project, key: &FrameKey, opts_ha
|
||||
disk_cache::frame_key(content, key.frame, key.scale, key.view ^ opts_hash)
|
||||
}
|
||||
|
||||
/// A frame for a [`RemoteFrames`] renderer.
|
||||
pub struct RemoteJob {
|
||||
pub project: Arc<Project>,
|
||||
pub revision: u64,
|
||||
pub comp: ItemId,
|
||||
pub t: Tick,
|
||||
pub opts: RenderOpts,
|
||||
}
|
||||
|
||||
/// Premultiplied RGBA8 pixels from a [`RemoteFrames`] renderer.
|
||||
pub struct RemoteFrame {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba: Vec<u8>,
|
||||
/// Render time (ms).
|
||||
pub ms: f64,
|
||||
}
|
||||
|
||||
/// Called once with a remote frame (or why there is none).
|
||||
pub type RemoteDone = Box<dyn FnOnce(Result<RemoteFrame, String>) + Send>;
|
||||
|
||||
/// Renders viewer frames elsewhere (the browser's frame worker), so the UI thread never does.
|
||||
pub trait RemoteFrames: Send + Sync {
|
||||
/// Frames it can render at the same time (0 when it is not usable: frames then render on
|
||||
/// the UI thread again).
|
||||
fn slots(&self) -> usize;
|
||||
/// Start rendering `job`; `done` runs when the frame arrives.
|
||||
fn start(&self, job: RemoteJob, done: RemoteDone);
|
||||
/// Drop cached intermediate results (Edit ▸ Purge).
|
||||
fn purge(&self) {}
|
||||
}
|
||||
|
||||
pub struct Frames {
|
||||
cache: Arc<Mutex<Cache>>,
|
||||
/// Keys queued or rendering.
|
||||
@@ -175,6 +209,9 @@ pub struct Frames {
|
||||
/// Render time of the last viewer (urgent) frame in ms, for the Info panel / perf readout.
|
||||
pub last_ms: Arc<Mutex<f64>>,
|
||||
content_keys: ContentKeys,
|
||||
/// Where frames render instead of the UI thread (wasm32), and how many it is rendering.
|
||||
remote: Option<Arc<dyn RemoteFrames>>,
|
||||
remote_busy: Arc<Mutex<usize>>,
|
||||
}
|
||||
|
||||
impl Default for Frames {
|
||||
@@ -190,6 +227,8 @@ impl Default for Frames {
|
||||
ctx: None,
|
||||
last_ms: Arc::new(Mutex::new(0.0)),
|
||||
content_keys: Arc::default(),
|
||||
remote: None,
|
||||
remote_busy: Arc::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -270,6 +309,9 @@ impl Frames {
|
||||
}
|
||||
|
||||
pub fn clear(&self) {
|
||||
if let Some(r) = &self.remote {
|
||||
r.purge();
|
||||
}
|
||||
if let Ok(mut c) = self.cache.lock() {
|
||||
c.map.clear();
|
||||
c.order.clear();
|
||||
@@ -324,7 +366,7 @@ impl Frames {
|
||||
q.jobs.push(Job { key, src: src.clone(), comp, t, opts, urgent, seq });
|
||||
drop(q);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if self.remote.is_none() {
|
||||
let w = self.worker();
|
||||
// One spawn per job; each spawn renders whichever queued job matters most right now.
|
||||
self.pool.spawn(move || {
|
||||
@@ -349,13 +391,102 @@ impl Frames {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Render frames with `remote` from now on (`None`: on this thread again).
|
||||
pub fn set_remote(&mut self, remote: Option<Arc<dyn RemoteFrames>>) {
|
||||
self.remote = remote;
|
||||
}
|
||||
|
||||
/// Whether frames go to a usable [`RemoteFrames`].
|
||||
pub fn remote_active(&self) -> bool {
|
||||
self.remote.as_ref().is_some_and(|r| r.slots() > 0)
|
||||
}
|
||||
|
||||
/// Frames the remote renderer renders at once (0 without one).
|
||||
pub fn remote_slots(&self) -> usize {
|
||||
self.remote.as_ref().map(|r| r.slots()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Frames being rendered remotely.
|
||||
pub fn remote_busy(&self) -> usize {
|
||||
self.remote_busy.lock().map(|b| *b).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Hand queued frames to the remote renderer while it has free slots, most important first
|
||||
/// (the viewer's frame, then prefetch in request order; a viewer frame requested while every
|
||||
/// slot is busy goes to the first one that frees up). Frames that the GPU compositor can keep
|
||||
/// on the GPU render here instead (no readback). Returns how many were started.
|
||||
pub fn dispatch_remote(&self) -> usize {
|
||||
let Some(remote) = self.remote.clone() else { return 0 };
|
||||
let slots = remote.slots();
|
||||
let w = self.worker();
|
||||
let mut started = 0;
|
||||
loop {
|
||||
let busy = self.remote_busy();
|
||||
if busy >= slots {
|
||||
break;
|
||||
}
|
||||
let job = {
|
||||
let Ok(mut q) = self.queue.lock() else { break };
|
||||
let Some(i) = Queue::best(&q.jobs) else { break };
|
||||
let job = q.jobs.swap_remove(i);
|
||||
q.running.insert(job.key);
|
||||
if job.urgent {
|
||||
q.urgent_running += 1;
|
||||
}
|
||||
job
|
||||
};
|
||||
if job.src.gpu.is_some() && job.src.gpu_display {
|
||||
let t0 = web_time::Instant::now();
|
||||
if let Some(img) = w.render_gpu(&job) {
|
||||
w.finish(&job, img, t0);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Ok(mut b) = self.remote_busy.lock() {
|
||||
*b += 1;
|
||||
}
|
||||
started += 1;
|
||||
let (key, urgent) = (job.key, job.urgent);
|
||||
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 };
|
||||
remote.start(
|
||||
rj,
|
||||
Box::new(move |r: Result<RemoteFrame, String>| {
|
||||
if let Ok(mut b) = busy.lock() {
|
||||
*b = b.saturating_sub(1);
|
||||
}
|
||||
match r {
|
||||
Ok(f) => {
|
||||
let img = egui::ColorImage::from_rgba_premultiplied([f.width as usize, f.height as usize], &f.rgba);
|
||||
fw.finish_key(key, urgent, FrameImage::Cpu(Arc::new(img)), t0);
|
||||
}
|
||||
Err(e) => {
|
||||
// Not rendered (a stale revision, a lost worker): the viewer asks again.
|
||||
log::debug!("remote frame: {e}");
|
||||
fw.release(key, urgent);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
started
|
||||
}
|
||||
|
||||
/// Render queued frames, most important first. With a usable [`RemoteFrames`] they are only
|
||||
/// handed over ([`Frames::dispatch_remote`]); otherwise they render on this thread until the
|
||||
/// queue is empty or `budget` has passed (at least one frame). Returns whether frames are
|
||||
/// still queued or rendering remotely. 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;
|
||||
}
|
||||
if self.remote_active() {
|
||||
self.dispatch_remote();
|
||||
return self.queue.lock().map(|q| !q.jobs.is_empty()).unwrap_or(false) || self.remote_busy() > 0;
|
||||
}
|
||||
let t0 = web_time::Instant::now();
|
||||
let w = self.worker();
|
||||
while w.run_next() {
|
||||
@@ -380,12 +511,10 @@ struct Worker {
|
||||
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, content_keys } = self;
|
||||
let Worker { queue, content_keys, .. } = 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 Some(i) = Queue::best(&q.jobs) else { return false };
|
||||
let job = q.jobs.swap_remove(i);
|
||||
q.running.insert(job.key);
|
||||
if job.urgent {
|
||||
@@ -407,27 +536,50 @@ impl Worker {
|
||||
ci
|
||||
}
|
||||
};
|
||||
if job.urgent
|
||||
&& let Ok(mut l) = last.lock()
|
||||
{
|
||||
self.finish(&job, ci, t0);
|
||||
true
|
||||
}
|
||||
|
||||
/// Store a finished frame and release its job.
|
||||
fn finish(&self, job: &Job, img: FrameImage, t0: web_time::Instant) {
|
||||
self.finish_key(job.key, job.urgent, img, t0);
|
||||
}
|
||||
|
||||
fn finish_key(&self, key: FrameKey, urgent: bool, img: FrameImage, t0: web_time::Instant) {
|
||||
if urgent && let Ok(mut l) = self.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 c) = self.cache.lock() {
|
||||
c.insert(key, img);
|
||||
}
|
||||
if let Ok(mut inf) = inflight.lock() {
|
||||
inf.remove(&job.key);
|
||||
self.release(key, urgent);
|
||||
}
|
||||
|
||||
/// The job of `key` is no longer queued or running (rendered or dropped).
|
||||
fn release(&self, key: FrameKey, urgent: bool) {
|
||||
if let Ok(mut inf) = self.inflight.lock() {
|
||||
inf.remove(&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) = self.queue.lock() {
|
||||
q.running.remove(&key);
|
||||
if urgent {
|
||||
q.urgent_running = q.urgent_running.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
if let Some(ctx) = ctx {
|
||||
if let Some(ctx) = &self.ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The frame on the GPU, kept there for the viewer, if the compositor can do it alone.
|
||||
fn render_gpu(&self, job: &Job) -> Option<FrameImage> {
|
||||
let g = job.src.gpu.as_ref()?;
|
||||
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);
|
||||
r.accel = Some(g as &dyn effectcraft_engine::render::Accelerator);
|
||||
r.active_accel()?;
|
||||
g.render_display(&r, job.comp, job.t).map(|f| FrameImage::Gpu(Arc::new(f)))
|
||||
}
|
||||
|
||||
fn render_job(&self, job: &Job) -> FrameImage {
|
||||
@@ -465,3 +617,10 @@ struct Queue {
|
||||
urgent_running: usize,
|
||||
seq: u64,
|
||||
}
|
||||
|
||||
impl Queue {
|
||||
/// The job that matters most: urgent first (newest), then prefetch in request order.
|
||||
fn best(jobs: &[Job]) -> Option<usize> {
|
||||
jobs.iter().enumerate().max_by_key(|(_, j)| (j.urgent, if j.urgent { j.seq as i64 } else { -(j.seq as i64) })).map(|(i, _)| i)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,6 +143,8 @@ pub struct EffectcraftApp {
|
||||
pub(crate) deferred: Vec<(ControlRequest, f64)>,
|
||||
pub(crate) synthetic: Vec<egui::Event>,
|
||||
pub(crate) input_waiters: Vec<Sender<serde_json::Value>>,
|
||||
/// Control requests waiting for an offloaded job (`wait: true` in the browser).
|
||||
pub(crate) job_waiters: Vec<(control::JobWaiter, Sender<serde_json::Value>)>,
|
||||
queued_screenshots: Vec<(u64, f64, u32)>,
|
||||
pending_screenshots: Vec<(u64, Option<String>, Option<[f32; 4]>, Sender<serde_json::Value>, f64)>,
|
||||
next_token: u64,
|
||||
@@ -210,6 +212,7 @@ impl EffectcraftApp {
|
||||
deferred: vec![],
|
||||
synthetic: vec![],
|
||||
input_waiters: vec![],
|
||||
job_waiters: vec![],
|
||||
queued_screenshots: vec![],
|
||||
pending_screenshots: vec![],
|
||||
next_token: 1,
|
||||
@@ -847,8 +850,9 @@ 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;
|
||||
// frame workers render one frame each; without them frames render one at a time
|
||||
// on the UI thread (`Frames::pump`)
|
||||
return self.frames.remote_slots().max(1);
|
||||
}
|
||||
std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4)
|
||||
}
|
||||
@@ -881,6 +885,10 @@ impl EffectcraftApp {
|
||||
}
|
||||
}
|
||||
control::Outcome::AfterInput => self.input_waiters.push(reply),
|
||||
control::Outcome::AwaitJobs(w) => {
|
||||
self.job_waiters.push((w, reply));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
control::Outcome::Screenshot { path, crop } => {
|
||||
// A covered or minimized window presents no frames (macOS skips its redraws), so
|
||||
// a screenshot would never arrive and nothing would tick its timeout.
|
||||
@@ -897,6 +905,28 @@ impl EffectcraftApp {
|
||||
}
|
||||
}
|
||||
self.control_rx = Some(rx);
|
||||
self.finish_job_waiters(ctx);
|
||||
}
|
||||
|
||||
/// Reply to the control requests whose offloaded jobs ended.
|
||||
fn finish_job_waiters(&mut self, ctx: &egui::Context) {
|
||||
if self.job_waiters.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.session.poll_render();
|
||||
self.session.poll_offload();
|
||||
let waiters = std::mem::take(&mut self.job_waiters);
|
||||
for (w, reply) in waiters {
|
||||
if w.pending(self) {
|
||||
self.job_waiters.push((w, reply));
|
||||
} else {
|
||||
let v = w.finish(self);
|
||||
let _ = reply.send(v);
|
||||
}
|
||||
}
|
||||
if !self.job_waiters.is_empty() {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
fn issue_screenshots(&mut self, ctx: &egui::Context) {
|
||||
|
||||
@@ -65,13 +65,13 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let p = ui.painter().with_clip_rect(rect);
|
||||
p.rect_filled(rect, 0.0, t.panel_bg);
|
||||
if !mb::available() {
|
||||
p.text(rect.center(), Align2::CENTER_CENTER, "The Media Browser needs the desktop app (use File ▸ Import here)", Tokens::ui(12.0), t.text_faint);
|
||||
let Some(b) = app.session.media_browser() else {
|
||||
p.text(rect.center(), Align2::CENTER_CENTER, "The Media Browser is not available here (use File ▸ Import)", Tokens::ui(12.0), t.text_faint);
|
||||
app.auto.add("mediaBrowser.unavailable", rect, "Media Browser unavailable");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let st = app.session.state.media_browser.clone();
|
||||
let dir = st.folder.clone().unwrap_or_else(mb::home);
|
||||
let dir = st.folder.clone().unwrap_or_else(|| b.home());
|
||||
// Listing cached per folder for a second.
|
||||
let lid = egui::Id::new(("mb-list", dir.clone(), st.importable_only));
|
||||
let now = ctx.input(|i| i.time);
|
||||
@@ -79,7 +79,7 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let entries = match listing {
|
||||
Some((at, l)) if now - at < 1.0 => l,
|
||||
_ => {
|
||||
let l = mb::list(&dir, st.importable_only);
|
||||
let l = b.list(&dir, st.importable_only);
|
||||
ctx.data_mut(|d| d.insert_temp(lid, (now, l.clone())));
|
||||
l
|
||||
}
|
||||
@@ -104,6 +104,20 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if only != st.importable_only {
|
||||
kit::exec(app, "mediaBrowser.go", json!({"path": dir, "importableOnly": only}));
|
||||
}
|
||||
// The browser's own actions (web: Open Folder…, Add Files…), right-aligned.
|
||||
let mut ax = rect.max.x - 8.0;
|
||||
for (id, label) in b.actions().iter().rev() {
|
||||
let w = 14.0 + label.chars().count() as f32 * 6.4;
|
||||
ax -= w;
|
||||
if ax < x + 96.0 {
|
||||
break;
|
||||
}
|
||||
if kit::button(app, ui, Rect::from_min_size(pos2(ax, y), vec2(w, 20.0)), &format!("mediaBrowser.action.{id}"), label, false) {
|
||||
kit::exec(app, "mediaBrowser.action", json!({"action": id}));
|
||||
ctx.data_mut(|d| d.remove::<(f64, Result<Vec<mb::Entry>, String>)>(lid));
|
||||
}
|
||||
ax -= 6.0;
|
||||
}
|
||||
// The path on its own row.
|
||||
let _ = x;
|
||||
let py = y + 24.0;
|
||||
@@ -114,7 +128,7 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
p.line_segment([side.right_top(), side.right_bottom()], Stroke::new(1.0, t.separator));
|
||||
p.text(pos2(side.min.x + 10.0, side.min.y + 10.0), Align2::LEFT_CENTER, "Favorites", Tokens::semibold(11.5), t.text_dim);
|
||||
let mut fy = side.min.y + 22.0;
|
||||
let mut places: Vec<(String, String)> = vec![("Home".into(), mb::home())];
|
||||
let mut places: Vec<(String, String)> = b.places();
|
||||
places.extend(
|
||||
st.favorites.iter().map(|f| (std::path::Path::new(f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| f.clone()), f.clone())),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
//! Headless checks for M13.10 (web app depth), run natively with stand-ins for the browser's
|
||||
//! workers:
|
||||
//!
|
||||
//! - viewer frames go to a [`RemoteFrames`] renderer (the browser's frame worker, here an
|
||||
//! in-process [`FrameServer`] fed through JSON with project diffs) instead of rendering on the
|
||||
//! UI thread, the viewer's frame first, and come back identical;
|
||||
//! - a control-channel `wait: true` command whose job is offloaded replies only when the job
|
||||
//! ends, while the UI keeps running.
|
||||
|
||||
use std::sync::mpsc::TryRecvError;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_engine::Session;
|
||||
use effectcraft_engine::offload::{Inbox, Offload, Post, WorkerRequest};
|
||||
use effectcraft_engine::remote::{FrameMsg, FrameReply, FrameServer, Mirror};
|
||||
use effectcraft_engine::render::RenderOpts;
|
||||
use effectcraft_ui_egui::frames::{FrameImage, FrameKey, Frames, RemoteDone, RemoteFrame, RemoteFrames, RemoteJob, RenderSource};
|
||||
use effectcraft_ui_egui::{ControlRequest, EffectcraftApp};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
/// A frame worker in the same process: messages go through JSON like `postMessage`; rendered
|
||||
/// frames are held until [`FakeWorker::deliver`] (a busy worker) or dropped by
|
||||
/// [`FakeWorker::lose`].
|
||||
struct FakeWorker {
|
||||
slots: usize,
|
||||
state: Mutex<(Mirror, FrameServer, Vec<(RemoteDone, RemoteFrame)>, u64)>,
|
||||
/// Patch / full-project syncs sent.
|
||||
syncs: Mutex<Vec<&'static str>>,
|
||||
}
|
||||
|
||||
impl FakeWorker {
|
||||
fn new(s: &Session, slots: usize) -> FakeWorker {
|
||||
FakeWorker { slots, state: Mutex::new((Mirror::default(), FrameServer::new(s.footage.clone(), s.expr.clone()), vec![], 0)), syncs: Mutex::default() }
|
||||
}
|
||||
fn pending(&self) -> usize {
|
||||
self.state.lock().unwrap().2.len()
|
||||
}
|
||||
fn take(&self) -> Vec<(RemoteDone, RemoteFrame)> {
|
||||
std::mem::take(&mut self.state.lock().unwrap().2)
|
||||
}
|
||||
/// Post every rendered frame back.
|
||||
fn deliver(&self) {
|
||||
for (done, f) in self.take() {
|
||||
done(Ok(f));
|
||||
}
|
||||
}
|
||||
/// The worker died: its frames never arrive.
|
||||
fn lose(&self) {
|
||||
for (done, _) in self.take() {
|
||||
done(Err("worker lost".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rt<T: serde::Serialize + for<'de> serde::Deserialize<'de>>(v: &T) -> T {
|
||||
serde_json::from_str(&serde_json::to_string(v).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
impl RemoteFrames for FakeWorker {
|
||||
fn slots(&self) -> usize {
|
||||
self.slots
|
||||
}
|
||||
fn start(&self, job: RemoteJob, done: RemoteDone) {
|
||||
let mut st = self.state.lock().unwrap();
|
||||
let (mirror, server, pending, next) = &mut *st;
|
||||
if let Some(m) = mirror.sync(job.revision, &job.project) {
|
||||
self.syncs.lock().unwrap().push(if matches!(m, FrameMsg::Patch { .. }) { "patch" } else { "project" });
|
||||
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) }));
|
||||
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)))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn source(s: &Session) -> RenderSource {
|
||||
RenderSource {
|
||||
project: s.project.clone(),
|
||||
footage: s.footage.clone(),
|
||||
expr: s.expr.clone(),
|
||||
layer_cache: s.layer_cache.clone(),
|
||||
gpu: None,
|
||||
gpu_display: false,
|
||||
disk: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewer_frames_render_remotely_from_project_diffs() {
|
||||
let mut s = Session::default();
|
||||
s.execute("file.openDemoProject", json!({})).unwrap();
|
||||
let comp = s.active_comp_id().unwrap();
|
||||
let c = s.project.comp(comp).unwrap().clone();
|
||||
let opts = RenderOpts { scale: 0.25, guides: true, ..Default::default() };
|
||||
let key = |rev: u64, f: i64| FrameKey { revision: rev, comp: comp.0, frame: f, scale: 250, view: 0 };
|
||||
let worker = Arc::new(FakeWorker::new(&s, 2));
|
||||
let mut frames = Frames::default();
|
||||
frames.set_remote(Some(worker.clone()));
|
||||
assert!(frames.remote_active());
|
||||
// Three prefetch frames, then the viewer's frame.
|
||||
for f in 1..=3 {
|
||||
frames.request(&source(&s), key(s.revision, f), comp, c.frame_rate.tick_of(f), opts);
|
||||
}
|
||||
frames.request_urgent(&source(&s), key(s.revision, 10), comp, c.frame_rate.tick_of(10), opts);
|
||||
assert_eq!(frames.inflight(), 4);
|
||||
// Nothing renders until dispatched (no frame threads with a remote renderer); the viewer's
|
||||
// frame goes first, then prefetch in request order.
|
||||
assert_eq!(frames.dispatch_remote(), 2);
|
||||
assert_eq!(frames.remote_busy(), 2);
|
||||
assert_eq!(worker.pending(), 2);
|
||||
assert_eq!(frames.dispatch_remote(), 0, "both slots are busy");
|
||||
assert_eq!(*worker.syncs.lock().unwrap(), vec!["project"], "the first sync is the whole project");
|
||||
// Frames arrive: the cache holds exactly what the page would have rendered.
|
||||
worker.deliver();
|
||||
assert_eq!(frames.remote_busy(), 0);
|
||||
let img = match frames.get(&key(s.revision, 10)).expect("viewer frame cached") {
|
||||
FrameImage::Cpu(c) => c,
|
||||
FrameImage::Gpu(_) => unreachable!(),
|
||||
};
|
||||
let local = effectcraft_ui_egui::frames::to_color_image(&s.render(comp, c.frame_rate.tick_of(10), opts));
|
||||
assert_eq!(img.size, local.size);
|
||||
assert_eq!(img.pixels, local.pixels);
|
||||
assert!(frames.is_cached(&key(s.revision, 1)));
|
||||
assert!(!frames.is_cached(&key(s.revision, 2)));
|
||||
// The rest; an edit later travels as a patch.
|
||||
frames.dispatch_remote();
|
||||
worker.deliver();
|
||||
frames.dispatch_remote();
|
||||
worker.deliver();
|
||||
assert_eq!(frames.inflight(), 0);
|
||||
s.execute("layer.newSolid", json!({"color": "#ff8800"})).unwrap();
|
||||
frames.request_urgent(&source(&s), key(s.revision, 10), comp, c.frame_rate.tick_of(10), opts);
|
||||
frames.dispatch_remote();
|
||||
worker.deliver();
|
||||
assert_eq!(worker.syncs.lock().unwrap().last(), Some(&"patch"));
|
||||
let FrameImage::Cpu(img) = frames.get(&key(s.revision, 10)).unwrap() else { unreachable!() };
|
||||
let local = effectcraft_ui_egui::frames::to_color_image(&s.render(comp, c.frame_rate.tick_of(10), opts));
|
||||
assert_eq!(img.pixels, local.pixels);
|
||||
// A lost frame is released (requested again later), not cached.
|
||||
frames.request(&source(&s), key(s.revision, 20), comp, c.frame_rate.tick_of(20), opts);
|
||||
frames.dispatch_remote();
|
||||
worker.lose();
|
||||
assert_eq!(frames.inflight(), 0);
|
||||
assert!(!frames.is_cached(&key(s.revision, 20)));
|
||||
// Without slots the remote renderer is unusable (frames render here again).
|
||||
frames.set_remote(Some(Arc::new(FakeWorker::new(&s, 0))));
|
||||
assert!(!frames.remote_active());
|
||||
}
|
||||
|
||||
/// Holds offloaded jobs until the test runs them.
|
||||
#[derive(Default)]
|
||||
struct Manual(Mutex<Vec<(WorkerRequest, Arc<Inbox>)>>);
|
||||
|
||||
impl Offload for Manual {
|
||||
fn start(&self, req: WorkerRequest, inbox: Arc<Inbox>) -> Result<(), String> {
|
||||
self.0.lock().unwrap().push((req, inbox));
|
||||
Ok(())
|
||||
}
|
||||
fn cancel(&self, _: u64) {}
|
||||
}
|
||||
|
||||
fn exporter() -> Arc<effectcraft_host::FileExporter> {
|
||||
let sink: Arc<dyn Fn(&str, Vec<u8>) + Send + Sync> = Arc::new(|_: &str, _: Vec<u8>| {});
|
||||
Arc::new(effectcraft_host::FileExporter { sink: Some(sink) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiting_commands_reply_when_their_offloaded_job_ends() {
|
||||
let off = Arc::new(Manual::default());
|
||||
let mut s = Session { offload: Some(off.clone()), exporter: Some(exporter()), ..Default::default() };
|
||||
s.execute("comp.new", json!({"name": "W", "width": 64, "height": 48, "frameRate": 10, "duration": 1})).unwrap();
|
||||
s.execute("layer.newSolid", json!({"color": "#406080"})).unwrap();
|
||||
s.execute("renderQueue.add", json!({"format": "gif", "output": "/w.gif"})).unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_eframe(|_| EffectcraftApp::new(s).with_control(rx));
|
||||
h.run_steps(2);
|
||||
// `renderQueue.render` waits by default: the job goes to the worker, the reply waits.
|
||||
let (req, reply) = ControlRequest::new("engine.execute", json!({"command": "renderQueue.render", "params": {}}));
|
||||
tx.send(req).unwrap();
|
||||
h.run_steps(4);
|
||||
assert_eq!(reply.try_recv().unwrap_err(), TryRecvError::Empty, "no reply while the job runs");
|
||||
assert!(h.state().session.is_rendering());
|
||||
let (job, inbox) = off.0.lock().unwrap().pop().expect("the render went to the worker");
|
||||
// The worker runs it.
|
||||
let mut w = Session { exporter: Some(exporter()), ..Default::default() };
|
||||
let post: Post = std::rc::Rc::new(move |r| inbox.push(r));
|
||||
effectcraft_engine::offload::run_request(&mut w, job, &post);
|
||||
h.run_steps(4);
|
||||
let v = reply.try_recv().expect("replied once the job ended");
|
||||
assert_eq!(v["ok"], true, "{v}");
|
||||
assert_eq!(v["result"]["rendering"], false, "{v}");
|
||||
assert_eq!(v["result"]["items"][0]["status"], "Done", "{v}");
|
||||
// `wait: false` replies at once.
|
||||
h.state_mut().session.execute("renderQueue.add", json!({"format": "gif", "output": "/w2.gif"})).unwrap();
|
||||
let (req, reply) = ControlRequest::new("engine.execute", json!({"command": "renderQueue.render", "params": {"wait": false}}));
|
||||
tx.send(req).unwrap();
|
||||
h.run_steps(2);
|
||||
let v = reply.try_recv().expect("immediate reply");
|
||||
assert_eq!(v["result"]["rendering"], true, "{v}");
|
||||
}
|
||||
Reference in New Issue
Block a user