M13.30: web depth and polish
- GPU in browser job workers: each job worker opens its own WebGPU device (deferred readbacks); the Render Queue export and the analyses' frame loops are futures (render::passes, offload::run_request_async) whose frames render in passes, awaiting the device between them. GPU particles and Advanced 3D read back under keys too. workers.jobs reports passes and readbacks; the smoke test measures them. - Layer buffers in the browser's OPFS disk cache: frame workers back their layer caches with a PrefetchStore; the page plans what to fetch before a request from recent misses (LayerPrefetch over the shared DiskIndex). - Templates embed footage (default on, size-capped with a warning) and creating from a template extracts it next to the new project / into browser storage. - ICC LUT profiles (lut8/lut16/lutAtoB/lutBtoA, from the public ICC spec) in Simulate Output > My Custom RGB, baked into a 3D LUT for the viewer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
d39c0e818c
commit
f3715aac32
+172
-5
@@ -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);
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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?;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user