M13.30: web depth and polish
- GPU in browser job workers: each job worker opens its own WebGPU device (deferred readbacks); the Render Queue export and the analyses' frame loops are futures (render::passes, offload::run_request_async) whose frames render in passes, awaiting the device between them. GPU particles and Advanced 3D read back under keys too. workers.jobs reports passes and readbacks; the smoke test measures them. - Layer buffers in the browser's OPFS disk cache: frame workers back their layer caches with a PrefetchStore; the page plans what to fetch before a request from recent misses (LayerPrefetch over the shared DiskIndex). - Templates embed footage (default on, size-capped with a warning) and creating from a template extracts it next to the new project / into browser storage. - ICC LUT profiles (lut8/lut16/lutAtoB/lutBtoA, from the public ICC spec) in Simulate Output > My Custom RGB, baked into a 3D LUT for the viewer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
d39c0e818c
commit
f3715aac32
@@ -20,7 +20,7 @@ use std::sync::{Arc, Mutex};
|
||||
use effectcraft_effects::camera_tracker::{self as ct, AVERAGE_ERROR, METHOD_USED, SOLVE, SOLVE_KEY, TRACKS, TRACKS_KEY};
|
||||
use effectcraft_keyframe::{Keyframe, Value};
|
||||
use effectcraft_project::{AutoOrient, GroupKind, ItemId, ItemKind, Layer, LayerId, Project, PropGroup, Uid};
|
||||
use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
|
||||
use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use effectcraft_track::camtrack::linalg::{self, Similarity, V3};
|
||||
use effectcraft_track::camtrack::{AnalyzeOpts, CameraSolve, CameraTracks, SolveSettings, Target, TrackAnalyzer};
|
||||
@@ -196,8 +196,11 @@ fn input_frame(r: &Renderer, ctx: &EvalCtx, layer: &Layer, effect_index: usize)
|
||||
Some((Arc::new(buf.img.clone()), buf.offset))
|
||||
}
|
||||
|
||||
fn run_work(w: CamWork, shared: &CameraShared) {
|
||||
async fn run_work(w: CamWork, shared: &CameraShared) {
|
||||
let t0 = web_time::Instant::now();
|
||||
// A browser job worker's GPU (deferred readbacks): frames render in passes.
|
||||
let accel = crate::offload::job_accel();
|
||||
let accel = accel.as_deref();
|
||||
let fail = |msg: &str| {
|
||||
let mut s = lock(&shared.state);
|
||||
s.error = Some(msg.to_string());
|
||||
@@ -215,29 +218,32 @@ fn run_work(w: CamWork, shared: &CameraShared) {
|
||||
let (tracks, fresh) = match w.tracks.clone() {
|
||||
Some(t) => (t, false),
|
||||
None => {
|
||||
let mut r = Renderer::new(&w.project, w.footage.as_ref(), RenderOpts { scale: 1.0, ..Default::default() });
|
||||
let mut r = Renderer::new(&w.project, w.footage.as_ref(), crate::offload::analysis_opts(accel));
|
||||
r.expr = w.expr.as_deref();
|
||||
r.cache = Some(&w.cache);
|
||||
let r = &r;
|
||||
let ctx0 = EvalCtx::new(&w.project, w.comp, comp, Tick::ZERO);
|
||||
let ctx0 = EvalCtx { expr: w.expr.as_deref(), ..ctx0 };
|
||||
let frame_at = |t: Tick| input_frame(r, &ctx0.at(t), layer, w.effect_index);
|
||||
let ctx0 = &ctx0;
|
||||
let frame_at = |t: Tick| crate::offload::in_passes(accel, move |a| input_frame(&r.with_accel(a), &ctx0.at(t), layer, w.effect_index));
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
s.step = 1;
|
||||
s.total = w.times.len() as u64;
|
||||
}
|
||||
let mut an = TrackAnalyzer::new(w.size, AnalyzeOpts { detailed: w.detailed });
|
||||
let mut next = frame_at(w.times[0]);
|
||||
let mut next = frame_at(w.times[0]).await;
|
||||
for k in 0..w.times.len() {
|
||||
if shared.cancel.load(Ordering::Relaxed) {
|
||||
return cancelled();
|
||||
}
|
||||
let Some(cur) = next.take() else { return fail(&format!("no frame at {:.3} s", w.times[k].seconds())) };
|
||||
let ((), nf) = rayon::join(
|
||||
let ((), nf) = crate::offload::join_fetch(
|
||||
accel.is_some(),
|
||||
|| an.push(&effectcraft_track::Frame { img: &cur.0, offset: cur.1 }),
|
||||
|| if k + 1 < w.times.len() { frame_at(w.times[k + 1]) } else { None },
|
||||
);
|
||||
|| async { if k + 1 < w.times.len() { frame_at(w.times[k + 1]).await } else { None } },
|
||||
)
|
||||
.await;
|
||||
next = nf;
|
||||
let mut s = lock(&shared.state);
|
||||
s.done = k as u64 + 1;
|
||||
@@ -350,11 +356,19 @@ impl Session {
|
||||
st.total = n as u64;
|
||||
}
|
||||
let thread = if wait {
|
||||
run_work(work, &shared);
|
||||
crate::offload::run_or_queue({
|
||||
let sh = shared.clone();
|
||||
async move { run_work(work, &sh).await }
|
||||
});
|
||||
None
|
||||
} else {
|
||||
let sh = shared.clone();
|
||||
Some(std::thread::Builder::new().name("camera-track".into()).spawn(move || run_work(work, &sh)).map_err(|e| e.to_string())?)
|
||||
Some(
|
||||
std::thread::Builder::new()
|
||||
.name("camera-track".into())
|
||||
.spawn(move || effectcraft_render::passes::block_on(run_work(work, &sh)))
|
||||
.map_err(|e| e.to_string())?,
|
||||
)
|
||||
};
|
||||
self.camera_job = Some(CameraJob { shared, thread, comp, layer, effect, key, solve_key });
|
||||
self.events.push(Event::ProjectChanged { revision: self.revision });
|
||||
|
||||
@@ -346,7 +346,13 @@ fn simulate_output(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn custom_rgb_json(c: &CustomRgb) -> Value {
|
||||
serde_json::to_value(c).unwrap_or_default()
|
||||
let mut v = serde_json::to_value(c).unwrap_or_default();
|
||||
// A LUT-based profile's tables stay in Settings; the reply says it is one.
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.remove("iccLut");
|
||||
o.insert("lutProfile".into(), json!(!c.icc_lut.is_empty()));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// View ▸ Simulate Output ▸ My Custom RGB…: define the custom output device (kept in Settings)
|
||||
@@ -367,6 +373,7 @@ fn custom_rgb(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => (1.0, false),
|
||||
};
|
||||
c.icc.clear();
|
||||
c.icc_lut = Default::default();
|
||||
c.name = format!("Custom ({})", prof.label());
|
||||
}
|
||||
}
|
||||
@@ -380,22 +387,33 @@ fn custom_rgb(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut typed = false;
|
||||
for (k, slot) in [("red", &mut c.red), ("green", &mut c.green), ("blue", &mut c.blue), ("white", &mut c.white)] {
|
||||
if let Some(v) = pt(k)? {
|
||||
typed |= *slot != v;
|
||||
*slot = v;
|
||||
}
|
||||
}
|
||||
if let Some(g) = f_p(p, "gamma") {
|
||||
typed |= c.gamma != g;
|
||||
c.gamma = g;
|
||||
}
|
||||
if let Some(b) = b_p(p, "srgbCurve") {
|
||||
typed |= c.srgb_curve != b;
|
||||
c.srgb_curve = b;
|
||||
}
|
||||
// Typed-in numbers replace a LUT-based profile's tables (they only approximated it).
|
||||
if typed {
|
||||
c.icc_lut = Default::default();
|
||||
}
|
||||
if let Some(n) = str_p(p, "name").map(str::trim).filter(|n| !n.is_empty()) {
|
||||
c.name = n.to_string();
|
||||
}
|
||||
match str_p(p, "icc").map(str::trim) {
|
||||
Some("") => c.icc.clear(),
|
||||
Some("") => {
|
||||
c.icc.clear();
|
||||
c.icc_lut = Default::default();
|
||||
}
|
||||
Some(path) if path != c.icc || b_p(p, "reload") == Some(true) => {
|
||||
let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
|
||||
let mut from = CustomRgb::from_icc(&bytes, path).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
@@ -475,7 +493,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"My Custom RGB...",
|
||||
[],
|
||||
None,
|
||||
"{name?, red?/green?/blue?/white?: [x, y] (CIE xy), gamma?, srgbCurve?: bool, icc?: path (RGB ICC profile; read when it changes, \"\" clears), reload?, from?: a Simulate Output profile to start from, reset?, preserveRgb?, apply?: bool (default true: simulate it)} → the definition (kept in Settings)",
|
||||
"{name?, red?/green?/blue?/white?: [x, y] (CIE xy), gamma?, srgbCurve?: bool, icc?: path (RGB ICC profile, matrix/TRC or LUT-based A2B0: read when it changes, \"\" clears; a LUT profile simulates through its tables, `lutProfile` in the reply; typed-in numbers replace it), reload?, from?: a Simulate Output profile to start from, reset?, preserveRgb?, apply?: bool (default true: simulate it)} → the definition (kept in Settings)",
|
||||
always,
|
||||
custom_rgb
|
||||
),
|
||||
|
||||
@@ -92,6 +92,15 @@ pub trait Services: Send + Sync {
|
||||
fn exists(&self, path: &str) -> bool {
|
||||
std::path::Path::new(path).exists()
|
||||
}
|
||||
/// Keep a file the app made for itself (footage extracted from a template): like
|
||||
/// [`Services::write_file`], creating its folder, but never offered as a download (web: it
|
||||
/// goes to browser storage only).
|
||||
fn store_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> {
|
||||
if let Some(d) = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
let _ = std::fs::create_dir_all(d);
|
||||
}
|
||||
self.write_file(path, data)
|
||||
}
|
||||
}
|
||||
|
||||
/// Native filesystem.
|
||||
@@ -109,6 +118,9 @@ impl Services for FsServices {
|
||||
pub trait Importer: Send + Sync {
|
||||
/// Probe a file and return footage metadata.
|
||||
fn probe(&self, path: &str) -> std::result::Result<effectcraft_project::Footage, String>;
|
||||
/// A footage file's bytes are now at `path` (extracted from a template): hosts whose media
|
||||
/// layer reads from memory (the browser) register them; file-based ones need nothing.
|
||||
fn register(&self, _path: &str, _data: &[u8]) {}
|
||||
}
|
||||
|
||||
/// A keyframe reference: layer, property uid, key time (layer time).
|
||||
|
||||
@@ -18,7 +18,7 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_keyframe::{Keyframe, ShapePath, Value};
|
||||
use effectcraft_project::{ItemId, LayerId, Project, Uid};
|
||||
use effectcraft_render::{ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
|
||||
use effectcraft_render::{ExprHost, FootageSource, LayerCache, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use effectcraft_track as trk;
|
||||
use effectcraft_track::fit::Model;
|
||||
@@ -200,8 +200,11 @@ pub(crate) struct MaskWork {
|
||||
pub times: Vec<Tick>,
|
||||
}
|
||||
|
||||
fn run_work(w: MaskWork, shared: &MaskTrackShared) {
|
||||
async fn run_work(w: MaskWork, shared: &MaskTrackShared) {
|
||||
let t0 = web_time::Instant::now();
|
||||
// A browser job worker's GPU (deferred readbacks): frames render in passes.
|
||||
let accel = crate::offload::job_accel();
|
||||
let accel = accel.as_deref();
|
||||
let fail = |msg: &str| {
|
||||
let mut s = lock(&shared.state);
|
||||
s.error = Some(msg.to_string());
|
||||
@@ -209,20 +212,22 @@ fn run_work(w: MaskWork, shared: &MaskTrackShared) {
|
||||
};
|
||||
let Some(comp) = w.project.comp(w.comp) else { return fail("composition missing") };
|
||||
let Some(layer) = comp.layer(w.layer) else { return fail("layer missing") };
|
||||
let mut r = Renderer::new(&w.project, w.footage.as_ref(), RenderOpts { scale: 1.0, ..Default::default() });
|
||||
let mut r = Renderer::new(&w.project, w.footage.as_ref(), crate::offload::analysis_opts(accel));
|
||||
r.expr = w.expr.as_deref();
|
||||
r.cache = Some(&w.cache);
|
||||
let r = &r;
|
||||
let frame_at = |t: Tick| source_frame(r, &w.project, w.comp, comp, layer, t, w.expr.as_deref());
|
||||
let wr = &w;
|
||||
let frame_at =
|
||||
|t: Tick| crate::offload::in_passes(accel, move |a| source_frame(&r.with_accel(a), &wr.project, wr.comp, comp, layer, t, wr.expr.as_deref()));
|
||||
lock(&shared.state).total = w.times.len().saturating_sub(1) as u64;
|
||||
let Some(first) = frame_at(w.times[0]) else { return fail("the layer has no pixels to track") };
|
||||
let Some(first) = frame_at(w.times[0]).await else { return fail("the layer has no pixels to track") };
|
||||
if w.method.is_face() {
|
||||
return run_face(&w, shared, first, &frame_at, layer, t0);
|
||||
return run_face(&w, shared, first, &frame_at, accel.is_some(), layer, t0).await;
|
||||
}
|
||||
let mut tracker = trk::mask::MaskTracker::new(w.method.model(), flatten(&w.path, 8), &trk::Frame { img: &first.0, offset: first.1 });
|
||||
let mut path = w.path.clone();
|
||||
lock(&shared.frames).push((layer.layer_time(w.times[0]), w.times[0], path.clone(), None));
|
||||
let mut next = if w.times.len() > 1 { frame_at(w.times[1]) } else { None };
|
||||
let mut next = if w.times.len() > 1 { frame_at(w.times[1]).await } else { None };
|
||||
for k in 1..w.times.len() {
|
||||
if shared.cancel.load(Ordering::Relaxed) {
|
||||
lock(&shared.state).cancelled = true;
|
||||
@@ -232,8 +237,12 @@ fn run_work(w: MaskWork, shared: &MaskTrackShared) {
|
||||
lock(&shared.state).error = Some(format!("no frame at {:.3} s", w.times[k].seconds()));
|
||||
break;
|
||||
};
|
||||
let (res, nf) =
|
||||
rayon::join(|| tracker.step(&trk::Frame { img: &cur.0, offset: cur.1 }), || if k + 1 < w.times.len() { frame_at(w.times[k + 1]) } else { None });
|
||||
let (res, nf) = crate::offload::join_fetch(
|
||||
accel.is_some(),
|
||||
|| tracker.step(&trk::Frame { img: &cur.0, offset: cur.1 }),
|
||||
|| async { if k + 1 < w.times.len() { frame_at(w.times[k + 1]).await } else { None } },
|
||||
)
|
||||
.await;
|
||||
next = nf;
|
||||
let Some(step) = res else {
|
||||
lock(&shared.state).error = Some(format!("lost the mask's pixels at {:.3} s (too little texture inside the mask)", w.times[k].seconds()));
|
||||
@@ -254,11 +263,13 @@ fn run_work(w: MaskWork, shared: &MaskTrackShared) {
|
||||
}
|
||||
|
||||
/// Face tracking: the face outline keys the mask; Detailed Features adds the landmarks.
|
||||
fn run_face(
|
||||
/// `deferred`: frames render in passes (awaited one after the other).
|
||||
async fn run_face<F: std::future::Future<Output = Option<(Arc<effectcraft_raster::Image>, [f64; 2])>>>(
|
||||
w: &MaskWork,
|
||||
shared: &MaskTrackShared,
|
||||
first: (Arc<effectcraft_raster::Image>, [f64; 2]),
|
||||
frame_at: &(dyn Fn(Tick) -> Option<(Arc<effectcraft_raster::Image>, [f64; 2])> + Sync),
|
||||
frame_at: &(impl Fn(Tick) -> F + Sync),
|
||||
deferred: bool,
|
||||
layer: &effectcraft_project::Layer,
|
||||
t0: web_time::Instant,
|
||||
) {
|
||||
@@ -273,7 +284,7 @@ fn run_face(
|
||||
let key = |fit: &trk::face::FaceFit| (outline_path(&fit.outline, 16, &w.path), detailed.then_some(fit.landmarks));
|
||||
let (path, pts) = key(&fit);
|
||||
lock(&shared.frames).push((layer.layer_time(w.times[0]), w.times[0], path, pts));
|
||||
let mut next = if w.times.len() > 1 { frame_at(w.times[1]) } else { None };
|
||||
let mut next = if w.times.len() > 1 { frame_at(w.times[1]).await } else { None };
|
||||
for k in 1..w.times.len() {
|
||||
if shared.cancel.load(Ordering::Relaxed) {
|
||||
lock(&shared.state).cancelled = true;
|
||||
@@ -283,8 +294,12 @@ fn run_face(
|
||||
lock(&shared.state).error = Some(format!("no frame at {:.3} s", w.times[k].seconds()));
|
||||
break;
|
||||
};
|
||||
let (res, nf) =
|
||||
rayon::join(|| tracker.step(&trk::Frame { img: &cur.0, offset: cur.1 }), || if k + 1 < w.times.len() { frame_at(w.times[k + 1]) } else { None });
|
||||
let (res, nf) = crate::offload::join_fetch(
|
||||
deferred,
|
||||
|| tracker.step(&trk::Frame { img: &cur.0, offset: cur.1 }),
|
||||
|| async { if k + 1 < w.times.len() { frame_at(w.times[k + 1]).await } else { None } },
|
||||
)
|
||||
.await;
|
||||
next = nf;
|
||||
let Some(fit) = res else {
|
||||
lock(&shared.state).error = Some(format!("lost the face at {:.3} s", w.times[k].seconds()));
|
||||
@@ -389,11 +404,19 @@ impl Session {
|
||||
let shared = Arc::new(MaskTrackShared::default());
|
||||
let (comp, layer) = (work.comp, work.layer);
|
||||
let thread = if wait {
|
||||
run_work(work, &shared);
|
||||
crate::offload::run_or_queue({
|
||||
let sh = shared.clone();
|
||||
async move { run_work(work, &sh).await }
|
||||
});
|
||||
None
|
||||
} else {
|
||||
let sh = shared.clone();
|
||||
Some(std::thread::Builder::new().name("mask-track".into()).spawn(move || run_work(work, &sh)).map_err(|e| e.to_string())?)
|
||||
Some(
|
||||
std::thread::Builder::new()
|
||||
.name("mask-track".into())
|
||||
.spawn(move || effectcraft_render::passes::block_on(run_work(work, &sh)))
|
||||
.map_err(|e| e.to_string())?,
|
||||
)
|
||||
};
|
||||
self.mask_job = Some(MaskTrackJob { shared, thread, comp, layer, mask, direction });
|
||||
self.poll_mask_track();
|
||||
|
||||
+168
-47
@@ -6,8 +6,10 @@
|
||||
//! [`Offload`] (set as [`Session::offload`]) ships a [`WorkerRequest`] — the serialized project,
|
||||
//! the footage files it reads and the job — and feeds the worker's [`WorkerReply`]s back into an
|
||||
//! [`Inbox`] that the session drains every frame ([`Session::poll_render`],
|
||||
//! [`Session::poll_offload`]). The worker side is [`run_request`]: a plain session fed the
|
||||
//! project runs the job blocking and reports through a callback.
|
||||
//! [`Session::poll_offload`]). The worker side is [`run_request_async`]: a plain session fed the
|
||||
//! project runs the job and reports through a callback. With a WebGPU device of the worker's
|
||||
//! own (deferred readbacks, `effectcraft_render::passes`) the job's frames render on the GPU in
|
||||
//! passes, the job awaiting the device between them; [`run_request`] runs it blocking.
|
||||
//!
|
||||
//! | Job | Worker runs | Reply applied on the UI thread |
|
||||
//! |---|---|---|
|
||||
@@ -26,6 +28,8 @@
|
||||
//! Queue item being rendered becomes "User Stopped".
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -34,6 +38,7 @@ use effectcraft_keyframe::ShapePath;
|
||||
use effectcraft_project::render_queue::{RenderQueueItem, RenderStatus};
|
||||
use effectcraft_project::tracking::TrackerSettings;
|
||||
use effectcraft_project::{ItemId, ItemKind, LayerId, Project, PropGroup, Uid};
|
||||
use effectcraft_render::{Accelerator, Backend, RenderOpts};
|
||||
use effectcraft_time::Tick;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -288,13 +293,92 @@ pub fn report(done: u64, total: u64) {
|
||||
});
|
||||
}
|
||||
|
||||
fn with_hook<R>(hook: Box<dyn FnMut(u64, u64)>, f: impl FnOnce() -> R) -> R {
|
||||
/// Run `f` (a future: an analysis awaited to its end) with `hook` receiving its progress.
|
||||
async fn with_hook<R>(hook: Box<dyn FnMut(u64, u64)>, f: impl Future<Output = R>) -> R {
|
||||
HOOK.with(|h| *h.borrow_mut() = Some(hook));
|
||||
let r = f();
|
||||
let r = f.await;
|
||||
HOOK.with(|h| *h.borrow_mut() = None);
|
||||
r
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- GPU in job workers
|
||||
|
||||
/// A boxed analysis future (see [`run_or_queue`]).
|
||||
type Queued = Pin<Box<dyn Future<Output = ()>>>;
|
||||
|
||||
thread_local! {
|
||||
/// The job worker's accelerator while it runs a request: a WebGPU device with deferred
|
||||
/// readbacks (see [`job_accel`]).
|
||||
static JOB_ACCEL: RefCell<Option<Arc<dyn Accelerator>>> = const { RefCell::new(None) };
|
||||
/// Analyses started while [`run_request_async`] runs a request on this thread: awaited by it
|
||||
/// (`None`: not inside one, analyses run to completion when started).
|
||||
static QUEUED: RefCell<Option<Vec<Queued>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// The accelerator analyses render their input frames with: the job worker's GPU while it runs
|
||||
/// a request ([`run_request_async`] with a session whose accelerator defers its readbacks).
|
||||
/// Elsewhere (the desktop's analysis threads) analyses render on the CPU, as before.
|
||||
pub(crate) fn job_accel() -> Option<Arc<dyn Accelerator>> {
|
||||
JOB_ACCEL.with(|a| a.borrow().clone())
|
||||
}
|
||||
|
||||
/// Render options of an analysis's input frames: 100 %; with an accelerator, the project's
|
||||
/// renderer (Mercury GPU Acceleration: its GPU effects on the device; Software Only: the CPU).
|
||||
pub(crate) fn analysis_opts(accel: Option<&dyn Accelerator>) -> RenderOpts {
|
||||
RenderOpts { scale: 1.0, backend: if accel.is_some() { Backend::Auto } else { Backend::Cpu }, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A render in passes ([`effectcraft_render::passes::in_passes`]): its value.
|
||||
pub(crate) async fn in_passes<'a, T>(accel: Option<&'a dyn Accelerator>, render: impl FnMut(Option<&'a dyn Accelerator>) -> T) -> T {
|
||||
effectcraft_render::passes::in_passes(accel, render).await.value
|
||||
}
|
||||
|
||||
/// `work()` while the next frame renders (`fetch`): side by side on the thread pool, or — with
|
||||
/// `deferred` readbacks, where a frame renders in passes awaiting the GPU — one after the other.
|
||||
pub(crate) async fn join_fetch<R: Send, F: Send, Fut: Future<Output = F>>(
|
||||
deferred: bool,
|
||||
work: impl FnOnce() -> R + Send,
|
||||
fetch: impl FnOnce() -> Fut + Send,
|
||||
) -> (R, F) {
|
||||
if deferred {
|
||||
let r = work();
|
||||
return (r, fetch().await);
|
||||
}
|
||||
rayon::join(work, || effectcraft_render::passes::block_on(fetch()))
|
||||
}
|
||||
|
||||
/// Run an analysis started with `wait`: inside [`run_request_async`] it is queued and awaited
|
||||
/// there (its frames may render in passes); anywhere else it runs to completion now.
|
||||
pub(crate) fn run_or_queue(f: impl Future<Output = ()> + 'static) {
|
||||
let f: Queued = Box::pin(f);
|
||||
let now = QUEUED.with(|q| match q.borrow_mut().as_mut() {
|
||||
Some(v) => {
|
||||
v.push(f);
|
||||
None
|
||||
}
|
||||
None => Some(f),
|
||||
});
|
||||
if let Some(f) = now {
|
||||
effectcraft_render::passes::block_on(f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Await the analyses [`run_or_queue`] queued, then let the session apply their results.
|
||||
async fn drain(s: &mut Session) {
|
||||
loop {
|
||||
let next = QUEUED.with(|q| q.borrow_mut().as_mut().and_then(|v| (!v.is_empty()).then(|| v.remove(0))));
|
||||
match next {
|
||||
Some(f) => f.await,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
s.poll_track();
|
||||
s.poll_mask_track();
|
||||
s.poll_warp(false);
|
||||
s.poll_camera(false);
|
||||
s.poll_roto(false);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- worker side
|
||||
|
||||
/// Where a worker sends its replies.
|
||||
@@ -303,19 +387,36 @@ pub type Post = Rc<dyn Fn(WorkerReply)>;
|
||||
/// Run `req` on `s` (a session with footage, expressions and an exporter, but no project yet),
|
||||
/// blocking, reporting through `post`. Always ends with [`WorkerReply::Done`].
|
||||
pub fn run_request(s: &mut Session, req: WorkerRequest, post: &Post) {
|
||||
effectcraft_render::passes::block_on(run_request_async(s, req, post));
|
||||
}
|
||||
|
||||
/// [`run_request`] as a future: with an accelerator whose readbacks are deferred
|
||||
/// ([`Session::accel`]: a browser job worker's own WebGPU device) the Render Queue's frames
|
||||
/// and the analyses' input frames render on it in passes, awaiting the device between them
|
||||
/// (the browser delivers readbacks only while the worker is back in its event loop).
|
||||
pub async fn run_request_async(s: &mut Session, req: WorkerRequest, post: &Post) {
|
||||
let accel = s.accel.clone().filter(|a| a.miss_gate().is_some());
|
||||
if let Some(a) = &accel {
|
||||
// Buffers computed from placeholders of a pass that missed are not kept.
|
||||
s.layer_cache.set_gate(a.miss_gate());
|
||||
}
|
||||
JOB_ACCEL.with(|a| *a.borrow_mut() = accel);
|
||||
QUEUED.with(|q| *q.borrow_mut() = Some(vec![]));
|
||||
match Project::from_json(&req.project) {
|
||||
Ok(p) => {
|
||||
s.replace_project(p, None);
|
||||
if let Err(e) = run_job(s, req.job, post.clone()) {
|
||||
if let Err(e) = run_job(s, req.job, post.clone()).await {
|
||||
post(WorkerReply::Failed { error: e });
|
||||
}
|
||||
}
|
||||
Err(e) => post(WorkerReply::Failed { error: format!("project: {e}") }),
|
||||
}
|
||||
QUEUED.with(|q| *q.borrow_mut() = None);
|
||||
JOB_ACCEL.with(|a| *a.borrow_mut() = None);
|
||||
post(WorkerReply::Done);
|
||||
}
|
||||
|
||||
fn run_job(s: &mut Session, job: WorkerJob, post: Post) -> Result<(), String> {
|
||||
async fn run_job(s: &mut Session, job: WorkerJob, post: Post) -> Result<(), String> {
|
||||
let kind = job.kind();
|
||||
let target = job.target();
|
||||
match job {
|
||||
@@ -334,50 +435,59 @@ fn run_job(s: &mut Session, job: WorkerJob, post: Post) -> Result<(), String> {
|
||||
post(WorkerReply::Render { state: sh.snapshot() });
|
||||
}
|
||||
};
|
||||
crate::render_queue::run_items(s, exporter, items, &shared, &mut |sh| notify(sh, false));
|
||||
crate::render_queue::run_items(s, exporter, items, &shared, &mut |sh| notify(sh, false)).await;
|
||||
notify(&shared, true);
|
||||
Ok(())
|
||||
}
|
||||
WorkerJob::Warp { comp, layer, effect } => analysis(s, kind, target, post, |s| s.start_warp(comp, layer, effect, true).map(|_| ())),
|
||||
WorkerJob::Camera { comp, layer, effect } => analysis(s, kind, target, post, |s| s.start_camera(comp, layer, effect, true).map(|_| ())),
|
||||
WorkerJob::RotoFreeze { comp, layer, effect } => analysis(s, kind, target, post, |s| {
|
||||
s.start_roto(comp, layer, effect, crate::roto::RotoTask::Freeze, crate::roto::Direction::Both, true).map(|_| ())
|
||||
}),
|
||||
WorkerJob::RotoPropagate { comp, layer, effect, direction } => propagate(s, comp, layer, effect, direction, post),
|
||||
WorkerJob::Track { comp, layer, tracker, direction, settings, points, times } => analysis(s, kind, target, post, |s| {
|
||||
let work = crate::tracking::Work {
|
||||
project: s.project.clone(),
|
||||
footage: s.footage.clone(),
|
||||
expr: s.expr.clone(),
|
||||
cache: s.layer_cache.clone(),
|
||||
comp,
|
||||
layer,
|
||||
settings,
|
||||
points,
|
||||
times,
|
||||
};
|
||||
s.start_track(work, tracker, direction, true)
|
||||
}),
|
||||
WorkerJob::MaskTrack { comp, layer, mask, direction, path, method, times } => analysis(s, kind, target, post, |s| {
|
||||
let work = crate::mask_track::MaskWork {
|
||||
project: s.project.clone(),
|
||||
footage: s.footage.clone(),
|
||||
expr: s.expr.clone(),
|
||||
cache: s.layer_cache.clone(),
|
||||
comp,
|
||||
layer,
|
||||
path,
|
||||
method,
|
||||
times,
|
||||
};
|
||||
s.start_mask_track(work, mask, direction, true)
|
||||
}),
|
||||
WorkerJob::Warp { comp, layer, effect } => analysis(s, kind, target, post, |s| s.start_warp(comp, layer, effect, true).map(|_| ())).await,
|
||||
WorkerJob::Camera { comp, layer, effect } => analysis(s, kind, target, post, |s| s.start_camera(comp, layer, effect, true).map(|_| ())).await,
|
||||
WorkerJob::RotoFreeze { comp, layer, effect } => {
|
||||
analysis(s, kind, target, post, |s| {
|
||||
s.start_roto(comp, layer, effect, crate::roto::RotoTask::Freeze, crate::roto::Direction::Both, true).map(|_| ())
|
||||
})
|
||||
.await
|
||||
}
|
||||
WorkerJob::RotoPropagate { comp, layer, effect, direction } => propagate(s, comp, layer, effect, direction, post).await,
|
||||
WorkerJob::Track { comp, layer, tracker, direction, settings, points, times } => {
|
||||
analysis(s, kind, target, post, |s| {
|
||||
let work = crate::tracking::Work {
|
||||
project: s.project.clone(),
|
||||
footage: s.footage.clone(),
|
||||
expr: s.expr.clone(),
|
||||
cache: s.layer_cache.clone(),
|
||||
comp,
|
||||
layer,
|
||||
settings,
|
||||
points,
|
||||
times,
|
||||
};
|
||||
s.start_track(work, tracker, direction, true)
|
||||
})
|
||||
.await
|
||||
}
|
||||
WorkerJob::MaskTrack { comp, layer, mask, direction, path, method, times } => {
|
||||
analysis(s, kind, target, post, |s| {
|
||||
let work = crate::mask_track::MaskWork {
|
||||
project: s.project.clone(),
|
||||
footage: s.footage.clone(),
|
||||
expr: s.expr.clone(),
|
||||
cache: s.layer_cache.clone(),
|
||||
comp,
|
||||
layer,
|
||||
path,
|
||||
method,
|
||||
times,
|
||||
};
|
||||
s.start_mask_track(work, mask, direction, true)
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Roto Brush propagation in a worker: the segmentations stream back (at most every 250 ms)
|
||||
/// as they are computed, so stopping the job keeps what was propagated.
|
||||
fn propagate(s: &mut Session, comp: ItemId, layer: LayerId, effect: Uid, dir: crate::roto::Direction, post: Post) -> Result<(), String> {
|
||||
async fn propagate(s: &mut Session, comp: ItemId, layer: LayerId, effect: Uid, dir: crate::roto::Direction, post: Post) -> Result<(), String> {
|
||||
let keys: Vec<u64> = s.roto_chain(comp, layer, effect).map(|c| c.keys.values().copied().collect()).ok_or("no Roto Brush strokes")?;
|
||||
let sent = Rc::new(RefCell::new(std::collections::HashSet::new()));
|
||||
let (p, k2, s2) = (post.clone(), keys.clone(), sent.clone());
|
||||
@@ -393,7 +503,12 @@ fn propagate(s: &mut Session, comp: ItemId, layer: LayerId, effect: Uid, dir: cr
|
||||
}
|
||||
});
|
||||
s.events.clear();
|
||||
with_hook(hook, || s.start_roto(comp, layer, effect, crate::roto::RotoTask::Propagate, dir, true))?;
|
||||
with_hook(hook, async {
|
||||
let r = s.start_roto(comp, layer, effect, crate::roto::RotoTask::Propagate, dir, true);
|
||||
drain(s).await;
|
||||
r
|
||||
})
|
||||
.await?;
|
||||
let segs = segs_to_send(&keys, &mut sent.borrow_mut());
|
||||
if !segs.is_empty() {
|
||||
post(WorkerReply::Segs { segs });
|
||||
@@ -407,7 +522,7 @@ fn propagate(s: &mut Session, comp: ItemId, layer: LayerId, effect: Uid, dir: cr
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn analysis(
|
||||
async fn analysis(
|
||||
s: &mut Session,
|
||||
kind: JobKind,
|
||||
target: Option<(ItemId, LayerId, Uid)>,
|
||||
@@ -425,7 +540,13 @@ fn analysis(
|
||||
p(WorkerReply::Progress { done, total });
|
||||
}
|
||||
});
|
||||
with_hook(hook, || run(s))?;
|
||||
with_hook(hook, async {
|
||||
let r = run(s);
|
||||
// The analysis was queued: await it, then the session writes its result.
|
||||
drain(s).await;
|
||||
r
|
||||
})
|
||||
.await?;
|
||||
let message = s
|
||||
.events
|
||||
.iter()
|
||||
@@ -856,10 +977,10 @@ mod tests {
|
||||
report(1, 2); // no hook: nothing happens
|
||||
let seen = Rc::new(RefCell::new(vec![]));
|
||||
let s2 = seen.clone();
|
||||
with_hook(Box::new(move |d, t| s2.borrow_mut().push((d, t))), || {
|
||||
effectcraft_render::passes::block_on(with_hook(Box::new(move |d, t| s2.borrow_mut().push((d, t))), async {
|
||||
report(1, 3);
|
||||
report(2, 3);
|
||||
});
|
||||
}));
|
||||
report(3, 3);
|
||||
assert_eq!(*seen.borrow(), vec![(1, 3), (2, 3)]);
|
||||
}
|
||||
|
||||
+168
-13
@@ -22,6 +22,14 @@
|
||||
//! - Disk cache: a render request may carry the frame's disk-cache key ([`FrameMsg::Render`]
|
||||
//! `disk`); the transport stores the finished frame under it (the browser: in the Origin
|
||||
//! Private File System) and reports [`FrameReply::Stored`].
|
||||
//! - Layer buffers on disk: with `layers`, the server's layer cache is backed by a
|
||||
//! [`PrefetchStore`] ([`FrameServer::set_layer_store`]): before the request the transport
|
||||
//! fetches the entries named in `prefetch` (recent misses that are on disk, chosen by the
|
||||
//! page, `disk_cache::LayerPrefetch`), so the lookups in the middle of the render find them;
|
||||
//! the reply lists the layer keys that missed and those served from the store
|
||||
//! ([`FrameReply::Frame`] `layer_misses` / `layer_hits`), and slow buffers queue up for the
|
||||
//! transport to write after the frame ([`PrefetchStore::take_writes`], reported as
|
||||
//! [`FrameReply::Stored`] with `layer`).
|
||||
//!
|
||||
//! The transport (structured-clone messages, transferable pixel buffers) is the web crate's;
|
||||
//! everything here is portable and tested natively.
|
||||
@@ -29,7 +37,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_project::{ItemId, Project};
|
||||
use effectcraft_render::{Accelerator, AutoKey, Backend, ExprHost, FootageSource, Image, LayerCache, RenderOpts, Renderer};
|
||||
use effectcraft_render::{Accelerator, AutoKey, Backend, ExprHost, FootageSource, Image, LayerCache, LayerStore, PrefetchStore, RenderOpts, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -140,6 +148,12 @@ pub enum FrameMsg {
|
||||
opts: Box<RenderOpts>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
disk: Option<String>,
|
||||
/// Back the layer cache with the disk cache's layer buffers (see the module docs).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
layers: bool,
|
||||
/// Layer entries (32 hex digits) the transport fetches before rendering.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
prefetch: Vec<String>,
|
||||
},
|
||||
/// Roto Brush segmentations computed elsewhere (a propagation worker).
|
||||
Segs { segs: Vec<SegData> },
|
||||
@@ -163,9 +177,21 @@ pub enum FrameReply {
|
||||
passes: u32,
|
||||
#[serde(default)]
|
||||
gpu: bool,
|
||||
/// Layer-cache lookups that missed the store (salted keys, 32 hex digits).
|
||||
#[serde(default, rename = "layerMisses", skip_serializing_if = "Vec::is_empty")]
|
||||
layer_misses: Vec<String>,
|
||||
/// Layer buffers served from the store (fetched from disk).
|
||||
#[serde(default, rename = "layerHits", skip_serializing_if = "Vec::is_empty")]
|
||||
layer_hits: Vec<String>,
|
||||
},
|
||||
/// The frame (or, with `layer`, a layer buffer) was stored in the disk cache under `key`
|
||||
/// (`bytes` on disk).
|
||||
Stored {
|
||||
key: String,
|
||||
bytes: u64,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
layer: bool,
|
||||
},
|
||||
/// The frame was stored in the disk cache under `key` (`bytes` on disk).
|
||||
Stored { key: String, bytes: u64 },
|
||||
/// The worker's renderer: its GPU adapter, or why it has none.
|
||||
Info {
|
||||
#[serde(default)]
|
||||
@@ -234,6 +260,9 @@ pub struct FrameServer {
|
||||
revision: Option<u64>,
|
||||
/// The frame being rendered in passes.
|
||||
pending: Option<Pending>,
|
||||
/// The disk cache's layer buffers (see the module docs) and the project's salt.
|
||||
layer_store: Option<Arc<PrefetchStore>>,
|
||||
salt: u64,
|
||||
}
|
||||
|
||||
/// A frame whose readbacks are in flight.
|
||||
@@ -254,7 +283,33 @@ pub const MAX_PASSES: u32 = 24;
|
||||
|
||||
impl FrameServer {
|
||||
pub fn new(footage: Arc<dyn FootageSource>, expr: Option<Arc<dyn ExprHost>>) -> FrameServer {
|
||||
FrameServer { footage, expr, cache: Arc::new(LayerCache::default()), accel: None, doc: Value::Null, project: None, revision: None, pending: None }
|
||||
FrameServer {
|
||||
footage,
|
||||
expr,
|
||||
cache: Arc::new(LayerCache::default()),
|
||||
accel: None,
|
||||
doc: Value::Null,
|
||||
project: None,
|
||||
revision: None,
|
||||
pending: None,
|
||||
layer_store: None,
|
||||
salt: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The store behind the layer cache when a request asks for `layers` (the browser: the
|
||||
/// disk cache's layer buffers, fetched before the request).
|
||||
pub fn set_layer_store(&mut self, store: Option<Arc<PrefetchStore>>) {
|
||||
self.layer_store = store;
|
||||
}
|
||||
|
||||
pub fn layer_store(&self) -> Option<&Arc<PrefetchStore>> {
|
||||
self.layer_store.as_ref()
|
||||
}
|
||||
|
||||
/// The salt of the replica's layer keys on disk (keys are `(salt, key)`).
|
||||
pub fn salt(&self) -> u64 {
|
||||
self.salt
|
||||
}
|
||||
|
||||
/// Render with `accel` when the request's backend asks for it (the worker's GPU). Its miss
|
||||
@@ -283,6 +338,8 @@ impl FrameServer {
|
||||
|
||||
fn load(&mut self, revision: u64) -> Result<(), String> {
|
||||
let p = Project::from_json(&self.doc.to_string()).map_err(|e| e.to_string())?;
|
||||
self.salt = effectcraft_render::disk_cache::footage_salt(&p);
|
||||
self.cache.set_store_salt(self.salt);
|
||||
self.project = Some(Arc::new(p));
|
||||
self.revision = Some(revision);
|
||||
Ok(())
|
||||
@@ -319,9 +376,14 @@ impl FrameServer {
|
||||
}
|
||||
FrameMsg::Purge => {
|
||||
self.cache.clear();
|
||||
if let Some(st) = &self.layer_store {
|
||||
st.clear();
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
FrameMsg::Render { id, revision, comp, time, opts, .. } => {
|
||||
FrameMsg::Render { id, revision, comp, time, opts, layers, .. } => {
|
||||
let store = self.layer_store.clone().filter(|_| layers);
|
||||
self.cache.set_store(store.map(|s| (s as Arc<dyn LayerStore>, self.salt)));
|
||||
let fail = |error: String, stale: bool| vec![(FrameReply::Failed { id, error, stale }, None)];
|
||||
if self.revision != Some(revision) {
|
||||
return fail(format!("the replica is at {:?}, not {revision}", self.revision), true);
|
||||
@@ -376,12 +438,20 @@ impl FrameServer {
|
||||
}
|
||||
let ms = pr.t0.elapsed().as_secs_f64() * 1000.0;
|
||||
let gpu = r.accel.is_some() && r.active_accel().is_some();
|
||||
let hex = |v: Vec<u128>| v.into_iter().map(|k| format!("{k:032x}")).collect::<Vec<_>>();
|
||||
let (layer_misses, layer_hits) = match &self.layer_store {
|
||||
Some(st) => (hex(st.take_misses()), hex(st.take_hits())),
|
||||
None => (vec![], vec![]),
|
||||
};
|
||||
if let (Some((key, chose)), Some(a)) = (pr.auto, &self.accel)
|
||||
&& let Some(pick) = a.auto_pick()
|
||||
{
|
||||
pick.record(key, chose, ms);
|
||||
}
|
||||
vec![(FrameReply::Frame { id: pr.id, width: img.width, height: img.height, ms, passes: pr.passes, gpu }, Some(rgba8_premultiplied(&img)))]
|
||||
vec![(
|
||||
FrameReply::Frame { id: pr.id, width: img.width, height: img.height, ms, passes: pr.passes, gpu, layer_misses, layer_hits },
|
||||
Some(rgba8_premultiplied(&img)),
|
||||
)]
|
||||
}
|
||||
|
||||
fn lost(&mut self, error: String) -> Vec<(FrameReply, Option<Vec<u8>>)> {
|
||||
@@ -435,6 +505,77 @@ mod tests {
|
||||
rgba8_premultiplied(&r.comp_frame(comp, t))
|
||||
}
|
||||
|
||||
/// Layer buffers through the disk store: a worker's slow buffers queue up as entries; the
|
||||
/// page plans what another worker fetches before its frame (recent misses on disk); that
|
||||
/// worker's mid-render lookups find them and the pixels match.
|
||||
#[test]
|
||||
fn layer_buffers_go_through_the_disk_store() {
|
||||
use effectcraft_render::disk_cache::{DiskIndex, Kind, LayerPrefetch};
|
||||
let mut s = Session::default();
|
||||
s.execute("file.openDemoProject", json!({})).unwrap();
|
||||
let comp = s.active_comp_id().unwrap();
|
||||
let opts = RenderOpts { scale: 0.25, ..Default::default() };
|
||||
let t = Tick::from_seconds_f64(1.0);
|
||||
let req = |id: u64, layers: bool, prefetch: Vec<String>| {
|
||||
round(&FrameMsg::Render { id, revision: s.revision, comp, time: t, opts: Box::new(opts), disk: None, layers, prefetch })
|
||||
};
|
||||
let worker = || {
|
||||
let mut w = server(&s);
|
||||
let store = Arc::new(PrefetchStore::new(64 << 20).with_min_ms(0));
|
||||
w.set_layer_store(Some(store.clone()));
|
||||
let mut m = Mirror::default();
|
||||
assert!(w.handle(round(&m.sync(s.revision, &s.project).unwrap())).is_empty());
|
||||
(w, store)
|
||||
};
|
||||
let unhex = |v: &[String]| v.iter().map(|k| u128::from_str_radix(k, 16).unwrap()).collect::<Vec<u128>>();
|
||||
// Worker A: everything misses; its buffers queue up for the disk.
|
||||
let (mut a, store_a) = worker();
|
||||
let out = a.handle(req(1, true, vec![]));
|
||||
let (FrameReply::Frame { layer_misses, layer_hits, .. }, Some(px_a)) = &out[0] else { panic!("{:?}", out[0].0) };
|
||||
assert!(!layer_misses.is_empty() && layer_hits.is_empty());
|
||||
let writes = store_a.take_writes();
|
||||
assert!(!writes.is_empty());
|
||||
assert!(writes.iter().all(|(k, _)| (*k >> 64) as u64 == a.salt()), "keys are salted per project");
|
||||
let mut index = DiskIndex::default();
|
||||
let mut disk = std::collections::HashMap::new();
|
||||
for (k, e) in writes {
|
||||
index.insert(Kind::Layer, k, e.len() as u64);
|
||||
disk.insert(k, e);
|
||||
}
|
||||
index.insert(Kind::Frame, 1, 10);
|
||||
// The page: recent misses that are on disk, most recent first.
|
||||
let mut plan = LayerPrefetch::default();
|
||||
plan.note_misses(unhex(layer_misses));
|
||||
let keys = plan.plan(&index, 64);
|
||||
assert!(!keys.is_empty() && keys.len() <= index.len());
|
||||
// Worker B fetches them before its first frame: its lookups hit.
|
||||
let (mut b, store_b) = worker();
|
||||
for k in &keys {
|
||||
assert!(store_b.provide(*k, &disk[k]));
|
||||
}
|
||||
assert!(!store_b.provide(1, b"damaged"));
|
||||
let out = b.handle(req(1, true, keys.iter().map(|k| format!("{k:032x}")).collect()));
|
||||
let (FrameReply::Frame { layer_misses: mb, layer_hits: hb, .. }, Some(px_b)) = &out[0] else { panic!("{:?}", out[0].0) };
|
||||
assert_eq!(unhex(hb).len(), keys.len(), "every fetched buffer was used");
|
||||
assert!(mb.len() < layer_misses.len());
|
||||
assert_eq!(px_a, px_b);
|
||||
assert_eq!(*px_b, local(&s, comp, t, opts));
|
||||
// Nothing new to write: what B rendered itself was rendered by A too.
|
||||
assert!(store_b.take_writes().iter().all(|(k, _)| disk.contains_key(k)));
|
||||
// Without `layers` the store is not consulted.
|
||||
let (mut c, store_c) = worker();
|
||||
c.handle(req(1, false, vec![]));
|
||||
assert!(store_c.take_misses().is_empty() && store_c.take_writes().is_empty());
|
||||
// Purge empties the store.
|
||||
b.handle(round(&FrameMsg::Purge));
|
||||
assert!(!store_b.has(keys[0]));
|
||||
// LRU across frames and layers in the shared index: a touched layer outlives the frame.
|
||||
index.touch(Kind::Layer, keys[0]);
|
||||
let order = index.lru_order();
|
||||
assert_eq!(order.last(), Some(&(Kind::Layer, keys[0])));
|
||||
assert!(order.iter().position(|e| *e == (Kind::Frame, 1)).unwrap() < order.len() - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replica_follows_edits_through_diffs_and_renders_the_same_frames() {
|
||||
let mut s = Session::default();
|
||||
@@ -450,8 +591,9 @@ mod tests {
|
||||
assert!(send(first, &mut w).is_empty());
|
||||
assert!(m.sync(s.revision, &s.project).is_none(), "nothing new");
|
||||
let t = Tick::from_seconds_f64(1.0);
|
||||
let render =
|
||||
|w: &mut FrameServer, rev: u64, id: u64| w.handle(round(&FrameMsg::Render { id, revision: rev, comp, time: t, opts: Box::new(opts), disk: None }));
|
||||
let render = |w: &mut FrameServer, rev: u64, id: u64| {
|
||||
w.handle(round(&FrameMsg::Render { id, revision: rev, comp, time: t, opts: Box::new(opts), disk: None, layers: false, prefetch: vec![] }))
|
||||
};
|
||||
let out = render(&mut w, s.revision, 1);
|
||||
let (FrameReply::Frame { id, width, height, .. }, Some(px)) = &out[0] else { panic!("{:?}", out[0].0) };
|
||||
assert_eq!((*id, *width as usize * *height as usize * 4), (1, px.len()));
|
||||
@@ -487,6 +629,8 @@ mod tests {
|
||||
time: Tick::from_seconds_f64(0.5),
|
||||
opts: Box::new(RenderOpts { scale: 0.5, draft: true, roi: Some([1.0, 2.0, 3.0, 4.0]), ..Default::default() }),
|
||||
disk: Some(format!("{:032x}", 0xabcdu128)),
|
||||
layers: true,
|
||||
prefetch: vec![format!("{:032x}", 7u128)],
|
||||
},
|
||||
] {
|
||||
let a = serde_json::to_string(&m).unwrap();
|
||||
@@ -494,8 +638,9 @@ mod tests {
|
||||
assert!(a.starts_with("{\"type\":"), "{a}");
|
||||
}
|
||||
for r in [
|
||||
FrameReply::Frame { id: 1, width: 2, height: 3, ms: 4.5, passes: 2, gpu: true },
|
||||
FrameReply::Stored { key: "00ff".into(), bytes: 9 },
|
||||
FrameReply::Frame { id: 1, width: 2, height: 3, ms: 4.5, passes: 2, gpu: true, layer_misses: vec!["0a".into()], layer_hits: vec![] },
|
||||
FrameReply::Stored { key: "00ff".into(), bytes: 9, layer: false },
|
||||
FrameReply::Stored { key: "00fe".into(), bytes: 8, layer: true },
|
||||
FrameReply::Info { gpu: Some("Adapter (BrowserWebGpu)".into()), error: None },
|
||||
FrameReply::Failed { id: 1, error: "x".into(), stale: true },
|
||||
FrameReply::Resync { error: "y".into() },
|
||||
@@ -596,7 +741,7 @@ mod tests {
|
||||
w.set_accel(Some(acc.clone()));
|
||||
let mut m = Mirror::default();
|
||||
w.handle(round(&m.sync(s.revision, &s.project).unwrap()));
|
||||
let req = |id| round(&FrameMsg::Render { id, revision: s.revision, comp, time: t, opts: Box::new(opts), disk: None });
|
||||
let req = |id| round(&FrameMsg::Render { id, revision: s.revision, comp, time: t, opts: Box::new(opts), disk: None, layers: false, prefetch: vec![] });
|
||||
assert!(w.handle(req(1)).is_empty() && w.waiting(), "the first pass misses");
|
||||
let mut out = vec![];
|
||||
for _ in 0..10 {
|
||||
@@ -621,11 +766,21 @@ mod tests {
|
||||
assert_eq!(out[0].1.as_deref(), Some(&px[..]));
|
||||
// CPU requests never touch the accelerator; Auto times whole frames.
|
||||
let cpu = RenderOpts { backend: Backend::Cpu, ..opts };
|
||||
let out = w.handle(round(&FrameMsg::Render { id: 3, revision: s.revision, comp, time: t, opts: Box::new(cpu), disk: None }));
|
||||
let out =
|
||||
w.handle(round(&FrameMsg::Render { id: 3, revision: s.revision, comp, time: t, opts: Box::new(cpu), disk: None, layers: false, prefetch: vec![] }));
|
||||
assert!(matches!(out[0].0, FrameReply::Frame { id: 3, passes: 1, gpu: false, .. }));
|
||||
for id in 4..12 {
|
||||
let auto = RenderOpts { backend: Backend::Auto, ..opts };
|
||||
let mut out = w.handle(round(&FrameMsg::Render { id, revision: s.revision, comp, time: t, opts: Box::new(auto), disk: None }));
|
||||
let mut out = w.handle(round(&FrameMsg::Render {
|
||||
id,
|
||||
revision: s.revision,
|
||||
comp,
|
||||
time: t,
|
||||
opts: Box::new(auto),
|
||||
disk: None,
|
||||
layers: false,
|
||||
prefetch: vec![],
|
||||
}));
|
||||
while w.waiting() {
|
||||
acc.settle();
|
||||
out = w.resume();
|
||||
|
||||
@@ -60,8 +60,17 @@ pub trait Exporter: Send + Sync {
|
||||
/// Render and write one item (blocking). `progress(done, total)` returns `false` to cancel;
|
||||
/// a cancelled export returns `Err("cancelled")`.
|
||||
fn export(&self, job: &ExportJob, progress: &mut dyn FnMut(u64, u64) -> bool) -> Result<ExportResult, String>;
|
||||
/// [`Exporter::export`] as a future: renders whose GPU readbacks are deferred (a browser
|
||||
/// job worker's WebGPU device) await the device between a frame's passes. The default runs
|
||||
/// the blocking export.
|
||||
fn export_async<'a>(&'a self, job: &'a ExportJob<'a>, progress: &'a mut dyn FnMut(u64, u64) -> bool) -> LocalFuture<'a, Result<ExportResult, String>> {
|
||||
Box::pin(async move { self.export(job, progress) })
|
||||
}
|
||||
}
|
||||
|
||||
/// A boxed future that stays on its thread.
|
||||
pub type LocalFuture<'a, T> = std::pin::Pin<Box<dyn std::future::Future<Output = T> + 'a>>;
|
||||
|
||||
/// The error string an [`Exporter`] returns when cancelled.
|
||||
pub const CANCELLED: &str = "cancelled";
|
||||
|
||||
@@ -196,8 +205,10 @@ fn unix_now() -> u64 {
|
||||
web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Render `items` with the session's footage, expressions and GPU (a worker's render).
|
||||
pub(crate) fn run_items(
|
||||
/// Render `items` with the session's footage, expressions and GPU (a worker's render). A
|
||||
/// future: with deferred GPU readbacks (a browser job worker) each frame awaits the device
|
||||
/// between its passes.
|
||||
pub(crate) async fn run_items(
|
||||
s: &Session,
|
||||
exporter: Arc<dyn Exporter>,
|
||||
items: Vec<Vec<(RenderQueueItem, String)>>,
|
||||
@@ -214,10 +225,10 @@ pub(crate) fn run_items(
|
||||
items,
|
||||
nested_switches: s.prefs.general.switches_affect_nested_comps,
|
||||
};
|
||||
run_work(work, shared, notify);
|
||||
run_work(work, shared, notify).await;
|
||||
}
|
||||
|
||||
fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared)) {
|
||||
async fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared)) {
|
||||
let t0 = web_time::Instant::now();
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
@@ -257,18 +268,21 @@ fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared)) {
|
||||
label: format!("#{index} {name} (output module {})", mi + 1),
|
||||
nested_switches: w.nested_switches,
|
||||
};
|
||||
let rr = w.exporter.export(&job, &mut |done, total| {
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
s.done = done;
|
||||
s.total = total;
|
||||
s.elapsed = t0.elapsed().as_secs_f64();
|
||||
s.item_elapsed = t1.elapsed().as_secs_f64();
|
||||
s.remaining = (done > 0).then(|| s.item_elapsed / done as f64 * total.saturating_sub(done) as f64);
|
||||
}
|
||||
notify(shared);
|
||||
!shared.cancel.load(Ordering::Relaxed)
|
||||
});
|
||||
let rr = w
|
||||
.exporter
|
||||
.export_async(&job, &mut |done, total| {
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
s.done = done;
|
||||
s.total = total;
|
||||
s.elapsed = t0.elapsed().as_secs_f64();
|
||||
s.item_elapsed = t1.elapsed().as_secs_f64();
|
||||
s.remaining = (done > 0).then(|| s.item_elapsed / done as f64 * total.saturating_sub(done) as f64);
|
||||
}
|
||||
notify(shared);
|
||||
!shared.cancel.load(Ordering::Relaxed)
|
||||
})
|
||||
.await;
|
||||
match rr {
|
||||
Ok(res) if mi == 0 => r = Ok(res),
|
||||
Ok(_) => {}
|
||||
@@ -474,11 +488,14 @@ impl Session {
|
||||
};
|
||||
let shared = Arc::new(JobShared::default());
|
||||
if wait {
|
||||
run_work(work, &shared, &mut |_| {});
|
||||
effectcraft_render::passes::block_on(run_work(work, &shared, &mut |_| {}));
|
||||
self.render_job = Some(RenderJob { shared, thread: None, remote: None });
|
||||
} else {
|
||||
let sh = shared.clone();
|
||||
let thread = std::thread::Builder::new().name("render-queue".into()).spawn(move || run_work(work, &sh, &mut |_| {})).map_err(|e| e.to_string())?;
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("render-queue".into())
|
||||
.spawn(move || effectcraft_render::passes::block_on(run_work(work, &sh, &mut |_| {})))
|
||||
.map_err(|e| e.to_string())?;
|
||||
self.render_job = Some(RenderJob { shared, thread: Some(thread), remote: None });
|
||||
}
|
||||
self.poll_render();
|
||||
|
||||
+66
-13
@@ -277,9 +277,14 @@ struct Work {
|
||||
task: RotoTask,
|
||||
}
|
||||
|
||||
/// Renders the effect's input frames for a worker, keeping the last few.
|
||||
/// Renders the effect's input frames for a worker, keeping the last few. With a browser job
|
||||
/// worker's GPU (deferred readbacks), [`FrameSource::prefetch`] renders the frames a step
|
||||
/// will read in passes beforehand; [`FrameSource::get`] renders on the CPU what it lacks.
|
||||
pub(crate) struct FrameSource<'a> {
|
||||
r: Renderer<'a>,
|
||||
accel: Option<&'a dyn effectcraft_render::Accelerator>,
|
||||
/// Frames in `memo`, oldest first.
|
||||
order: std::collections::VecDeque<i64>,
|
||||
ctx0: EvalCtx<'a>,
|
||||
comp: &'a effectcraft_project::Comp,
|
||||
layer: &'a Layer,
|
||||
@@ -305,15 +310,55 @@ impl<'a> FrameSource<'a> {
|
||||
r.expr = expr;
|
||||
r.cache = Some(cache);
|
||||
let ctx0 = EvalCtx { expr, ..EvalCtx::new(project, cid, comp, Tick::ZERO) };
|
||||
FrameSource { r, ctx0, comp, layer, index, size, memo: HashMap::new() }
|
||||
FrameSource { r, accel: None, order: Default::default(), ctx0, comp, layer, index, size, memo: HashMap::new() }
|
||||
}
|
||||
|
||||
/// Render with `accel` (deferred readbacks: see [`FrameSource::prefetch`]).
|
||||
pub(crate) fn with_accel(mut self, accel: Option<&'a dyn effectcraft_render::Accelerator>) -> Self {
|
||||
self.accel = accel;
|
||||
self.r.opts = crate::offload::analysis_opts(accel);
|
||||
self
|
||||
}
|
||||
|
||||
/// Render frames `fs` (those not kept yet) in passes on the GPU, so the step that reads
|
||||
/// them finds them ([`FrameSource::get`] can't wait for the GPU).
|
||||
pub(crate) async fn prefetch(&mut self, fs: &[i64]) {
|
||||
let Some(a) = self.accel else { return };
|
||||
for &f in fs {
|
||||
if self.memo.contains_key(&f) {
|
||||
continue;
|
||||
}
|
||||
let this = &*self;
|
||||
let img = crate::offload::in_passes(Some(a), |acc| this.render(f, &this.r.with_accel(acc))).await;
|
||||
if let Some(img) = img {
|
||||
self.keep(f, img);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn keep(&mut self, f: i64, img: Arc<Image>) {
|
||||
while self.order.len() >= 8 {
|
||||
if let Some(old) = self.order.pop_front() {
|
||||
self.memo.remove(&old);
|
||||
}
|
||||
}
|
||||
self.order.push_back(f);
|
||||
self.memo.insert(f, img);
|
||||
}
|
||||
|
||||
pub(crate) fn get(&mut self, f: i64) -> Option<Arc<Image>> {
|
||||
if let Some(i) = self.memo.get(&f) {
|
||||
return Some(i.clone());
|
||||
}
|
||||
// Not prefetched: the CPU (a pass of the GPU could only return placeholders here).
|
||||
let img = self.render(f, &self.r.with_accel(None))?;
|
||||
self.keep(f, img.clone());
|
||||
Some(img)
|
||||
}
|
||||
|
||||
fn render(&self, f: i64, r: &Renderer) -> Option<Arc<Image>> {
|
||||
let t = comp_time_of(self.comp, self.layer, f);
|
||||
let buf = self.r.layer_input(&self.ctx0.at(t), self.layer, self.index)?;
|
||||
let buf = r.layer_input(&self.ctx0.at(t), self.layer, self.index)?;
|
||||
let buf = if (buf.scale - 1.0).abs() > 1e-9 && buf.scale > 0.0 {
|
||||
let w = (buf.img.width as f64 / buf.scale).round().max(1.0) as u32;
|
||||
let h = (buf.img.height as f64 / buf.scale).round().max(1.0) as u32;
|
||||
@@ -325,17 +370,14 @@ impl<'a> FrameSource<'a> {
|
||||
} else {
|
||||
(*buf).clone()
|
||||
};
|
||||
let img = Arc::new(fx::layer_grid(&buf, self.size));
|
||||
if self.memo.len() > 4 {
|
||||
self.memo.clear();
|
||||
}
|
||||
self.memo.insert(f, img.clone());
|
||||
Some(img)
|
||||
Some(Arc::new(fx::layer_grid(&buf, self.size)))
|
||||
}
|
||||
}
|
||||
|
||||
fn run_work(w: Work, shared: &RotoShared) {
|
||||
async fn run_work(w: Work, shared: &RotoShared) {
|
||||
let t0 = web_time::Instant::now();
|
||||
// A browser job worker's GPU (deferred readbacks): input frames render in passes.
|
||||
let accel = crate::offload::job_accel();
|
||||
let fail = |msg: &str| {
|
||||
let mut s = lock(&shared.state);
|
||||
s.error = Some(msg.to_string());
|
||||
@@ -343,7 +385,8 @@ fn run_work(w: Work, shared: &RotoShared) {
|
||||
};
|
||||
let Some(comp) = w.project.comp(w.comp) else { return fail("composition missing") };
|
||||
let Some(layer) = comp.layer(w.layer) else { return fail("layer missing") };
|
||||
let mut src = FrameSource::new(&w.project, w.footage.as_ref(), w.expr.as_deref(), &w.cache, w.comp, comp, layer, w.effect_index, w.size);
|
||||
let mut src =
|
||||
FrameSource::new(&w.project, w.footage.as_ref(), w.expr.as_deref(), &w.cache, w.comp, comp, layer, w.effect_index, w.size).with_accel(accel.as_deref());
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
s.task = Some(w.task);
|
||||
@@ -359,6 +402,8 @@ fn run_work(w: Work, shared: &RotoShared) {
|
||||
s.finished = true;
|
||||
return;
|
||||
}
|
||||
// The frame and its neighbours (what a step reads), on the GPU.
|
||||
src.prefetch(&[*f, f - 1, f + 1]).await;
|
||||
let mut get = |g: i64| src.get(g);
|
||||
let ok = match w.task {
|
||||
RotoTask::Propagate => chain.ensure(*f, &mut get, &cancel).is_some(),
|
||||
@@ -516,11 +561,19 @@ impl Session {
|
||||
let wait = wait || cfg!(target_arch = "wasm32");
|
||||
let shared = Arc::new(RotoShared::default());
|
||||
let thread = if wait {
|
||||
run_work(work, &shared);
|
||||
crate::offload::run_or_queue({
|
||||
let sh = shared.clone();
|
||||
async move { run_work(work, &sh).await }
|
||||
});
|
||||
None
|
||||
} else {
|
||||
let sh = shared.clone();
|
||||
Some(std::thread::Builder::new().name("roto".into()).spawn(move || run_work(work, &sh)).map_err(|e| e.to_string())?)
|
||||
Some(
|
||||
std::thread::Builder::new()
|
||||
.name("roto".into())
|
||||
.spawn(move || effectcraft_render::passes::block_on(run_work(work, &sh)))
|
||||
.map_err(|e| e.to_string())?,
|
||||
)
|
||||
};
|
||||
self.roto_job = Some(RotoJob { shared, thread, comp, layer, effect, task, strokes });
|
||||
self.events.push(Event::ProjectChanged { revision: self.revision });
|
||||
|
||||
+344
-13
@@ -8,6 +8,13 @@
|
||||
//! (the open template container of `essential.exportTemplate`: a stored ZIP with
|
||||
//! `manifest.json` (`kind: "project"`), `project.ecproj`, `poster.png` and `thumb.txt`) into
|
||||
//! the config store's `Templates` folder.
|
||||
//! - **Embedded footage**: saving embeds the footage files the project reads (default on,
|
||||
//! `embedFootage`), as `media/<item>/<file>` entries like `essential.exportTemplate`, up to
|
||||
//! [`EMBED_LIMIT_MB`] in all (`embedLimitMB`); footage beyond the cap stays referenced by its
|
||||
//! path and the save warns. Creating from the template extracts the files next to the new
|
||||
//! project (`projectPath`: `<project dir>/<stem> Footage/`), into `footageDir`, or into the
|
||||
//! settings folder's `Template Footage/<name>/` (the browser: its storage), and points the
|
||||
//! footage at them.
|
||||
//! - Opening a template (`templates.create`) makes an untitled copy: the template itself is never
|
||||
//! changed.
|
||||
//!
|
||||
@@ -31,6 +38,10 @@ use crate::{EngineError, Result, Session, cmd, query};
|
||||
pub const TEMPLATES_DIR: &str = "Templates";
|
||||
/// Template file extension.
|
||||
pub const EXT: &str = "ectemplate";
|
||||
/// Default cap on the footage a saved template embeds (MB, all files together).
|
||||
pub const EMBED_LIMIT_MB: f64 = 256.0;
|
||||
/// Folder (under the settings folder) that footage extracted from templates goes to.
|
||||
pub const FOOTAGE_DIR: &str = "Template Footage";
|
||||
/// Gallery thumbnail size (RGB, letterboxed).
|
||||
pub const THUMB_W: usize = 256;
|
||||
pub const THUMB_H: usize = 144;
|
||||
@@ -611,20 +622,148 @@ pub fn list(s: &Session) -> Vec<TemplateInfo> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The project of a template id (or of an `.ectemplate` file).
|
||||
fn project_of(s: &Session, id: Option<&str>, path: Option<&str>) -> Result<(Project, String)> {
|
||||
/// A template's project, its name and its archive entries (embedded footage), by id or by
|
||||
/// `.ectemplate` file.
|
||||
type Opened = (Project, String, Vec<(String, Vec<u8>)>);
|
||||
|
||||
fn project_of(s: &Session, id: Option<&str>, path: Option<&str>) -> Result<Opened> {
|
||||
if let Some(path) = path {
|
||||
let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
|
||||
let (m, p, _) = read_template(&bytes).map_err(|e| bad("templates.create", e))?;
|
||||
return Ok((p, str_of(&m, "name")));
|
||||
let (m, p, e) = read_template(&bytes).map_err(|e| bad("templates.create", e))?;
|
||||
return Ok((p, str_of(&m, "name"), e));
|
||||
}
|
||||
let id = id.ok_or_else(|| bad("templates.create", "missing `id` (see templates.list) or `path`"))?;
|
||||
if let Some(f) = id.strip_prefix("user/") {
|
||||
let (m, p, _) = read_template(&read_user(s, f)?).map_err(|e| bad("templates.create", e))?;
|
||||
return Ok((p, str_of(&m, "name")));
|
||||
let (m, p, e) = read_template(&read_user(s, f)?).map_err(|e| bad("templates.create", e))?;
|
||||
return Ok((p, str_of(&m, "name"), e));
|
||||
}
|
||||
let b = builtin(id).ok_or_else(|| bad("templates.create", format!("unknown template `{id}` (see templates.list)")))?;
|
||||
Ok((cached_builtin(id)?, b.name.to_string()))
|
||||
Ok((cached_builtin(id)?, b.name.to_string(), vec![]))
|
||||
}
|
||||
|
||||
fn base_name(path: &str) -> String {
|
||||
path.rsplit(['/', '\\']).next().filter(|n| !n.is_empty()).unwrap_or("footage").to_string()
|
||||
}
|
||||
|
||||
/// What [`embed_footage`] did.
|
||||
#[derive(Default)]
|
||||
struct Embedded {
|
||||
/// `{item, files, bytes}` per embedded footage item (the manifest's `media`).
|
||||
media: Vec<Value>,
|
||||
bytes: u64,
|
||||
/// Footage left referenced: `{item, name, bytes?, reason}`.
|
||||
skipped: Vec<Value>,
|
||||
}
|
||||
|
||||
/// Embed the footage files `proj` reads as `media/<item>/<file>` entries (paths rewritten to
|
||||
/// the entries), until `limit` bytes; the rest stays referenced.
|
||||
fn embed_footage(s: &Session, proj: &mut Project, entries: &mut Vec<(String, Vec<u8>)>, limit: u64) -> Embedded {
|
||||
let mut out = Embedded::default();
|
||||
let mut ids: Vec<ItemId> = proj.items.keys().copied().collect();
|
||||
ids.sort_by_key(|i| i.0);
|
||||
for id in ids {
|
||||
let Some(it) = proj.items.get_mut(&id) else { continue };
|
||||
let name = it.name.clone();
|
||||
let effectcraft_project::ItemKind::Footage(f) = &mut it.kind else { continue };
|
||||
if f.data.is_some() || f.path.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let files: Vec<String> = if f.sequence.is_empty() { vec![f.path.clone()] } else { f.sequence.clone() };
|
||||
let mut data = vec![];
|
||||
let mut missing = None;
|
||||
for file in &files {
|
||||
match s.services.read_file(file) {
|
||||
Ok(b) => data.push((file.clone(), b)),
|
||||
Err(e) => {
|
||||
missing = Some(format!("{file}: {e}"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(reason) = missing {
|
||||
out.skipped.push(json!({"item": id.0, "name": name, "reason": reason}));
|
||||
continue;
|
||||
}
|
||||
let size: u64 = data.iter().map(|(_, b)| b.len() as u64).sum();
|
||||
if out.bytes + size > limit {
|
||||
out.skipped.push(json!({"item": id.0, "name": name, "bytes": size, "reason": "over the size limit"}));
|
||||
continue;
|
||||
}
|
||||
let mut stored = vec![];
|
||||
for (file, bytes) in data {
|
||||
let entry = format!("media/{}/{}", id.0, base_name(&file));
|
||||
entries.push((entry.clone(), bytes));
|
||||
stored.push(entry);
|
||||
}
|
||||
f.path = stored[0].clone();
|
||||
if !f.sequence.is_empty() {
|
||||
f.sequence = stored.clone();
|
||||
}
|
||||
out.bytes += size;
|
||||
out.media.push(json!({"item": id.0, "files": stored, "bytes": size}));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where footage extracted from template `name` goes (see the module docs).
|
||||
fn footage_dir(s: &Session, name: &str, footage_dir: Option<&str>, project_path: Option<&str>) -> String {
|
||||
if let Some(d) = footage_dir.filter(|d| !d.is_empty()) {
|
||||
return d.trim_end_matches(['/', '\\']).to_string();
|
||||
}
|
||||
if let Some(pp) = project_path.map(std::path::Path::new) {
|
||||
let stem = pp.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Project".into());
|
||||
return pp.parent().unwrap_or(std::path::Path::new("")).join(format!("{stem} Footage")).to_string_lossy().into_owned();
|
||||
}
|
||||
let safe: String = name.chars().map(|c| if c.is_alphanumeric() || " -_()".contains(c) { c } else { '_' }).collect();
|
||||
let safe = if safe.trim().is_empty() { "Template".to_string() } else { safe.trim().to_string() };
|
||||
let base = match s.config.as_ref().and_then(|c| c.dir()) {
|
||||
Some(d) => d.join(FOOTAGE_DIR),
|
||||
None => PathBuf::from(format!("/{FOOTAGE_DIR}")),
|
||||
};
|
||||
// A fresh folder per created project.
|
||||
let mut k = 1;
|
||||
loop {
|
||||
let d = base.join(if k == 1 { safe.clone() } else { format!("{safe} {k}") });
|
||||
let ds = d.to_string_lossy().into_owned();
|
||||
if !s.services.exists(&ds) || k > 999 {
|
||||
return ds;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a template's embedded footage (`media/…` entries) into `dir` and point the project's
|
||||
/// footage at the files. Returns the files written.
|
||||
fn extract_footage(s: &Session, proj: &mut Project, entries: &[(String, Vec<u8>)], dir: &str) -> Result<Vec<String>> {
|
||||
let mut written = std::collections::HashMap::new();
|
||||
let mut used = std::collections::HashSet::new();
|
||||
for (k, v) in entries.iter().filter(|(k, _)| k.starts_with("media/")) {
|
||||
// `media/<item>/<file>` → one folder; a name another item took gets the item's id.
|
||||
let file = base_name(k);
|
||||
let item = k.trim_start_matches("media/").split('/').next().unwrap_or("0");
|
||||
let name = if used.insert(file.clone()) { file } else { format!("{item}-{file}") };
|
||||
let out = format!("{dir}/{name}");
|
||||
s.services.store_file(&out, v).map_err(|e| EngineError::Other(format!("cannot write {out}: {e}")))?;
|
||||
if let Some(imp) = &s.importer {
|
||||
imp.register(&out, v);
|
||||
}
|
||||
written.insert(k.clone(), out);
|
||||
}
|
||||
for it in proj.items.values_mut() {
|
||||
if let effectcraft_project::ItemKind::Footage(f) = &mut it.kind {
|
||||
if let Some(w) = written.get(&f.path) {
|
||||
f.path = w.clone();
|
||||
}
|
||||
for x in &mut f.sequence {
|
||||
if let Some(w) = written.get(x) {
|
||||
*x = w.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut v: Vec<String> = written.into_values().collect();
|
||||
v.sort();
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------- commands
|
||||
@@ -648,7 +787,13 @@ fn thumb_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (proj, name) = project_of(s, str_p(p, "id"), str_p(p, "path"))?;
|
||||
let (mut proj, name, entries) = project_of(s, str_p(p, "id"), str_p(p, "path"))?;
|
||||
let project_path = str_p(p, "projectPath").filter(|p| !p.is_empty());
|
||||
let mut footage = vec![];
|
||||
if entries.iter().any(|(k, _)| k.starts_with("media/")) {
|
||||
let dir = footage_dir(s, &name, str_p(p, "footageDir"), project_path);
|
||||
footage = extract_footage(s, &mut proj, &entries, &dir)?;
|
||||
}
|
||||
let cid = main_comp(&proj);
|
||||
let poster = cid.and_then(|c| proj.comp(c)).map(|c| c.poster_time).unwrap_or(Tick::ZERO);
|
||||
s.replace_project(proj, None);
|
||||
@@ -657,8 +802,13 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.open_comp(c);
|
||||
s.set_time(poster);
|
||||
}
|
||||
let mut untitled = true;
|
||||
if let Some(pp) = project_path {
|
||||
s.execute("file.saveAs", json!({"path": pp}))?;
|
||||
untitled = false;
|
||||
}
|
||||
s.toast(format!("New project from template “{name}”"));
|
||||
Ok(json!({"template": name, "comp": cid.map(|c| c.0), "untitled": true}))
|
||||
Ok(json!({"template": name, "comp": cid.map(|c| c.0), "untitled": untitled, "footage": footage}))
|
||||
}
|
||||
|
||||
fn save_as(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -700,9 +850,26 @@ fn save_as(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"poster": "poster.png",
|
||||
"thumbnail": "thumb.txt",
|
||||
});
|
||||
let mut manifest = manifest;
|
||||
// Embedded footage (default on, capped): the rest stays referenced, with a warning.
|
||||
let mut media_entries = vec![];
|
||||
let mut warning = None;
|
||||
if p.get("embedFootage").and_then(Value::as_bool).unwrap_or(true) {
|
||||
let limit_mb = p.get("embedLimitMB").and_then(Value::as_f64).unwrap_or(EMBED_LIMIT_MB).max(0.0);
|
||||
let e = embed_footage(s, &mut proj, &mut media_entries, (limit_mb * 1024.0 * 1024.0) as u64);
|
||||
let over: Vec<&Value> = e.skipped.iter().filter(|v| v["reason"] == "over the size limit").collect();
|
||||
if !over.is_empty() {
|
||||
let mb = over.iter().filter_map(|v| v["bytes"].as_u64()).sum::<u64>() as f64 / 1048576.0;
|
||||
warning = Some(format!("{} footage item(s) ({mb:.1} MB) are over the {limit_mb:.0} MB embedding limit and stay linked to their files", over.len()));
|
||||
}
|
||||
manifest["media"] = json!(e.media);
|
||||
manifest["embeddedBytes"] = json!(e.bytes);
|
||||
manifest["linkedFootage"] = json!(e.skipped);
|
||||
}
|
||||
let t = s.time_of(cid);
|
||||
let mut entries: Vec<(String, Vec<u8>)> =
|
||||
vec![("manifest.json".into(), serde_json::to_vec_pretty(&manifest).unwrap_or_default()), ("project.ecproj".into(), proj.to_json().into_bytes())];
|
||||
entries.extend(media_entries);
|
||||
if let Ok((w, h, rgba)) = s.render_rgba8(cid, t, 320) {
|
||||
if let Ok(png) = crate::commands::comp_more::encode_png(&rgba, w, h) {
|
||||
entries.push(("poster.png".into(), png));
|
||||
@@ -711,8 +878,20 @@ fn save_as(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let bytes = effectcraft_lottie::zip::store(&entries);
|
||||
let at = write_user(s, &file, &bytes)?;
|
||||
s.toast(format!("Saved template “{name}”"));
|
||||
Ok(json!({"id": format!("user/{file}"), "name": name, "path": at, "bytes": bytes.len()}))
|
||||
match &warning {
|
||||
Some(w) => s.events.push(crate::Event::Toast { message: format!("Saved template “{name}”: {w}"), error: false }),
|
||||
None => s.toast(format!("Saved template “{name}”")),
|
||||
}
|
||||
Ok(json!({
|
||||
"id": format!("user/{file}"),
|
||||
"name": name,
|
||||
"path": at,
|
||||
"bytes": bytes.len(),
|
||||
"embedded": manifest["media"].as_array().map_or(0, |m| m.len()),
|
||||
"embeddedBytes": manifest["embeddedBytes"],
|
||||
"linked": manifest["linkedFootage"],
|
||||
"warning": warning,
|
||||
}))
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -735,13 +914,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
list_cmd
|
||||
),
|
||||
query!("templates.thumbnail", "Template Thumbnail", "{id} → {id, width, height, rgb (hex)}", thumb_cmd),
|
||||
cmd!("templates.create", "New Project from Template", [], None, "{id (templates.list) | path (.ectemplate)} → an untitled copy", always, create),
|
||||
cmd!(
|
||||
"templates.create",
|
||||
"New Project from Template",
|
||||
[],
|
||||
None,
|
||||
"{id (templates.list) | path (.ectemplate), projectPath? (save the new project there; embedded footage goes to `<stem> Footage/` next to it), footageDir?} → an untitled copy (embedded footage extracted: `footage` lists the files)",
|
||||
always,
|
||||
create
|
||||
),
|
||||
cmd!(
|
||||
"templates.saveAs",
|
||||
"Save as Template...",
|
||||
["File"],
|
||||
None,
|
||||
"{name, description?, category?, overwrite?: bool (default true)} → {id, path}",
|
||||
"{name, description?, category?, overwrite?: bool (default true), embedFootage?: bool (default true: the footage files go into the template), embedLimitMB? (default 256: footage beyond it stays linked, with a warning)} → {id, path, embedded, embeddedBytes, linked: [{item, name, reason}], warning?}",
|
||||
has_comps,
|
||||
save_as
|
||||
),
|
||||
@@ -864,6 +1051,150 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn add_footage(s: &mut Session, name: &str, path: &str, sequence: Vec<String>) -> ItemId {
|
||||
let f = effectcraft_project::Footage { path: path.into(), width: 4, height: 4, has_video: true, sequence, ..Default::default() };
|
||||
Arc::make_mut(&mut s.project).add_item(name, effectcraft_color::Label::Aqua, None, effectcraft_project::ItemKind::Footage(f))
|
||||
}
|
||||
|
||||
fn footage_paths(s: &Session) -> Vec<(String, String, Vec<String>)> {
|
||||
let mut v: Vec<_> = s
|
||||
.project
|
||||
.items
|
||||
.values()
|
||||
.filter_map(|i| match &i.kind {
|
||||
effectcraft_project::ItemKind::Footage(f) => Some((i.name.clone(), f.path.clone(), f.sequence.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// Saving embeds the footage (capped, with a warning); creating extracts it next to the
|
||||
/// new project, or into the settings folder, and points the footage at the copies.
|
||||
#[test]
|
||||
fn templates_embed_and_extract_footage() {
|
||||
let root = std::env::temp_dir().join(format!("ec-tpl-footage-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let media = root.join("media");
|
||||
std::fs::create_dir_all(&media).unwrap();
|
||||
let file = |n: &str, len: usize, b: u8| {
|
||||
let p = media.join(n);
|
||||
std::fs::write(&p, vec![b; len]).unwrap();
|
||||
p.to_string_lossy().into_owned()
|
||||
};
|
||||
let still = file("still.png", 1000, 1);
|
||||
let seq: Vec<String> = (0..3).map(|k| file(&format!("shot_{k:03}.png"), 500, 10 + k as u8)).collect();
|
||||
let big = file("big.mov", 2 * 1024 * 1024, 7);
|
||||
let mut s = Session { config: Some(Arc::new(DirConfig::new(root.join("config")))), ..Default::default() };
|
||||
s.execute("templates.create", json!({"id": "lower-third"})).unwrap();
|
||||
add_footage(&mut s, "Still", &still, vec![]);
|
||||
add_footage(&mut s, "Shot", &seq[0], seq.clone());
|
||||
add_footage(&mut s, "Big", &big, vec![]);
|
||||
add_footage(&mut s, "Gone", &media.join("gone.png").to_string_lossy(), vec![]);
|
||||
let r = s.execute("templates.saveAs", json!({"name": "With Footage", "embedLimitMB": 1})).unwrap();
|
||||
assert_eq!(r["embedded"], 2, "{r}");
|
||||
assert_eq!(r["embeddedBytes"], 2500);
|
||||
let linked = r["linked"].as_array().unwrap();
|
||||
assert_eq!(linked.len(), 2, "{r}");
|
||||
let warning = r["warning"].as_str().unwrap();
|
||||
assert!(warning.contains("1 footage item") && warning.contains("1 MB"), "{warning}");
|
||||
assert!(s.events.iter().any(|e| matches!(e, crate::Event::Toast { message, .. } if message.contains("embedding limit"))));
|
||||
// The archive holds the files under media/<item>/.
|
||||
let bytes = read_user(&s, "With Footage.ectemplate").unwrap();
|
||||
let entries = effectcraft_lottie::zip::read_stored(&bytes);
|
||||
let names: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).filter(|k| k.starts_with("media/")).collect();
|
||||
assert_eq!(names.len(), 4, "{names:?}");
|
||||
assert!(names.iter().any(|n| n.ends_with("/still.png")) && names.iter().any(|n| n.ends_with("/shot_002.png")));
|
||||
// The originals go away: the template still has them.
|
||||
std::fs::remove_file(&still).unwrap();
|
||||
for f in &seq {
|
||||
std::fs::remove_file(f).unwrap();
|
||||
}
|
||||
let proj_path = root.join("work").join("Promo.ecproj");
|
||||
std::fs::create_dir_all(proj_path.parent().unwrap()).unwrap();
|
||||
let r = s.execute("templates.create", json!({"id": "user/With Footage.ectemplate", "projectPath": proj_path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["untitled"], false);
|
||||
assert_eq!(r["footage"].as_array().unwrap().len(), 4, "{r}");
|
||||
assert_eq!(s.path.as_deref(), Some(&*proj_path.to_string_lossy()));
|
||||
assert!(proj_path.exists());
|
||||
let dir = root.join("work").join("Promo Footage");
|
||||
let fp = footage_paths(&s);
|
||||
let get = |n: &str| fp.iter().find(|f| f.0 == n).unwrap().clone();
|
||||
assert_eq!(get("Still").1, dir.join("still.png").to_string_lossy());
|
||||
assert_eq!(std::fs::read(dir.join("still.png")).unwrap(), vec![1u8; 1000]);
|
||||
let shot = get("Shot");
|
||||
assert_eq!(shot.2.len(), 3);
|
||||
assert_eq!(shot.1, shot.2[0]);
|
||||
assert_eq!(std::fs::read(&shot.2[2]).unwrap(), vec![12u8; 500]);
|
||||
// Over the cap: still linked to the original file.
|
||||
assert_eq!(get("Big").1, big);
|
||||
// Without a project path: a fresh folder under the settings folder each time.
|
||||
s.execute("templates.create", json!({"id": "user/With Footage.ectemplate"})).unwrap();
|
||||
let base = root.join("config").join(FOOTAGE_DIR);
|
||||
assert!(base.join("With Footage").join("still.png").exists());
|
||||
assert!(s.path.is_none());
|
||||
s.execute("templates.create", json!({"id": "user/With Footage.ectemplate"})).unwrap();
|
||||
assert!(base.join("With Footage 2").join("still.png").exists());
|
||||
// Not embedding: no media entries.
|
||||
let r = s.execute("templates.saveAs", json!({"name": "Linked", "embedFootage": false})).unwrap();
|
||||
assert_eq!(r["embedded"], 0);
|
||||
let entries = effectcraft_lottie::zip::read_stored(&read_user(&s, "Linked.ectemplate").unwrap());
|
||||
assert!(entries.iter().all(|(k, _)| !k.starts_with("media/")));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// The browser: no settings folder; the files go to browser storage quietly
|
||||
/// (`Services::store_file`) and the media layer is told about them (`Importer::register`).
|
||||
#[test]
|
||||
fn template_footage_into_browser_storage() {
|
||||
#[derive(Default)]
|
||||
struct Mem(Mutex<std::collections::HashMap<String, Vec<u8>>>, Mutex<Vec<String>>);
|
||||
struct Svc(Arc<Mem>);
|
||||
impl crate::Services for Svc {
|
||||
fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>> {
|
||||
self.0.0.lock().unwrap().get(path).cloned().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, path.to_string()))
|
||||
}
|
||||
fn write_file(&self, _: &str, _: &[u8]) -> std::io::Result<()> {
|
||||
Err(std::io::Error::other("downloads are not for extracted footage"))
|
||||
}
|
||||
fn store_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> {
|
||||
self.0.0.lock().unwrap().insert(path.into(), data.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
fn exists(&self, path: &str) -> bool {
|
||||
self.0.0.lock().unwrap().keys().any(|k| k == path || k.starts_with(&format!("{path}/")))
|
||||
}
|
||||
}
|
||||
struct Imp(Arc<Mem>);
|
||||
impl crate::Importer for Imp {
|
||||
fn probe(&self, path: &str) -> std::result::Result<effectcraft_project::Footage, String> {
|
||||
Err(path.into())
|
||||
}
|
||||
fn register(&self, path: &str, _: &[u8]) {
|
||||
self.0.1.lock().unwrap().push(path.into());
|
||||
}
|
||||
}
|
||||
let mem = Arc::new(Mem::default());
|
||||
mem.0.lock().unwrap().insert("/clip.png".into(), vec![3; 64]);
|
||||
let mut s = Session {
|
||||
config: Some(Arc::new(MemoryConfig::default())),
|
||||
services: Arc::new(Svc(mem.clone())),
|
||||
importer: Some(Arc::new(Imp(mem.clone()))),
|
||||
..Default::default()
|
||||
};
|
||||
s.execute("templates.create", json!({"id": "title-card"})).unwrap();
|
||||
add_footage(&mut s, "Clip", "/clip.png", vec![]);
|
||||
s.execute("templates.saveAs", json!({"name": "Web"})).unwrap();
|
||||
s.execute("templates.create", json!({"id": "user/Web.ectemplate"})).unwrap();
|
||||
let want = format!("/{FOOTAGE_DIR}/Web/clip.png");
|
||||
assert_eq!(mem.0.lock().unwrap().get(&want), Some(&vec![3; 64]));
|
||||
assert_eq!(*mem.1.lock().unwrap(), vec![want.clone()]);
|
||||
assert!(footage_paths(&s).iter().any(|f| f.1 == want));
|
||||
s.execute("templates.create", json!({"id": "user/Web.ectemplate"})).unwrap();
|
||||
assert!(mem.0.lock().unwrap().contains_key(&format!("/{FOOTAGE_DIR}/Web 2/clip.png")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_names_are_safe() {
|
||||
assert_eq!(file_name_for("A/B: C"), "A_B_ C.ectemplate");
|
||||
|
||||
@@ -286,3 +286,69 @@ fn my_custom_rgb_simulation() {
|
||||
assert_eq!(s.prefs.custom_rgb, crate::viewer::CustomRgb::default());
|
||||
assert_eq!(s.execute("view.displayColor", json!({})).unwrap()["customRgb"]["gamma"], json!(2.2));
|
||||
}
|
||||
|
||||
/// My Custom RGB from a LUT-based (`A2B0`) ICC profile: the viewer runs the profile's tables
|
||||
/// (baked into a 3D LUT) and matches the same device described as a matrix/TRC profile.
|
||||
#[test]
|
||||
fn my_custom_rgb_lut_profiles() {
|
||||
use effectcraft_color::icc::{D50, LutKind, write_lut_profile};
|
||||
use effectcraft_color::space;
|
||||
let mut s = session();
|
||||
s.config = Some(std::sync::Arc::new(crate::config::MemoryConfig::default()));
|
||||
s.execute("file.projectSettings", json!({"workingSpace": "srgb"})).unwrap();
|
||||
// The device: P3 primaries, D65 white, gamma 2.4.
|
||||
let p3 = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]];
|
||||
let d65 = [0.3127, 0.3290];
|
||||
let m = space::mul(&space::bradford(d65, D50), &space::rgb_to_xyz(p3, d65));
|
||||
let mi = space::invert(&m);
|
||||
let to = move |c: [f64; 3]| space::mul_vec(&m, c.map(|v| v.powf(2.4)));
|
||||
let from = move |x: [f64; 3]| space::mul_vec(&mi, x).map(|v| v.clamp(0.0, 1.0).powf(1.0 / 2.4));
|
||||
s.execute(
|
||||
"view.customRgb",
|
||||
json!({"name": "Matrix", "red": p3[0], "green": p3[1], "blue": p3[2], "white": d65, "gamma": 2.4, "srgbCurve": false, "preserveRgb": false}),
|
||||
)
|
||||
.unwrap();
|
||||
// (Inside both gamuts, away from the edges where a coarse B2A0 grid bends.)
|
||||
let colors = [px(128, 90, 200), px(90, 170, 110), px(225, 225, 225), px(60, 60, 60), px(200, 120, 100)];
|
||||
let reference: Vec<Vec<[u8; 4]>> = colors
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mut c = c.clone();
|
||||
DisplayColor::of(&s).unwrap().apply(&mut c);
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
let dir = std::env::temp_dir();
|
||||
for (k, (kind, b2a)) in [(LutKind::Lut16, true), (LutKind::AToB, true), (LutKind::Lut8, true), (LutKind::Lut16, false)].into_iter().enumerate() {
|
||||
let icc = write_lut_profile("LUT Display", kind, 33, &to, if b2a { Some(&from) } else { None });
|
||||
let path = dir.join(format!("ec-lut-{}-{k}.icc", std::process::id()));
|
||||
std::fs::write(&path, &icc).unwrap();
|
||||
let r = s.execute("view.customRgb", json!({"icc": path.to_string_lossy(), "preserveRgb": false})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!((r["name"].as_str(), r["lutProfile"].as_bool()), (Some("LUT Display"), Some(true)), "{r}");
|
||||
assert!(r.get("iccLut").is_none());
|
||||
// The numbers approximate the device.
|
||||
let c = s.prefs.custom_rgb.clone();
|
||||
assert!((c.red[0] - 0.680).abs() < 0.01 && (c.green[1] - 0.690).abs() < 0.01, "{kind:?} {c:?}");
|
||||
assert!((c.gamma - 2.4).abs() < 0.1, "{kind:?} {}", c.gamma);
|
||||
let dc = DisplayColor::of(&s).unwrap();
|
||||
assert!(dc.is_lut());
|
||||
let tol = if kind == LutKind::Lut8 { 6 } else { 4 };
|
||||
for (c, want) in colors.iter().zip(&reference) {
|
||||
let mut got = c.clone();
|
||||
dc.apply(&mut got);
|
||||
let d = (0..3).map(|i| (got[0][i] as i32 - want[0][i] as i32).abs()).max().unwrap();
|
||||
assert!(d <= tol, "{kind:?} b2a {b2a}: {c:?} → {got:?}, matrix {want:?}");
|
||||
}
|
||||
}
|
||||
// Kept in Settings (base64) and restored with the preferences.
|
||||
let saved = s.config.as_ref().unwrap().read(crate::prefs::PREFS_FILE).unwrap();
|
||||
assert!(saved.contains("\"iccLut\""));
|
||||
let back: crate::viewer::CustomRgb = serde_json::from_value(serde_json::from_str::<serde_json::Value>(&saved).unwrap()["customRgb"].clone()).unwrap();
|
||||
assert_eq!(back, s.prefs.custom_rgb);
|
||||
assert!(format!("{back:?}").len() < 400);
|
||||
// Typed-in numbers replace the tables.
|
||||
s.execute("view.customRgb", json!({"gamma": 2.2})).unwrap();
|
||||
assert!(s.prefs.custom_rgb.icc_lut.is_empty());
|
||||
assert!(!DisplayColor::of(&s).unwrap().is_lut());
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use effectcraft_geom::{Mat3, vec2};
|
||||
use effectcraft_project::tracking::{LowConfidence, TrackChannel, TrackKind, TrackerOptions, TrackerSettings};
|
||||
use effectcraft_project::{Comp, ItemId, Keyframe, Layer, LayerId, Project, PropGroup, Uid, Value};
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
|
||||
use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use effectcraft_track as trk;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -228,8 +228,11 @@ pub(crate) fn source_frame(
|
||||
Some((Arc::new(buf.img), buf.offset))
|
||||
}
|
||||
|
||||
pub(crate) fn run_work(w: Work, shared: &TrackShared) {
|
||||
pub(crate) async fn run_work(w: Work, shared: &TrackShared) {
|
||||
let t0 = web_time::Instant::now();
|
||||
// A browser job worker's GPU (deferred readbacks): frames render in passes.
|
||||
let accel = crate::offload::job_accel();
|
||||
let accel = accel.as_deref();
|
||||
let fail = |msg: &str| {
|
||||
let mut s = lock(&shared.state);
|
||||
s.error = Some(msg.to_string());
|
||||
@@ -237,16 +240,18 @@ pub(crate) fn run_work(w: Work, shared: &TrackShared) {
|
||||
};
|
||||
let Some(comp) = w.project.comp(w.comp) else { return fail("composition missing") };
|
||||
let Some(layer) = comp.layer(w.layer) else { return fail("layer missing") };
|
||||
let mut r = Renderer::new(&w.project, w.footage.as_ref(), RenderOpts { scale: 1.0, ..Default::default() });
|
||||
let mut r = Renderer::new(&w.project, w.footage.as_ref(), crate::offload::analysis_opts(accel));
|
||||
r.expr = w.expr.as_deref();
|
||||
r.cache = Some(&w.cache);
|
||||
let r = &r;
|
||||
let frame_at = |t: Tick| source_frame(r, &w.project, w.comp, comp, layer, t, w.expr.as_deref());
|
||||
let wr = &w;
|
||||
let frame_at =
|
||||
|t: Tick| crate::offload::in_passes(accel, move |a| source_frame(&r.with_accel(a), &wr.project, wr.comp, comp, layer, t, wr.expr.as_deref()));
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
s.total = w.times.len().saturating_sub(1) as u64;
|
||||
}
|
||||
let Some(first) = frame_at(w.times[0]) else { return fail("the layer has no pixels to track") };
|
||||
let Some(first) = frame_at(w.times[0]).await else { return fail("the layer has no pixels to track") };
|
||||
let specs: Vec<trk::PointSpec> = w.points.iter().map(|p| p.spec).collect();
|
||||
let mut tracker = trk::Tracker::new(track_options(&w.settings.options), &specs, &trk::Frame { img: &first.0, offset: first.1 });
|
||||
let ref_c: Vec<[f64; 2]> = specs.iter().map(|s| s.center).collect();
|
||||
@@ -263,7 +268,7 @@ pub(crate) fn run_work(w: Work, shared: &TrackShared) {
|
||||
.map(|(p, a)| (p.uid, trk::PointResult { center: p.spec.center, confidence: 100.0, rotation: 0.0, scale: 1.0, status: trk::Status::Tracked }, *a))
|
||||
.collect(),
|
||||
});
|
||||
let mut next = if w.times.len() > 1 { frame_at(w.times[1]) } else { None };
|
||||
let mut next = if w.times.len() > 1 { frame_at(w.times[1]).await } else { None };
|
||||
for k in 1..w.times.len() {
|
||||
if shared.cancel.load(Ordering::Relaxed) {
|
||||
lock(&shared.state).cancelled = true;
|
||||
@@ -274,8 +279,12 @@ pub(crate) fn run_work(w: Work, shared: &TrackShared) {
|
||||
break;
|
||||
};
|
||||
// Track this frame while the next one renders.
|
||||
let (res, nf) =
|
||||
rayon::join(|| tracker.step(&trk::Frame { img: &cur.0, offset: cur.1 }), || if k + 1 < w.times.len() { frame_at(w.times[k + 1]) } else { None });
|
||||
let (res, nf) = crate::offload::join_fetch(
|
||||
accel.is_some(),
|
||||
|| tracker.step(&trk::Frame { img: &cur.0, offset: cur.1 }),
|
||||
|| async { if k + 1 < w.times.len() { frame_at(w.times[k + 1]).await } else { None } },
|
||||
)
|
||||
.await;
|
||||
next = nf;
|
||||
if res.iter().any(|p| p.status == trk::Status::Stopped) {
|
||||
lock(&shared.state).low_confidence_stop = true;
|
||||
@@ -363,11 +372,19 @@ impl Session {
|
||||
let shared = Arc::new(TrackShared::default());
|
||||
let (comp, layer) = (work.comp, work.layer);
|
||||
let thread = if wait {
|
||||
run_work(work, &shared);
|
||||
crate::offload::run_or_queue({
|
||||
let sh = shared.clone();
|
||||
async move { run_work(work, &sh).await }
|
||||
});
|
||||
None
|
||||
} else {
|
||||
let sh = shared.clone();
|
||||
Some(std::thread::Builder::new().name("track-analyze".into()).spawn(move || run_work(work, &sh)).map_err(|e| e.to_string())?)
|
||||
Some(
|
||||
std::thread::Builder::new()
|
||||
.name("track-analyze".into())
|
||||
.spawn(move || effectcraft_render::passes::block_on(run_work(work, &sh)))
|
||||
.map_err(|e| e.to_string())?,
|
||||
)
|
||||
};
|
||||
self.track_job = Some(TrackJob { shared, thread, comp, layer, tracker, direction });
|
||||
self.poll_track();
|
||||
|
||||
+173
-22
@@ -522,11 +522,72 @@ pub struct CustomRgb {
|
||||
pub srgb_curve: bool,
|
||||
/// The ICC profile the numbers were read from (empty: typed in).
|
||||
pub icc: String,
|
||||
/// A LUT-based (`A2B0`) profile's bytes: the simulation runs the profile's tables (baked
|
||||
/// into a 3D LUT) instead of the numbers above, which then only approximate it.
|
||||
#[serde(skip_serializing_if = "IccLut::is_empty")]
|
||||
pub icc_lut: IccLut,
|
||||
}
|
||||
|
||||
/// The bytes of a LUT-based ICC profile, kept in Settings as base64.
|
||||
#[derive(Clone, Default, PartialEq)]
|
||||
pub struct IccLut(pub Option<Arc<Vec<u8>>>);
|
||||
|
||||
impl IccLut {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_none()
|
||||
}
|
||||
|
||||
/// The parsed profile.
|
||||
pub fn profile(&self) -> Option<effectcraft_color::icc::LutProfile> {
|
||||
match effectcraft_color::icc::parse_profile(self.0.as_deref()?) {
|
||||
Ok(effectcraft_color::icc::Profile::Lut(p)) => Some(p),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn hash(&self) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
self.0.as_deref().hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for IccLut {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match &self.0 {
|
||||
Some(b) => write!(f, "IccLut({} bytes, {:016x})", b.len(), self.hash()),
|
||||
None => write!(f, "IccLut(none)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for IccLut {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&self.0.as_deref().map(|b| effectcraft_track::roto::rle::base64_encode(b)).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for IccLut {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
|
||||
let s = String::deserialize(d)?;
|
||||
Ok(IccLut(effectcraft_track::roto::rle::base64_decode(&s).filter(|b| !b.is_empty()).map(Arc::new)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CustomRgb {
|
||||
fn default() -> Self {
|
||||
CustomRgb { name: "My Custom RGB".into(), red: P709[0], green: P709[1], blue: P709[2], white: D65, gamma: 2.2, srgb_curve: false, icc: String::new() }
|
||||
CustomRgb {
|
||||
name: "My Custom RGB".into(),
|
||||
red: P709[0],
|
||||
green: P709[1],
|
||||
blue: P709[2],
|
||||
white: D65,
|
||||
gamma: 2.2,
|
||||
srgb_curve: false,
|
||||
icc: String::new(),
|
||||
icc_lut: IccLut::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -564,26 +625,54 @@ impl CustomRgb {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take primaries, white and curve from an RGB ICC profile.
|
||||
/// Take primaries, white and curve from an RGB ICC profile. A LUT-based profile is kept
|
||||
/// whole ([`CustomRgb::icc_lut`]); its numbers are the primaries' and white's colours
|
||||
/// (adapted to D65) and the gamma that fits its neutral ramp.
|
||||
pub fn from_icc(bytes: &[u8], path: &str) -> std::result::Result<CustomRgb, String> {
|
||||
let p = effectcraft_color::icc::parse(bytes)?;
|
||||
let name = if p.description.trim().is_empty() {
|
||||
std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "ICC Profile".into())
|
||||
} else {
|
||||
p.description.trim().to_string()
|
||||
};
|
||||
let gamma = (p.trc.iter().map(|t| t.fit_gamma()).sum::<f64>() / 3.0 * 1000.0).round() / 1000.0;
|
||||
use effectcraft_color::icc::{Profile, parse_profile};
|
||||
let stem = || std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "ICC Profile".into());
|
||||
let name = |d: &str| if d.trim().is_empty() { stem() } else { d.trim().to_string() };
|
||||
let r = |c: [f64; 2]| c.map(|v| (v * 1e5).round() / 1e5);
|
||||
Ok(CustomRgb {
|
||||
name,
|
||||
red: r(p.primaries[0]),
|
||||
green: r(p.primaries[1]),
|
||||
blue: r(p.primaries[2]),
|
||||
white: r(p.white),
|
||||
gamma,
|
||||
srgb_curve: p.trc[0].is_srgb(),
|
||||
icc: path.to_string(),
|
||||
})
|
||||
match parse_profile(bytes)? {
|
||||
Profile::Matrix(p) => {
|
||||
let gamma = (p.trc.iter().map(|t| t.fit_gamma()).sum::<f64>() / 3.0 * 1000.0).round() / 1000.0;
|
||||
Ok(CustomRgb {
|
||||
name: name(&p.description),
|
||||
red: r(p.primaries[0]),
|
||||
green: r(p.primaries[1]),
|
||||
blue: r(p.primaries[2]),
|
||||
white: r(p.white),
|
||||
gamma,
|
||||
srgb_curve: p.trc[0].is_srgb(),
|
||||
icc: path.to_string(),
|
||||
icc_lut: IccLut::default(),
|
||||
})
|
||||
}
|
||||
Profile::Lut(p) => {
|
||||
let (prims, _, gamma) = p.approximate();
|
||||
// The PCS is D50-relative: the device white shows as the viewer's D65.
|
||||
let a = space::bradford(effectcraft_color::icc::D50, D65);
|
||||
let adapt = |c: [f64; 2]| {
|
||||
let v = space::mul_vec(&a, [c[0] / c[1], 1.0, (1.0 - c[0] - c[1]) / c[1]]);
|
||||
let sum = v[0] + v[1] + v[2];
|
||||
let c = [(v[0] / sum).clamp(1e-4, 0.9998), (v[1] / sum).clamp(1e-4, 0.9998)];
|
||||
// Table rounding can put a primary a hair outside the spectrum locus.
|
||||
let k = (0.9999 / (c[0] + c[1])).min(1.0);
|
||||
[c[0] * k, c[1] * k]
|
||||
};
|
||||
Ok(CustomRgb {
|
||||
name: name(&p.description),
|
||||
red: r(adapt(prims[0])),
|
||||
green: r(adapt(prims[1])),
|
||||
blue: r(adapt(prims[2])),
|
||||
white: D65,
|
||||
gamma: (gamma * 1000.0).round() / 1000.0,
|
||||
srgb_curve: false,
|
||||
icc: path.to_string(),
|
||||
icc_lut: IccLut(Some(Arc::new(bytes.to_vec()))),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prof(&self) -> Prof {
|
||||
@@ -643,10 +732,12 @@ const D65: [f64; 2] = [0.3127, 0.3290];
|
||||
/// The viewer's colour conversion from the rendered frame (sRGB-encoded display pixels) to
|
||||
/// what the monitor shows (View ▸ Use Display Color Management, View ▸ Simulate Output and
|
||||
/// the display profile in Settings ▸ Previews). `None` when nothing changes.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DisplayColor {
|
||||
sim: Option<(Conv, Option<Conv>)>,
|
||||
display: Option<Conv>,
|
||||
/// A LUT-based My Custom RGB profile: the whole simulation baked into a 3D LUT.
|
||||
lut: Option<Arc<effectcraft_color::icc::Lut3d>>,
|
||||
}
|
||||
|
||||
impl DisplayColor {
|
||||
@@ -669,7 +760,12 @@ impl DisplayColor {
|
||||
if !dcm {
|
||||
// Without display colour management the working space's numbers go to the screen.
|
||||
let raw = Conv::new(src, Prof::of(ws, linear));
|
||||
return Some(DisplayColor { sim: None, display: Some(raw) });
|
||||
return Some(DisplayColor { sim: None, display: Some(raw), lut: None });
|
||||
}
|
||||
if sim.profile == SimProfile::MyCustom
|
||||
&& let Some(lut) = lut_simulation(custom, src, display, sim.preserve_rgb)
|
||||
{
|
||||
return Some(DisplayColor { sim: None, display: None, lut: Some(lut) });
|
||||
}
|
||||
let out = match sim.profile {
|
||||
SimProfile::MyCustom => Some(custom.prof()),
|
||||
@@ -686,7 +782,7 @@ impl DisplayColor {
|
||||
)
|
||||
});
|
||||
let display = (display != source).then(|| Conv::new(src, Prof::of(display, false)));
|
||||
(sim.is_some() || display.is_some()).then_some(DisplayColor { sim, display })
|
||||
(sim.is_some() || display.is_some()).then_some(DisplayColor { sim, display, lut: None })
|
||||
}
|
||||
|
||||
/// The conversion a session's viewer uses.
|
||||
@@ -706,8 +802,16 @@ impl DisplayColor {
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether the simulation runs a LUT-based ICC profile (baked into a 3D LUT).
|
||||
pub fn is_lut(&self) -> bool {
|
||||
self.lut.is_some()
|
||||
}
|
||||
|
||||
/// One straight colour (0..1 floats).
|
||||
pub fn apply_straight(&self, c: [f32; 3]) -> [f32; 3] {
|
||||
if let Some(l) = &self.lut {
|
||||
return l.eval(c.map(|v| v.clamp(0.0, 1.0))).map(|v| v.clamp(0.0, 1.0));
|
||||
}
|
||||
let c = match &self.sim {
|
||||
// Through the output's 8-bit encoding (clipped and quantised like the real output),
|
||||
// then shown on the display: converted from the output profile, or — Preserve RGB —
|
||||
@@ -739,6 +843,53 @@ impl DisplayColor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Grid points per axis of a baked LUT simulation (a profile without `B2A0` is inverted
|
||||
/// numerically per point, so its grid is coarser).
|
||||
const SIM_LUT_SIZE: usize = 33;
|
||||
const SIM_LUT_SIZE_INVERTED: usize = 17;
|
||||
|
||||
/// My Custom RGB with a LUT-based profile: rendered colours (`src`) → the device's numbers
|
||||
/// (`B2A0`, or `A2B0` inverted), clipped and quantised to 8 bits like the real output → what the
|
||||
/// device shows (`A2B0`; Preserve RGB: the numbers taken as sRGB) → the display. Baked once per
|
||||
/// profile and conversion (the last one is cached).
|
||||
fn lut_simulation(custom: &CustomRgb, src: Prof, display: ColorSpace, preserve: bool) -> Option<Arc<effectcraft_color::icc::Lut3d>> {
|
||||
type Cache = Option<(u64, Arc<effectcraft_color::icc::Lut3d>)>;
|
||||
static CACHE: std::sync::Mutex<Cache> = std::sync::Mutex::new(None);
|
||||
custom.icc_lut.0.as_ref()?;
|
||||
let key = {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
(custom.icc_lut.hash(), format!("{src:?}{display:?}{preserve}")).hash(&mut h);
|
||||
h.finish()
|
||||
};
|
||||
if let Some((k, l)) = CACHE.lock().ok()?.as_ref()
|
||||
&& *k == key
|
||||
{
|
||||
return Some(l.clone());
|
||||
}
|
||||
let prof = custom.icc_lut.profile()?;
|
||||
let to_d50 = space::mul(&space::bradford(D65, effectcraft_color::icc::D50), &src.xyz);
|
||||
let from_d50 = space::bradford(effectcraft_color::icc::D50, D65);
|
||||
let disp = Prof::of(display, false);
|
||||
let disp_inv = space::invert(&disp.xyz);
|
||||
let srgb_to_display = Conv::new(Prof::new(P709, Curve::Srgb), disp);
|
||||
let size = if prof.b2a.is_some() { SIM_LUT_SIZE } else { SIM_LUT_SIZE_INVERTED };
|
||||
let lut = effectcraft_color::icc::Lut3d::bake(size, |c| {
|
||||
let lin = c.map(|v| src.curve.decode(v as f32) as f64);
|
||||
let dev = prof.from_xyz(space::mul_vec(&to_d50, lin), c).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0);
|
||||
if preserve {
|
||||
return srgb_to_display.apply(dev.map(|v| v as f32)).map(|v| v as f64);
|
||||
}
|
||||
let xyz = space::mul_vec(&from_d50, prof.to_xyz(dev));
|
||||
space::mul_vec(&disp_inv, xyz).map(|v| disp.curve.encode(v as f32) as f64)
|
||||
});
|
||||
let lut = Arc::new(lut);
|
||||
if let Ok(mut c) = CACHE.lock() {
|
||||
*c = Some((key, lut.clone()));
|
||||
}
|
||||
Some(lut)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- snapshot
|
||||
|
||||
/// Take Snapshot (Shift+F5): a rendered frame kept for comparison (Show Snapshot, F5).
|
||||
|
||||
+24
-10
@@ -19,7 +19,7 @@ use effectcraft_effects::warp_stab::{self, ANALYSIS, ANALYSIS_KEY};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Project, PropGroup, Uid};
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
|
||||
use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use effectcraft_track::stabilize::{AnalyzeOpts, Analyzer, StabSettings, WarpAnalysis};
|
||||
use serde::Serialize;
|
||||
@@ -193,8 +193,11 @@ fn input_frame(r: &Renderer, ctx: &EvalCtx, layer: &Layer, effect_index: usize)
|
||||
Some((Arc::new(buf.img.clone()), buf.offset))
|
||||
}
|
||||
|
||||
fn run_work(w: WarpWork, shared: &WarpShared) {
|
||||
async fn run_work(w: WarpWork, shared: &WarpShared) {
|
||||
let t0 = web_time::Instant::now();
|
||||
// A browser job worker's GPU (deferred readbacks): frames render in passes.
|
||||
let accel = crate::offload::job_accel();
|
||||
let accel = accel.as_deref();
|
||||
let fail = |msg: &str| {
|
||||
let mut s = lock(&shared.state);
|
||||
s.error = Some(msg.to_string());
|
||||
@@ -202,20 +205,21 @@ fn run_work(w: WarpWork, shared: &WarpShared) {
|
||||
};
|
||||
let Some(comp) = w.project.comp(w.comp) else { return fail("composition missing") };
|
||||
let Some(layer) = comp.layer(w.layer) else { return fail("layer missing") };
|
||||
let mut r = Renderer::new(&w.project, w.footage.as_ref(), RenderOpts { scale: 1.0, ..Default::default() });
|
||||
let mut r = Renderer::new(&w.project, w.footage.as_ref(), crate::offload::analysis_opts(accel));
|
||||
r.expr = w.expr.as_deref();
|
||||
r.cache = Some(&w.cache);
|
||||
let r = &r;
|
||||
let ctx0 = EvalCtx::new(&w.project, w.comp, comp, Tick::ZERO);
|
||||
let ctx0 = EvalCtx { expr: w.expr.as_deref(), ..ctx0 };
|
||||
let frame_at = |t: Tick| input_frame(r, &ctx0.at(t), layer, w.effect_index);
|
||||
let ctx0 = &ctx0;
|
||||
let frame_at = |t: Tick| crate::offload::in_passes(accel, move |a| input_frame(&r.with_accel(a), &ctx0.at(t), layer, w.effect_index));
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
s.step = 1;
|
||||
s.total = w.times.len() as u64;
|
||||
}
|
||||
let mut an = Analyzer::new(w.size, AnalyzeOpts { detailed: w.detailed });
|
||||
let mut next = frame_at(w.times[0]);
|
||||
let mut next = frame_at(w.times[0]).await;
|
||||
for k in 0..w.times.len() {
|
||||
if shared.cancel.load(Ordering::Relaxed) {
|
||||
let mut s = lock(&shared.state);
|
||||
@@ -224,10 +228,12 @@ fn run_work(w: WarpWork, shared: &WarpShared) {
|
||||
return;
|
||||
}
|
||||
let Some(cur) = next.take() else { return fail(&format!("no frame at {:.3} s", w.times[k].seconds())) };
|
||||
let ((), nf) = rayon::join(
|
||||
let ((), nf) = crate::offload::join_fetch(
|
||||
accel.is_some(),
|
||||
|| an.push(&effectcraft_track::Frame { img: &cur.0, offset: cur.1 }),
|
||||
|| if k + 1 < w.times.len() { frame_at(w.times[k + 1]) } else { None },
|
||||
);
|
||||
|| async { if k + 1 < w.times.len() { frame_at(w.times[k + 1]).await } else { None } },
|
||||
)
|
||||
.await;
|
||||
next = nf;
|
||||
let mut s = lock(&shared.state);
|
||||
s.done = k as u64 + 1;
|
||||
@@ -343,11 +349,19 @@ impl Session {
|
||||
let wait = wait || cfg!(target_arch = "wasm32");
|
||||
let shared = Arc::new(WarpShared::default());
|
||||
let thread = if wait {
|
||||
run_work(work, &shared);
|
||||
crate::offload::run_or_queue({
|
||||
let sh = shared.clone();
|
||||
async move { run_work(work, &sh).await }
|
||||
});
|
||||
None
|
||||
} else {
|
||||
let sh = shared.clone();
|
||||
Some(std::thread::Builder::new().name("warp-analyze".into()).spawn(move || run_work(work, &sh)).map_err(|e| e.to_string())?)
|
||||
Some(
|
||||
std::thread::Builder::new()
|
||||
.name("warp-analyze".into())
|
||||
.spawn(move || effectcraft_render::passes::block_on(run_work(work, &sh)))
|
||||
.map_err(|e| e.to_string())?,
|
||||
)
|
||||
};
|
||||
self.warp_job = Some(WarpJob { shared, thread, comp, layer, effect, key });
|
||||
self.events.push(Event::ProjectChanged { revision: self.revision });
|
||||
|
||||
Reference in New Issue
Block a user