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:
Brandon Thomas
2026-10-04 02:57:17 -04:00
co-authored by Claude Opus 5.5
parent d39c0e818c
commit f3715aac32
46 changed files with 3304 additions and 387 deletions
+739 -2
View File
@@ -3,8 +3,15 @@
//! `bXYZ`), the media white point (`wtpt`), the chromatic adaptation (`chad`), the tone curves
//! (`rTRC`, `gTRC`, `bTRC` as `curv` or `para`) and the description (`desc` / `mluc`).
//!
//! Used by View ▸ Simulate Output ▸ My Custom RGB: the profile becomes primaries, a white point
//! and a curve. LUT-based (`A2B0`) and non-RGB profiles are rejected.
//! LUT-based profiles ([`parse_profile`], [`LutProfile`]): `A2B0` / `B2A0` tables of type
//! `lut8Type`, `lut16Type`, `lutAToBType` and `lutBToAType` (ICC.1:2010 §10.10–10.12):
//! curves (`curv`, `para`), matrices and multilinear CLUT interpolation, with the PCS in XYZ or
//! Lab (the legacy 16-bit Lab encoding for `lut16Type`). A profile without `B2A0` is inverted
//! numerically. Implemented from the public specification only.
//!
//! Used by View ▸ Simulate Output ▸ My Custom RGB: a matrix/TRC profile becomes primaries, a white
//! point and a curve; a LUT-based profile is baked into a 3D LUT for the viewer ([`Lut3d`]).
//! Non-RGB profiles are rejected.
use crate::space::{bradford, invert, mul_vec};
@@ -296,6 +303,645 @@ pub fn write_matrix_profile(desc: &str, primaries: [[f64; 2]; 3], white: [f64; 2
out
}
// ---------------------------------------------------------------- LUT-based profiles
/// One processing element of a LUT transform. Values between elements are normalised to 0..1
/// (ICC.1:2010 §10.10–10.12: `lut8Type`, `lut16Type`, `lutAToBType`, `lutBToAType`).
#[derive(Clone, Debug, PartialEq)]
pub enum Stage {
/// One curve per channel.
Curves(Vec<Trc>),
/// A 3×3 matrix and offsets (`lutAToBType` / `lutBToAType`; `lut8/16Type` without offsets).
Matrix([[f64; 3]; 3], [f64; 3]),
Clut(Clut),
}
/// A colour lookup table: `grid[i]` points along input `i`, `outputs` values per point
/// (normalised 0..1), the first input varying slowest (ICC order).
#[derive(Clone, Debug, PartialEq)]
pub struct Clut {
pub grid: Vec<usize>,
pub outputs: usize,
pub data: Vec<f32>,
}
impl Clut {
/// Multilinear interpolation at `x` (0..1 per input).
pub fn eval(&self, x: &[f64]) -> Vec<f64> {
let n = self.grid.len();
let mut base = 0usize;
let mut stride = vec![0usize; n];
let mut s = self.outputs;
for i in (0..n).rev() {
stride[i] = s;
s *= self.grid[i].max(1);
}
let mut frac = vec![0.0; n];
let mut step = vec![0usize; n];
for i in 0..n {
let g = self.grid[i].max(1);
let f = x.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0) * (g - 1) as f64;
let k = (f.floor() as usize).min(g.saturating_sub(2));
frac[i] = if g > 1 { f - k as f64 } else { 0.0 };
step[i] = if g > 1 { stride[i] } else { 0 };
base += k * stride[i];
}
let mut out = vec![0.0; self.outputs];
for corner in 0..(1usize << n) {
let mut w = 1.0;
let mut off = base;
for i in 0..n {
if corner >> i & 1 == 1 {
w *= frac[i];
off += step[i];
} else {
w *= 1.0 - frac[i];
}
}
if w == 0.0 {
continue;
}
for (o, v) in out.iter_mut().enumerate() {
*v += w * self.data.get(off + o).copied().unwrap_or(0.0) as f64;
}
}
out
}
}
/// A LUT transform (`A2B0` device → PCS, or `B2A0` PCS → device).
#[derive(Clone, Debug, PartialEq)]
pub struct Lut {
pub inputs: usize,
pub outputs: usize,
pub stages: Vec<Stage>,
/// `lut16Type`: PCS Lab uses the legacy 16-bit encoding (0xFF00 = L 100).
pub legacy_lab: bool,
}
impl Lut {
/// Run the transform on normalised values.
pub fn eval(&self, x: &[f64]) -> Vec<f64> {
let mut v: Vec<f64> = x.iter().map(|v| v.clamp(0.0, 1.0)).collect();
for s in &self.stages {
v = match s {
Stage::Curves(c) => v.iter().enumerate().map(|(i, x)| c.get(i).map_or(*x, |t| t.eval(*x))).collect(),
Stage::Matrix(m, o) if v.len() == 3 => (0..3).map(|i| (m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2] + o[i]).clamp(0.0, 1.0)).collect(),
Stage::Matrix(..) => v,
Stage::Clut(c) => c.eval(&v),
};
}
v
}
}
/// The profile connection space of a profile.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pcs {
Xyz,
Lab,
}
/// D50 white (X, Y, Z) of the PCS.
const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249];
fn lab_to_xyz(l: [f64; 3]) -> [f64; 3] {
let fy = (l[0] + 16.0) / 116.0;
let fx = fy + l[1] / 500.0;
let fz = fy - l[2] / 200.0;
let inv = |t: f64| if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f64 / 29.0).powi(2) * (t - 4.0 / 29.0) };
[D50_XYZ[0] * inv(fx), D50_XYZ[1] * inv(fy), D50_XYZ[2] * inv(fz)]
}
fn xyz_to_lab(x: [f64; 3]) -> [f64; 3] {
let f = |t: f64| if t > (6.0f64 / 29.0).powi(3) { t.cbrt() } else { t / (3.0 * (6.0f64 / 29.0).powi(2)) + 4.0 / 29.0 };
let (fx, fy, fz) = (f(x[0] / D50_XYZ[0]), f(x[1] / D50_XYZ[1]), f(x[2] / D50_XYZ[2]));
[116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]
}
/// Normalised PCS values (a LUT's output or input) → CIE XYZ (D50).
pub fn pcs_to_xyz(pcs: Pcs, legacy: bool, n: &[f64]) -> [f64; 3] {
let g = |i: usize| n.get(i).copied().unwrap_or(0.0);
match pcs {
Pcs::Xyz => [0, 1, 2].map(|i| g(i) * 65535.0 / 32768.0),
Pcs::Lab => {
let k = if legacy { 65535.0 / 65280.0 } else { 1.0 };
lab_to_xyz([g(0) * k * 100.0, g(1) * k * 255.0 - 128.0, g(2) * k * 255.0 - 128.0])
}
}
}
/// CIE XYZ (D50) → normalised PCS values.
pub fn xyz_to_pcs(pcs: Pcs, legacy: bool, xyz: [f64; 3]) -> [f64; 3] {
match pcs {
Pcs::Xyz => xyz.map(|v| (v * 32768.0 / 65535.0).clamp(0.0, 1.0)),
Pcs::Lab => {
let l = xyz_to_lab(xyz);
let k = if legacy { 65280.0 / 65535.0 } else { 1.0 };
[(l[0] / 100.0 * k).clamp(0.0, 1.0), ((l[1] + 128.0) / 255.0 * k).clamp(0.0, 1.0), ((l[2] + 128.0) / 255.0 * k).clamp(0.0, 1.0)]
}
}
}
/// What a LUT-based RGB profile says: its `A2B0` (device → PCS) and, when present, its `B2A0`
/// (PCS → device).
#[derive(Clone, Debug, PartialEq)]
pub struct LutProfile {
pub description: String,
pub pcs: Pcs,
pub a2b: Lut,
pub b2a: Option<Lut>,
pub version: u8,
}
impl LutProfile {
/// Device RGB (0..1) → CIE XYZ (D50, relative to the PCS white).
pub fn to_xyz(&self, rgb: [f64; 3]) -> [f64; 3] {
pcs_to_xyz(self.pcs, self.a2b.legacy_lab, &self.a2b.eval(&rgb))
}
/// CIE XYZ (D50) → device RGB (0..1): through `B2A0`, or by inverting `A2B0` (Gauss-Newton
/// from `guess`, clipped to the device cube) when the profile has none.
pub fn from_xyz(&self, xyz: [f64; 3], guess: [f64; 3]) -> [f64; 3] {
if let Some(b) = &self.b2a {
let v = b.eval(&xyz_to_pcs(self.pcs, b.legacy_lab, xyz));
return [0, 1, 2].map(|i| v.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0));
}
self.invert(xyz, guess)
}
/// Device RGB whose `A2B0` result is closest to `xyz` (least squares in CIE Lab).
pub fn invert(&self, xyz: [f64; 3], guess: [f64; 3]) -> [f64; 3] {
let target = xyz_to_lab(xyz);
let err = |rgb: [f64; 3]| {
let l = xyz_to_lab(self.to_xyz(rgb));
[l[0] - target[0], l[1] - target[1], l[2] - target[2]]
};
let norm = |e: [f64; 3]| e[0] * e[0] + e[1] * e[1] + e[2] * e[2];
let mut x = guess.map(|v| v.clamp(0.0, 1.0));
let mut e = err(x);
for _ in 0..24 {
if norm(e) < 1e-6 {
break;
}
// Finite-difference Jacobian (one-sided, inward at the cube's faces).
let h = 1e-3;
let mut j = [[0.0; 3]; 3];
for c in 0..3 {
let mut y = x;
let d = if x[c] + h <= 1.0 { h } else { -h };
y[c] += d;
let ey = err(y);
for r in 0..3 {
j[r][c] = (ey[r] - e[r]) / d;
}
}
let det = j[0][0] * (j[1][1] * j[2][2] - j[1][2] * j[2][1]) - j[0][1] * (j[1][0] * j[2][2] - j[1][2] * j[2][0])
+ j[0][2] * (j[1][0] * j[2][1] - j[1][1] * j[2][0]);
if det.abs() < 1e-12 {
break;
}
let ji = crate::space::invert(&j);
let dx = crate::space::mul_vec(&ji, e);
// Damped step: halve until the error drops.
let mut t = 1.0;
let mut improved = false;
for _ in 0..8 {
let y = [0, 1, 2].map(|i| (x[i] - t * dx[i]).clamp(0.0, 1.0));
let ey = err(y);
if norm(ey) < norm(e) {
x = y;
e = ey;
improved = true;
break;
}
t *= 0.5;
}
if !improved {
break;
}
}
x
}
/// Chromaticities and white the profile's device approximately has (what the dialog shows):
/// the primaries' and white's `A2B0` results (CIE xy, D50-relative), and the gamma that
/// best fits its neutral ramp.
pub fn approximate(&self) -> ([[f64; 2]; 3], [f64; 2], f64) {
let prim = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]].map(|c| xy(self.to_xyz(c)));
let wy = self.to_xyz([1.0; 3])[1].max(1e-9);
let ramp = Trc::Table((0..=64).map(|i| ((self.to_xyz([i as f64 / 64.0; 3])[1] / wy).clamp(0.0, 1.0) * 65535.0).round() as u16).collect());
(prim, D50, ramp.fit_gamma())
}
}
/// A parsed RGB profile: matrix/TRC, or LUT-based (`A2B0`, which takes precedence when both are
/// present, as the ICC specification says).
#[derive(Clone, Debug, PartialEq)]
pub enum Profile {
Matrix(RgbProfile),
Lut(LutProfile),
}
fn tag_table(b: &[u8]) -> Result<std::collections::HashMap<String, &[u8]>, String> {
let n = be32(b, 128).ok_or("truncated tag table")? as usize;
let mut tags = std::collections::HashMap::new();
for i in 0..n.min(200) {
let o = 132 + i * 12;
let sig = b.get(o..o + 4).ok_or("truncated tag table")?;
let off = be32(b, o + 4).ok_or("truncated tag table")? as usize;
let size = be32(b, o + 8).ok_or("truncated tag table")? as usize;
if off.checked_add(size).is_some_and(|e| e <= b.len()) {
tags.insert(String::from_utf8_lossy(sig).into_owned(), &b[off..off + size]);
}
}
Ok(tags)
}
/// Parse an RGB ICC profile, LUT-based or matrix/TRC.
pub fn parse_profile(b: &[u8]) -> Result<Profile, String> {
if b.len() < 132 || b.get(36..40) != Some(b"acsp") {
return Err("not an ICC profile".into());
}
if b.get(16..20) != Some(b"RGB ") {
return Err("not an RGB profile (only RGB display profiles can be simulated)".into());
}
let pcs = match b.get(20..24) {
Some(b"XYZ ") => Pcs::Xyz,
Some(b"Lab ") => Pcs::Lab,
_ => return Err("unknown profile connection space".into()),
};
let tags = tag_table(b)?;
let Some(a2b) = tags.get("A2B0") else { return parse(b).map(Profile::Matrix) };
let a2b = parse_lut(a2b, false).map_err(|e| format!("A2B0: {e}"))?;
if a2b.inputs != 3 || a2b.outputs != 3 {
return Err("A2B0 must map 3 device channels to 3 PCS values".into());
}
let b2a = match tags.get("B2A0").map(|t| parse_lut(t, true)) {
Some(Ok(l)) if l.inputs == 3 && l.outputs == 3 => Some(l),
_ => None,
};
Ok(Profile::Lut(LutProfile { description: description(tags.get("desc").copied()).unwrap_or_default(), pcs, a2b, b2a, version: b[8] }))
}
/// A `curv` or `para` element at `o` of `t`; returns it and its padded length.
fn curve_at(t: &[u8], o: usize) -> Result<(Trc, usize), String> {
match t.get(o..o + 4) {
Some(b"curv") => {
let count = be32(t, o + 8).ok_or("bad curv")? as usize;
let trc = match count {
0 => Trc::Gamma(1.0),
1 => Trc::Gamma(be16(t, o + 12).ok_or("bad curv")? as f64 / 256.0),
_ => Trc::Table((0..count).map(|i| be16(t, o + 12 + i * 2)).collect::<Option<Vec<_>>>().ok_or("truncated curv")?),
};
Ok((trc, (12 + count * 2).div_ceil(4) * 4))
}
Some(b"para") => {
let ty = be16(t, o + 8).ok_or("bad para")?;
let np = [1, 3, 4, 5, 7].get(ty as usize).copied().ok_or("unknown para function")?;
let mut p = [0.0; 7];
for (k, v) in p.iter_mut().enumerate().take(np) {
*v = s15f16(t, o + 12 + k * 4).ok_or("truncated para")?;
}
Ok((if ty == 0 { Trc::Gamma(p[0]) } else { Trc::Parametric(ty, p) }, 12 + np * 4))
}
_ => Err("unsupported curve element".into()),
}
}
fn curves_at(t: &[u8], o: usize, n: usize) -> Result<Vec<Trc>, String> {
let mut v = vec![];
let mut o = o;
for _ in 0..n {
let (c, len) = curve_at(t, o)?;
v.push(c);
o += len;
}
Ok(v)
}
fn clut_len(grid: &[usize], outputs: usize) -> Option<usize> {
grid.iter().try_fold(outputs, |a, g| a.checked_mul(*g)).filter(|n| *n <= 1 << 26)
}
/// `lut8Type` / `lut16Type` / `lutAToBType` / `lutBToAType`. `b2a`: the element order of a
/// PCS → device table.
pub fn parse_lut(t: &[u8], b2a: bool) -> Result<Lut, String> {
let sig = t.get(0..4).ok_or("empty tag")?;
match sig {
b"mft1" | b"mft2" => {
let wide = sig == b"mft2";
let (i, o, g) = (*t.get(8).ok_or("truncated")? as usize, *t.get(9).ok_or("truncated")? as usize, *t.get(10).ok_or("truncated")? as usize);
if i == 0 || o == 0 || i > 8 || o > 15 || g < 2 {
return Err("bad table dimensions".into());
}
let mut m = [[0.0; 3]; 3];
for (k, v) in m.iter_mut().flatten().enumerate() {
*v = s15f16(t, 12 + k * 4).ok_or("truncated matrix")?;
}
let (n_in, n_out, mut p) =
if wide { (be16(t, 48).ok_or("truncated")? as usize, be16(t, 50).ok_or("truncated")? as usize, 52) } else { (256, 256, 48) };
if n_in < 2 || n_out < 2 {
return Err("bad table sizes".into());
}
let w = if wide { 2 } else { 1 };
let read = |p: usize| -> Option<u16> { if wide { be16(t, p) } else { t.get(p).map(|v| *v as u16 * 257) } };
let table = |n: usize, p: &mut usize| -> Result<Trc, String> {
let v = (0..n).map(|k| read(*p + k * w)).collect::<Option<Vec<_>>>().ok_or("truncated table")?;
*p += n * w;
Ok(Trc::Table(v))
};
let ins = (0..i).map(|_| table(n_in, &mut p)).collect::<Result<Vec<_>, _>>()?;
let grid = vec![g; i];
let len = clut_len(&grid, o).ok_or("table too large")?;
let data = (0..len).map(|k| read(p + k * w).map(|v| v as f32 / 65535.0)).collect::<Option<Vec<_>>>().ok_or("truncated table")?;
p += len * w;
let outs = (0..o).map(|_| table(n_out, &mut p)).collect::<Result<Vec<_>, _>>()?;
let mut stages = vec![];
// The matrix applies only to XYZ input (a PCS → device table); identity is skipped.
let ident = m == [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
if b2a && i == 3 && !ident {
stages.push(Stage::Matrix(m, [0.0; 3]));
}
stages.push(Stage::Curves(ins));
stages.push(Stage::Clut(Clut { grid, outputs: o, data }));
stages.push(Stage::Curves(outs));
Ok(Lut { inputs: i, outputs: o, stages, legacy_lab: wide })
}
b"mAB " | b"mBA " => {
let (i, o) = (*t.get(8).ok_or("truncated")? as usize, *t.get(9).ok_or("truncated")? as usize);
if i == 0 || o == 0 || i > 15 || o > 15 {
return Err("bad channel counts".into());
}
let off = |k: usize| be32(t, 12 + k * 4).map(|v| v as usize).ok_or("truncated offsets");
let (ob, om, oc, oclut, oa) = (off(0)?, off(1)?, off(2)?, off(3)?, off(4)?);
let a_n = if sig == b"mAB " { i } else { o };
let b_n = if sig == b"mAB " { o } else { i };
let bc = if ob > 0 { Some(Stage::Curves(curves_at(t, ob, b_n)?)) } else { None };
let ac = if oa > 0 { Some(Stage::Curves(curves_at(t, oa, a_n)?)) } else { None };
let mtx = if om > 0 {
let v = (0..12).map(|k| s15f16(t, om + k * 4)).collect::<Option<Vec<_>>>().ok_or("truncated matrix")?;
Some(Stage::Matrix([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]], [v[9], v[10], v[11]]))
} else {
None
};
let mc = if oc > 0 { Some(Stage::Curves(curves_at(t, oc, 3)?)) } else { None };
let clut = if oclut > 0 {
let (ci, co) = (i, o);
let grid: Vec<usize> = (0..ci).map(|k| t.get(oclut + k).map(|v| *v as usize)).collect::<Option<_>>().ok_or("truncated clut")?;
if grid.iter().any(|g| *g < 2) {
return Err("bad grid".into());
}
let prec = *t.get(oclut + 16).ok_or("truncated clut")? as usize;
let len = clut_len(&grid, co).ok_or("table too large")?;
let d = oclut + 20;
let data = match prec {
1 => (0..len).map(|k| t.get(d + k).map(|v| *v as f32 / 255.0)).collect::<Option<Vec<_>>>(),
2 => (0..len).map(|k| be16(t, d + k * 2).map(|v| v as f32 / 65535.0)).collect::<Option<Vec<_>>>(),
_ => return Err("bad clut precision".into()),
}
.ok_or("truncated clut")?;
Some(Stage::Clut(Clut { grid, outputs: co, data }))
} else {
None
};
if bc.is_none() {
return Err("the B curves are required".into());
}
// A → CLUT → M → matrix → B (A2B); B → matrix → M → CLUT → A (B2A).
let order = if sig == b"mAB " { [ac, clut, mc, mtx, bc] } else { [bc, mtx, mc, clut, ac] };
Ok(Lut { inputs: i, outputs: o, stages: order.into_iter().flatten().collect(), legacy_lab: false })
}
_ => Err(format!("unsupported table type `{}`", String::from_utf8_lossy(sig))),
}
}
/// The kind of table [`write_lut_profile`] writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LutKind {
/// `lut8Type` (PCS Lab).
Lut8,
/// `lut16Type` (PCS XYZ).
Lut16,
/// `lutAToBType` / `lutBToAType` (PCS Lab, v4) with power-curve A curves and a matrix element.
AToB,
}
/// Build a LUT-based RGB display profile (tests, generated profiles): `A2B0` samples `to_xyz`
/// (device RGB → XYZ D50) on a `grid`³ table; with `from_xyz`, a `B2A0` samples it on the PCS.
pub fn write_lut_profile(
desc: &str,
kind: LutKind,
grid: usize,
to_xyz: &dyn Fn([f64; 3]) -> [f64; 3],
from_xyz: Option<&dyn Fn([f64; 3]) -> [f64; 3]>,
) -> Vec<u8> {
let (pcs, legacy) = match kind {
LutKind::Lut8 => (Pcs::Lab, false),
LutKind::Lut16 => (Pcs::Xyz, true),
LutKind::AToB => (Pcs::Lab, false),
};
// The A curves of an AToB table (a power curve) spread the grid evenly over lightness.
let a_gamma = 0.75;
let pt = |k: usize| k as f64 / (grid - 1) as f64;
let mut a2b_vals = vec![];
let mut b2a_vals = vec![];
for r in 0..grid {
for g in 0..grid {
for b in 0..grid {
let mut rgb = [pt(r), pt(g), pt(b)];
if kind == LutKind::AToB {
rgb = rgb.map(|v| v.powf(1.0 / a_gamma));
}
a2b_vals.extend(xyz_to_pcs(pcs, legacy, to_xyz(rgb)));
if let Some(f) = from_xyz {
// A lut16 B2A0 over XYZ gets cube-root input curves (even steps in lightness).
let node = [pt(r), pt(g), pt(b)];
let x = pcs_to_xyz(pcs, legacy, &if kind == LutKind::Lut16 { node.map(|v| v * v * v) } else { node });
let d = f(x).map(|v| v.clamp(0.0, 1.0));
b2a_vals.extend(d);
}
}
}
}
let s15 = |v: f64| ((v * 65536.0).round() as i32).to_be_bytes();
let pad4 = |t: &mut Vec<u8>| {
while !t.len().is_multiple_of(4) {
t.push(0);
}
};
let mft = |vals: &[f64], wide: bool, cube_in: bool| -> Vec<u8> {
let mut t = if wide { b"mft2\0\0\0\0".to_vec() } else { b"mft1\0\0\0\0".to_vec() };
t.extend([3, 3, grid as u8, 0]);
for k in 0..9 {
t.extend(s15(if k % 4 == 0 { 1.0 } else { 0.0 }));
}
let n = 256usize;
if wide {
t.extend((n as u16).to_be_bytes());
t.extend((n as u16).to_be_bytes());
}
let put = |t: &mut Vec<u8>, v: f64| {
if wide { t.extend(((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_be_bytes()) } else { t.push((v.clamp(0.0, 1.0) * 255.0).round() as u8) }
};
for _ in 0..3 {
for k in 0..n {
let x = k as f64 / (n - 1) as f64;
put(&mut t, if cube_in { x.cbrt() } else { x });
}
}
for v in vals {
put(&mut t, *v);
}
for _ in 0..3 {
for k in 0..n {
put(&mut t, k as f64 / (n - 1) as f64);
}
}
pad4(&mut t);
t
};
let curv_identity = || b"curv\0\0\0\0\0\0\0\0".to_vec();
let para_gamma = |g: f64| {
let mut t = b"para\0\0\0\0\0\0\0\0".to_vec();
t.extend(s15(g));
t
};
let mab = |vals: &[f64], a2b: bool| -> Vec<u8> {
let mut t = if a2b { b"mAB \0\0\0\0".to_vec() } else { b"mBA \0\0\0\0".to_vec() };
t.extend([3, 3, 0, 0]);
let offsets_at = t.len();
t.extend([0u8; 20]);
// B curves (identity).
let ob = t.len();
for _ in 0..3 {
t.extend(curv_identity());
}
// Matrix: identity, zero offsets (exercises the element).
let om = t.len();
for k in 0..9 {
t.extend(s15(if k % 4 == 0 { 1.0 } else { 0.0 }));
}
for _ in 0..3 {
t.extend(s15(0.0));
}
// M curves (identity).
let oc = t.len();
for _ in 0..3 {
t.extend(curv_identity());
}
let oclut = t.len();
let mut g = [0u8; 16];
g[..3].fill(grid as u8);
t.extend(g);
t.extend([2, 0, 0, 0]);
for v in vals {
t.extend(((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_be_bytes());
}
pad4(&mut t);
let oa = t.len();
for _ in 0..3 {
t.extend(para_gamma(if a2b { a_gamma } else { 1.0 }));
}
for (k, o) in [ob, om, oc, oclut, oa].into_iter().enumerate() {
t[offsets_at + k * 4..offsets_at + k * 4 + 4].copy_from_slice(&(o as u32).to_be_bytes());
}
t
};
let table = |vals: &[f64], a2b: bool| match kind {
LutKind::Lut8 => mft(vals, false, false),
LutKind::Lut16 => mft(vals, true, !a2b),
LutKind::AToB => mab(vals, a2b),
};
let dsc = {
let mut t = b"desc\0\0\0\0".to_vec();
t.extend((desc.len() as u32 + 1).to_be_bytes());
t.extend(desc.as_bytes());
t.push(0);
t.extend([0u8; 12 + 67]);
pad4(&mut t);
t
};
let mut tags: Vec<(&[u8; 4], Vec<u8>)> = vec![(b"desc", dsc), (b"A2B0", table(&a2b_vals, true))];
if from_xyz.is_some() {
tags.push((b"B2A0", table(&b2a_vals, false)));
}
let mut tab = vec![];
let mut data = vec![];
let base = 128 + 4 + tags.len() * 12;
for (sig, t) in &tags {
tab.extend(*sig);
tab.extend(((base + data.len()) as u32).to_be_bytes());
tab.extend((t.len() as u32).to_be_bytes());
data.extend(t);
pad4(&mut data);
}
let total = base + data.len();
let mut h = vec![0u8; 128];
h[0..4].copy_from_slice(&(total as u32).to_be_bytes());
h[8] = if kind == LutKind::AToB { 4 } else { 2 };
h[12..16].copy_from_slice(b"mntr");
h[16..20].copy_from_slice(b"RGB ");
h[20..24].copy_from_slice(if pcs == Pcs::Lab { b"Lab " } else { b"XYZ " });
h[36..40].copy_from_slice(b"acsp");
for (k, v) in D50_XYZ.into_iter().enumerate() {
h[68 + k * 4..72 + k * 4].copy_from_slice(&s15(v));
}
let mut out = h;
out.extend((tags.len() as u32).to_be_bytes());
out.extend(tab);
out.extend(data);
out
}
/// A baked 3D lookup table: `size`³ RGB points over the unit cube (red varying slowest),
/// evaluated trilinearly.
#[derive(Clone, Debug, PartialEq)]
pub struct Lut3d {
pub size: usize,
pub data: Vec<[f32; 3]>,
}
impl Lut3d {
/// Sample `f` on a `size`³ grid.
pub fn bake(size: usize, f: impl Fn([f64; 3]) -> [f64; 3]) -> Lut3d {
let size = size.max(2);
let pt = |k: usize| k as f64 / (size - 1) as f64;
let data = (0..size * size * size)
.map(|i| {
let (r, g, b) = (i / (size * size), i / size % size, i % size);
f([pt(r), pt(g), pt(b)]).map(|v| v as f32)
})
.collect();
Lut3d { size, data }
}
pub fn eval(&self, c: [f32; 3]) -> [f32; 3] {
let n = self.size;
let mut k = [0usize; 3];
let mut f = [0f32; 3];
for i in 0..3 {
let x = c[i].clamp(0.0, 1.0) * (n - 1) as f32;
k[i] = (x.floor() as usize).min(n - 2);
f[i] = x - k[i] as f32;
}
let at = |r: usize, g: usize, b: usize| self.data[(r * n + g) * n + b];
let mut out = [0f32; 3];
for corner in 0..8 {
let (dr, dg, db) = (corner >> 2 & 1, corner >> 1 & 1, corner & 1);
let w = (if dr == 1 { f[0] } else { 1.0 - f[0] }) * (if dg == 1 { f[1] } else { 1.0 - f[1] }) * (if db == 1 { f[2] } else { 1.0 - f[2] });
if w == 0.0 {
continue;
}
let v = at(k[0] + dr, k[1] + dg, k[2] + db);
for i in 0..3 {
out[i] += w * v[i];
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -334,4 +980,95 @@ mod tests {
b[16..20].copy_from_slice(b"CMYK");
assert!(parse(&b).unwrap_err().contains("RGB"));
}
/// A display: P3 primaries, D65 white, gamma 2.2 → XYZ D50 (and back).
fn device() -> (impl Fn([f64; 3]) -> [f64; 3], impl Fn([f64; 3]) -> [f64; 3]) {
let p3 = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]];
let m = crate::space::mul(&bradford(D65, D50), &crate::space::rgb_to_xyz(p3, D65));
let mi = invert(&m);
(move |c: [f64; 3]| mul_vec(&m, c.map(|v| v.powf(2.2))), move |x: [f64; 3]| mul_vec(&mi, x).map(|v| v.clamp(0.0, 1.0).powf(1.0 / 2.2)))
}
fn lab_de(a: [f64; 3], b: [f64; 3]) -> f64 {
let (a, b) = (xyz_to_lab(a), xyz_to_lab(b));
((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
}
#[test]
fn lut_profiles_evaluate_their_a2b0() {
let (to, from) = device();
for (kind, grid, tol) in [(LutKind::Lut16, 17, 2.5), (LutKind::Lut8, 17, 3.0), (LutKind::AToB, 17, 1.5)] {
let b = write_lut_profile("LUT Monitor", kind, grid, &to, Some(&from));
let Profile::Lut(p) = parse_profile(&b).unwrap() else { panic!("{kind:?}: not a LUT profile") };
assert_eq!(p.description, "LUT Monitor");
assert!(p.b2a.is_some());
let mut worst = 0.0f64;
for k in 0..125 {
let c = [(k / 25) as f64 / 4.0, (k / 5 % 5) as f64 / 4.0, (k % 5) as f64 / 4.0];
worst = worst.max(lab_de(p.to_xyz(c), to(c)));
// PCS → device through B2A0 lands back on mid-gamut colours (a coarse grid
// over linear XYZ can't follow the gamma curve: checked at its nodes below).
if p.pcs == Pcs::Lab && c.iter().all(|v| (0.25..=0.75).contains(v)) {
let back = p.from_xyz(to(c), [0.5; 3]);
assert!(lab_de(to(back), to(c)) < 6.0, "{kind:?} {c:?} → {back:?}");
}
}
assert!(worst < tol, "{kind:?}: ΔE {worst}");
// At B2A0's grid nodes the table gives what was sampled.
let b2a = p.b2a.as_ref().unwrap();
let q = match kind {
LutKind::Lut8 => 2.0 / 255.0,
LutKind::Lut16 => 3e-3,
LutKind::AToB => 1e-3,
};
for node in [[0.5, 0.5, 0.5], [0.25, 0.5, 0.75], [1.0, 0.0, 0.5]] {
// (lut16: through its cube-root input curves)
let node = if kind == LutKind::Lut16 { node.map(|v: f64| v * v * v) } else { node };
let want = from(pcs_to_xyz(p.pcs, b2a.legacy_lab, &node));
let got = b2a.eval(&node);
assert!((0..3).all(|i| (got[i] - want[i]).abs() < q), "{kind:?} {node:?}: {got:?} vs {want:?}");
}
// The matrix reader rejects it; the approximation finds the primaries.
assert!(parse(&b).is_err());
let (prim, _, gamma) = p.approximate();
let red = xy(to([1.0, 0.0, 0.0]));
assert!((prim[0][0] - red[0]).abs() < 0.01 && (prim[0][1] - red[1]).abs() < 0.01, "{kind:?} {prim:?}");
assert!((gamma - 2.2).abs() < 0.1, "{kind:?} gamma {gamma}");
}
}
#[test]
fn a2b0_without_b2a0_is_inverted() {
let (to, _) = device();
let b = write_lut_profile("A2B only", LutKind::Lut16, 17, &to, None);
let Profile::Lut(p) = parse_profile(&b).unwrap() else { panic!() };
assert!(p.b2a.is_none());
for c in [[0.2, 0.5, 0.8], [0.9, 0.1, 0.3], [0.5, 0.5, 0.5], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]] {
let x = to(c);
let back = p.from_xyz(x, [0.5; 3]);
assert!(lab_de(p.to_xyz(back), x) < 0.5, "{c:?} → {back:?}");
}
// A matrix/TRC profile still parses as one.
assert!(matches!(parse_profile(&write_matrix_profile("m", P709, D65, 2.2)).unwrap(), Profile::Matrix(_)));
}
#[test]
fn clut_and_lut3d_interpolate() {
// A 2-point identity CLUT on 3 inputs is exact for every point.
let mut data = vec![];
for r in 0..2 {
for g in 0..2 {
for b in 0..2 {
data.extend([r as f32, g as f32, b as f32]);
}
}
}
let c = Clut { grid: vec![2; 3], outputs: 3, data };
let v = c.eval(&[0.25, 0.5, 0.75]);
assert!((v[0] - 0.25).abs() < 1e-6 && (v[1] - 0.5).abs() < 1e-6 && (v[2] - 0.75).abs() < 1e-6);
let l = Lut3d::bake(5, |c| [c[0] * c[0], c[1], 1.0 - c[2]]);
let o = l.eval([0.5, 0.3, 0.2]);
assert!((o[0] - 0.25).abs() < 1e-6 && (o[1] - 0.3).abs() < 1e-6 && (o[2] - 0.8).abs() < 1e-6, "{o:?}");
assert!(parse_lut(b"xxxx\0\0\0\0", false).is_err());
}
}
+24 -10
View File
@@ -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 });
+21 -3
View File
@@ -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
),
+12
View File
@@ -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).
+39 -16
View File
@@ -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
View File
@@ -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
View File
@@ -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();
+35 -18
View File
@@ -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
View File
@@ -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
View File
@@ -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");
+66
View File
@@ -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());
}
+27 -10
View File
@@ -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
View File
@@ -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
View File
@@ -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 });
+4 -4
View File
@@ -249,7 +249,7 @@ pub(crate) fn pcm_bytes(buf: &[f32], fmt: AudioFormat, big_endian: bool) -> Vec<
type Writer<'f, 's> = Mp4Writer<&'f mut crate::out::Out<'s>>;
pub(crate) fn movie(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) -> Result<Report> {
let rate = job.settings.rate(comp);
let fmt = job.output.format;
let channels = match job.output.channels {
@@ -264,11 +264,11 @@ pub(crate) fn movie(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Re
};
let brand = if fmt == OutputFormat::ProRes { Brand::Mov } else { Brand::Mp4 };
let batch = batch_size();
let render = |k: u64| -> Vec<u8> { job.pixels(&job.frame(comp, k), comp, channels, w, h) };
let render = |_: u64, img: effectcraft_raster::Image| -> Vec<u8> { job.pixels(&img, comp, channels, w, h) };
// Encode the first batch before creating tracks: encoders finalise their config on frame 1.
let first_end = batch.min(st.total);
let first: Vec<Vec<u8>> = (0..first_end).into_par_iter().map(render).collect();
let first: Vec<Vec<u8>> = job.frames(comp, (0..first_end).collect(), render).await;
let mut pending = Vec::new();
for (k, px) in first.iter().enumerate() {
pending.extend(venc.encode(px, k as u64)?);
@@ -356,7 +356,7 @@ pub(crate) fn movie(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Re
let mut i = first_end;
while i < total {
let end = (i + batch).min(total);
let frames: Vec<Vec<u8>> = (i..end).into_par_iter().map(render).collect();
let frames: Vec<Vec<u8>> = job.frames(comp, (i..end).collect(), render).await;
for (k, px) in frames.iter().enumerate() {
let ps = venc.encode(px, i + k as u64)?;
write_video(&mut mux, ps)?;
+23 -22
View File
@@ -41,7 +41,6 @@ use effectcraft_project::render_queue::{AudioOutput, Channels, OutputFormat, Out
use effectcraft_project::{Comp, ItemId, Project};
use effectcraft_raster::Image;
use effectcraft_render::{ExprHost, FootageSource};
use rayon::prelude::*;
pub use effectcraft_project::render_queue;
pub use effectcraft_project::render_queue::StorageQuota;
@@ -159,9 +158,17 @@ pub fn wants_audio(job: &Job) -> bool {
/// Run the export (blocking). `progress` is called after every batch; returning `false` cancels.
pub fn export(job: &Job, progress: &mut dyn FnMut(&Progress) -> bool) -> Result<Report> {
effectcraft_render::passes::block_on(export_async(job, progress))
}
/// [`export`] as a future: with an accelerator whose readbacks are deferred (WebGPU in a
/// browser worker) every frame renders in passes, awaiting the device in between
/// ([`effectcraft_render::passes`]); otherwise it never waits and frames render in parallel
/// batches as in [`export`].
pub async fn export_async(job: &Job<'_>, progress: &mut dyn FnMut(&Progress) -> bool) -> Result<Report> {
let t0 = Instant::now();
let cx = Cx::new(job);
let mut r = export_with(&cx, progress, t0);
let mut r = export_with(&cx, progress, t0).await;
let log = cx.write_log(&r, t0.elapsed().as_secs_f64());
if let Ok(rep) = &mut r {
rep.log = log;
@@ -170,19 +177,19 @@ pub fn export(job: &Job, progress: &mut dyn FnMut(&Progress) -> bool) -> Result<
r
}
fn export_with(cx: &Cx, progress: &mut dyn FnMut(&Progress) -> bool, t0: Instant) -> Result<Report> {
async fn export_with(cx: &Cx<'_>, progress: &mut dyn FnMut(&Progress) -> bool, t0: Instant) -> Result<Report> {
let comp = cx.comp().ok_or(ExportError::NoComp)?;
let total = cx.settings.frame_count(comp);
let mut st = State { t0, total, done: 0, progress };
st.advance(0)?;
let (w, h) = output_size(comp, cx.settings, cx.output);
let mut report = match cx.output.format {
OutputFormat::H264 | OutputFormat::Hevc | OutputFormat::Av1 | OutputFormat::ProRes => encode::movie(cx, comp, w, h, &mut st)?,
OutputFormat::Gif => gif_export(cx, comp, w, h, &mut st)?,
OutputFormat::WebM => webm::webm(cx, comp, w, h, &mut st)?,
OutputFormat::H264 | OutputFormat::Hevc | OutputFormat::Av1 | OutputFormat::ProRes => encode::movie(cx, comp, w, h, &mut st).await?,
OutputFormat::Gif => gif_export(cx, comp, w, h, &mut st).await?,
OutputFormat::WebM => webm::webm(cx, comp, w, h, &mut st).await?,
OutputFormat::Wav => webm::audio_file(cx, comp, false, &mut st)?,
OutputFormat::Aiff => webm::audio_file(cx, comp, true, &mut st)?,
f if f.is_sequence() => sequence(cx, comp, w, h, &mut st)?,
f if f.is_sequence() => sequence(cx, comp, w, h, &mut st).await?,
f => return Err(ExportError::Unsupported(f.label().into())),
};
report.seconds = t0.elapsed().as_secs_f64();
@@ -233,7 +240,7 @@ fn first_frame_number(job: &Job, comp: &Comp) -> i64 {
job.settings.first_frame(comp)
}
fn sequence(cx: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
async fn sequence(cx: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) -> Result<Report> {
let f0 = first_frame_number(cx, comp);
let fmt = cx.output.format;
let channels = match cx.output.channels {
@@ -245,14 +252,10 @@ fn sequence(cx: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Repo
let mut i = 0;
while i < st.total {
let end = (i + batch).min(st.total);
let written: Vec<Result<u64>> = (i..end)
.into_par_iter()
.map(|k| {
let ks: Vec<u64> = (i..end).filter(|k| !(cx.settings.skip_existing && out::exists(cx.sink, &sequence_path(cx.path, f0 + *k as i64)))).collect();
let written: Vec<Result<u64>> = cx
.frames(comp, ks, |k, img| {
let path = sequence_path(cx.path, f0 + k as i64);
if cx.settings.skip_existing && out::exists(cx.sink, &path) {
return Ok(0);
}
let img = cx.frame(comp, k);
// Encode in memory first: the storage hook decides where it fits.
let mut buf = std::io::Cursor::new(Vec::new());
write_still(cx, &mut buf, fmt, &img, comp, channels, w, h, cx.output.quality)?;
@@ -262,7 +265,7 @@ fn sequence(cx: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Repo
std::io::Write::write_all(&mut f, &data).map_err(io)?;
f.finish()
})
.collect();
.await;
for r in written {
bytes += r?;
}
@@ -340,7 +343,7 @@ fn write_still<W: std::io::Write + std::io::Seek>(
}
}
fn gif_export(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) -> Result<Report> {
if w > u16::MAX as u32 || h > u16::MAX as u32 {
return Err(ExportError::Unsupported("GIF frames are limited to 65535 px".into()));
}
@@ -357,14 +360,12 @@ fn gif_export(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<R
let mut i = 0;
while i < st.total {
let end = (i + batch).min(st.total);
let frames: Vec<gif::Frame<'static>> = (i..end)
.into_par_iter()
.map(|k| {
let img = job.frame(comp, k);
let frames: Vec<gif::Frame<'static>> = job
.frames(comp, (i..end).collect(), |_, img| {
let mut px = job.pixels(&img, comp, job.output.channels, w, h);
gif::Frame::from_rgba_speed(w as u16, h as u16, &mut px, 10)
})
.collect();
.await;
for mut f in frames {
clock += cs_per_frame;
let d = (clock.round() as u64).saturating_sub(emitted).max(1);
+31 -5
View File
@@ -75,7 +75,7 @@ impl<'a> Cx<'a> {
self.project.comp(self.job.comp)
}
fn render_at(&self, t: Tick) -> Image {
async fn render_at(&self, t: Tick) -> Image {
let s = self.job.settings;
let opts = RenderOpts {
scale: s.resolution.clamp(0.01, 4.0),
@@ -93,17 +93,43 @@ impl<'a> Cx<'a> {
let mut r = Renderer::new(&self.project, self.job.footage, opts);
r.expr = self.job.expr;
r.accel = self.job.accel;
r.comp_frame(self.job.comp, t)
// With deferred GPU readbacks (a browser worker) the frame renders in passes.
effectcraft_render::passes::comp_frame(&r, self.job.comp, t).await
}
/// Whether frames render in passes (an accelerator with deferred readbacks).
pub fn deferred(&self) -> bool {
effectcraft_render::passes::is_deferred(self.job.accel)
}
/// Output frames `ks`, each mapped by `f` (encoding): rendered in parallel batches, or one
/// by one in passes when readbacks are deferred ([`Cx::deferred`]).
pub async fn frames<T: Send>(&self, comp: &Comp, ks: Vec<u64>, f: impl Fn(u64, Image) -> T + Sync + Send) -> Vec<T> {
if self.deferred() {
let mut out = Vec::with_capacity(ks.len());
for k in ks {
let img = self.frame_async(comp, k).await;
out.push(f(k, img));
}
return out;
}
use rayon::prelude::*;
ks.into_par_iter().map(|k| f(k, self.frame(comp, k))).collect()
}
/// Output frame `i`: sampled (fields, pulldown), at the colour depth, cropped and resized.
pub fn frame(&self, comp: &Comp, i: u64) -> Image {
effectcraft_render::passes::block_on(self.frame_async(comp, i))
}
/// [`Cx::frame`] as a future (deferred readbacks: the frame renders in passes).
pub async fn frame_async(&self, comp: &Comp, i: u64) -> Image {
let t0 = Instant::now();
let img = match self.job.settings.sample(comp, i) {
FrameSample::Progressive(t) => self.render_at(t),
FrameSample::Progressive(t) => self.render_at(t).await,
FrameSample::Fields { first, second, upper_first } => {
let a = self.render_at(first);
if second == first { a } else { interleave(&a, &self.render_at(second), upper_first) }
let a = self.render_at(first).await;
if second == first { a } else { interleave(&a, &self.render_at(second).await, upper_first) }
}
};
let mut img = img;
+3 -4
View File
@@ -17,7 +17,6 @@ use std::io::{Seek, SeekFrom, Write};
use effectcraft_project::Comp;
use effectcraft_project::render_queue::{AudioFormat, Channels};
use effectcraft_time::{TICKS_PER_SECOND, Tick};
use rayon::prelude::*;
use crate::encode::{mix, pcm_bytes};
use crate::{Cx, Report, Result, State, batch_size, io, wants_audio};
@@ -134,9 +133,9 @@ pub(crate) fn opus_encoder(job: &Cx) -> effectcraft_opusenc::OpusEncoder {
effectcraft_opusenc::OpusEncoder::with_application(channels, job.output.opus_bitrate_kbps.clamp(6, 510) * 1000, app)
}
pub(crate) fn webm(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) -> Result<Report> {
if job.output.webm_codec == effectcraft_project::render_queue::WebmVideoCodec::Av1 {
return crate::webm_av1::webm_av1(job, comp, w, h, st);
return crate::webm_av1::webm_av1(job, comp, w, h, st).await;
}
let rate = job.settings.rate(comp);
let alpha = job.output.channels == Channels::Rgba;
@@ -260,7 +259,7 @@ pub(crate) fn webm(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Res
// Frames render in parallel; the VP9 streams (inter-coded) encode in order, colour and
// alpha side by side.
let pixels: Vec<Vec<u8>> =
(i..end).into_par_iter().map(|k| job.pixels(&job.frame(comp, k), comp, if alpha { Channels::Rgba } else { colour_channels }, w, h)).collect();
job.frames(comp, (i..end).collect(), |_, img| job.pixels(&img, comp, if alpha { Channels::Rgba } else { colour_channels }, w, h)).await;
let mut frames: Vec<Frame> = Vec::with_capacity(pixels.len());
for (j, px) in pixels.iter().enumerate() {
let (color, a) = rayon::join(
+2 -3
View File
@@ -9,7 +9,6 @@ use std::io::{Seek, SeekFrom, Write};
use effectcraft_project::Comp;
use effectcraft_project::render_queue::Channels;
use effectcraft_time::{TICKS_PER_SECOND, Tick};
use rayon::prelude::*;
use crate::encode::VideoEncoder;
use crate::encode::mix;
@@ -41,7 +40,7 @@ fn cluster(blocks: &mut [Block]) -> Vec<u8> {
out
}
pub(crate) fn webm_av1(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) -> Result<Report> {
let rate = job.settings.rate(comp);
let mut venc = crate::hevc_av1::Av1::new(w, h, rate, job.output)?;
let with_audio = wants_audio(job);
@@ -149,7 +148,7 @@ pub(crate) fn webm_av1(job: &Cx, comp: &Comp, w: u32, h: u32, st: &mut State) ->
let end = (i + batch).min(total);
// RGB, or the alpha matte alone (Channels: Alpha); AV1 in WebM carries no alpha track.
let channels = if job.output.channels == Channels::Alpha { Channels::Alpha } else { Channels::Rgb };
let frames: Vec<Vec<u8>> = (i..end).into_par_iter().map(|k| job.pixels(&job.frame(comp, k), comp, channels, w, h)).collect();
let frames: Vec<Vec<u8>> = job.frames(comp, (i..end).collect(), |_, img| job.pixels(&img, comp, channels, w, h)).await;
for (j, px) in frames.iter().enumerate() {
let k = i + j as u64;
for p in venc.encode(px, k)? {
+144 -5
View File
@@ -324,14 +324,44 @@ fn raster_into(e: &mut Enc, s: &Scene) -> Option<(wgpu::Texture, wgpu::Texture)>
/// Rasterise a scene and read it back ([`effectcraft_render::Accelerator::raster_3d`]). `None`
/// when the device can't (no readback, size or buffer limits).
///
/// With deferred readbacks (a browser worker) both targets are read back under the scene's key
/// ([`crate::deferred`]): the first pass starts them and gets an empty target (the pass misses).
pub(crate) fn render(g: &GpuContext, s: &Scene) -> Option<Target> {
if !g.can_wait() {
if !g.can_readback() {
return None;
}
let mut e = Enc::new(g);
let (color, zout) = raster_into(&mut e, s)?;
let cb = e.read_texture(&color, s.width, s.height, 8)?;
let zb = e.read_texture(&zout, s.width, s.height, 4)?;
let (cb, zb) = match g.deferred.clone() {
Some(d) => {
use crate::deferred::Lookup::*;
let mut k = crate::deferred::Key::new(4);
key_scene(&mut k, s);
let kc = k.finish();
let kz = kc ^ 1;
match (d.lookup(kc), d.lookup(kz)) {
(Ready(c), Ready(z)) => (c?.bytes, z?.bytes),
(Absent, Absent) => {
let (color, zout) = raster_into(&mut e, s)?;
e.read_texture_async(&color, s.width, s.height, 8, d.start(kc, s.width, s.height, [0.0; 2], 1.0));
e.read_texture_async(&zout, s.width, s.height, 4, d.start(kz, s.width, s.height, [0.0; 2], 1.0));
d.miss();
return Some(empty_target(s.width, s.height));
}
_ => {
d.miss();
return Some(empty_target(s.width, s.height));
}
}
}
None => {
let (color, zout) = raster_into(&mut e, s)?;
(e.read_texture(&color, s.width, s.height, 8)?, e.read_texture(&zout, s.width, s.height, 4)?)
}
};
if cb.len() != (s.width * s.height * 8) as usize || zb.len() != (s.width * s.height * 4) as usize {
return None;
}
let color = cb.chunks_exact(8).map(|c| [0, 1, 2, 3].map(|k| half_to_f32(u16::from_le_bytes([c[2 * k], c[2 * k + 1]])))).collect();
let depth = zb
.chunks_exact(4)
@@ -343,6 +373,34 @@ pub(crate) fn render(g: &GpuContext, s: &Scene) -> Option<Target> {
Some(Target { width: s.width, height: s.height, color, depth })
}
/// A placeholder target (a pass whose readbacks are in flight).
fn empty_target(w: u32, h: u32) -> Target {
let n = (w * h) as usize;
Target { width: w, height: h, color: vec![[0.0; 4]; n], depth: vec![f32::INFINITY; n] }
}
/// Everything that determines a scene's pixels, for deferred readback keys: the packed
/// buffers, the geometry, the target size.
fn key_scene(k: &mut crate::deferred::Key, s: &Scene) {
k.u64(s.width as u64);
k.u64(s.height as u64);
k.u64(s.ssaa as u64);
k.u64(s.opaque_count as u64);
for b in pack(s) {
k.u64(b.len() as u64);
k.bytes(&b);
}
let mut v = Vec::with_capacity(s.vertices.len() * VERTEX_SIZE as usize);
for x in &s.vertices {
for f in x.pos.iter().chain(&x.normal).chain(&x.uv).chain(&x.tangent) {
v.extend_from_slice(&f.to_le_bytes());
}
v.extend_from_slice(&x.material.to_le_bytes());
}
k.bytes(&v);
k.bytes(&s.indices.iter().flat_map(|i| i.to_le_bytes()).collect::<Vec<u8>>());
}
// ---------------------------------------------------------------- after the rasteriser
/// Compute kernels of `adv3d.wgsl` (resolve, motion-blur accumulation, depth of field,
@@ -673,9 +731,12 @@ pub(crate) fn finish(e: &mut Enc, r: &Resolved, encode: bool, canvas: Option<&Gp
/// [`effectcraft_render::Accelerator::render_3d`]: the whole prepared run on the GPU, read
/// back.
pub(crate) fn render_prepared(g: &GpuContext, prep: &Prepared) -> Option<Rendered> {
if !g.can_wait() {
if !g.can_readback() {
return None;
}
if let Some(d) = g.deferred.clone() {
return render_prepared_deferred(g, &d, prep);
}
let mut e = Enc::new(g);
let Some(r) = resolve_run(&mut e, prep)? else { return Some(None) };
let img = finish(&mut e, &r, !prep.linear, None);
@@ -692,6 +753,84 @@ pub(crate) fn render_prepared(g: &GpuContext, prep: &Prepared) -> Option<Rendere
Some(Some((img, depth)))
}
/// [`render_prepared`] with deferred readbacks: the image and the depth are read back under the
/// run's key (every sub-sample's scene, the output size and encoding). A depth of field needs a
/// readback in the middle of the run: such runs go to the CPU path (whose scenes still
/// rasterise here, [`render`]).
fn render_prepared_deferred(g: &GpuContext, d: &std::sync::Arc<crate::deferred::Deferred>, prep: &Prepared) -> Option<Rendered> {
use crate::deferred::Lookup::*;
if prep.dof.is_some() {
return None;
}
let (w, h) = prep.out;
let mut k = crate::deferred::Key::new(5);
k.u64(w as u64);
k.u64(h as u64);
k.u64(prep.samples as u64);
k.f64(prep.scale);
k.u64(prep.linear as u64);
let mut any = false;
for i in 0..prep.samples.max(1) {
let s = prep.scene(i);
any |= !s.indices.is_empty();
key_scene(&mut k, &s);
}
if !any {
return Some(None);
}
let ki = k.finish();
let kz = ki ^ 1;
match (d.lookup(ki), d.lookup(kz)) {
(Ready(a), Ready(b)) => {
let (a, b) = (a?, b?);
let mut img = effectcraft_render::Image::new(a.width, a.height);
let dst: &mut [u8] = bytemuck::cast_slice_mut(&mut img.data);
if dst.len() != a.bytes.len() || b.bytes.len() != dst.len() / 4 {
return None;
}
dst.copy_from_slice(&a.bytes);
let depth = b
.bytes
.chunks_exact(4)
.map(|c| {
let z = f32::from_le_bytes([c[0], c[1], c[2], c[3]]);
if z >= BIG * 0.5 { f32::INFINITY } else { z }
})
.collect();
return Some(Some((img, depth)));
}
(Absent, Absent) => {}
_ => {
d.miss();
return Some(None);
}
}
let mut e = Enc::new(g);
let Some(r) = resolve_run(&mut e, prep)? else { return Some(None) };
let img = finish(&mut e, &r, !prep.linear, None);
let _ = e.read_keyed(&img, ki, [0.0; 2], 1.0);
let size = w as u64 * h as u64 * 4;
let rb = g.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("adv3d depth readback"),
size,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
e.encoder().copy_buffer_to_buffer(&r.depth, 0, &rb, 0, size);
e.submit();
let done = d.start(kz, w, h, [0.0; 2], 1.0);
let b = rb.clone();
rb.map_async(wgpu::MapMode::Read, .., move |res| {
let out = res.ok().and_then(|_| b.get_mapped_range(..).ok().map(|v| v.to_vec()));
b.unmap();
done(out);
});
#[cfg(not(target_arch = "wasm32"))]
let _ = g.device.poll(wgpu::PollType::Poll);
d.miss();
Some(None)
}
/// Draw a prepared run over the GPU canvas (the compositor's walk; no readback unless the
/// depth of field needs its radius range). `None` = render it on the CPU.
pub(crate) fn draw_run(e: &mut Enc, prep: &Prepared, canvas: &GpuImage) -> Option<GpuImage> {
+13 -1
View File
@@ -269,7 +269,7 @@ impl Accelerator for Gpu {
}
fn particles(&self) -> Option<&dyn effectcraft_effects::psim::ParticleSim> {
self.ctx.can_wait().then_some(self as &dyn effectcraft_effects::psim::ParticleSim)
self.ctx.can_readback().then_some(self as &dyn effectcraft_effects::psim::ParticleSim)
}
fn auto_pick(&self) -> Option<&effectcraft_render::AutoPick> {
@@ -295,6 +295,16 @@ impl Accelerator for Gpu {
fn miss_gate(&self) -> Option<Arc<std::sync::atomic::AtomicBool>> {
self.ctx.deferred().map(|d| d.gate())
}
fn settle(&self) -> Option<std::pin::Pin<Box<dyn std::future::Future<Output = ()> + '_>>> {
let d = self.ctx.deferred()?.clone();
// Natively the device delivers the readbacks when polled: wait for them here.
#[cfg(not(target_arch = "wasm32"))]
if d.in_flight() > 0 {
let _ = self.ctx.device.poll(wgpu::PollType::wait_indefinitely());
}
Some(Box::pin(async move { d.settled().await }))
}
}
impl effectcraft_effects::psim::ParticleSim for Gpu {
@@ -314,6 +324,8 @@ mod tests_adv3d;
#[cfg(test)]
mod tests_deferred;
#[cfg(test)]
mod tests_deferred_jobs;
#[cfg(test)]
mod tests_fx_color;
#[cfg(test)]
mod tests_fx_depth;
+56 -7
View File
@@ -108,14 +108,30 @@ fn uniforms(req: &SimRequest, n: u32, s0: u64, prev_n: u32) -> Vec<u8> {
}
/// Simulate `req` (see [`effectcraft_effects::psim::ParticleSim`]).
///
/// With deferred readbacks (a browser worker) the state's readback is keyed by the request
/// ([`crate::deferred`]): the first pass starts it and gets no particles (the pass misses and is
/// rendered again), later passes read the bytes.
pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimParticle>> {
if !g.can_wait() || req.steps > u32::MAX as u64 {
if !g.can_readback() || req.steps > u32::MAX as u64 {
return None;
}
let n = req.births.len() as u32;
if n == 0 {
return Some(vec![]);
}
let deferred = g.deferred.clone();
let key = deferred.as_ref().map(|_| sim_key(req));
if let (Some(d), Some(k)) = (&deferred, key) {
match d.lookup(k) {
crate::deferred::Lookup::Ready(r) => return r.map(|r| parse(&r.bytes)),
crate::deferred::Lookup::InFlight => {
d.miss();
return Some(vec![]);
}
crate::deferred::Lookup::Absent => {}
}
}
let size = n as u64 * STATE_BYTES;
if size > g.device.limits().max_storage_buffer_binding_size {
return None;
@@ -176,6 +192,20 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimPartic
}
enc.copy_buffer_to_buffer(&next, 0, &read, 0, size);
g.queue.submit([enc.finish()]);
if let (Some(d), Some(k)) = (&deferred, key) {
let done = d.start(k, n, 1, [0.0; 2], 1.0);
let b = read.clone();
read.map_async(wgpu::MapMode::Read, .., move |r| {
let out = r.ok().and_then(|_| b.get_mapped_range(..).ok().map(|v| v.to_vec()));
b.unmap();
done(out);
});
#[cfg(not(target_arch = "wasm32"))]
let _ = g.device.poll(wgpu::PollType::Poll);
keep_checkpoint(g, req, n, next);
d.miss();
return Some(vec![]);
}
let (tx, rx) = std::sync::mpsc::channel();
read.map_async(wgpu::MapMode::Read, .., move |r| {
let _ = tx.send(r);
@@ -183,16 +213,36 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimPartic
g.device.poll(wgpu::PollType::wait_indefinitely()).ok()?;
rx.recv().ok()?.ok()?;
let view = read.get_mapped_range(..).ok()?;
let f: Vec<f32> = view.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
let parts = parse(&view);
drop(view);
read.unmap();
let parts = f
.chunks_exact(12)
keep_checkpoint(g, req, n, next);
Some(parts)
}
/// The deferred readback key of a request: everything that determines the state.
fn sim_key(req: &SimRequest) -> u128 {
let mut k = crate::deferred::Key::new(3);
k.u64(req.key);
k.u64(req.steps);
k.u64(req.births.len() as u64);
k.bytes(&req.births.iter().flat_map(|b| b.to_le_bytes()).collect::<Vec<u8>>());
k.debug(&req.system);
k.finish()
}
/// Live particles of a state buffer's bytes.
fn parse(bytes: &[u8]) -> Vec<SimParticle> {
let f: Vec<f32> = bytes.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
f.chunks_exact(12)
.enumerate()
.filter(|(_, s)| s[9] != 0.0)
.map(|(id, s)| SimParticle { p: [s[0], s[1], s[2]], v: [s[4], s[5], s[6]], age: s[3], life: s[7], rnd: s[8], id: id as u32 })
.collect();
// Keep the new state as a checkpoint.
.collect()
}
/// Keep a simulated state on the GPU as a checkpoint (the oldest go beyond the limit).
fn keep_checkpoint(g: &GpuContext, req: &SimRequest, n: u32, next: wgpu::Buffer) {
if let Ok(mut c) = g.particle_states.lock() {
let now = c.clock;
c.list.retain(|k| !(k.key == req.key && k.steps == req.steps));
@@ -202,7 +252,6 @@ pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimPartic
c.list.remove(i);
}
}
Some(parts)
}
pub(crate) type PipesCell = OnceLock<Pipes>;
+5 -5
View File
@@ -35,7 +35,7 @@ fn set(l: &mut effectcraft_project::Layer, path: &str, v: Value) {
/// Primitives with metal/dielectric materials, a shadow-casting spot light and a point light,
/// an environment light, a semi-transparent textured card.
fn scene_project() -> (Project, ItemId) {
pub(crate) fn scene_project() -> (Project, ItemId) {
let mut p = Project::default();
let mut c = Comp::new(240, 160, FrameRate::FPS_30, Tick::from_seconds_f64(1.0));
c.renderer = R3::Advanced3D;
@@ -90,7 +90,7 @@ fn scene_project() -> (Project, ItemId) {
(p, cid)
}
fn scene(p: &Project, cid: ItemId) -> Scene {
pub(crate) fn scene(p: &Project, cid: ItemId) -> Scene {
let r = Renderer::new(p, &NoFootage, RenderOpts::default());
let ctx = EvalCtx { project: p, comp_id: cid, comp: p.comp(cid).unwrap(), time: Tick::ZERO, expr: None, footage: None };
let run: Vec<&effectcraft_project::Layer> = ctx.comp.layers.iter().rev().filter(|l| l.is_3d() && l.has_video()).collect();
@@ -177,7 +177,7 @@ fn gpu_raster_perf_smoke() {
/// The lit scene seen through a depth-of-field camera (hexagonal iris, diffraction fringe,
/// highlight boost) with the sphere moving under motion blur.
fn dof_mb_project() -> (Project, ItemId) {
pub(crate) fn dof_mb_project() -> (Project, ItemId) {
let (mut p, cid) = scene_project();
add(&mut p, cid, LayerSource::Camera, |l| {
let zoom = match l.props.prop_mut("cameraOptions/zoom").unwrap().value {
@@ -208,7 +208,7 @@ fn dof_mb_project() -> (Project, ItemId) {
/// Share of pixels (0–1) differing by more than 1/255 on any channel, and the largest
/// difference.
fn off_share(a: &[[f32; 4]], b: &[[f32; 4]]) -> (f64, f32) {
pub(crate) fn off_share(a: &[[f32; 4]], b: &[[f32; 4]]) -> (f64, f32) {
let mut off = 0;
let mut max = 0.0f32;
for (p, q) in a.iter().zip(b) {
@@ -222,7 +222,7 @@ fn off_share(a: &[[f32; 4]], b: &[[f32; 4]]) -> (f64, f32) {
(off as f64 / a.len().max(1) as f64, max)
}
fn run_of(p: &Project, cid: ItemId) -> (EvalCtx<'_>, Vec<&effectcraft_project::Layer>) {
pub(crate) fn run_of(p: &Project, cid: ItemId) -> (EvalCtx<'_>, Vec<&effectcraft_project::Layer>) {
let ctx = EvalCtx { project: p, comp_id: cid, comp: p.comp(cid).unwrap(), time: Tick::ZERO, expr: None, footage: None };
let run: Vec<&effectcraft_project::Layer> = ctx.comp.layers.iter().rev().filter(|l| l.is_3d() && l.has_video()).collect();
(ctx, run)
+3 -3
View File
@@ -16,7 +16,7 @@ use crate::tests::{Pattern, Scene, diff, n, set, tolerance, v3};
/// The device, held exclusively: deferred state is per device and a frame renders at a time
/// (a frame worker renders one frame at a time too).
fn deferred_gpu() -> Option<(&'static Gpu, std::sync::MutexGuard<'static, ()>)> {
pub(crate) fn deferred_gpu() -> Option<(&'static Gpu, std::sync::MutexGuard<'static, ()>)> {
static G: OnceLock<Option<Gpu>> = OnceLock::new();
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
let g = G.get_or_init(|| pollster::block_on(Gpu::request_deferred()).map_err(|e| eprintln!("deferred gpu tests skipped: {e}")).ok()).as_ref()?;
@@ -25,7 +25,7 @@ fn deferred_gpu() -> Option<(&'static Gpu, std::sync::MutexGuard<'static, ()>)>
/// Footage with GPU effects around a CPU-only one, a solid with Glow, and a precomp whose
/// layer is blurred inside and outside (a chain whose input is another chain's result).
fn scene() -> Scene {
pub(crate) fn scene() -> Scene {
let cpu_only = "ec.blur.ccradial";
assert!(!effectcraft_effects::GPU_EFFECTS.contains(&cpu_only));
let mut s = Scene::new(BitDepth::Bpc32);
@@ -56,7 +56,7 @@ fn scene() -> Scene {
}
/// Render in passes with deferred readbacks; returns the frame and the number of passes.
fn render_passes(g: &Gpu, s: &Scene, opts: RenderOpts, cache: &LayerCache, t: Tick) -> (effectcraft_raster::Image, usize) {
pub(crate) fn render_passes(g: &Gpu, s: &Scene, opts: RenderOpts, cache: &LayerCache, t: Tick) -> (effectcraft_raster::Image, usize) {
cache.set_gate(g.miss_gate());
let mut r = Renderer::new(&s.p, &Pattern, opts);
r.accel = Some(g);
+109
View File
@@ -0,0 +1,109 @@
//! Deferred readbacks for what job workers and frame workers render besides effect chains:
//! GPU particles and Advanced 3D read back under keys too, so they render on the device in
//! passes; and the job loops' pass driver (`effectcraft_render::passes`) settles natively.
use effectcraft_effects::EffectCtx;
use effectcraft_project::BitDepth;
use effectcraft_render::three_d::adv;
use effectcraft_render::{Accelerator, Backend, LayerCache, NoFootage, RenderOpts, Renderer};
use effectcraft_time::Tick;
use crate::tests::{Pattern, diff, n, tolerance};
use crate::tests_adv3d::{off_share, run_of, scene, scene_project};
use crate::tests_deferred::{deferred_gpu, render_passes};
use crate::tests_particles::{Host, agree, params};
/// The device's readbacks have landed (the browser's event loop; natively a poll).
fn settle(g: &crate::Gpu) {
g.wait();
pollster::block_on(g.settled());
}
#[test]
fn particles_resolve_in_passes() {
let Some((g, _lock)) = deferred_gpu() else { return };
let host = Host(g);
for (id, vals) in [
("ec.sim.ccparticleworld", vec![("birthRate", n(2.0)), ("longevity", n(1.2)), ("extras/randomSeed", n(7.0))]),
("ec.sim.particleplayground", vec![("grid/particlesAcross", n(0.0)), ("cannon/particlesPerSecond", n(90.0))]),
] {
let p = params(id, &vals);
let ctx = |env| EffectCtx { params: &p, time: 1.5, layer_size: [320.0, 240.0], seed: 5, adjustment: false, env };
let run = |c: &EffectCtx| {
if id == "ec.sim.particleplayground" { effectcraft_effects::playground_state(c) } else { effectcraft_effects::particle_state(id, c) }
};
let cpu = run(&ctx(Default::default())).unwrap();
let env = || effectcraft_effects::EffectEnv { host: Some(&host), ..Default::default() };
g.frame_begin();
g.pass_begin();
// First pass: the simulation runs, its readback starts; no particles yet, the pass missed.
let first = run(&ctx(env())).unwrap();
assert!(first.is_empty() && g.pass_missed(), "{id}");
settle(g);
g.pass_begin();
let gpu = run(&ctx(env())).unwrap();
assert!(!g.pass_missed(), "{id}: served from the readback");
agree(&format!("deferred {id}"), &cpu, &gpu, 0.01, cpu.len() / 100 + 1);
}
}
#[test]
fn advanced_3d_resolves_in_passes() {
let Some((g, _lock)) = deferred_gpu() else { return };
let (p, cid) = scene_project();
// One scene rasterised (the CPU compositor's per-scene path).
let s = scene(&p, cid);
let cpu = adv::raster::render(&s);
g.frame_begin();
g.pass_begin();
let t = g.raster_3d(&s).expect("handled");
assert!(g.pass_missed() && t.color.iter().all(|c| c[3] == 0.0), "a placeholder first");
settle(g);
g.pass_begin();
let t = g.raster_3d(&s).expect("handled");
assert!(!g.pass_missed());
let (share, _) = off_share(&cpu.color, &t.color);
assert!(share < 0.015, "raster: {:.3} % of pixels differ", share * 100.0);
// A whole prepared run (resolve, encoding) read back under its key.
let (ctx, run) = run_of(&p, cid);
let out = (ctx.comp.width, ctx.comp.height);
let r = Renderer::new(&p, &NoFootage, RenderOpts::default());
let prep = adv::Prepared::new(&r, &ctx, &run, out);
let (cimg, _) = adv::render_prepared(&prep).expect("cpu drew");
g.frame_begin();
g.pass_begin();
assert!(matches!(g.render_3d(&prep), Some(None)) && g.pass_missed(), "nothing drawn yet: a placeholder");
settle(g);
g.pass_begin();
let (gimg, depth) = g.render_3d(&prep).expect("handled").expect("drawn");
assert!(!g.pass_missed());
assert_eq!(depth.len(), (out.0 * out.1) as usize);
let (share, _) = off_share(&cimg.data, &gimg.data);
assert!(share <= 0.01, "run: {:.3} % of pixels differ", share * 100.0);
}
/// The job loops' driver: `passes::comp_frame` awaits the device between passes (natively
/// `Accelerator::settle` polls it) and gives the frame `render_passes` gives.
#[test]
fn job_frames_render_in_passes() {
let Some((g, _lock)) = deferred_gpu() else { return };
let s = crate::tests_deferred::scene();
let t = Tick::from_seconds_f64(0.5);
let cache = LayerCache::default();
cache.set_gate(g.miss_gate());
let opts = RenderOpts { backend: Backend::Gpu, ..Default::default() };
let (want, _) = render_passes(g, &s, opts, &LayerCache::default(), t);
let mut r = Renderer::new(&s.p, &Pattern, opts);
r.accel = Some(g);
r.cache = Some(&cache);
let before = g.deferred_stats().unwrap();
let img = effectcraft_render::passes::block_on(effectcraft_render::passes::comp_frame(&r, s.cid, t));
let after = g.deferred_stats().unwrap();
assert!(after.0 - before.0 >= 2 && after.1 > before.1, "rendered in passes with readbacks: {before:?} → {after:?}");
assert_eq!(img.data, want.data);
let cpu = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Cpu, ..Default::default() }).comp_frame_cpu(s.cid, t);
assert_eq!(diff(&cpu, &img, tolerance(BitDepth::Bpc32) * 2.0).over, 0);
// `in_passes` without a deferred accelerator: one pass, at once.
let one = effectcraft_render::passes::block_on(effectcraft_render::passes::in_passes(None, |_| 7));
assert_eq!((one.value, one.passes, one.accelerated), (7, 1, false));
}
+3 -3
View File
@@ -10,7 +10,7 @@ use effectcraft_keyframe::Value;
use crate::Gpu;
use crate::tests::{gpu, n};
struct Host(&'static Gpu);
pub(crate) struct Host(pub(crate) &'static Gpu);
impl EffectHost for Host {
fn layer(&self, _id: u64, _masks_and_effects: bool) -> Option<LayerPixels> {
@@ -24,7 +24,7 @@ impl EffectHost for Host {
}
}
fn params(id: &str, vals: &[(&str, Value)]) -> Params {
pub(crate) fn params(id: &str, vals: &[(&str, Value)]) -> Params {
let spec = effectcraft_effects::find(id).unwrap();
let size = [320.0, 240.0];
let mut p = Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, size))).collect() };
@@ -47,7 +47,7 @@ fn states(id: &str, p: &Params, t: f64, host: &Host) -> (Vec<SimParticle>, Vec<S
/// Same ids alive (up to `id_slack` particles dying a step apart), positions within `tol`
/// (world units) for 99 % of them and on average within `tol / 10`.
fn agree(label: &str, cpu: &[SimParticle], gpu: &[SimParticle], tol: f32, id_slack: usize) {
pub(crate) fn agree(label: &str, cpu: &[SimParticle], gpu: &[SimParticle], tol: f32, id_slack: usize) {
assert!(cpu.len() > 20, "{label}: the scene has particles ({})", cpu.len());
let gi: std::collections::HashMap<u32, &SimParticle> = gpu.iter().map(|q| (q.id, q)).collect();
let mut missing = 0;
+43 -33
View File
@@ -30,39 +30,49 @@ impl Exporter for FileExporter {
effectcraft_export::available_formats()
}
fn export(&self, job: &ExportJob, progress: &mut dyn FnMut(u64, u64) -> bool) -> Result<ExportResult, String> {
let j = effectcraft_export::Job {
project: job.project,
footage: job.footage,
expr: job.expr,
accel: job.accel,
comp: job.item.comp,
settings: &job.item.settings,
output: &job.item.output,
path: job.path,
sink: self.sink.as_deref(),
options: effectcraft_export::JobOptions {
log: job.item.log,
label: job.label.clone(),
storage: job.storage,
overflow: job.project.render_prefs.overflow_folders.clone(),
},
nested_switches: job.nested_switches,
};
match effectcraft_export::export(&j, &mut |p| progress(p.done, p.total)) {
Ok(r) => Ok(ExportResult {
path: r.path,
frames: r.frames,
width: r.width,
height: r.height,
bytes: r.bytes,
seconds: r.seconds,
audio: r.audio,
log: r.log,
overflow: r.overflow,
}),
Err(effectcraft_export::ExportError::Cancelled) => Err(effectcraft_engine::render_queue::CANCELLED.into()),
Err(e) => Err(e.to_string()),
}
effectcraft_engine::render::passes::block_on(self.export_async(job, progress))
}
fn export_async<'a>(
&'a self,
job: &'a ExportJob<'a>,
progress: &'a mut dyn FnMut(u64, u64) -> bool,
) -> effectcraft_engine::render_queue::LocalFuture<'a, Result<ExportResult, String>> {
Box::pin(async move {
let j = effectcraft_export::Job {
project: job.project,
footage: job.footage,
expr: job.expr,
accel: job.accel,
comp: job.item.comp,
settings: &job.item.settings,
output: &job.item.output,
path: job.path,
sink: self.sink.as_deref(),
options: effectcraft_export::JobOptions {
log: job.item.log,
label: job.label.clone(),
storage: job.storage,
overflow: job.project.render_prefs.overflow_folders.clone(),
},
nested_switches: job.nested_switches,
};
match effectcraft_export::export_async(&j, &mut |p| progress(p.done, p.total)).await {
Ok(r) => Ok(ExportResult {
path: r.path,
frames: r.frames,
width: r.width,
height: r.height,
bytes: r.bytes,
seconds: r.seconds,
audio: r.audio,
log: r.log,
overflow: r.overflow,
}),
Err(effectcraft_export::ExportError::Cancelled) => Err(effectcraft_engine::render_queue::CANCELLED.into()),
Err(e) => Err(e.to_string()),
}
})
}
}
+172 -5
View File
@@ -32,6 +32,8 @@ use crate::eval::EvalCtx;
pub struct LayerCache {
inner: Mutex<Inner>,
disk: Mutex<Option<(Arc<crate::disk_cache::DiskCache>, u64)>>,
/// Another persistent store when there is no disk cache (the browser's, [`PrefetchStore`]).
store: Mutex<Option<(Arc<dyn LayerStore>, u64)>>,
/// While set, inserts are dropped (see [`LayerCache::set_gate`]).
gate: Mutex<Option<Arc<std::sync::atomic::AtomicBool>>>,
}
@@ -74,6 +76,7 @@ impl LayerCache {
LayerCache {
inner: Mutex::new(Inner { map: HashMap::new(), bytes: 0, budget, clock: 0, hits: 0, misses: 0, missed_at: HashMap::new() }),
disk: Mutex::new(None),
store: Mutex::new(None),
gate: Mutex::new(None),
}
}
@@ -113,10 +116,32 @@ impl LayerCache {
self.disk.lock().ok()?.as_ref().map(|d| d.0.clone())
}
fn disk_key(&self, key: u64) -> Option<(Arc<crate::disk_cache::DiskCache>, u128)> {
let d = self.disk.lock().ok()?;
let (dc, salt) = d.as_ref()?;
Some((dc.clone(), ((*salt as u128) << 64) | key as u128))
/// Attach (or detach) a [`LayerStore`] used when no disk cache is attached (the browser's
/// Origin Private File System through a [`PrefetchStore`]); `salt` as in
/// [`LayerCache::set_disk`].
pub fn set_store(&self, store: Option<(Arc<dyn LayerStore>, u64)>) {
if let Ok(mut s) = self.store.lock() {
*s = store;
}
}
/// Change the store's salt (a new project or footage), keeping the store.
pub fn set_store_salt(&self, salt: u64) {
if let Ok(mut d) = self.store.lock()
&& let Some((_, s)) = d.as_mut()
{
*s = salt;
}
}
fn disk_key(&self, key: u64) -> Option<(Arc<dyn LayerStore>, u128)> {
let salted = |salt: u64| ((salt as u128) << 64) | key as u128;
if let Some((dc, salt)) = self.disk.lock().ok()?.as_ref() {
return Some((dc.clone() as Arc<dyn LayerStore>, salted(*salt)));
}
let s = self.store.lock().ok()?;
let (st, salt) = s.as_ref()?;
Some((st.clone(), salted(*salt)))
}
pub fn get(&self, key: u64) -> Option<Arc<Buf>> {
@@ -139,7 +164,7 @@ impl LayerCache {
drop(g);
// Disk cache: a hit comes back into memory.
let (dc, dk) = self.disk_key(key)?;
let buf = Arc::new(dc.get_layer(dk)?);
let buf = dc.get_layer(dk)?;
self.insert_mem(key, buf.clone());
Some(buf)
}
@@ -223,6 +248,148 @@ impl LayerCache {
}
}
/// Persistent storage of layer buffers behind a [`LayerCache`] (keys salted per project).
pub trait LayerStore: Send + Sync {
/// A stored buffer (synchronous: mid-render).
fn get_layer(&self, key: u128) -> Option<Arc<Buf>>;
/// Keep a buffer that was slow to render.
fn put_layer(&self, key: u128, buf: &Buf);
/// Buffers faster to render than this (ms) are not stored.
fn min_layer_ms(&self) -> u64 {
0
}
}
/// Layers buffers rendered slower than this go to the browser's disk cache (ms).
pub const PREFETCH_MIN_LAYER_MS: u64 = 20;
/// A [`LayerStore`] over storage that can't be read in the middle of a render (the browser's
/// Origin Private File System, read asynchronously). Lookups are served from buffers fetched
/// before the frame ([`PrefetchStore::provide`]); the keys a render looked up and didn't find
/// are recorded ([`PrefetchStore::take_misses`]) so the transport can fetch them before the next
/// frame; buffers to store queue up as sealed entries ([`PrefetchStore::take_writes`]) for the
/// transport to write after the frame. Fetched buffers are kept least recently used first, up
/// to a byte budget.
pub struct PrefetchStore {
st: Mutex<Prefetched>,
budget: usize,
min_ms: u64,
}
#[derive(Default)]
struct Prefetched {
ready: HashMap<u128, (Arc<Buf>, u64)>,
bytes: usize,
clock: u64,
misses: Vec<u128>,
hits: Vec<u128>,
writes: Vec<(u128, Vec<u8>)>,
/// Keys stored or queued (not written twice).
known: std::collections::HashSet<u128>,
}
impl Default for PrefetchStore {
fn default() -> Self {
PrefetchStore::new(256 << 20)
}
}
impl PrefetchStore {
pub fn new(budget: usize) -> PrefetchStore {
PrefetchStore { st: Mutex::new(Prefetched::default()), budget, min_ms: PREFETCH_MIN_LAYER_MS }
}
/// Store buffers that took at least `ms` to render (default [`PREFETCH_MIN_LAYER_MS`]).
pub fn with_min_ms(mut self, ms: u64) -> PrefetchStore {
self.min_ms = ms;
self
}
/// Whether `key`'s buffer is here.
pub fn has(&self, key: u128) -> bool {
self.st.lock().is_ok_and(|s| s.ready.contains_key(&key))
}
/// A fetched entry (sealed bytes, [`crate::disk_cache::layer_entry`]) for `key`; `false`
/// when damaged.
pub fn provide(&self, key: u128, entry: &[u8]) -> bool {
let Some(buf) = crate::disk_cache::read_layer_entry(entry) else { return false };
let bytes = buf.img.data.len() * std::mem::size_of::<effectcraft_raster::Px>();
let Ok(mut s) = self.st.lock() else { return false };
s.clock += 1;
let now = s.clock;
if let Some((old, _)) = s.ready.insert(key, (Arc::new(buf), now)) {
s.bytes -= old.img.data.len() * std::mem::size_of::<effectcraft_raster::Px>();
}
s.bytes += bytes;
s.known.insert(key);
while s.bytes > self.budget {
let Some((&k, _)) = s.ready.iter().min_by_key(|(_, (_, t))| *t) else { break };
if let Some((b, _)) = s.ready.remove(&k) {
s.bytes -= b.img.data.len() * std::mem::size_of::<effectcraft_raster::Px>();
}
}
true
}
/// Keys looked up and not found since the last call (each once).
pub fn take_misses(&self) -> Vec<u128> {
self.st.lock().map(|mut s| std::mem::take(&mut s.misses)).unwrap_or_default()
}
/// Keys served since the last call (each once).
pub fn take_hits(&self) -> Vec<u128> {
self.st.lock().map(|mut s| std::mem::take(&mut s.hits)).unwrap_or_default()
}
/// Entries to write: (key, sealed bytes).
pub fn take_writes(&self) -> Vec<(u128, Vec<u8>)> {
self.st.lock().map(|mut s| std::mem::take(&mut s.writes)).unwrap_or_default()
}
/// Forget everything (Empty Disk Cache, Purge).
pub fn clear(&self) {
if let Ok(mut s) = self.st.lock() {
*s = Prefetched::default();
}
}
}
impl LayerStore for PrefetchStore {
fn get_layer(&self, key: u128) -> Option<Arc<Buf>> {
let mut s = self.st.lock().ok()?;
s.clock += 1;
let now = s.clock;
match s.ready.get_mut(&key) {
Some((b, t)) => {
*t = now;
let b = b.clone();
if !s.hits.contains(&key) {
s.hits.push(key);
}
Some(b)
}
None => {
if !s.misses.contains(&key) && s.misses.len() < 1024 {
s.misses.push(key);
}
None
}
}
}
fn put_layer(&self, key: u128, buf: &Buf) {
let Ok(mut s) = self.st.lock() else { return };
if s.known.insert(key) {
s.writes.push((key, crate::disk_cache::layer_entry(buf)));
}
}
fn min_layer_ms(&self) -> u64 {
self.min_ms
}
}
/// FNV-1a style 64-bit hasher fed by `Debug` output (exact float formatting) and raw values.
struct KeyHasher(u64);
+55
View File
@@ -173,6 +173,38 @@ impl DiskIndex {
}
}
/// Which layer buffers a browser frame worker should fetch from the disk cache before its next
/// frame (its lookups mid-render are synchronous, the Origin Private File System is not): the
/// layer-cache misses the workers reported for recent frames, most recent first, that are on
/// disk ([`DiskIndex`], kind [`Kind::Layer`]).
#[derive(Default)]
pub struct LayerPrefetch {
recent: std::collections::VecDeque<u128>,
}
/// Misses [`LayerPrefetch`] remembers.
const PREFETCH_RECENT: usize = 512;
impl LayerPrefetch {
/// A frame's layer-cache misses (salted keys).
pub fn note_misses(&mut self, keys: impl IntoIterator<Item = u128>) {
for k in keys {
self.recent.retain(|x| *x != k);
self.recent.push_front(k);
}
self.recent.truncate(PREFETCH_RECENT);
}
/// Up to `max` keys to fetch before the next frame.
pub fn plan(&self, index: &DiskIndex, max: usize) -> Vec<u128> {
self.recent.iter().copied().filter(|k| index.contains(Kind::Layer, *k)).take(max).collect()
}
pub fn clear(&mut self) {
self.recent.clear();
}
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
enum Job {
Write(Kind, u128, Vec<u8>),
@@ -584,6 +616,29 @@ pub fn read_frame_entry(data: &[u8]) -> Option<Frame8> {
decode_frame(verify(data, Kind::Frame)?)
}
/// A sealed layer-buffer entry: what the browser's frame workers write to the Origin Private
/// File System (`layers/<32 hex>.ecc`).
pub fn layer_entry(buf: &Buf) -> Vec<u8> {
seal(Kind::Layer, &encode_layer(buf))
}
/// A layer buffer from a sealed entry's bytes (`None` when damaged).
pub fn read_layer_entry(data: &[u8]) -> Option<Buf> {
decode_layer(verify(data, Kind::Layer)?)
}
impl crate::cache::LayerStore for DiskCache {
fn get_layer(&self, key: u128) -> Option<Arc<Buf>> {
DiskCache::get_layer(self, key).map(Arc::new)
}
fn put_layer(&self, key: u128, buf: &Buf) {
DiskCache::put_layer(self, key, buf);
}
fn min_layer_ms(&self) -> u64 {
DiskCache::min_layer_ms(self)
}
}
/// An entry's file name in its kind's folder (`<32 hex>.ecc`).
pub fn entry_name(key: u128) -> String {
format!("{key:032x}.ecc")
+15 -1
View File
@@ -14,6 +14,7 @@ pub mod disk_cache;
use color::Region;
pub mod eval;
pub mod masks;
pub mod passes;
pub mod shapes;
pub mod styles;
pub mod text;
@@ -22,7 +23,7 @@ pub mod three_d;
use std::sync::Arc;
pub use auto::{AutoKey, AutoPick};
pub use cache::{CacheStats, LayerCache};
pub use cache::{CacheStats, LayerCache, LayerStore, PrefetchStore};
use effectcraft_color::BlendMode;
use effectcraft_effects::{Buf, EffectCtx, EffectEnv, EffectHost, LayerPixels, Params};
use effectcraft_geom::{Mat3, Mat4, vec2};
@@ -313,6 +314,13 @@ pub trait Accelerator: Send + Sync {
fn miss_gate(&self) -> Option<Arc<std::sync::atomic::AtomicBool>> {
None
}
/// With deferred readbacks: a future that resolves once the readbacks in flight have
/// landed (the browser delivers them from its event loop; natively the device is polled
/// before it returns, so the future is ready). `None` = nothing to wait for. See
/// [`passes::in_passes`].
fn settle(&self) -> Option<std::pin::Pin<Box<dyn std::future::Future<Output = ()> + '_>>> {
None
}
}
/// Where an effect stack runs (see [`Renderer::run_effects_on`]): a CPU buffer, or an image
@@ -631,6 +639,12 @@ impl<'a> Renderer<'a> {
EvalCtx { project: self.project, comp_id, comp, time: t, expr: self.expr, footage: Some(self.footage) }
}
/// This renderer with another accelerator (or none): the passes of
/// [`passes::in_passes`] render with the accelerator, its CPU fallback without.
pub fn with_accel(&self, accel: Option<&'a dyn Accelerator>) -> Renderer<'a> {
Renderer { accel, ..*self }
}
/// The accelerator to use for this render, if any (see [`Backend`]).
pub fn active_accel(&self) -> Option<&'a dyn Accelerator> {
let a = self.accel?;
+104
View File
@@ -0,0 +1,104 @@
//! Rendering with deferred readbacks from loops that are not frame servers (the browser's
//! job workers: Render Queue renders and analyses).
//!
//! A frame worker renders one frame per request and resumes it pass by pass
//! (`FrameServer::resume`). Jobs render many frames from a loop; written as `async` functions,
//! the loop awaits [`in_passes`] for each frame: with an accelerator whose readbacks are
//! deferred ([`Accelerator::miss_gate`]), the render runs again after every pass that missed,
//! awaiting the device in between ([`Accelerator::settle`]), until a pass completes; with any
//! other accelerator (or none) it runs once and the future is ready at once. Desktop threads
//! drive the same futures with [`block_on`].
use std::future::Future;
use std::task::{Context, Poll, Waker};
use effectcraft_project::ItemId;
use effectcraft_raster::Image;
use effectcraft_time::Tick;
use crate::{Accelerator, AutoKey, Backend, Renderer};
/// Passes before a frame gives up on deferred readbacks and renders on the CPU.
pub const MAX_PASSES: u32 = 24;
/// What [`in_passes`] returns.
#[derive(Clone, Debug)]
pub struct Passed<T> {
pub value: T,
/// Render passes (1 without deferred readbacks).
pub passes: u32,
/// Rendered with the accelerator (not the CPU fallback after [`MAX_PASSES`]).
pub accelerated: bool,
}
/// Whether `accel` defers its readbacks (renders take passes).
pub fn is_deferred(accel: Option<&dyn Accelerator>) -> bool {
accel.is_some_and(|a| a.miss_gate().is_some())
}
/// Run `render` (one render with the accelerator it is given) until a pass doesn't miss: see
/// the module docs. After [`MAX_PASSES`] it renders once without the accelerator (the CPU).
/// Caches the render writes to must hold the accelerator's miss gate
/// ([`crate::LayerCache::set_gate`]).
pub async fn in_passes<'a, T>(accel: Option<&'a dyn Accelerator>, mut render: impl FnMut(Option<&'a dyn Accelerator>) -> T) -> Passed<T> {
let Some(a) = accel.filter(|a| a.miss_gate().is_some()) else {
return Passed { value: render(accel), passes: 1, accelerated: accel.is_some() };
};
a.frame_begin();
for pass in 1..=MAX_PASSES {
a.pass_begin();
let value = render(Some(a));
if !a.pass_missed() {
return Passed { value, passes: pass, accelerated: true };
}
match a.settle() {
Some(s) => s.await,
None => break,
}
}
Passed { value: render(None), passes: MAX_PASSES + 1, accelerated: false }
}
/// A top-level comp frame through [`in_passes`] ([`Renderer::comp_frame`] in passes). Backend
/// Auto picks CPU or GPU for the whole frame (all its passes) and is timed as a whole, as the
/// frame workers do.
pub async fn comp_frame(r: &Renderer<'_>, comp: ItemId, t: Tick) -> Image {
let Some(a) = r.accel.filter(|a| a.miss_gate().is_some()) else { return r.comp_frame(comp, t) };
let mut opts = r.opts;
let mut auto = None;
if opts.backend == Backend::Auto {
if !r.project.settings.gpu_acceleration {
opts.backend = Backend::Cpu;
} else if opts.roi.is_none()
&& let Some(pick) = a.auto_pick()
{
let key = AutoKey::new(comp, opts.scale, false);
let gpu = pick.choose(key);
opts.backend = if gpu { Backend::Gpu } else { Backend::Cpu };
auto = Some((key, gpu));
}
}
let t0 = web_time::Instant::now();
let img = if opts.backend == Backend::Cpu {
Renderer { opts, accel: None, ..*r }.comp_frame(comp, t)
} else {
in_passes(Some(a), |acc| Renderer { opts, accel: acc, ..*r }.comp_frame(comp, t)).await.value
};
if let (Some((key, chose)), Some(pick)) = (auto, a.auto_pick()) {
pick.record(key, chose, t0.elapsed().as_secs_f64() * 1e3);
}
img
}
/// Drive `f` to completion on this thread. For futures that only wait on deferred readbacks,
/// whose [`Accelerator::settle`] blocks natively: they never stay pending there.
pub fn block_on<F: Future>(f: F) -> F::Output {
let mut f = std::pin::pin!(f);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(v) = f.as_mut().poll(&mut cx) {
return v;
}
std::thread::yield_now();
}
}
+2
View File
@@ -583,6 +583,8 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
Field::text("name", "Template name", &name),
Field::text("description", "Description", ""),
Field::text("category", "Category", "My Templates"),
Field::bool("embedFootage", "Embed footage files", true),
Field::num("embedLimitMB", "Embed up to (MB)", effectcraft_engine::templates::EMBED_LIMIT_MB),
],
)
}
+2 -1
View File
@@ -218,10 +218,11 @@ mod tests {
assert_eq!(app.dialog_state.form.command, "templates.saveAs");
app.dialog_state.form.fields[0].kind = crate::panels::forms::FieldKind::Text("Brand Intro".into());
frame(&mut app, &ctx);
for id in ["form.field.name", "form.field.description", "form.ok", "form.cancel"] {
for id in ["form.field.name", "form.field.description", "form.field.embedFootage", "form.field.embedLimitMB", "form.ok", "form.cancel"] {
assert!(app.auto.find(id).is_some(), "{id}");
}
let params = app.dialog_state.form.params();
assert_eq!((params["embedFootage"].as_bool(), params["embedLimitMB"].as_f64()), (Some(true), Some(256.0)), "{params}");
app.session.execute("templates.saveAs", params).unwrap();
app.dialog = None;
app.ui.start_screen = true;
@@ -79,6 +79,8 @@ impl RemoteFrames for GpuWorker {
time: job.t,
opts: Box::new(job.opts),
disk: disk.clone(),
layers: false,
prefetch: vec![],
}));
// The worker awaits its device between passes (`Gpu::settled`); natively a poll.
while server.waiting() {
+123
View File
@@ -0,0 +1,123 @@
//! Headless checks for M13.30 (GPU in the browser's job workers), run natively: a job worker
//! session whose accelerator is a device with deferred readbacks (the worker's own WebGPU
//! device) runs the Render Queue and an analysis with their frames rendered on the device in
//! passes (`offload::run_request_async`, `render::passes`), and gets what a CPU worker gets.
use std::sync::{Arc, Mutex};
use effectcraft_engine::Session;
use effectcraft_engine::offload::{Inbox, Offload, Post, WorkerReply, WorkerRequest};
use effectcraft_gpu::Gpu;
use serde_json::json;
/// Holds offloaded jobs until the test runs them.
#[derive(Default)]
struct Manual(Mutex<Vec<(WorkerRequest, Arc<Inbox>)>>);
impl Offload for Manual {
fn start(&self, req: WorkerRequest, inbox: Arc<Inbox>) -> Result<(), String> {
self.0.lock().unwrap().push((req, inbox));
Ok(())
}
fn cancel(&self, _: u64) {}
}
type Files = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
fn exporter(files: Files) -> Arc<effectcraft_host::FileExporter> {
let sink: Arc<dyn Fn(&str, Vec<u8>) + Send + Sync> = Arc::new(move |p: &str, d: Vec<u8>| files.lock().unwrap().push((p.to_string(), d)));
Arc::new(effectcraft_host::FileExporter { sink: Some(sink) })
}
/// Run `req` on a worker session (`gpu`: its accelerator); its replies and the files it wrote.
fn run(req: WorkerRequest, gpu: Option<&Gpu>) -> (Vec<WorkerReply>, Vec<(String, Vec<u8>)>) {
let files: Files = Arc::default();
let mut w = Session { exporter: Some(exporter(files.clone())), ..Default::default() };
w.accel = gpu.map(|g| Arc::new(g.clone()) as Arc<dyn effectcraft_engine::render::Accelerator>);
let replies = Arc::new(Mutex::new(vec![]));
let r2 = replies.clone();
let post: Post = std::rc::Rc::new(move |r| r2.lock().unwrap().push(r));
effectcraft_engine::offload::run_request(&mut w, req, &post);
let r = replies.lock().unwrap().clone();
let f = files.lock().unwrap().clone();
(r, f)
}
fn page() -> (Session, Arc<Manual>) {
let off = Arc::new(Manual::default());
let mut s = Session { offload: Some(off.clone()), exporter: Some(exporter(Arc::default())), ..Default::default() };
s.execute("comp.new", json!({"name": "Job", "width": 96, "height": 64, "frameRate": 10, "duration": 0.6})).unwrap();
let l = s.execute("layer.newSolid", json!({"color": "#3070c0"})).unwrap()["layer"].as_u64().unwrap();
// Moving texture (Fractal Noise, offset animated), then a blur: GPU effects.
s.execute("effect.apply", json!({"layers": [l], "effect": "ec.noise.fractal"})).unwrap();
s.execute("prop.addKey", json!({"layer": l, "path": "effects/#1/transform/offset", "time": 0.0, "value": [0.5, 0.5]})).unwrap();
s.execute("prop.addKey", json!({"layer": l, "path": "effects/#1/transform/offset", "time": 0.5, "value": [0.6, 0.56]})).unwrap();
s.execute("effect.apply", json!({"layers": [l], "effect": "ec.blur.gaussian"})).unwrap();
s.execute("prop.set", json!({"layer": l, "path": "effects/#2/blurriness", "value": 3.0})).unwrap();
(s, off)
}
#[test]
fn render_queue_jobs_render_on_the_worker_gpu() {
let Some(g) = Gpu::headless_deferred() else {
eprintln!("no GPU adapter: skipped");
return;
};
let (mut s, off) = page();
s.execute("renderQueue.add", json!({"format": "png", "output": "/job/f_[#####].png"})).unwrap();
s.execute("renderQueue.render", json!({"wait": false})).unwrap();
let (req, _) = off.0.lock().unwrap().pop().expect("the render went to the worker");
let (cpu_replies, mut cpu_files) = run(req.clone(), None);
let before = g.deferred_stats().unwrap();
let (gpu_replies, mut gpu_files) = run(req, Some(&g));
// (the CPU worker writes a batch's files in parallel)
cpu_files.sort();
gpu_files.sort();
let after = g.deferred_stats().unwrap();
let done = |r: &[WorkerReply]| r.iter().any(|r| matches!(r, WorkerReply::Item { update } if format!("{update:?}").contains("Done")));
assert!(done(&cpu_replies) && done(&gpu_replies), "{gpu_replies:?}");
assert!(matches!(gpu_replies.last(), Some(WorkerReply::Done)));
// Backend Auto (what renders use) warms up both sides, GPU first: the GPU frames rendered
// in passes on the device (their chains, then the frame read back).
let frames = gpu_files.len() as u64;
assert_eq!(frames, 6);
assert!(after.0 - before.0 >= 6, "passes {before:?} → {after:?}");
assert!(after.1 - before.1 >= 6, "readbacks {before:?} → {after:?}");
assert_eq!(after.2, 0, "nothing left in flight");
// The same frames as the CPU worker's (within GPU rounding).
assert_eq!(cpu_files.iter().map(|f| &f.0).collect::<Vec<_>>(), gpu_files.iter().map(|f| &f.0).collect::<Vec<_>>());
for ((name, a), (_, b)) in cpu_files.iter().zip(&gpu_files) {
let a = image::load_from_memory(a).unwrap().to_rgba8();
let b = image::load_from_memory(b).unwrap().to_rgba8();
assert_eq!(a.dimensions(), b.dimensions());
let worst = a.as_raw().iter().zip(b.as_raw()).map(|(x, y)| x.abs_diff(*y)).max().unwrap();
assert!(worst <= 3, "{name}: differs by {worst} levels");
}
}
#[test]
fn analyses_render_their_input_on_the_worker_gpu() {
let Some(g) = Gpu::headless_deferred() else {
eprintln!("no GPU adapter: skipped");
return;
};
let (mut s, off) = page();
let l = s.active_comp().unwrap().layers[0].id;
s.execute("layer.select", json!({"layers": [l.0]})).unwrap();
s.execute("effect.apply", json!({"layers": [l.0], "effect": "Warp Stabilizer"})).unwrap();
s.execute("warp.analyze", json!({"layer": l.0, "wait": false})).unwrap();
let (req, _) = off.0.lock().unwrap().pop().expect("the analysis went to the worker");
let (cpu, _) = run(req.clone(), None);
let before = g.deferred_stats().unwrap();
let (gpu, _) = run(req, Some(&g));
let after = g.deferred_stats().unwrap();
let group = |r: &[WorkerReply]| r.iter().find_map(|r| if let WorkerReply::Group { group, .. } = r { Some(group.clone()) } else { None });
let failed = |r: &[WorkerReply]| r.iter().find_map(|r| if let WorkerReply::Failed { error } = r { Some(error.clone()) } else { None });
assert_eq!(group(&cpu).is_some(), group(&gpu).is_some(), "cpu {:?} / gpu {:?}", failed(&cpu), failed(&gpu));
assert!(group(&gpu).is_some(), "{:?}", failed(&gpu));
// The input frames (the effects above Warp Stabilizer) rendered on the device in passes.
assert!(after.1 - before.1 >= 6, "readbacks {before:?} → {after:?}");
assert!(after.0 - before.0 >= 12, "passes {before:?} → {after:?}");
let progress = gpu.iter().filter(|r| matches!(r, WorkerReply::Progress { .. })).count();
assert!(progress >= 1);
}
+10 -1
View File
@@ -69,7 +69,16 @@ impl RemoteFrames for FakeWorker {
assert!(server.handle(rt(&m)).is_empty());
}
*next += 1;
let out = server.handle(rt(&FrameMsg::Render { id: *next, revision: job.revision, comp: job.comp, time: job.t, opts: Box::new(job.opts), disk: None }));
let out = server.handle(rt(&FrameMsg::Render {
id: *next,
revision: job.revision,
comp: job.comp,
time: job.t,
opts: Box::new(job.opts),
disk: None,
layers: false,
prefetch: vec![],
}));
match out.into_iter().next() {
Some((FrameReply::Frame { width, height, ms, .. }, Some(rgba))) => pending.push((done, RemoteFrame { width, height, rgba, ms })),
other => done(Err(format!("{:?}", other.map(|o| o.0)))),