Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M8.2/M8.3: Lumetri Input LUT and Creative Look LUTs, project LUT library, GPU tetrahedral LUT, section bypass switches

Brandon Thomasa7c1cfd9563b
diff --git a/crates/engine/src/color.rs b/crates/engine/src/color.rs
new file mode 100644
index 000000000..023bf1558
--- /dev/null
+++ b/crates/engine/src/color.rs
@@ -0,0 +1,197 @@
+//! Colour commands: the project LUT library (`lut.*`), Lumetri LUT slots and section switches
+//! (`lumetri.*`).
+//!
+//! Lumetri commands address a clip by `clip` (default: the first selected video clip with
+//! Lumetri Color, else the first selected video clip — Lumetri is added if missing).
+
+use filmcraft_color::{Lut, LutFormat};
+use filmcraft_project::{ClipId, ParamValue, ProjectLut, TrackKind};
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, always, bad, bool_p, clip_p, has_seq, str_p};
+use crate::{Result, Session};
+
+type Run = fn(&mut Session, &Value) -> Result<Value>;
+type Enabled = fn(&Session) -> std::result::Result<(), String>;
+
+fn spec(id: &'static str, label: &'static str, menu: &'static [&'static str], params: &'static str, enabled: Enabled, run: Run) -> CommandSpec {
+ CommandSpec { id, label, menu, shortcut: None, params, enabled, run, journal: true }
+}
+fn query(id: &'static str, label: &'static str, params: &'static str, run: Run) -> CommandSpec {
+ CommandSpec { id, label, menu: &[], shortcut: None, params, enabled: always, run, journal: false }
+}
+
+pub(crate) fn commands() -> Vec<CommandSpec> {
+ vec![
+ spec("lut.import", "Import LUT…", &[], r#"{"path":str,"name":str?}"#, always, import),
+ query("lut.list", "List LUTs", "{}", list),
+ spec("lut.remove", "Remove LUT", &[], r#"{"id":str}"#, always, remove),
+ query("lut.export", "Export LUT", r#"{"lut":"lib:<id>"|"builtin:<id>","path":str,"format":"cube"|"3dl"?}"#, export),
+ spec("lumetri.setInputLut", "Set Input LUT", &[], r#"{"clip":id?,"lut":"lib:<id>"|"builtin:<id>"|""?,"path":str?}"#, has_seq, |s, p| {
+ set_lut(s, p, "input_lut")
+ }),
+ spec("lumetri.setLook", "Set Creative Look", &[], r#"{"clip":id?,"lut":"lib:<id>"|"builtin:<id>"|""?,"path":str?}"#, has_seq, |s, p| {
+ set_lut(s, p, "look_lut")
+ }),
+ spec(
+ "lumetri.setSection",
+ "Toggle Lumetri Section",
+ &[],
+ r#"{"clip":id?,"section":"basic"|"creative"|"curves"|"wheels"|"hsl"|"vignette","on":bool?}"#,
+ has_seq,
+ set_section,
+ ),
+ ]
+}
+
+fn import_lut(s: &mut Session, path: &str, name: Option<&str>) -> Result<(String, Value)> {
+ let text = std::fs::read_to_string(path).map_err(|e| bad("lut.import", format!("{path}: {e}")))?;
+ let fmt = LutFormat::from_path(path).ok_or_else(|| bad("lut.import", "expected a .cube or .3dl file"))?;
+ let lut = Lut::parse(&text, Some(fmt)).map_err(|e| bad("lut.import", format!("{path}: {e}")))?;
+ let stem = std::path::Path::new(path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "LUT".into());
+ let name = name.map(str::to_string).unwrap_or(stem);
+ // re-importing identical content reuses the entry
+ if let Some(l) = s.project.luts.iter().find(|l| *l.text == *text) {
+ return Ok((l.id.clone(), json!({"id": l.id, "ref": format!("lib:{}", l.id), "name": l.name, "reused": true})));
+ }
+ let info = json!({
+ "size3d": lut.cube.as_ref().map(|c| c.size),
+ "size1d": lut.shaper.as_ref().map(|c| c.size()),
+ "title": lut.title,
+ });
+ let mut id = String::new();
+ s.edit("Import LUT", |pr, _| {
+ id = format!("lut{}", pr.alloc_id());
+ pr.luts.push(ProjectLut {
+ id: id.clone(),
+ name: name.clone(),
+ source_path: Some(path.to_string()),
+ format: fmt.extension().into(),
+ text: text.as_str().into(),
+ });
+ Ok(())
+ })?;
+ Ok((id.clone(), json!({"id": id, "ref": format!("lib:{id}"), "name": name, "lut": info})))
+}
+
+fn import(s: &mut Session, p: &Value) -> Result<Value> {
+ let path = str_p(p, "path").ok_or_else(|| bad("lut.import", "need `path`"))?.to_string();
+ Ok(import_lut(s, &path, str_p(p, "name"))?.1)
+}
+
+fn list(s: &mut Session, _: &Value) -> Result<Value> {
+ let lib: Vec<Value> = s
+ .project
+ .luts
+ .iter()
+ .map(|l| json!({"id": l.id, "ref": format!("lib:{}", l.id), "name": l.name, "format": l.format, "source": l.source_path}))
+ .collect();
+ let builtin: Vec<Value> = filmcraft_render::luts::builtins()
+ .iter()
+ .map(|b| json!({"ref": format!("builtin:{}", b.id), "name": b.label, "input": filmcraft_render::luts::input_builtins().any(|i| i.id == b.id)}))
+ .collect();
+ Ok(json!({"library": lib, "builtin": builtin}))
+}
+
+fn remove(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = str_p(p, "id").ok_or_else(|| bad("lut.remove", "need `id`"))?.trim_start_matches("lib:").to_string();
+ if !s.project.luts.iter().any(|l| l.id == id) {
+ return Err(bad("lut.remove", format!("no LUT `{id}`")));
+ }
+ s.edit("Remove LUT", |pr, _| {
+ pr.luts.retain(|l| l.id != id);
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn export(s: &mut Session, p: &Value) -> Result<Value> {
+ let r = str_p(p, "lut").ok_or_else(|| bad("lut.export", "need `lut`"))?;
+ let path = str_p(p, "path").ok_or_else(|| bad("lut.export", "need `path`"))?;
+ let lut = filmcraft_render::luts::resolve(Some(&s.project), r).ok_or_else(|| bad("lut.export", format!("unknown LUT `{r}`")))?;
+ let fmt = match str_p(p, "format") {
+ Some("3dl") => LutFormat::ThreeDl,
+ Some("cube") => LutFormat::Cube,
+ Some(o) => return Err(bad("lut.export", format!("unknown format `{o}`"))),
+ None => LutFormat::from_path(path).unwrap_or(LutFormat::Cube),
+ };
+ let text = match fmt {
+ LutFormat::Cube => lut.to_cube(),
+ LutFormat::ThreeDl => lut.to_3dl().map_err(|e| bad("lut.export", e))?,
+ };
+ std::fs::write(path, &text).map_err(|e| bad("lut.export", format!("{path}: {e}")))?;
+ Ok(json!({"path": path, "bytes": text.len()}))
+}
+
+/// The target clip and the index of its Lumetri effect (applying Lumetri when missing).
+pub(crate) fn lumetri_clip(s: &mut Session, p: &Value, cmd: &str) -> Result<(ClipId, usize)> {
+ let seq = s.active_sequence().ok_or_else(|| bad(cmd, "no active sequence"))?;
+ let video = |c: &ClipId| seq.find_item(*c).is_some_and(|(t, _)| seq.track(t).is_some_and(|t| t.kind == TrackKind::Video));
+ let has = |c: &ClipId| seq.find_item(*c).is_some_and(|(_, it)| it.effects.iter().any(|e| e.effect == "lumetri"));
+ let clip = match clip_p(p, "clip") {
+ Some(c) if video(&c) => c,
+ Some(_) => return Err(bad(cmd, "not a video clip")),
+ None => {
+ let sel: Vec<ClipId> = s.state.selection.iter().copied().filter(video).collect();
+ sel.iter().copied().find(has).or(sel.first().copied()).ok_or_else(|| bad(cmd, "select a video clip"))?
+ }
+ };
+ if !has(&clip) {
+ s.execute("effects.apply", json!({"clips": [clip.0], "effect": "lumetri"}))?;
+ }
+ let seq = s.active_sequence().ok_or_else(|| bad(cmd, "no active sequence"))?;
+ let idx = seq.find_item(clip).and_then(|(_, it)| it.effects.iter().position(|e| e.effect == "lumetri")).ok_or_else(|| bad(cmd, "no Lumetri"))?;
+ Ok((clip, idx))
+}
+
+/// Set a Lumetri parameter (inserting it when an older project's instance lacks it).
+pub(crate) fn set_lumetri_param(s: &mut Session, clip: ClipId, idx: usize, param: &str, v: ParamValue, label: &str) -> Result<()> {
+ let param = param.to_string();
+ s.edit_sequence(label, |q, _, _| {
+ let (_, it) = q.find_item_mut(clip).ok_or(filmcraft_edit::EditError::NoItem(clip))?;
+ let e = it.effects.get_mut(idx).ok_or_else(|| bad("lumetri", "no Lumetri"))?;
+ e.params.entry(param.clone()).or_insert_with(|| filmcraft_project::Param::new(v.clone())).value = v.clone();
+ Ok(())
+ })?;
+ Ok(())
+}
+
+fn set_lut(s: &mut Session, p: &Value, param: &str) -> Result<Value> {
+ let cmd = if param == "input_lut" { "lumetri.setInputLut" } else { "lumetri.setLook" };
+ let r = match (str_p(p, "path"), str_p(p, "lut")) {
+ (Some(path), _) => {
+ let path = path.to_string();
+ format!("lib:{}", import_lut(s, &path, None)?.0)
+ }
+ (None, Some(r)) => r.to_string(),
+ (None, None) => String::new(),
+ };
+ if !r.is_empty() && filmcraft_render::luts::resolve(Some(&s.project), &r).is_none() {
+ return Err(bad(cmd, format!("unknown LUT `{r}`")));
+ }
+ let (clip, idx) = lumetri_clip(s, p, cmd)?;
+ set_lumetri_param(s, clip, idx, param, ParamValue::Text(r.clone()), if param == "input_lut" { "Input LUT" } else { "Creative Look" })?;
+ Ok(json!({"clip": clip.0, "lut": r, "name": filmcraft_render::luts::label(Some(&s.project), &r)}))
+}
+
+fn set_section(s: &mut Session, p: &Value) -> Result<Value> {
+ let sec = str_p(p, "section").ok_or_else(|| bad("lumetri.setSection", "need `section`"))?;
+ let param = match sec.to_ascii_lowercase().as_str() {
+ "basic" | "basic correction" => "basic_on",
+ "creative" => "creative_on",
+ "curves" => "curves_on",
+ "wheels" | "color wheels" | "color wheels & match" => "wheels_on",
+ "hsl" | "hsl secondary" => "hsl_on",
+ "vignette" => "vignette_on",
+ o => return Err(bad("lumetri.setSection", format!("unknown section `{o}`"))),
+ };
+ let (clip, idx) = lumetri_clip(s, p, "lumetri.setSection")?;
+ let cur = s
+ .active_sequence()
+ .and_then(|q| q.find_item(clip))
+ .and_then(|(_, it)| it.effects.get(idx).and_then(|e| e.param(param)).and_then(|v| v.value.as_bool()))
+ .unwrap_or(param != "hsl_on");
+ let v = bool_p(p, "on").unwrap_or(!cur);
+ set_lumetri_param(s, clip, idx, param, ParamValue::Bool(v), "Lumetri Section")?;
+ Ok(json!({"clip": clip.0, "param": param, "on": v}))
+}
diff --git a/crates/engine/src/color_tests.rs b/crates/engine/src/color_tests.rs
new file mode 100644
index 000000000..14ea4078b
--- /dev/null
+++ b/crates/engine/src/color_tests.rs
@@ -0,0 +1,132 @@
+use serde_json::json;
+
+use crate::Session;
+use filmcraft_color::{Lut, Lut3d};
+use filmcraft_project::{ClipId, ParamValue};
+
+fn demo() -> Session {
+ let mut s = Session::default();
+ s.execute("file.openDemoProject", json!({})).unwrap();
+ s
+}
+
+/// The first V1 clip under the playhead, selected.
+fn pick_clip(s: &mut Session) -> ClipId {
+ let q = s.active_sequence().unwrap();
+ let t = s.playhead();
+ let c = q.video_tracks[0].item_at(t).or(q.video_tracks[0].items.first()).unwrap();
+ let id = c.id;
+ s.set_playhead(c.start + filmcraft_time::Tick(1000));
+ s.state.selection = vec![id];
+ id
+}
+
+fn lumetri_text(s: &Session, clip: ClipId, p: &str) -> String {
+ let q = s.active_sequence().unwrap();
+ let (_, it) = q.find_item(clip).unwrap();
+ let e = it.effects.iter().find(|e| e.effect == "lumetri").unwrap();
+ match e.param(p).map(|v| &v.value) {
+ Some(ParamValue::Text(t)) => t.clone(),
+ _ => String::new(),
+ }
+}
+
+fn mean(img: &filmcraft_render::Image) -> [f32; 3] {
+ let mut m = [0f64; 3];
+ for p in img.px.chunks_exact(4) {
+ for k in 0..3 {
+ m[k] += p[k] as f64;
+ }
+ }
+ let n = (img.px.len() / 4) as f64;
+ m.map(|v| (v / n) as f32)
+}
+
+fn tmp(name: &str) -> String {
+ let d = std::env::temp_dir().join(format!("filmcraft-color-{}-{name}", std::process::id()));
+ d.to_string_lossy().to_string()
+}
+
+#[test]
+fn import_lut_set_input_and_look_then_undo() {
+ let mut s = demo();
+ let clip = pick_clip(&mut s);
+ let before = mean(&s.render_program(0.125).unwrap());
+ // a LUT that swaps red and blue
+ let path = tmp("swap.cube");
+ std::fs::write(&path, Lut::from_cube(Lut3d::from_fn(17, |c| [c[2], c[1], c[0]])).to_cube()).unwrap();
+ let r = s.execute("lumetri.setInputLut", json!({"path": path})).unwrap();
+ let lref = r["lut"].as_str().unwrap().to_string();
+ assert!(lref.starts_with("lib:"));
+ assert_eq!(s.project.luts.len(), 1);
+ assert_eq!(lumetri_text(&s, clip, "input_lut"), lref);
+ let after = mean(&s.render_program(0.125).unwrap());
+ assert!((after[0] - before[2]).abs() < 0.02 && (after[2] - before[0]).abs() < 0.02, "{before:?} → {after:?}");
+ // importing the same file again reuses the library entry
+ let again = s.execute("lut.import", json!({"path": path})).unwrap();
+ assert_eq!(again["reused"], true);
+ // Input LUT section switch: Basic Correction off bypasses it
+ s.execute("lumetri.setSection", json!({"section": "basic", "on": false})).unwrap();
+ let off = mean(&s.render_program(0.125).unwrap());
+ assert!((off[0] - before[0]).abs() < 0.01, "{off:?} vs {before:?}");
+ s.execute("lumetri.setSection", json!({"section": "basic"})).unwrap();
+ // built-in look by reference
+ s.execute("lumetri.setLook", json!({"lut": "builtin:look-monochrome"})).unwrap();
+ let mono = mean(&s.render_program(0.125).unwrap());
+ assert!((mono[0] - mono[2]).abs() < 0.03, "{mono:?}");
+ assert!(s.execute("lumetri.setLook", json!({"lut": "lib:nope"})).is_err());
+ // the library and the references survive save/load
+ let lib = s.execute("lut.list", json!({})).unwrap();
+ assert_eq!(lib["library"].as_array().unwrap().len(), 1);
+ assert!(lib["builtin"].as_array().unwrap().iter().any(|b| b["ref"] == "builtin:slog3-sgamut3cine-to-rec709"));
+ let js = serde_json::to_string(&*s.project).unwrap();
+ let back: filmcraft_project::Project = serde_json::from_str(&js).unwrap();
+ assert_eq!(back.luts, s.project.luts);
+ // undo the look, the section toggles and the input LUT
+ for _ in 0..4 {
+ s.execute("edit.undo", json!({})).unwrap();
+ }
+ assert_eq!(lumetri_text(&s, clip, "look_lut"), "");
+ let _ = std::fs::remove_file(&path);
+}
+
+#[test]
+fn export_builtin_and_library_luts() {
+ let mut s = demo();
+ for (fmt, ext) in [("cube", "cube"), ("3dl", "3dl")] {
+ let path = tmp(&format!("slog3.{ext}"));
+ s.execute("lut.export", json!({"lut": "builtin:slog3-sgamut3cine-to-rec709", "path": path, "format": fmt})).unwrap();
+ let text = std::fs::read_to_string(&path).unwrap();
+ let back = Lut::parse(&text, filmcraft_color::LutFormat::from_path(&path)).unwrap();
+ let orig = filmcraft_render::luts::resolve(None, "builtin:slog3-sgamut3cine-to-rec709").unwrap();
+ for c in [[0.4, 0.4, 0.4], [0.6, 0.3, 0.2]] {
+ let (a, b) = (orig.apply(c), back.apply(c));
+ assert!((0..3).all(|k| (a[k] - b[k]).abs() < 2e-3), "{fmt}: {a:?} vs {b:?}");
+ }
+ // round trip through the library
+ let r = s.execute("lut.import", json!({"path": path})).unwrap();
+ assert!(r["ref"].as_str().unwrap().starts_with("lib:"));
+ let _ = std::fs::remove_file(&path);
+ }
+ assert_eq!(s.project.luts.len(), 2);
+ let id = s.project.luts[0].id.clone();
+ s.execute("lut.remove", json!({"id": id})).unwrap();
+ assert_eq!(s.project.luts.len(), 1);
+ assert!(s.execute("lut.import", json!({"path": "/nonexistent.cube"})).is_err());
+}
+
+#[test]
+fn set_param_fills_in_parameters_missing_from_old_instances() {
+ let mut s = demo();
+ let clip = pick_clip(&mut s);
+ s.execute("effects.apply", json!({"clips": [clip.0], "effect": "lumetri"})).unwrap();
+ // simulate an instance saved before the section switches existed
+ s.edit_sequence("strip", |q, _, _| {
+ let (_, it) = q.find_item_mut(clip).unwrap();
+ let e = it.effects.iter_mut().find(|e| e.effect == "lumetri").unwrap();
+ e.params.remove("vignette_on");
+ Ok(())
+ })
+ .unwrap();
+ s.execute("effects.setParam", json!({"clip": clip.0, "effect": "lumetri", "param": "vignette_on", "value": false})).unwrap();
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 7f3ae7e09..a47ed4aba 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -149,7 +149,7 @@ pub(crate) fn time_p(s: &Session, p: &Value, prefix: &str) -> Option<Tick> {
None
}
-fn clip_p(p: &Value, k: &str) -> Option<ClipId> {
+pub(crate) fn clip_p(p: &Value, k: &str) -> Option<ClipId> {
u64_p(p, k).map(ClipId)
}
fn clips_p(s: &Session, p: &Value) -> Vec<ClipId> {
@@ -1679,6 +1679,12 @@ fn build() -> Vec<CommandSpec> {
if eff == json!("opacity") || eff == json!("motion") {
e.enabled = true;
}
+ // instances saved before a parameter existed get it from the definition
+ if !e.params.contains_key(&pid)
+ && let Some(d) = e.def().and_then(|d| d.param(&pid))
+ {
+ e.params.insert(pid.clone(), filmcraft_project::Param::new(d.default.clone()));
+ }
let prm = e.params.get_mut(&pid).ok_or_else(|| bad("effects.setParam", format!("no param `{pid}`")))?;
let v = json_to_param(&prm.value, &val).ok_or_else(|| bad("effects.setParam", "value has the wrong type"))?;
prm.set_at(mt, v);
@@ -1849,6 +1855,7 @@ fn build() -> Vec<CommandSpec> {
];
v.extend(crate::captions::commands());
v.extend(crate::mixer::commands());
+ v.extend(crate::color::commands());
v.extend(crate::graphics::commands());
v.extend(crate::shortcuts::commands());
// Labels as individual commands (Edit ▸ Label ▸ <name>)
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index e9a9f2788..15aff7a42 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -10,6 +10,7 @@
pub mod autosave;
pub mod captions;
+pub mod color;
pub mod commands;
pub mod demo;
pub mod graphics;
@@ -555,6 +556,8 @@ pub fn media_duration(p: &Project, _pool: &MediaPool, id: ItemId) -> Option<Tick
#[cfg(test)]
mod autosave_tests;
#[cfg(test)]
+mod color_tests;
+#[cfg(test)]
mod file_tests;
#[cfg(test)]
mod mixer_tests;
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index 790861692..3bd203203 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -16,6 +16,9 @@ use filmcraft_color::{Matrix, Range, Transfer};
use filmcraft_frame::{Chroma, PixelData, VideoFrame};
use filmcraft_render::plan::{FramePlan, PlanLayer};
+pub mod lut;
+pub use lut::GpuLut;
+
/// Output texture format: gamma-encoded RGBA8 (what egui expects of native textures); the resolve
/// shader applies the sRGB encoding.
pub const OUTPUT_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
diff --git a/crates/gpu/src/lut.rs b/crates/gpu/src/lut.rs
new file mode 100644
index 000000000..7d53710b7
--- /dev/null
+++ b/crates/gpu/src/lut.rs
@@ -0,0 +1,120 @@
+//! GPU 3D LUT application (WGSL compute, tetrahedral interpolation), the counterpart of
+//! [`filmcraft_color::Lut3d::apply`]. Tested for parity with the CPU path.
+
+use filmcraft_color::Lut3d;
+
+pub struct GpuLut {
+ device: wgpu::Device,
+ queue: wgpu::Queue,
+ pipeline: wgpu::ComputePipeline,
+ bgl: wgpu::BindGroupLayout,
+}
+
+fn storage(binding: u32, read_only: bool) -> wgpu::BindGroupLayoutEntry {
+ wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None },
+ count: None,
+ }
+}
+
+impl GpuLut {
+ pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("filmcraft-lut"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("lut.wgsl").into()),
+ });
+ let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("lut"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
+ count: None,
+ },
+ storage(1, true),
+ storage(2, true),
+ storage(3, false),
+ ],
+ });
+ let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("lut"), bind_group_layouts: &[Some(&bgl)], immediate_size: 0 });
+ let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("lut"),
+ layout: Some(&pl),
+ module: &shader,
+ entry_point: Some("main"),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ GpuLut { device: device.clone(), queue: queue.clone(), pipeline, bgl }
+ }
+
+ /// Apply `lut` to straight RGBA f32 pixels (alpha passes through). Blocks until done.
+ pub fn apply(&self, lut: &Lut3d, rgba: &[f32]) -> Option<Vec<f32>> {
+ use wgpu::util::DeviceExt;
+ let count = (rgba.len() / 4) as u32;
+ if count == 0 {
+ return Some(Vec::new());
+ }
+ let mut params = Vec::with_capacity(48);
+ for v in [lut.size as u32, count, 0, 0] {
+ params.extend_from_slice(&v.to_le_bytes());
+ }
+ for v in lut.domain_min.iter().chain(&[0.0]).chain(lut.domain_max.iter()).chain(&[1.0]) {
+ params.extend_from_slice(&v.to_le_bytes());
+ }
+ let lut_bytes: Vec<u8> = lut.data.iter().flat_map(|c| [c[0], c[1], c[2], 0.0]).flat_map(f32::to_le_bytes).collect();
+ let src_bytes: Vec<u8> = rgba.iter().flat_map(|v| v.to_le_bytes()).collect();
+ let d = &self.device;
+ let ub = d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("lut-params"), contents: &params, usage: wgpu::BufferUsages::UNIFORM });
+ let lb = d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("lut-data"), contents: &lut_bytes, usage: wgpu::BufferUsages::STORAGE });
+ let sb = d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("lut-src"), contents: &src_bytes, usage: wgpu::BufferUsages::STORAGE });
+ let size = src_bytes.len() as u64;
+ let ob = d.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("lut-dst"),
+ size,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ mapped_at_creation: false,
+ });
+ let rb = d.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("lut-read"),
+ size,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+ let bg = d.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("lut"),
+ layout: &self.bgl,
+ entries: &[
+ wgpu::BindGroupEntry { binding: 0, resource: ub.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 1, resource: lb.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 2, resource: sb.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 3, resource: ob.as_entire_binding() },
+ ],
+ });
+ let mut enc = d.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("lut") });
+ {
+ let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("lut"), timestamp_writes: None });
+ pass.set_pipeline(&self.pipeline);
+ pass.set_bind_group(0, &bg, &[]);
+ let groups = count.div_ceil(64);
+ pass.dispatch_workgroups(groups.min(65535), groups.div_ceil(65535), 1);
+ }
+ enc.copy_buffer_to_buffer(&ob, 0, &rb, 0, size);
+ self.queue.submit([enc.finish()]);
+ let slice = rb.slice(..);
+ let (tx, rx) = std::sync::mpsc::channel();
+ slice.map_async(wgpu::MapMode::Read, move |r| {
+ let _ = tx.send(r);
+ });
+ let _ = d.poll(wgpu::PollType::wait_indefinitely());
+ rx.recv().ok()?.ok()?;
+ let data = slice.get_mapped_range().ok()?;
+ let out = data.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();
+ drop(data);
+ rb.unmap();
+ Some(out)
+ }
+}
diff --git a/crates/gpu/src/lut.wgsl b/crates/gpu/src/lut.wgsl
new file mode 100644
index 000000000..c40f59ac5
--- /dev/null
+++ b/crates/gpu/src/lut.wgsl
@@ -0,0 +1,63 @@
+// 3D LUT application with tetrahedral interpolation (same math as filmcraft_color::Lut3d::apply).
+// Pixels are straight (unpremultiplied) display-encoded RGBA; alpha passes through.
+
+struct Params {
+ size: u32,
+ count: u32,
+ _pad0: u32,
+ _pad1: u32,
+ dmin: vec4<f32>,
+ dmax: vec4<f32>,
+};
+
+@group(0) @binding(0) var<uniform> params: Params;
+@group(0) @binding(1) var<storage, read> lut: array<vec4<f32>>;
+@group(0) @binding(2) var<storage, read> src: array<vec4<f32>>;
+@group(0) @binding(3) var<storage, read_write> dst: array<vec4<f32>>;
+
+fn at(r: u32, g: u32, b: u32) -> vec3<f32> {
+ let n = params.size;
+ return lut[r + g * n + b * n * n].xyz;
+}
+
+fn tetra(c: vec3<f32>) -> vec3<f32> {
+ let n = params.size;
+ let m = f32(n - 1u);
+ let t = clamp((c - params.dmin.xyz) / (params.dmax.xyz - params.dmin.xyz), vec3(0.0), vec3(1.0)) * m;
+ let i = min(vec3<u32>(t), vec3(n - 2u));
+ let f = t - vec3<f32>(i);
+ let fr = f.x;
+ let fg = f.y;
+ let fb = f.z;
+ let c000 = at(i.x, i.y, i.z);
+ let c111 = at(i.x + 1u, i.y + 1u, i.z + 1u);
+ var ca: vec3<f32>;
+ var cb: vec3<f32>;
+ var w: vec4<f32>;
+ if (fr > fg) {
+ if (fg > fb) {
+ ca = at(i.x + 1u, i.y, i.z); cb = at(i.x + 1u, i.y + 1u, i.z); w = vec4(1.0 - fr, fr - fg, fg - fb, fb);
+ } else if (fr > fb) {
+ ca = at(i.x + 1u, i.y, i.z); cb = at(i.x + 1u, i.y, i.z + 1u); w = vec4(1.0 - fr, fr - fb, fb - fg, fg);
+ } else {
+ ca = at(i.x, i.y, i.z + 1u); cb = at(i.x + 1u, i.y, i.z + 1u); w = vec4(1.0 - fb, fb - fr, fr - fg, fg);
+ }
+ } else if (fb > fg) {
+ ca = at(i.x, i.y, i.z + 1u); cb = at(i.x, i.y + 1u, i.z + 1u); w = vec4(1.0 - fb, fb - fg, fg - fr, fr);
+ } else if (fb > fr) {
+ ca = at(i.x, i.y + 1u, i.z); cb = at(i.x, i.y + 1u, i.z + 1u); w = vec4(1.0 - fg, fg - fb, fb - fr, fr);
+ } else {
+ ca = at(i.x, i.y + 1u, i.z); cb = at(i.x + 1u, i.y + 1u, i.z); w = vec4(1.0 - fg, fg - fr, fr - fb, fb);
+ }
+ return w.x * c000 + w.y * ca + w.z * cb + w.w * c111;
+}
+
+@compute @workgroup_size(64)
+fn main(@builtin(global_invocation_id) id: vec3<u32>) {
+ let k = id.x + id.y * 65535u * 64u;
+ if (k >= params.count) {
+ return;
+ }
+ let p = src[k];
+ dst[k] = vec4(tetra(p.xyz), p.w);
+}
diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs
index f787d7056..acc549606 100644
--- a/crates/gpu/src/tests.rs
+++ b/crates/gpu/src/tests.rs
@@ -95,3 +95,43 @@ fn upload_cache_keeps_buffers_alive() {
drop(plan);
assert!(Arc::strong_count(&px) > 1, "cached upload must own its pixel buffer");
}
+
+/// The WGSL tetrahedral LUT matches `Lut3d::apply` on the CPU.
+#[test]
+fn gpu_lut_matches_cpu_tetrahedral() {
+ let Some((dev, q)) = device() else {
+ eprintln!("no GPU adapter; skipping");
+ return;
+ };
+ let g = GpuLut::new(&dev, &q);
+ for size in [2usize, 17, 33, 65] {
+ let mut lut = filmcraft_color::Lut3d::from_fn(size, |c| {
+ [(c[0] * c[1] + c[2] * c[2]).sin(), c[1].powf(0.45) * (1.0 - 0.3 * c[0]), (c[0] - c[2]).abs() + 0.1 * c[1]]
+ });
+ if size == 17 {
+ lut.domain_min = [-0.1, 0.0, 0.0];
+ lut.domain_max = [1.2, 1.0, 2.0];
+ }
+ let mut s = 99u64;
+ let mut px = Vec::new();
+ for _ in 0..70_000 {
+ for k in 0..4 {
+ s ^= s << 13;
+ s ^= s >> 7;
+ s ^= s << 17;
+ px.push(if k == 3 { 0.5 } else { (s % 10_001) as f32 / 10_000.0 * 1.2 - 0.1 });
+ }
+ }
+ let gpu = g.apply(&lut, &px).expect("gpu lut");
+ let mut worst = 0f32;
+ for (i, p) in px.chunks_exact(4).enumerate() {
+ let c = lut.apply([p[0], p[1], p[2]]);
+ for k in 0..3 {
+ worst = worst.max((c[k] - gpu[i * 4 + k]).abs());
+ }
+ assert_eq!(gpu[i * 4 + 3], 0.5);
+ }
+ eprintln!("LUT {size}³: max |cpu − gpu| = {worst:e}");
+ assert!(worst < 1e-4, "size {size}: max |cpu - gpu| = {worst}");
+ }
+}
diff --git a/crates/project/src/effect.rs b/crates/project/src/effect.rs
index 9d0378bd6..c0b567c7f 100644
--- a/crates/project/src/effect.rs
+++ b/crates/project/src/effect.rs
@@ -212,6 +212,9 @@ fn curve(id: &'static str, label: &'static str, hue: bool) -> ParamDef {
fn wheel(id: &'static str, label: &'static str) -> ParamDef {
ParamDef { id, label, kind: ParamKind::Wheel, default: ParamValue::Vec2(Vec2::new(0.0, 0.0)), animatable: true, group: None }
}
+fn txt(id: &'static str, label: &'static str) -> ParamDef {
+ ParamDef { id, label, kind: ParamKind::Text, default: ParamValue::Text(String::new()), animatable: false, group: None }
+}
fn grp(mut p: ParamDef, g: &'static str) -> ParamDef {
p.group = Some(g);
p
@@ -399,6 +402,8 @@ fn build_effects() -> Vec<EffectDef> {
"Lumetri Color",
COLOR_CORR,
vec![
+ grp(b("basic_on", "Basic Correction", true), "Basic Correction"),
+ grp(txt("input_lut", "Input LUT"), "Basic Correction"),
grp(f("temperature", "Temperature", 0.0, -100.0, 100.0, ""), "Basic Correction"),
grp(f("tint", "Tint", 0.0, -100.0, 100.0, ""), "Basic Correction"),
grp(fs("exposure", "Exposure", 0.0, (-5.0, 5.0), (-5.0, 5.0), "", 1), "Basic Correction"),
@@ -408,6 +413,7 @@ fn build_effects() -> Vec<EffectDef> {
grp(f("whites", "Whites", 0.0, -100.0, 100.0, ""), "Basic Correction"),
grp(f("blacks", "Blacks", 0.0, -100.0, 100.0, ""), "Basic Correction"),
grp(fs("saturation", "Saturation", 100.0, (0.0, 200.0), (0.0, 200.0), "", 1), "Basic Correction"),
+ grp(b("creative_on", "Creative", true), "Creative"),
grp(
ch(
"look",
@@ -417,6 +423,7 @@ fn build_effects() -> Vec<EffectDef> {
),
"Creative",
),
+ grp(txt("look_lut", "Look LUT"), "Creative"),
grp(fs("look_intensity", "Intensity", 100.0, (0.0, 200.0), (0.0, 200.0), "", 1), "Creative"),
grp(f("faded_film", "Faded Film", 0.0, 0.0, 100.0, ""), "Creative"),
grp(f("sharpen", "Sharpen", 0.0, -100.0, 100.0, ""), "Creative"),
@@ -424,6 +431,7 @@ fn build_effects() -> Vec<EffectDef> {
grp(fs("creative_sat", "Saturation", 100.0, (0.0, 200.0), (0.0, 200.0), "", 1), "Creative"),
grp(col("shadow_tint", "Shadow Tint", [0.5, 0.5, 0.5, 1.0]), "Creative"),
grp(col("highlight_tint", "Highlight Tint", [0.5, 0.5, 0.5, 1.0]), "Creative"),
+ grp(b("curves_on", "Curves", true), "Curves"),
grp(curve("curve_luma", "Luma Curve", false), "Curves"),
grp(curve("curve_red", "Red Curve", false), "Curves"),
grp(curve("curve_green", "Green Curve", false), "Curves"),
@@ -433,6 +441,7 @@ fn build_effects() -> Vec<EffectDef> {
grp(curve("hue_vs_luma", "Hue vs Luma", true), "Curves"),
grp(curve("luma_vs_sat", "Luma vs Sat", true), "Curves"),
grp(curve("sat_vs_sat", "Sat vs Sat", true), "Curves"),
+ grp(b("wheels_on", "Color Wheels & Match", true), "Color Wheels & Match"),
grp(wheel("wheel_shadows", "Shadows"), "Color Wheels & Match"),
grp(f("wheel_shadows_l", "Shadows Lightness", 0.0, -100.0, 100.0, ""), "Color Wheels & Match"),
grp(wheel("wheel_midtones", "Midtones"), "Color Wheels & Match"),
@@ -451,6 +460,7 @@ fn build_effects() -> Vec<EffectDef> {
grp(f("hsl_tint", "Tint", 0.0, -100.0, 100.0, ""), "HSL Secondary"),
grp(fs("hsl_sat", "Saturation", 100.0, (0.0, 200.0), (0.0, 200.0), "", 1), "HSL Secondary"),
grp(f("hsl_hue_shift", "Hue Shift", 0.0, -180.0, 180.0, "°"), "HSL Secondary"),
+ grp(b("vignette_on", "Vignette", true), "Vignette"),
grp(f("vignette_amount", "Amount", 0.0, -5.0, 5.0, ""), "Vignette"),
grp(f("vignette_midpoint", "Midpoint", 50.0, 0.0, 100.0, ""), "Vignette"),
grp(f("vignette_roundness", "Roundness", 0.0, -100.0, 100.0, ""), "Vignette"),
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
index b502794fd..4bd4cafd4 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -778,6 +778,24 @@ pub struct Project {
pub items: BTreeMap<ItemId, ProjectItem>,
/// Monotonic id source for all id types.
pub next_id: u64,
+ /// The project's LUT library (Lumetri Input LUT / Creative Look "Browse…"). LUT files are
+ /// embedded, so projects render without the original files.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub luts: Vec<ProjectLut>,
+}
+
+/// A LUT imported into the project (`lut.import`). Lumetri refers to it as `lib:<id>`.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct ProjectLut {
+ pub id: String,
+ pub name: String,
+ /// Where it was imported from (informational).
+ #[serde(default)]
+ pub source_path: Option<String>,
+ /// `cube` or `3dl`.
+ pub format: String,
+ /// The file's text.
+ pub text: std::sync::Arc<str>,
}
impl Default for Project {
@@ -794,6 +812,7 @@ impl Project {
root: Bin { id: BinId(0), name: name.into(), children: Vec::new() },
items: BTreeMap::new(),
next_id: 1,
+ luts: Vec::new(),
}
}
diff --git a/crates/render/src/effects.rs b/crates/render/src/effects.rs
index fe40bbd4d..09350fe77 100644
--- a/crates/render/src/effects.rs
+++ b/crates/render/src/effects.rs
@@ -24,6 +24,8 @@ pub struct FxCtx<'a> {
/// Formatted sequence timecode (for the Timecode effect).
pub timecode: &'a str,
pub clip_name: &'a str,
+ /// The project (LUT library for Lumetri); `None` in isolated effect tests.
+ pub project: Option<&'a filmcraft_project::Project>,
}
fn f(e: &EffectInstance, id: &str, cx: &FxCtx) -> f32 {
@@ -32,6 +34,16 @@ fn f(e: &EffectInstance, id: &str, cx: &FxCtx) -> f32 {
fn b(e: &EffectInstance, id: &str) -> bool {
e.param(id).and_then(|p| p.value.as_bool()).unwrap_or(false)
}
+/// A section switch (missing in older projects = on).
+fn on(e: &EffectInstance, id: &str) -> bool {
+ e.param(id).and_then(|p| p.value.as_bool()).unwrap_or(true)
+}
+fn text<'e>(e: &'e EffectInstance, id: &str) -> &'e str {
+ match e.param(id).map(|p| &p.value) {
+ Some(ParamValue::Text(s)) => s,
+ _ => "",
+ }
+}
fn choice(e: &EffectInstance, id: &str) -> u32 {
match e.param(id).map(|p| &p.value) {
Some(ParamValue::Choice(c)) => *c,
@@ -828,28 +840,35 @@ fn key(img: &mut Image, e: &EffectInstance, cx: &FxCtx) {
}
fn lumetri(img: &mut Image, e: &EffectInstance, cx: &FxCtx) {
- let temp = f(e, "temperature", cx) / 100.0;
- let tint = f(e, "tint", cx) / 100.0;
- let exposure = 2f32.powf(f(e, "exposure", cx));
- let contrast = f(e, "contrast", cx) / 100.0;
- let hl = f(e, "highlights", cx) / 100.0;
- let sh = f(e, "shadows", cx) / 100.0;
- let wh = f(e, "whites", cx) / 100.0;
- let bl = f(e, "blacks", cx) / 100.0;
- let sat = f(e, "saturation", cx) / 100.0 * f(e, "creative_sat", cx) / 100.0;
- let vib = f(e, "vibrance", cx) / 100.0;
- let faded = f(e, "faded_film", cx) / 100.0;
+ let (basic_on, creative_on, vignette_on) = (on(e, "basic_on"), on(e, "creative_on"), on(e, "vignette_on"));
+ let input_lut = if basic_on { crate::luts::resolve(cx.project, text(e, "input_lut")) } else { None };
+ let bf = |id: &str| if basic_on { f(e, id, cx) } else { 0.0 };
+ let temp = bf("temperature") / 100.0;
+ let tint = bf("tint") / 100.0;
+ let exposure = 2f32.powf(bf("exposure"));
+ let contrast = bf("contrast") / 100.0;
+ let hl = bf("highlights") / 100.0;
+ let sh = bf("shadows") / 100.0;
+ let wh = bf("whites") / 100.0;
+ let bl = bf("blacks") / 100.0;
+ let sat = if basic_on { f(e, "saturation", cx) / 100.0 } else { 1.0 } * if creative_on { f(e, "creative_sat", cx) / 100.0 } else { 1.0 };
+ let vib = if creative_on { f(e, "vibrance", cx) / 100.0 } else { 0.0 };
+ let faded = if creative_on { f(e, "faded_film", cx) / 100.0 } else { 0.0 };
let st = color(e, "shadow_tint", cx);
let ht = color(e, "highlight_tint", cx);
- let va = f(e, "vignette_amount", cx);
+ let va = if vignette_on { f(e, "vignette_amount", cx) } else { 0.0 };
let vmid = f(e, "vignette_midpoint", cx) / 100.0;
let vround = f(e, "vignette_roundness", cx) / 100.0;
let vfeather = f(e, "vignette_feather", cx) / 100.0;
- let sharpen = f(e, "sharpen", cx) / 100.0;
+ let sharpen = if creative_on { f(e, "sharpen", cx) / 100.0 } else { 0.0 };
let gains = [1.0 + 0.35 * temp, 1.0 - 0.3 * tint, 1.0 - 0.35 * temp];
let (w, h) = (img.w as f32, img.h as f32);
let aspect = w / h;
img.map_rgb(|c, x, y| {
+ let c = match &input_lut {
+ Some(l) => dec(l.apply(enc(c))),
+ None => c,
+ };
// white balance + exposure in linear light
let lin = [c[0] * gains[0] * exposure, c[1] * gains[1] * exposure, c[2] * gains[2] * exposure];
let mut v = enc(lin);
@@ -880,9 +899,11 @@ fn lumetri(img: &mut Image, e: &EffectInstance, cx: &FxCtx) {
v = v.map(|q| q * (1.0 - 0.25 * faded) + 0.12 * faded);
}
// split tone
- let l2 = (0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2]).clamp(0.0, 1.0);
- for k in 0..3 {
- v[k] += (st[k] - 0.5) * 0.3 * (1.0 - l2) + (ht[k] - 0.5) * 0.3 * l2;
+ if creative_on {
+ let l2 = (0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2]).clamp(0.0, 1.0);
+ for k in 0..3 {
+ v[k] += (st[k] - 0.5) * 0.3 * (1.0 - l2) + (ht[k] - 0.5) * 0.3 * l2;
+ }
}
// saturation & vibrance
let l3 = 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];
@@ -1079,7 +1100,7 @@ mod tests {
use filmcraft_project::find_effect;
fn cx() -> FxCtx<'static> {
- FxCtx { t: Tick::ZERO, px_scale: 1.0, seconds: 0.0, timecode: "00:00:01:00", clip_name: "x" }
+ FxCtx { t: Tick::ZERO, px_scale: 1.0, seconds: 0.0, timecode: "00:00:01:00", clip_name: "x", project: None }
}
#[test]
@@ -1229,7 +1250,7 @@ fn wheel_rgb(v: Vec2) -> [f32; 3] {
}
/// Looks: our own procedural grades (no third-party LUTs), applied on display-encoded colour.
-fn apply_look(look: u32, c: [f32; 3]) -> [f32; 3] {
+pub fn apply_look(look: u32, c: [f32; 3]) -> [f32; 3] {
let l = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
let mix = |a: [f32; 3], b: [f32; 3], k: f32| [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k];
let s_curve = |v: f32, k: f32| {
@@ -1260,16 +1281,19 @@ fn apply_look(look: u32, c: [f32; 3]) -> [f32; 3] {
fn lumetri_advanced(img: &mut Image, e: &EffectInstance, cx: &FxCtx) {
const N: usize = 1024;
- let lut = |id: &str| curve_param(e, id).filter(|c| !is_identity_curve(c)).map(|c| curve_lut(&c, N));
+ let (creative_on, curves_on, wheels_on) = (on(e, "creative_on"), on(e, "curves_on"), on(e, "wheels_on"));
+ let lut = |id: &str| curve_param(e, id).filter(|c| curves_on && !is_identity_curve(c)).map(|c| curve_lut(&c, N));
let (luma_c, red_c, green_c, blue_c) = (lut("curve_luma"), lut("curve_red"), lut("curve_green"), lut("curve_blue"));
- let hue = |id: &str| curve_param(e, id).and_then(|c| hue_lut(&c, N));
+ let hue = |id: &str| curve_param(e, id).filter(|_| curves_on).and_then(|c| hue_lut(&c, N));
let (hvs, hvh, hvl, lvs, svs) = (hue("hue_vs_sat"), hue("hue_vs_hue"), hue("hue_vs_luma"), hue("luma_vs_sat"), hue("sat_vs_sat"));
- let look = choice(e, "look");
+ // Creative ▸ Look: a LUT ("Browse…" / built-in) takes precedence over the procedural menu
+ let look_lut = if creative_on { crate::luts::resolve(cx.project, text(e, "look_lut")) } else { None };
+ let look = if creative_on && look_lut.is_none() { choice(e, "look") } else { 0 };
let look_k = f(e, "look_intensity", cx) / 100.0;
let v2 = |id: &str| e.param(id).map(|p| p.vec2_at(cx.t)).unwrap_or_default();
let (ws, wm, wh) = (wheel_rgb(v2("wheel_shadows")), wheel_rgb(v2("wheel_midtones")), wheel_rgb(v2("wheel_highlights")));
let (ls, lm, lh) = (f(e, "wheel_shadows_l", cx) / 100.0, f(e, "wheel_midtones_l", cx) / 100.0, f(e, "wheel_highlights_l", cx) / 100.0);
- let wheels = ws.iter().chain(&wm).chain(&wh).any(|v| v.abs() > 1e-5) || ls.abs() + lm.abs() + lh.abs() > 1e-5;
+ let wheels = wheels_on && (ws.iter().chain(&wm).chain(&wh).any(|v| v.abs() > 1e-5) || ls.abs() + lm.abs() + lh.abs() > 1e-5);
let hsl_on = b(e, "hsl_on");
let any = luma_c.is_some()
|| red_c.is_some()
@@ -1281,6 +1305,7 @@ fn lumetri_advanced(img: &mut Image, e: &EffectInstance, cx: &FxCtx) {
|| lvs.is_some()
|| svs.is_some()
|| look > 0
+ || look_lut.is_some()
|| wheels
|| hsl_on;
if !any {
@@ -1300,7 +1325,10 @@ fn lumetri_advanced(img: &mut Image, e: &EffectInstance, cx: &FxCtx) {
};
img.map_rgb(|c, _, _| {
let mut v = enc(c);
- if look > 0 {
+ if let Some(l) = &look_lut {
+ let lk = l.apply(v);
+ v = [v[0] + (lk[0] - v[0]) * look_k, v[1] + (lk[1] - v[1]) * look_k, v[2] + (lk[2] - v[2]) * look_k];
+ } else if look > 0 {
let lk = apply_look(look, v);
v = [v[0] + (lk[0] - v[0]) * look_k, v[1] + (lk[1] - v[1]) * look_k, v[2] + (lk[2] - v[2]) * look_k];
}
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index f221e7f44..74e3e0b1a 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -14,6 +14,7 @@ pub mod effects;
pub mod graphic_clip;
pub mod graphics;
pub mod image;
+pub mod luts;
pub mod mixer;
pub mod plan;
pub mod preview;
@@ -114,7 +115,14 @@ fn render_seq(project: &Project, seq: &Sequence, t: Tick, opts: RenderOptions, s
}
let mt = item.source_time_at(t);
let mut adjusted = canvas.clone();
- let cx = effects::FxCtx { t: mt, px_scale: opts.scale, seconds: (t - item.start).seconds(), timecode: &tc, clip_name: &item.name };
+ let cx = effects::FxCtx {
+ t: mt,
+ px_scale: opts.scale,
+ seconds: (t - item.start).seconds(),
+ timecode: &tc,
+ clip_name: &item.name,
+ project: Some(project),
+ };
for e in item.effects.iter().filter(|e| e.def().is_some_and(|d| !d.intrinsic)) {
effects::apply(&mut adjusted, e, &cx);
}
@@ -256,7 +264,7 @@ pub(crate) fn item_layer(
};
let px_scale = layer.w as f32 / src_size.0.max(1) as f32;
if opts.effects {
- let cx = effects::FxCtx { t: mt, px_scale, seconds: (t - item.start).seconds(), timecode: tc, clip_name: &item.name };
+ let cx = effects::FxCtx { t: mt, px_scale, seconds: (t - item.start).seconds(), timecode: tc, clip_name: &item.name, project: Some(project) };
for e in item.effects.iter().filter(|e| e.def().is_some_and(|d| !d.intrinsic) && !filmcraft_project::graphic::is_layer(e)) {
effects::apply(&mut layer, e, &cx);
}
diff --git a/crates/render/src/luts.rs b/crates/render/src/luts.rs
new file mode 100644
index 000000000..aa2c29632
--- /dev/null
+++ b/crates/render/src/luts.rs
@@ -0,0 +1,172 @@
+//! LUT resolution for Lumetri (Input LUT, Creative Look) and the built-in LUTs.
+//!
+//! Lumetri stores a LUT reference as text:
+//! * `""` — none;
+//! * `lib:<id>` — a LUT in the project's LUT library (`Project::luts`, imported `.cube`/`.3dl`);
+//! * `builtin:<id>` — a LUT FilmCraft generates from code: camera log → Rec. 709 conversions
+//! (from the published curves in `filmcraft-color`; input is video-range normalised, as camera
+//! LUTs expect) and the procedural Creative looks.
+//!
+//! Parsed LUTs are cached by content, so a library LUT is parsed once however many clips use it.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, OnceLock};
+
+use filmcraft_color::{ColorSpace, Lut, Lut3d, LutFormat, Range};
+use filmcraft_project::Project;
+
+/// A built-in LUT: id, label, and how it is made.
+pub struct Builtin {
+ pub id: String,
+ pub label: String,
+ kind: BuiltinKind,
+}
+
+#[derive(Clone, Copy)]
+enum BuiltinKind {
+ LogTo709(ColorSpace),
+ Look(u32),
+}
+
+/// Built-in LUTs offered in the Input LUT menu (camera conversions) and the Look menu.
+pub fn builtins() -> &'static [Builtin] {
+ static B: OnceLock<Vec<Builtin>> = OnceLock::new();
+ B.get_or_init(|| {
+ let mut v: Vec<Builtin> = ColorSpace::ALL
+ .into_iter()
+ .filter(|c| c.is_log())
+ .map(|c| Builtin { id: format!("{}-to-rec709", c.id()), label: format!("{} to Rec. 709", c.label()), kind: BuiltinKind::LogTo709(c) })
+ .collect();
+ let looks = filmcraft_project::find_effect("lumetri")
+ .and_then(|d| d.param("look"))
+ .and_then(|p| if let filmcraft_project::ParamKind::Choice(o) = p.kind { Some(o) } else { None })
+ .unwrap_or(&[]);
+ for (i, name) in looks.iter().enumerate().skip(1) {
+ v.push(Builtin { id: format!("look-{}", slug(name)), label: (*name).to_string(), kind: BuiltinKind::Look(i as u32) });
+ }
+ v
+ })
+}
+
+/// The camera conversions only (Input LUT menu).
+pub fn input_builtins() -> impl Iterator<Item = &'static Builtin> {
+ builtins().iter().filter(|b| matches!(b.kind, BuiltinKind::LogTo709(_)))
+}
+
+fn slug(s: &str) -> String {
+ let mut o = String::new();
+ for c in s.chars() {
+ if c.is_ascii_alphanumeric() {
+ o.push(c.to_ascii_lowercase());
+ } else if !o.ends_with('-') {
+ o.push('-');
+ }
+ }
+ o.trim_matches('-').to_string()
+}
+
+impl Builtin {
+ /// Generate the LUT (33³; our own procedural work).
+ pub fn generate(&self) -> Lut {
+ let mut cube = match self.kind {
+ BuiltinKind::LogTo709(cs) => {
+ let t = filmcraft_color::InputTransform::new(cs, Range::Limited, &filmcraft_color::ColorPipeline::REC709, None);
+ Lut3d::from_fn(33, |c| t.convert(c).map(|v| filmcraft_color::linear_to_srgb(v.clamp(0.0, 1.0))))
+ }
+ BuiltinKind::Look(n) => Lut3d::from_fn(33, |c| crate::effects::apply_look(n, c).map(|v| v.clamp(0.0, 1.0))),
+ };
+ cube.title = format!("FilmCraft {}", self.label);
+ Lut::from_cube(cube)
+ }
+}
+
+fn cache() -> &'static Mutex<HashMap<String, Arc<Lut>>> {
+ static C: OnceLock<Mutex<HashMap<String, Arc<Lut>>>> = OnceLock::new();
+ C.get_or_init(Default::default)
+}
+
+fn cached(key: String, make: impl FnOnce() -> Option<Lut>) -> Option<Arc<Lut>> {
+ if let Some(l) = cache().lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
+ return Some(l.clone());
+ }
+ let l = Arc::new(make()?);
+ let mut c = cache().lock().unwrap_or_else(|e| e.into_inner());
+ if c.len() > 64 {
+ c.clear();
+ }
+ c.insert(key, l.clone());
+ Some(l)
+}
+
+/// Resolve a Lumetri LUT reference (see module docs). `None` for "" or unknown references.
+pub fn resolve(project: Option<&Project>, spec: &str) -> Option<Arc<Lut>> {
+ let spec = spec.trim();
+ if let Some(id) = spec.strip_prefix("builtin:") {
+ let b = builtins().iter().find(|b| b.id == id)?;
+ return cached(format!("builtin:{id}"), || Some(b.generate()));
+ }
+ let id = spec.strip_prefix("lib:")?;
+ let entry = project?.luts.iter().find(|l| l.id == id)?;
+ let key = format!("lib:{:016x}", hash(&entry.text));
+ let fmt = LutFormat::from_path(&format!("x.{}", entry.format));
+ cached(key, || Lut::parse(&entry.text, fmt).ok())
+}
+
+fn hash(s: &str) -> u64 {
+ // FNV-1a
+ let mut h = 0xcbf2_9ce4_8422_2325u64;
+ for b in s.as_bytes() {
+ h ^= *b as u64;
+ h = h.wrapping_mul(0x100_0000_01b3);
+ }
+ h ^ s.len() as u64
+}
+
+/// Human-readable name of a LUT reference (for panels).
+pub fn label(project: Option<&Project>, spec: &str) -> String {
+ if spec.is_empty() {
+ return "None".into();
+ }
+ if let Some(id) = spec.strip_prefix("builtin:") {
+ return builtins().iter().find(|b| b.id == id).map(|b| b.label.clone()).unwrap_or_else(|| id.to_string());
+ }
+ if let Some(id) = spec.strip_prefix("lib:") {
+ return project.and_then(|p| p.luts.iter().find(|l| l.id == id)).map(|l| l.name.clone()).unwrap_or_else(|| format!("{id} (missing)"));
+ }
+ spec.to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn builtins_generate_and_resolve() {
+ assert!(input_builtins().count() >= 9);
+ let b = builtins().iter().find(|b| b.id == "slog3-sgamut3cine-to-rec709").unwrap();
+ let l = b.generate();
+ // S-Log3 mid grey (code 420; the LUT sees video-range normalised values like the rest of
+ // Lumetri) → ≈ 18 % linear on the sRGB curve
+ let g = l.apply([(420.0 - 64.0) / 876.0; 3]);
+ assert!((g[0] - filmcraft_color::linear_to_srgb(0.18)).abs() < 0.03, "{g:?}");
+ assert!(resolve(None, "builtin:slog3-sgamut3cine-to-rec709").is_some());
+ assert!(resolve(None, "builtin:look-teal-orange").is_some());
+ assert!(resolve(None, "").is_none() && resolve(None, "lib:nope").is_none());
+ // a look LUT reproduces the procedural look
+ let lk = resolve(None, "builtin:look-teal-orange").unwrap();
+ let c = [0.3, 0.5, 0.7];
+ let (a, want) = (lk.apply(c), crate::effects::apply_look(1, c));
+ assert!((0..3).all(|k| (a[k] - want[k]).abs() < 0.01), "{a:?} vs {want:?}");
+ }
+
+ #[test]
+ fn library_luts_resolve_by_content() {
+ let mut p = Project::new("t");
+ let text = Lut::from_cube(Lut3d::from_fn(5, |c| [c[2], c[1], c[0]])).to_cube();
+ p.luts.push(filmcraft_project::ProjectLut { id: "lut1".into(), name: "Swap".into(), source_path: None, format: "cube".into(), text: text.into() });
+ let l = resolve(Some(&p), "lib:lut1").unwrap();
+ assert_eq!(l.apply([1.0, 0.0, 0.0]), [0.0, 0.0, 1.0]);
+ assert_eq!(label(Some(&p), "lib:lut1"), "Swap");
+ assert_eq!(label(Some(&p), "lib:x"), "x (missing)");
+ }
+}
diff --git a/crates/render/src/preview_tests.rs b/crates/render/src/preview_tests.rs
index 3acfb1ec5..c62608f60 100644
--- a/crates/render/src/preview_tests.rs
+++ b/crates/render/src/preview_tests.rs
@@ -225,7 +225,7 @@ fn effect_costs() {
for d in filmcraft_project::effect_defs().iter().filter(|d| d.kind == filmcraft_project::EffectKind::Video && !d.intrinsic) {
let mut img = crate::Image::filled(1920, 1080, [0.4, 0.5, 0.6, 1.0]);
let e = d.instance();
- let cx = FxCtx { t: Tick::ZERO, px_scale: 1.0, seconds: 0.0, timecode: "00:00:00:00", clip_name: "x" };
+ let cx = FxCtx { t: Tick::ZERO, px_scale: 1.0, seconds: 0.0, timecode: "00:00:00:00", clip_name: "x", project: None };
apply(&mut img, &e, &cx);
let t0 = std::time::Instant::now();
for _ in 0..3 {
diff --git a/crates/ui-egui/src/panels/lumetri.rs b/crates/ui-egui/src/panels/lumetri.rs
index 5032e5c82..a11febd98 100644
--- a/crates/ui-egui/src/panels/lumetri.rs
+++ b/crates/ui-egui/src/panels/lumetri.rs
@@ -51,8 +51,11 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
});
});
let set = |actions: &mut Actions, param: &str, v: Value| actions.push(json!({"clip": clip.0, "effect": idx, "param": param, "value": v}));
+ let mut sections: Vec<&'static str> = Vec::new();
+ let mut lut_actions: Vec<(&'static str, Value)> = Vec::new();
egui::ScrollArea::vertical().auto_shrink([false, false]).show(&mut bui, |ui| {
- if section(ui, app, "Basic Correction") {
+ if open_section(ui, app, &e, "Basic Correction", "basic_on", "basic", &mut sections) {
+ lut_combo(ui, app, &e, "input_lut", "Input LUT", true, &mut lut_actions);
sub(ui, &t, "Color");
slider(ui, &e, mt, "temperature", "Temperature", Some(Gradient::Temp), &t, &mut actions, clip, idx);
slider(ui, &e, mt, "tint", "Tint", Some(Gradient::Tint), &t, &mut actions, clip, idx);
@@ -69,7 +72,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
slider(ui, &e, mt, id, label, None, &t, &mut actions, clip, idx);
}
}
- if section(ui, app, "Creative") {
+ if open_section(ui, app, &e, "Creative", "creative_on", "creative", &mut sections) {
let look = match e.param("look").map(|p| &p.value) {
Some(ParamValue::Choice(c)) => *c as usize,
_ => 0,
@@ -83,7 +86,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let mut sel = look;
egui::ComboBox::from_id_salt("lumetri-look")
.selected_text(opts.get(look).copied().unwrap_or("None"))
- .width(ui.available_width() - 8.0)
+ .width((ui.available_width() - 40.0).max(60.0))
.show_ui(ui, |ui| {
for (i, o) in opts.iter().enumerate() {
if ui.selectable_value(&mut sel, i, *o).changed() {
@@ -92,13 +95,14 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
});
});
+ lut_combo(ui, app, &e, "look_lut", "Look LUT", false, &mut lut_actions);
slider(ui, &e, mt, "look_intensity", "Intensity", None, &t, &mut actions, clip, idx);
sub(ui, &t, "Adjustments");
for (id, label) in [("faded_film", "Faded Film"), ("sharpen", "Sharpen"), ("vibrance", "Vibrance"), ("creative_sat", "Saturation")] {
slider(ui, &e, mt, id, label, None, &t, &mut actions, clip, idx);
}
}
- if section(ui, app, "Curves") {
+ if open_section(ui, app, &e, "Curves", "curves_on", "curves", &mut sections) {
sub(ui, &t, "RGB Curves");
let key = egui::Id::new("lumetri-curve-channel");
let mut ch: usize = ui.data(|d| d.get_temp(key)).unwrap_or(0);
@@ -136,7 +140,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
curve_editor(ui, &e, id, true, Color32::WHITE, &t, &mut actions, clip, idx);
}
}
- if section(ui, app, "Color Wheels & Match") {
+ if open_section(ui, app, &e, "Color Wheels & Match", "wheels_on", "wheels", &mut sections) {
let w = ((ui.available_width() - 24.0) / 3.0).min(120.0);
ui.horizontal(|ui| {
for (id, lid, label) in [
@@ -151,12 +155,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
});
}
- if section(ui, app, "HSL Secondary") {
- let on = e.param("hsl_on").and_then(|p| p.value.as_bool()).unwrap_or(false);
- let mut v = on;
- if ui.checkbox(&mut v, "Enable key").changed() {
- set(&mut actions, "hsl_on", json!(v));
- }
+ if open_section(ui, app, &e, "HSL Secondary", "hsl_on", "hsl", &mut sections) {
sub(ui, &t, "Key");
slider(ui, &e, mt, "hsl_hue", "Hue", Some(Gradient::Hue), &t, &mut actions, clip, idx);
for (id, label) in [
@@ -189,7 +188,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
slider(ui, &e, mt, "hsl_sat", "Saturation", None, &t, &mut actions, clip, idx);
slider(ui, &e, mt, "hsl_hue_shift", "Hue Shift", Some(Gradient::Hue), &t, &mut actions, clip, idx);
}
- if section(ui, app, "Vignette") {
+ if open_section(ui, app, &e, "Vignette", "vignette_on", "vignette", &mut sections) {
for (id, label) in
[("vignette_amount", "Amount"), ("vignette_midpoint", "Midpoint"), ("vignette_roundness", "Roundness"), ("vignette_feather", "Feather")]
{
@@ -203,9 +202,81 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.ui.status = err.to_string();
}
}
+ for sec in sections {
+ if let Err(err) = app.session.execute("lumetri.setSection", json!({"clip": clip.0, "section": sec})) {
+ app.ui.status = err.to_string();
+ }
+ }
+ for (cmd, mut p) in lut_actions {
+ if p.get("browse").is_some() {
+ let Some(path) = app.hooks.pick_open_file.as_mut().and_then(|f| f("LUT", &["cube", "3dl"])) else { continue };
+ p = json!({"path": path});
+ }
+ p["clip"] = json!(clip.0);
+ if let Err(err) = app.session.execute(cmd, p) {
+ app.ui.status = err.to_string();
+ }
+ }
+}
+
+fn open_section(
+ ui: &mut egui::Ui,
+ app: &mut FilmcraftApp,
+ e: &EffectInstance,
+ name: &str,
+ param: &str,
+ sec: &'static str,
+ out: &mut Vec<&'static str>,
+) -> bool {
+ let on = e.param(param).and_then(|p| p.value.as_bool()).unwrap_or(param != "hsl_on");
+ let (open, toggled) = section(ui, app, name, on);
+ if toggled {
+ out.push(sec);
+ }
+ open
}
-fn section(ui: &mut egui::Ui, app: &mut FilmcraftApp, name: &str) -> bool {
+/// LUT menu: None, built-ins, the project's LUT library, Browse… (file dialog → `lut.import`).
+fn lut_combo(ui: &mut egui::Ui, app: &mut FilmcraftApp, e: &EffectInstance, param: &str, label: &str, input: bool, out: &mut Vec<(&'static str, Value)>) {
+ let t = app.tokens;
+ let cur = match e.param(param).map(|p| &p.value) {
+ Some(ParamValue::Text(s)) => s.clone(),
+ _ => String::new(),
+ };
+ let cmd: &'static str = if input { "lumetri.setInputLut" } else { "lumetri.setLook" };
+ let shown = filmcraft_render::luts::label(Some(&app.session.project), &cur);
+ let mut entries: Vec<(String, String)> = vec![(String::new(), "None".into())];
+ let builtins: Vec<&filmcraft_render::luts::Builtin> = if input {
+ filmcraft_render::luts::input_builtins().collect()
+ } else {
+ filmcraft_render::luts::builtins().iter().filter(|b| b.id.starts_with("look-")).collect()
+ };
+ entries.extend(builtins.into_iter().map(|b| (format!("builtin:{}", b.id), b.label.clone())));
+ entries.extend(app.session.project.luts.iter().map(|l| (format!("lib:{}", l.id), l.name.clone())));
+ let mut rect = Rect::NOTHING;
+ ui.horizontal(|ui| {
+ ui.add_sized(vec2(110.0, 20.0), egui::Label::new(egui::RichText::new(label).color(t.text_dim)));
+ let r = egui::ComboBox::from_id_salt(("lumetri-lut", param)).selected_text(shown).truncate().width((ui.available_width() - 40.0).max(60.0)).show_ui(
+ ui,
+ |ui| {
+ for (r, name) in &entries {
+ if ui.selectable_label(*r == cur, name).clicked() && *r != cur {
+ out.push((cmd, json!({"lut": r})));
+ }
+ }
+ ui.separator();
+ if ui.selectable_label(false, "Browse…").clicked() {
+ out.push((cmd, json!({"browse": true})));
+ }
+ },
+ );
+ rect = r.response.rect;
+ });
+ app.auto.add(&format!("lumetri.{param}"), rect, label);
+}
+
+/// A section header; returns (expanded, switch clicked). `on` is the section's enable switch.
+fn section(ui: &mut egui::Ui, app: &mut FilmcraftApp, name: &str, on: bool) -> (bool, bool) {
let t = app.tokens;
let key = format!("lumetri2:{name}");
let open = !app.ui.collapsed_fx.contains(&key) && (name == "Basic Correction" || app.ui.expanded_fx.contains(&key));
@@ -219,11 +290,16 @@ fn section(ui: &mut egui::Ui, app: &mut FilmcraftApp, name: &str) -> bool {
t.text_dim,
);
ui.painter().text(pos2(r.min.x + 20.0, r.center().y), Align2::LEFT_CENTER, name, Tokens::semibold(13.0), t.text);
- // toggle switch (visual; section bypass lands with per-section enables)
+ // enable switch (section bypass)
let sw = Rect::from_center_size(pos2(r.max.x - 18.0, r.center().y), vec2(26.0, 14.0));
- ui.painter().rect_filled(sw, 7.0, t.accent);
- ui.painter().circle_filled(pos2(sw.max.x - 7.0, sw.center().y), 5.0, Color32::WHITE);
+ let sw_resp = ui.interact(sw.expand(3.0), egui::Id::new(("lumetri-switch", name)), Sense::click());
+ ui.painter().rect_filled(sw, 7.0, if on { t.accent } else { Color32::from_rgb(0x55, 0x55, 0x55) });
+ ui.painter().circle_filled(pos2(if on { sw.max.x - 7.0 } else { sw.min.x + 7.0 }, sw.center().y), 5.0, Color32::WHITE);
+ app.auto.add(&format!("lumetri.switch.{name}"), sw.expand(3.0), &format!("{name} on/off"));
app.auto.add(&format!("lumetri.section.{name}"), r, name);
+ if sw_resp.clicked() {
+ return (open, true);
+ }
if resp.clicked() {
if open {
app.ui.collapsed_fx.push(key.clone());
@@ -233,7 +309,7 @@ fn section(ui: &mut egui::Ui, app: &mut FilmcraftApp, name: &str) -> bool {
app.ui.expanded_fx.push(key);
}
}
- open
+ (open, false)
}
fn sub(ui: &mut egui::Ui, t: &Tokens, name: &str) {
diff --git a/crates/ui-egui/tests/color_ui.rs b/crates/ui-egui/tests/color_ui.rs
new file mode 100644
index 000000000..091d9ab68
--- /dev/null
+++ b/crates/ui-egui/tests/color_ui.rs
@@ -0,0 +1,167 @@
+//! Headless UI tests of colour features: the Lumetri Color panel's LUT menus and section
+//! switches, Interpret Footage ▸ Color Management and the sequence colour settings, driven by
+//! automation id through the control channel.
+//!
+//! Set `FILMCRAFT_UI_SNAPSHOT_DIR=<dir>` to also render offscreen with wgpu and write `color-*.png`.
+
+#![allow(dead_code)]
+
+use std::sync::mpsc::{Sender, channel};
+
+use egui_kittest::Harness;
+use filmcraft_engine::Session;
+use filmcraft_ui_egui::FilmcraftApp;
+use filmcraft_ui_egui::control::ControlRequest;
+use serde_json::{Value, json};
+
+struct Driver {
+ harness: Harness<'static, FilmcraftApp>,
+ tx: Sender<ControlRequest>,
+ snapshots: Option<std::path::PathBuf>,
+}
+
+impl Driver {
+ fn demo() -> Self {
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ let (tx, rx) = channel();
+ let app = FilmcraftApp::new(session).with_control(rx);
+ let snapshots = std::env::var_os("FILMCRAFT_UI_SNAPSHOT_DIR").map(std::path::PathBuf::from);
+ let mut b = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000);
+ if snapshots.is_some() {
+ b = b.wgpu();
+ }
+ let harness = b.build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, snapshots };
+ d.frames(4);
+ d
+ }
+
+ fn frames(&mut self, n: usize) {
+ for _ in 0..n {
+ let ctx = self.harness.ctx.clone();
+ let mut raw = std::mem::take(self.harness.input_mut());
+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);
+ *self.harness.input_mut() = raw;
+ self.harness.step();
+ }
+ }
+
+ fn call(&mut self, method: &str, params: Value) -> Value {
+ let (req, reply) = ControlRequest::new(method, params.clone());
+ self.tx.send(req).unwrap();
+ for _ in 0..600 {
+ self.frames(1);
+ if let Ok(v) = reply.try_recv() {
+ return v;
+ }
+ }
+ panic!("no reply to {method} {params}");
+ }
+
+ fn ok(&mut self, method: &str, params: Value) -> Value {
+ let v = self.call(method, params.clone());
+ assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");
+ v["result"].clone()
+ }
+
+ fn exec(&mut self, command: &str, params: Value) -> Value {
+ self.ok("engine.execute", json!({"command": command, "params": params}))
+ }
+
+ fn click(&mut self, id: &str) {
+ self.ok("ui.click", json!({"id": id}));
+ self.frames(2);
+ }
+
+ fn element(&mut self, id: &str) -> Option<[f32; 4]> {
+ let v = self.ok("ui.elements", json!({"prefix": id}));
+ v.as_array()?.iter().find(|e| e["id"] == id).map(|e| {
+ let r = &e["rect"];
+ [r[0].as_f64().unwrap() as f32, r[1].as_f64().unwrap() as f32, r[2].as_f64().unwrap() as f32, r[3].as_f64().unwrap() as f32]
+ })
+ }
+
+ fn ids(&mut self, prefix: &str) -> Vec<String> {
+ let v = self.ok("ui.elements", json!({"prefix": prefix}));
+ v.as_array().unwrap().iter().filter_map(|e| e["id"].as_str().map(str::to_string)).collect()
+ }
+
+ /// Offscreen render of the window (or the bounding box of the elements under `prefix`).
+ fn snapshot(&mut self, name: &str, prefix: Option<&str>) {
+ let Some(dir) = self.snapshots.clone() else { return };
+ let crop = prefix.map(|p| {
+ let v = self.ok("ui.elements", json!({"prefix": p}));
+ let mut bb = [f32::MAX, f32::MAX, f32::MIN, f32::MIN];
+ for e in v.as_array().unwrap() {
+ let r = &e["rect"];
+ let (x, y, w, h) = (r[0].as_f64().unwrap() as f32, r[1].as_f64().unwrap() as f32, r[2].as_f64().unwrap() as f32, r[3].as_f64().unwrap() as f32);
+ bb = [bb[0].min(x), bb[1].min(y), bb[2].max(x + w), bb[3].max(y + h)];
+ }
+ bb
+ });
+ self.frames(2);
+ let img = match self.harness.render() {
+ Ok(i) => i,
+ Err(e) => {
+ eprintln!("snapshot {name} skipped: {e}");
+ return;
+ }
+ };
+ let ppp = img.width() as f32 / 1600.0;
+ let img = match crop {
+ Some(bb) => {
+ let x0 = ((bb[0] - 24.0) * ppp).max(0.0) as u32;
+ let y0 = ((bb[1] - 30.0) * ppp).max(0.0) as u32;
+ let x1 = (((bb[2] + 16.0) * ppp) as u32).min(img.width());
+ let y1 = (((bb[3] + 46.0) * ppp) as u32).min(img.height());
+ image::imageops::crop_imm(&img, x0, y0, x1 - x0, y1 - y0).to_image()
+ }
+ None => img,
+ };
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join(format!("{name}.png"));
+ img.save(&path).unwrap();
+ eprintln!("snapshot: {}", path.display());
+ }
+}
+
+/// Select the first clip on V1 and park the playhead on it.
+fn select_first_clip(d: &mut Driver) -> u64 {
+ let seq = d.exec("sequence.inspect", json!({}));
+ let first = seq["video"][0]["items"][0].clone();
+ let clip = first["clip"].as_u64().unwrap_or_else(|| panic!("no clip: {seq}"));
+ d.exec("timeline.select", json!({"clips": [clip]}));
+ clip
+}
+
+fn lumetri(d: &mut Driver, clip: u64) -> Value {
+ let seq = d.exec("sequence.inspect", json!({}));
+ let items = seq["video"][0]["items"].as_array().unwrap().clone();
+ let it = items.into_iter().find(|i| i["clip"] == clip).unwrap();
+ it["effects"].as_array().unwrap().iter().find(|e| e["effect"] == "lumetri").cloned().unwrap_or(Value::Null)
+}
+
+#[test]
+fn lumetri_lut_menus_and_section_switches() {
+ let mut d = Driver::demo();
+ d.ok("ui.set", json!({"workspace": "Color"}));
+ d.frames(3);
+ let clip = select_first_clip(&mut d);
+ d.exec("lumetri.setInputLut", json!({"lut": "builtin:slog3-sgamut3cine-to-rec709"}));
+ d.frames(3);
+ let ids = d.ids("lumetri.");
+ for id in ["lumetri.input_lut", "lumetri.switch.Basic Correction", "lumetri.switch.Creative", "lumetri.switch.Vignette"] {
+ assert!(ids.iter().any(|i| i == id), "{id} missing from {ids:?}");
+ }
+ d.click("lumetri.section.Creative");
+ assert!(d.ids("lumetri.").iter().any(|i| i == "lumetri.look_lut"));
+ d.snapshot("color-lumetri-panel", None);
+ // clicking a section switch bypasses the section (an undoable engine command)
+ d.click("lumetri.switch.Creative");
+ let e = lumetri(&mut d, clip);
+ assert_eq!(e["params"]["creative_on"]["value"], json!("Bool(false)"), "{e}");
+ d.exec("edit.undo", json!({}));
+ let e = lumetri(&mut d, clip);
+ assert_eq!(e["params"]["creative_on"]["value"], json!("Bool(true)"), "{e}");
+}