FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M8.5: Colour Match (Lumetri ▸ Color Wheels & Match ▸ Apply Match) with skin-tone protection
Brandon Thomas3dab45f45af8
diff --git a/ROADMAP.md b/ROADMAP.mdindex 07f802140..998f711f3 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -36,7 +36,7 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. Estimates are remaining| M5 | Effects, keyframes, GPU | 🟡 | ~60 CPU effects, 30 transitions, keyframes + value/velocity graphs, wgpu compositor | Full ~150-effect catalogue, WGSL parity for all, masks + tracking, adjustment layers, presets, Warp Stabilizer, Morph Cut | 30–45 || M6 | Export | ✅ | Own H.264 encoder (High/Main/Baseline, B-frames, VBR/CBR/2-pass) → MP4 + own AAC; ProRes, MJPEG, PNG, GIF, WAV; background jobs | Preset library, queue UI, smart render | 6–8 || M7 | Audio | 🟡 | Mixer graph (tracks → submixes → Mix, pre/post-fader inserts and sends, latency-compensated, sample-accurate, ~6× realtime for 24 tracks × 3 effects on one core), Audio Track Mixer + Audio Clip Mixer panels, track automation (Off/Read/Latch/Touch/Write, recorded live while playing, thinned to keyframes, timeline lanes with pen editing), solo/solo-safe, channel mapping basics, peak + BS.1770 loudness meters (match ffmpeg), DSP crate with 12 clip/track effects, Audio Gain (set/adjust/normalize), Constant Power / Constant Gain / Exponential Fade | Essential Sound, 5.1 panner and multichannel buses, voice-over record, effect editor windows (EQ curve), remaining effects (multiband, convolution reverb), clip-mixer automation recording | 6–9 |-| M8 | Colour | 🟡 | Lumetri: basic, creative + looks, RGB & hue curves, wheels, HSL secondary, vignette; basic scopes | LUT import UI, colour match, colour management + HDR (PQ/HLG, log, tone mapping) | 8–12 |+| M8 | Colour | 🟡 | Lumetri: basic, creative + looks, RGB & hue curves, wheels, HSL secondary, vignette, section bypass; Input LUT / Look LUT (.cube 1D/3D/shaper, .3dl; tetrahedral CPU + WGSL; project LUT library; built-in camera conversions); Colour Match (Oklab tonal-range statistics, skin protection, solved in Lumetri wheels); colour management: Rec. 709 / Rec. 2100 PQ / HLG working spaces + wide gamut, Interpret Footage colour space (S-Log3, V-Log, Canon Log 2/3, LogC3/4, Apple Log, D-Log from published specs), metadata auto-detect, BT.2390 tone mapping, gamut mapping, HDR export signalling (VUI/colr/mdcv/clli/SEI, ffprobe-verified); scopes incl. HDR nits waveform | Parade/histogram/HLS scopes, HDR-aware Lumetri maths, macOS EDR monitors, mastering metadata → tone-map peak, D-Log M (no published formula), HSL Secondary refine | 3–5 || M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), VP9 decoder (profiles 0–3, 8/10/12-bit, bit-exact on 50+ fixtures; WebM/MKV `V_VP9` and MP4 `vp09` import with key-frame-checked seeking), Matroska/WebM import (H.264/HEVC/VP9/ProRes/MJPEG + AAC/Opus/FLAC/MP3/Vorbis/PCM), Opus decoder (SILK/CELT/hybrid, 5.1/7.1 multistream; all RFC 8251 vectors range-exact; WebM/MKV/MP4) | VP9 frame threading, Ogg Opus files, AV1 (rav1d), DNxHR, MXF, hardware decode | 12–20 || M10 | Graphics & captions | 🟡 | Caption tracks (Subtitle/CEA-608/708/Teletext formats, track style), SRT/WebVTT/SCC import+export (frame-exact, property-tested), caption editing (add/split/merge/trim/move, sync-locked insert/extract), Text panel Captions tab, burn-in in Program monitor and export; text engine (`crates/text`: bundled + system fonts, harfrust shaping, bidi, line breaking, paragraph layout, glyph cache; 3-line 1080p title ≈ 0.15 ms warm); graphic clips with text + shape layers (fill, 2 strokes, background, shadow, keyframable transform), Type tool with on-monitor editing, shape/pen tools, Properties/Essential Graphics editor, align/distribute | Responsive design pins, rolls/crawls, per-character styles, motion graphics templates, MCC/STL/TTML, 608/708 embedding, speech-to-text | 12–18 || M11 | Interchange & project management | 🟡 | `.fcproj` schema versions + migrations, atomic saves, Save a Copy/Revert, auto-save ring + crash-recovery journal (Preferences ▸ Auto Save, recovery prompt), FCP7 XML, FCPXML, EDL, OTIO | Relink/offline, project manager, proxies | 8 |@@ -48,6 +48,8 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. Estimates are remaining## Log+- **2026-10-01 (night):** M8 colour: camera log curves and gamuts from published specs, colour-managed pipeline (PQ/HLG working spaces, Interpret Footage, BT.2390 tone mapping), HDR export signalling verified with ffprobe, LUTs (.cube/.3dl, tetrahedral CPU + WGSL, project library, Lumetri Input LUT / Look), Colour Match, Lumetri section bypass, HDR scopes.+- **2026-10-01 (later):** text engine (shaping, bidi, line breaking) + Type/Shape/Pen tools + graphic clips + graphics panel; Trim Monitor + dynamic trimming; Keyboard Shortcuts editor; audio mixer with automation. Fixed: MP4 muxer wrote unreadable all-empty sample tables; system font scan race.- **2026-10-01:** Audio mixing (M7.2/M7.5/M7.6 basics): mixer graph with submixes, sends, inserts and latency compensation; Audio Track / Clip Mixer panels; Latch/Touch/Write automation recorded live; timeline track keyframes; Audio Gain dialog.diff --git a/crates/engine/src/color.rs b/crates/engine/src/color.rsindex 80d9766fd..3128aa811 100644--- a/crates/engine/src/color.rs+++ b/crates/engine/src/color.rs@@ -9,7 +9,7 @@ use filmcraft_color::{ColorSpace, Lut, LutFormat, WorkingSpace};use filmcraft_project::{ClipId, ItemId, ItemKind, ParamValue, ProjectLut, TrackKind};use serde_json::{Value, json};-use crate::commands::{CommandSpec, always, bad, bool_p, clip_p, has_seq, item_p, str_p};+use crate::commands::{CommandSpec, always, bad, bool_p, clip_p, has_seq, item_p, str_p, time_p};use crate::{Result, Session};type Run = fn(&mut Session, &Value) -> Result<Value>;@@ -52,6 +52,14 @@ pub(crate) fn commands() -> Vec<CommandSpec> {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.applyMatch",+ "Apply Match",+ &[],+ r#"{"clip":id?,"referenceTime":ticks?|"referenceFrame":n?|"referenceTimecode":str?,"faceDetection":bool=true}"#,+ has_seq,+ apply_match,+ ),spec("lumetri.setSection","Toggle Lumetri Section",@@ -317,3 +325,59 @@ fn color_info(s: &mut Session, p: &Value) -> Result<Value> {"hdr": effective.is_some_and(|c| c.is_hdr()),}))}++/// Lumetri ▸ Color Wheels & Match ▸ Apply Match (see `filmcraft_render::color_match`): match the+/// clip at the playhead to the sequence frame at the reference time. Sets the three wheels, their+/// lightness and Basic saturation in one undo step.+fn apply_match(s: &mut Session, p: &Value) -> Result<Value> {+ let (clip, idx) = lumetri_clip(s, p, "lumetri.applyMatch")?;+ let seq_id = s.state.active_sequence.ok_or_else(|| bad("lumetri.applyMatch", "no active sequence"))?;+ let reference_t = time_p(s, p, "reference").ok_or_else(|| bad("lumetri.applyMatch", "need `referenceTime`, `referenceFrame` or `referenceTimecode`"))?;+ let skin = bool_p(p, "faceDetection").unwrap_or(true);+ let q = s.active_sequence().ok_or_else(|| bad("lumetri.applyMatch", "no active sequence"))?;+ let (_, it) = q.find_item(clip).ok_or_else(|| bad("lumetri.applyMatch", "no such clip"))?;+ let t = s.playhead().clamp(it.start, it.end() - filmcraft_time::Tick(1));+ if it.range().contains(reference_t) {+ return Err(bad("lumetri.applyMatch", "the reference frame is inside the clip being matched; pick a frame from another shot"));+ }+ let base = it.effects[idx].clone();+ // the current shot as Lumetri sees it: the clip with its Lumetri switched off+ let mut probe = (*s.project).clone();+ if let Some((_, pi)) = probe.sequence_mut(seq_id).and_then(|q| q.find_item_mut(clip)) {+ pi.effects[idx].enabled = false;+ }+ let provider = s.media.provider(s.project.clone(), s.services.clone());+ let opts = filmcraft_render::RenderOptions { scale: 0.25, working_output: true, ..Default::default() };+ let current =+ filmcraft_render::render_clip(&probe, seq_id, clip, t, opts, &provider).ok_or_else(|| bad("lumetri.applyMatch", "the clip has no picture"))?;+ let reference = filmcraft_render::render_sequence(&s.project, seq_id, reference_t, opts, &provider);+ let m = filmcraft_render::color_match::solve(¤t, &reference, &base, skin);+ let v2 = |a: [f32; 2]| ParamValue::Vec2(filmcraft_geom::Vec2::new(a[0] as f64, a[1] as f64));+ let values = [+ ("wheel_shadows", v2(m.shadows)),+ ("wheel_midtones", v2(m.midtones)),+ ("wheel_highlights", v2(m.highlights)),+ ("wheel_shadows_l", ParamValue::Float(m.lightness[0] as f64)),+ ("wheel_midtones_l", ParamValue::Float(m.lightness[1] as f64)),+ ("wheel_highlights_l", ParamValue::Float(m.lightness[2] as f64)),+ ("saturation", ParamValue::Float(m.saturation as f64)),+ ("wheels_on", ParamValue::Bool(true)),+ ];+ s.edit_sequence("Apply Match", |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.applyMatch", "no Lumetri"))?;+ for (k, v) in &values {+ let prm = e.params.entry(k.to_string()).or_insert_with(|| filmcraft_project::Param::new(v.clone()));+ prm.keyframes.clear();+ prm.value = v.clone();+ }+ e.enabled = true;+ Ok(())+ })?;+ Ok(json!({+ "clip": clip.0,+ "shadows": m.shadows, "midtones": m.midtones, "highlights": m.highlights,+ "lightness": m.lightness, "saturation": m.saturation,+ "distanceBefore": m.before, "distanceAfter": m.after,+ }))+}diff --git a/crates/engine/src/color_tests.rs b/crates/engine/src/color_tests.rsindex 205c6dd95..b6ba088aa 100644--- a/crates/engine/src/color_tests.rs+++ b/crates/engine/src/color_tests.rs@@ -131,6 +131,34 @@ fn set_param_fills_in_parameters_missing_from_old_instances() {s.execute("effects.setParam", json!({"clip": clip.0, "effect": "lumetri", "param": "vignette_on", "value": false})).unwrap();}+#[test]+fn apply_match_grades_the_clip_towards_the_reference() {+ let mut s = demo();+ let clip = pick_clip(&mut s);+ let q = s.active_sequence().unwrap();+ // reference: the middle of the last clip on V1 (a different shot)+ let other = q.video_tracks[0].items.iter().rfind(|i| i.id != clip).unwrap();+ let reference = other.start + filmcraft_time::Tick(other.duration.0 / 2);+ let r = s.execute("lumetri.applyMatch", json!({"referenceTime": reference.0, "faceDetection": true})).unwrap();+ let (before, after) = (r["distanceBefore"].as_f64().unwrap(), r["distanceAfter"].as_f64().unwrap());+ assert!(after < before * 0.8, "match improves the statistics distance: {r}");+ let q = s.active_sequence().unwrap();+ let e = q.find_item(clip).unwrap().1.effects.iter().find(|e| e.effect == "lumetri").unwrap().clone();+ let moved = ["wheel_shadows", "wheel_midtones", "wheel_highlights"]+ .iter()+ .any(|w| e.param(w).and_then(|p| p.value.as_vec2()).is_some_and(|v| v.x.abs() + v.y.abs() > 1e-3));+ assert!(moved, "{r}");+ // one undo step+ s.execute("edit.undo", json!({})).unwrap();+ let q = s.active_sequence().unwrap();+ let e = q.find_item(clip).unwrap().1.effects.iter().find(|e| e.effect == "lumetri").unwrap();+ assert_eq!(e.param("wheel_midtones").and_then(|p| p.value.as_vec2()).map(|v| v.x), Some(0.0));+ // a reference inside the clip itself is refused+ let inside = s.playhead();+ assert!(s.execute("lumetri.applyMatch", json!({"referenceTime": inside.0})).is_err());+ assert!(s.execute("lumetri.applyMatch", json!({})).is_err());+}+#[test]fn interpret_footage_and_sequence_colour_settings() {let mut s = demo();diff --git a/crates/render/src/color_match.rs b/crates/render/src/color_match.rsnew file mode 100644index 000000000..4ff6c86b3--- /dev/null+++ b/crates/render/src/color_match.rs@@ -0,0 +1,443 @@+//! Lumetri ▸ Color Wheels & Match ▸ **Apply Match**: grade the current clip so its colour matches+//! a reference frame. A documented, non-ML method:+//!+//! 1. Both frames are downsampled (≤ 96 px wide) and converted to **Oklab** (Björn Ottosson, 2020),+//! a perceptual space where L is lightness and (a, b) the colour axes.+//! 2. Each pixel is weighted into three **tonal ranges** by its L — shadows `smoothstep(0.55, 0.15,+//! L)`, highlights `smoothstep(0.45, 0.85, L)`, midtones the rest — and per range we take the+//! mean L, a and b. A global **chroma** statistic (mean √(a² + b²)) captures saturation.+//! 3. **Skin-tone protection** ("Face Detection"): pixels near the skin-tone line (Oklab hue+//! 20°–75°, chroma 0.02–0.2, L 0.25–0.92) are down-weighted (×0.2) in the colour statistics, so+//! faces do not drive the cast; afterwards the solved cast is scaled down until the mean hue of+//! the current frame's skin pixels moves by at most 8°.+//! 4. The match is solved **in Lumetri's own parameters** — the three colour wheels (x, y), their+//! lightness sliders and Basic saturation (10 unknowns) — by damped Gauss–Newton+//! (Levenberg–Marquardt) with numerical derivatives through the real Lumetri implementation+//! ([`crate::effects::apply`]), so the result is an ordinary, editable grade. A small penalty+//! on the parameters keeps the grade minimal when the statistics are already close.++use filmcraft_geom::Vec2;+use filmcraft_project::{EffectInstance, ParamValue};+use filmcraft_time::Tick;++use crate::Image;+use crate::effects::{FxCtx, apply};++/// sRGB-primaries linear RGB → Oklab.+pub fn oklab(c: [f32; 3]) -> [f32; 3] {+ let [r, g, b] = c.map(|v| v.max(0.0));+ let l = 0.412_221_47 * r + 0.536_332_55 * g + 0.051_445_995 * b;+ let m = 0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b;+ let s = 0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b;+ let (l, m, s) = (l.cbrt(), m.cbrt(), s.cbrt());+ [+ 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,+ 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,+ 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,+ ]+}++fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {+ let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);+ t * t * (3.0 - 2.0 * t)+}++/// Tonal-range weights (shadows, midtones, highlights) of an Oklab lightness.+pub fn tonal_weights(l: f32) -> [f32; 3] {+ let s = smoothstep(0.55, 0.15, l);+ let h = smoothstep(0.45, 0.85, l);+ [s, (1.0 - s - h).max(0.0), h]+}++/// How much a pixel looks like skin (0..1).+pub fn skin_weight(lab: [f32; 3]) -> f32 {+ let c = (lab[1] * lab[1] + lab[2] * lab[2]).sqrt();+ if !(0.02..=0.2).contains(&c) || !(0.25..=0.92).contains(&lab[0]) {+ return 0.0;+ }+ let h = lab[2].atan2(lab[1]).to_degrees();+ let d = if h < 20.0 {+ 20.0 - h+ } else if h > 75.0 {+ h - 75.0+ } else {+ 0.0+ };+ (1.0 - d / 10.0).clamp(0.0, 1.0)+}++/// Statistics of a frame: per tonal range (weight, mean L, mean a, mean b), mean chroma, and+/// the mean (a, b) of its skin pixels with their total weight.+#[derive(Clone, Debug, PartialEq)]+pub struct Stats {+ pub bands: [[f32; 4]; 3],+ pub chroma: f32,+ pub skin: [f32; 3],+}++/// Downsample to at most `max_w` pixels wide (box filter).+pub fn shrink(img: &Image, max_w: usize) -> Image {+ let mut out = img.clone();+ while out.w > max_w {+ out = out.downsample2();+ }+ out+}++pub fn stats(img: &Image, skin_protect: bool) -> Stats {+ let mut acc = [[0f64; 4]; 3];+ let mut chroma = (0f64, 0f64);+ let mut skin = [0f64; 3];+ for p in img.px.chunks_exact(4) {+ if p[3] <= 1e-3 {+ continue;+ }+ let lab = oklab([p[0] / p[3], p[1] / p[3], p[2] / p[3]]);+ let sk = skin_weight(lab);+ let cw = if skin_protect { 1.0 - 0.8 * sk } else { 1.0 } as f64;+ let w = tonal_weights(lab[0]);+ for k in 0..3 {+ let wk = w[k] as f64;+ acc[k][0] += wk;+ acc[k][1] += wk * lab[0] as f64;+ // colour means use the skin-protected weight (stored relative to wk)+ acc[k][2] += wk * cw * lab[1] as f64;+ acc[k][3] += wk * cw * lab[2] as f64;+ }+ chroma.0 += cw * ((lab[1] * lab[1] + lab[2] * lab[2]).sqrt()) as f64;+ chroma.1 += cw;+ skin[0] += sk as f64 * lab[1] as f64;+ skin[1] += sk as f64 * lab[2] as f64;+ skin[2] += sk as f64;+ }+ // colour weights per band for normalisation+ let mut cwsum = [0f64; 3];+ for p in img.px.chunks_exact(4) {+ if p[3] <= 1e-3 {+ continue;+ }+ let lab = oklab([p[0] / p[3], p[1] / p[3], p[2] / p[3]]);+ let cw = if skin_protect { 1.0 - 0.8 * skin_weight(lab) } else { 1.0 } as f64;+ let w = tonal_weights(lab[0]);+ for k in 0..3 {+ cwsum[k] += w[k] as f64 * cw;+ }+ }+ let n = img.px.len().max(4) as f64 / 4.0;+ let bands = std::array::from_fn(|k| {+ let w = acc[k][0].max(1e-9);+ let cw = cwsum[k].max(1e-9);+ [(acc[k][0] / n) as f32, (acc[k][1] / w) as f32, (acc[k][2] / cw) as f32, (acc[k][3] / cw) as f32]+ });+ let sw = skin[2].max(1e-9);+ Stats { bands, chroma: (chroma.0 / chroma.1.max(1e-9)) as f32, skin: [(skin[0] / sw) as f32, (skin[1] / sw) as f32, (skin[2] / n) as f32] }+}++/// Residuals between graded statistics and the reference's (bands weighted by how much of both+/// frames they cover).+fn residuals(cur: &Stats, refs: &Stats) -> Vec<f32> {+ let mut r = Vec::with_capacity(10);+ for k in 0..3 {+ let w = (cur.bands[k][0].min(refs.bands[k][0]) * 3.0).clamp(0.0, 1.0).sqrt();+ r.push((cur.bands[k][1] - refs.bands[k][1]) * w);+ r.push((cur.bands[k][2] - refs.bands[k][2]) * w * 2.0);+ r.push((cur.bands[k][3] - refs.bands[k][3]) * w * 2.0);+ }+ r.push((cur.chroma - refs.chroma) * 2.0);+ r+}++/// The solved grade.+#[derive(Clone, Debug, PartialEq)]+pub struct Match {+ pub shadows: [f32; 2],+ pub midtones: [f32; 2],+ pub highlights: [f32; 2],+ /// Lightness sliders (−100..100).+ pub lightness: [f32; 3],+ /// Basic Correction saturation (0..200).+ pub saturation: f32,+ /// Remaining residual norm (statistics distance) before and after.+ pub before: f32,+ pub after: f32,+}++// unknowns: [sx, sy, mx, my, hx, hy, sl, ml, hl, sat] (wheel offsets in −1..1, lightness/100, sat−1)+fn set_params(base: &EffectInstance, x: &[f32; 10]) -> EffectInstance {+ let mut e = base.clone();+ let mut put = |id: &str, v: ParamValue| {+ let prm = e.params.entry(id.to_string()).or_insert_with(|| filmcraft_project::Param::new(v.clone()));+ prm.value = v;+ };+ put("wheel_shadows", ParamValue::Vec2(Vec2::new(x[0] as f64, x[1] as f64)));+ put("wheel_midtones", ParamValue::Vec2(Vec2::new(x[2] as f64, x[3] as f64)));+ put("wheel_highlights", ParamValue::Vec2(Vec2::new(x[4] as f64, x[5] as f64)));+ put("wheel_shadows_l", ParamValue::Float(x[6] as f64 * 100.0));+ put("wheel_midtones_l", ParamValue::Float(x[7] as f64 * 100.0));+ put("wheel_highlights_l", ParamValue::Float(x[8] as f64 * 100.0));+ put("saturation", ParamValue::Float((1.0 + x[9] as f64) * 100.0));+ put("wheels_on", ParamValue::Bool(true));+ put("basic_on", ParamValue::Bool(true));+ e.enabled = true;+ e+}++fn graded_stats(img: &Image, base: &EffectInstance, x: &[f32; 10], skin_protect: bool) -> Stats {+ let mut g = img.clone();+ let cx = FxCtx { t: Tick::ZERO, px_scale: g.w as f32 / 1920.0, seconds: 0.0, timecode: "", clip_name: "", project: None };+ apply(&mut g, &set_params(base, x), &cx);+ stats(&g, skin_protect)+}++/// Solve the grade that matches `current` (the clip before its wheels) to `reference`. `base` is+/// the clip's Lumetri instance (its other settings are kept; wheels and saturation are solved).+pub fn solve(current: &Image, reference: &Image, base: &EffectInstance, skin_protect: bool) -> Match {+ let cur = shrink(current, 96);+ let refs = stats(&shrink(reference, 96), skin_protect);+ let mut x = [0f32; 10];+ let lambda_reg = 0.02f32;+ let cost = |x: &[f32; 10]| -> (Vec<f32>, f32) {+ let r = residuals(&graded_stats(&cur, base, x, skin_protect), &refs);+ let c = r.iter().map(|v| v * v).sum::<f32>() + lambda_reg * lambda_reg * x.iter().map(|v| v * v).sum::<f32>();+ (r, c)+ };+ let (mut r, mut c) = cost(&x);+ let before = c.sqrt();+ let mut mu = 1e-3f32;+ for _ in 0..12 {+ // numerical Jacobian (forward differences)+ let h = 1e-2f32;+ let mut jac = vec![[0f32; 10]; r.len()];+ for j in 0..10 {+ let mut xp = x;+ xp[j] += h;+ let (rp, _) = cost(&xp);+ for (i, row) in jac.iter_mut().enumerate() {+ row[j] = (rp[i] - r[i]) / h;+ }+ }+ // normal equations with Tikhonov regularisation and LM damping+ let mut a = [[0f64; 10]; 10];+ let mut g = [0f64; 10];+ for (i, row) in jac.iter().enumerate() {+ for p in 0..10 {+ g[p] += (row[p] * r[i]) as f64;+ for q in 0..10 {+ a[p][q] += (row[p] * row[q]) as f64;+ }+ }+ }+ for p in 0..10 {+ g[p] += (lambda_reg * lambda_reg * x[p]) as f64;+ a[p][p] += (lambda_reg * lambda_reg) as f64 + mu as f64 * (1.0 + a[p][p]);+ }+ let Some(dx) = solve_linear(a, g.map(|v| -v)) else { break };+ let mut xn = x;+ for p in 0..10 {+ xn[p] = (x[p] + dx[p] as f32).clamp(-1.0, 1.0);+ }+ let (rn, cn) = cost(&xn);+ if cn < c {+ x = xn;+ r = rn;+ let improved = c - cn;+ c = cn;+ mu = (mu * 0.3).max(1e-6);+ if improved < 1e-7 {+ break;+ }+ } else {+ mu *= 10.0;+ if mu > 1e4 {+ break;+ }+ }+ }+ if skin_protect {+ // limit the hue shift of the current frame's skin tones to 8°+ let s0 = stats(&cur, true);+ if s0.skin[2] > 0.002 {+ let hue = |s: &Stats| s.skin[1].atan2(s.skin[0]).to_degrees();+ let h0 = hue(&s0);+ let mut k = 1.0f32;+ for _ in 0..8 {+ let xs: [f32; 10] = std::array::from_fn(|i| if i < 6 { x[i] * k } else { x[i] });+ let s1 = graded_stats(&cur, base, &xs, true);+ let mut d = (hue(&s1) - h0).abs();+ if d > 180.0 {+ d = 360.0 - d;+ }+ if d <= 8.0 {+ break;+ }+ k *= 0.7;+ }+ for v in x.iter_mut().take(6) {+ *v *= k;+ }+ c = cost(&x).1;+ }+ }+ Match {+ shadows: [x[0], x[1]],+ midtones: [x[2], x[3]],+ highlights: [x[4], x[5]],+ lightness: [x[6] * 100.0, x[7] * 100.0, x[8] * 100.0],+ saturation: ((1.0 + x[9]) * 100.0).clamp(0.0, 200.0),+ before,+ after: c.sqrt(),+ }+}++/// Gaussian elimination with partial pivoting.+fn solve_linear(mut a: [[f64; 10]; 10], mut b: [f64; 10]) -> Option<[f64; 10]> {+ for col in 0..10 {+ let piv = (col..10).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs()))?;+ if a[piv][col].abs() < 1e-14 {+ return None;+ }+ a.swap(col, piv);+ b.swap(col, piv);+ for row in col + 1..10 {+ let f = a[row][col] / a[col][col];+ for k in col..10 {+ a[row][k] -= f * a[col][k];+ }+ b[row] -= f * b[col];+ }+ }+ let mut x = [0f64; 10];+ for i in (0..10).rev() {+ let s: f64 = (i + 1..10).map(|k| a[i][k] * x[k]).sum();+ x[i] = (b[i] - s) / a[i][i];+ }+ Some(x)+}++#[cfg(test)]+mod tests {+ use super::*;+ use filmcraft_project::find_effect;++ /// A synthetic frame: a lightness ramp with colour patches and a skin-tone block.+ fn frame(skin: bool) -> Image {+ let (w, h) = (192, 108);+ let mut img = Image::new(w, h);+ for y in 0..h {+ for x in 0..w {+ let t = x as f32 / w as f32;+ let mut c = [t * t, t * t * 0.9 + 0.02, t * 0.8 * t + 0.03];+ if y < h / 3 {+ c = [c[0] * 0.6, c[1] * 1.1, c[2] * 0.7]; // greenish band+ } else if y > 2 * h / 3 {+ c = [c[0] * 0.8, c[1] * 0.85, c[2] * 1.2]; // bluish band+ }+ if skin && (60..120).contains(&x) && (40..70).contains(&y) {+ c = [0.55, 0.32, 0.22]; // linear skin tone+ }+ let i = (y * w + x) * 4;+ img.px[i..i + 4].copy_from_slice(&[c[0], c[1], c[2], 1.0]);+ }+ }+ img+ }++ fn graded(img: &Image, base: &EffectInstance, x: [f32; 10]) -> Image {+ let mut g = img.clone();+ let cx = FxCtx { t: Tick::ZERO, px_scale: 0.1, seconds: 0.0, timecode: "", clip_name: "", project: None };+ apply(&mut g, &set_params(base, &x), &cx);+ g+ }++ #[test]+ fn oklab_reference_values() {+ // Ottosson's published table: white → (1, 0, 0); sRGB red → (0.6279, 0.2249, 0.1258)+ let w = oklab([1.0, 1.0, 1.0]);+ assert!((w[0] - 1.0).abs() < 1e-3 && w[1].abs() < 1e-3 && w[2].abs() < 1e-3, "{w:?}");+ let r = oklab([1.0, 0.0, 0.0]);+ assert!((r[0] - 0.6279).abs() < 2e-3 && (r[1] - 0.2249).abs() < 2e-3 && (r[2] - 0.1258).abs() < 2e-3, "{r:?}");+ let w = tonal_weights(0.1);+ assert!(w[0] > 0.99 && w[2] == 0.0);+ assert!(skin_weight(oklab([0.55, 0.32, 0.22])) > 0.9);+ assert_eq!(skin_weight(oklab([0.2, 0.3, 0.8])), 0.0);+ }++ #[test]+ fn matching_a_frame_to_itself_changes_nothing() {+ let base = find_effect("lumetri").unwrap().instance();+ let f = frame(false);+ let m = solve(&f, &f, &base, false);+ assert!(m.before < 1e-4, "{m:?}");+ for v in m.shadows.iter().chain(&m.midtones).chain(&m.highlights) {+ assert!(v.abs() < 0.02, "{m:?}");+ }+ assert!(m.lightness.iter().all(|v| v.abs() < 2.0) && (m.saturation - 100.0).abs() < 2.0, "{m:?}");+ }++ #[test]+ fn recovers_a_known_grade() {+ let base = find_effect("lumetri").unwrap().instance();+ let f = frame(false);+ // reference = the frame with a warm-highlights / cool-shadows grade and lifted shadows+ let truth = [-0.3, -0.2, 0.0, 0.1, 0.35, 0.15, 0.1, 0.0, -0.05, 0.2];+ let reference = graded(&f, &base, truth);+ let m = solve(&f, &reference, &base, false);+ eprintln!("known grade: {m:?}");+ assert!(m.after < m.before * 0.15, "{m:?}");+ // the matched render's statistics are close to the reference's+ let x = [+ m.shadows[0],+ m.shadows[1],+ m.midtones[0],+ m.midtones[1],+ m.highlights[0],+ m.highlights[1],+ m.lightness[0] / 100.0,+ m.lightness[1] / 100.0,+ m.lightness[2] / 100.0,+ m.saturation / 100.0 - 1.0,+ ];+ let out = stats(&graded(&f, &base, x), false);+ let want = stats(&reference, false);+ for k in 0..3 {+ for c in 1..4 {+ assert!((out.bands[k][c] - want.bands[k][c]).abs() < 0.02, "band {k} channel {c}: {:?} vs {:?}", out.bands[k], want.bands[k]);+ }+ }+ }++ #[test]+ fn skin_protection_limits_the_skin_hue_shift() {+ let base = find_effect("lumetri").unwrap().instance();+ let f = frame(true);+ // a strong green/teal cast reference+ let reference = graded(&f, &base, [-0.6, 0.5, -0.6, 0.5, -0.5, 0.4, 0.0, 0.0, 0.0, 0.0]);+ let hue = |img: &Image| {+ let s = stats(img, true);+ s.skin[1].atan2(s.skin[0]).to_degrees()+ };+ let h0 = hue(&f);+ let shift = |m: &Match| {+ let x = [+ m.shadows[0],+ m.shadows[1],+ m.midtones[0],+ m.midtones[1],+ m.highlights[0],+ m.highlights[1],+ m.lightness[0] / 100.0,+ m.lightness[1] / 100.0,+ m.lightness[2] / 100.0,+ m.saturation / 100.0 - 1.0,+ ];+ let d = (hue(&graded(&f, &base, x)) - h0).abs();+ if d > 180.0 { 360.0 - d } else { d }+ };+ let free = solve(&f, &reference, &base, false);+ let protected = solve(&f, &reference, &base, true);+ let (a, b) = (shift(&free), shift(&protected));+ eprintln!("skin hue shift: free {a:.1}°, protected {b:.1}°");+ assert!(b <= 8.5, "protected skin hue shift {b}° (unprotected {a}°)");+ assert!(a > b, "protection reduces the skin shift: {a}° vs {b}°");+ }+}diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex 80086fa7a..399b7b14b 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -10,6 +10,7 @@pub mod audio;pub mod audio_fx;pub mod blend;+pub mod color_match;pub mod colorman;pub mod effects;pub mod graphic_clip;@@ -294,6 +295,22 @@ pub(crate) fn item_layer(Some((placed, op, bl))}+/// The layer of one clip at timeline `t` with its effects applied, on a canvas the size of the+/// sequence output (transparent elsewhere), before opacity and blending. Used by Apply Match.+pub fn render_clip(+ project: &Project,+ seq_id: ItemId,+ clip: filmcraft_project::ClipId,+ t: Tick,+ opts: RenderOptions,+ sources: &dyn SourceProvider,+) -> Option<Image> {+ let seq = project.sequence(seq_id)?;+ let (_, item) = seq.find_item(clip)?;+ let tc = format_time(t, seq.settings.frame_rate, seq.settings.drop_frame, TimeDisplay::Timecode, seq.settings.sample_rate as i64);+ item_layer(project, seq, item, t, opts, sources, &tc).map(|(img, _, _)| img)+}+/// Largest power-of-two box decimation that keeps at least `target_w` pixels of width.fn decimation(have_w: f32, target_w: f32) -> usize {let mut n = 1usize;diff --git a/crates/ui-egui/src/panels/lumetri.rs b/crates/ui-egui/src/panels/lumetri.rsindex a11febd98..2dd2ce2ca 100644--- a/crates/ui-egui/src/panels/lumetri.rs+++ b/crates/ui-egui/src/panels/lumetri.rs@@ -154,6 +154,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {});}});+ match_controls(ui, app, &mut lut_actions);}if open_section(ui, app, &e, "HSL Secondary", "hsl_on", "hsl", &mut sections) {sub(ui, &t, "Key");@@ -567,3 +568,30 @@ fn color_wheel(ui: &mut egui::Ui, e: &EffectInstance, mt: Tick, id: &str, lid: &}let _ = StrokeKind::Inside;}++/// Color Match: reference frame (sequence timecode), Face Detection (skin-tone protection),+/// Apply Match (`lumetri.applyMatch`).+fn match_controls(ui: &mut egui::Ui, app: &mut FilmcraftApp, out: &mut Vec<(&'static str, Value)>) {+ let t = app.tokens;+ sub(ui, &t, "Color Match");+ let key = egui::Id::new("lumetri-match-ref");+ let fd_key = egui::Id::new("lumetri-match-face");+ let mut tc: String = ui.data(|d| d.get_temp(key)).unwrap_or_else(|| "00:00:00:00".to_string());+ let mut face: bool = ui.data(|d| d.get_temp(fd_key)).unwrap_or(true);+ ui.horizontal(|ui| {+ ui.add_sized(vec2(110.0, 20.0), egui::Label::new(egui::RichText::new("Reference").color(t.text_dim)));+ let r = ui.add(egui::TextEdit::singleline(&mut tc).desired_width(96.0));+ app.auto.add("lumetri.match.reference", r.rect, "Reference timecode");+ });+ let r = ui.checkbox(&mut face, "Face Detection (protect skin tones)");+ app.auto.add("lumetri.match.faceDetection", r.rect, "Face Detection");+ let b = ui.button("Apply Match");+ app.auto.add("lumetri.match.apply", b.rect, "Apply Match");+ if b.clicked() {+ out.push(("lumetri.applyMatch", json!({"referenceTimecode": tc, "faceDetection": face})));+ }+ ui.data_mut(|d| {+ d.insert_temp(key, tc);+ d.insert_temp(fd_key, face);+ });+}diff --git a/crates/ui-egui/tests/color_ui.rs b/crates/ui-egui/tests/color_ui.rsindex f4d92d61b..00547bcb2 100644--- a/crates/ui-egui/tests/color_ui.rs+++ b/crates/ui-egui/tests/color_ui.rs@@ -203,3 +203,31 @@ fn interpret_footage_and_sequence_color_dialogs_and_hdr_scopes() {let info = d.exec("media.colorInfo", json!({"item": item}));assert_eq!(info["override"], Value::Null, "{info}");}++#[test]+fn apply_match_from_the_color_wheels_section() {+ let mut d = Driver::demo();+ d.ok("ui.set", json!({"workspace": "Color"}));+ d.frames(3);+ let clip = select_first_clip(&mut d);+ d.exec("effects.apply", json!({"clips": [clip], "effect": "lumetri"}));+ d.frames(2);+ d.click("lumetri.section.Color Wheels & Match");+ for id in ["lumetri.match.reference", "lumetri.match.faceDetection", "lumetri.match.apply"] {+ assert!(d.ids("lumetri.match").iter().any(|i| i == id), "{id} missing");+ }+ // reference: a frame of the last V1 clip (another shot), typed into the field+ let seq = d.exec("sequence.inspect", json!({}));+ let last = seq["video"][0]["items"].as_array().unwrap().last().unwrap().clone();+ let frame = last["startFrame"].as_i64().unwrap() + last["durationFrames"].as_i64().unwrap() / 2;+ let r = d.exec("lumetri.applyMatch", json!({"referenceFrame": frame}));+ assert!(r["distanceAfter"].as_f64().unwrap() < r["distanceBefore"].as_f64().unwrap(), "{r}");+ d.frames(4);+ d.snapshot("color-apply-match", None);+ let e = lumetri(&mut d, clip);+ assert!(e["params"]["wheel_highlights"]["value"].as_str().unwrap() != "Vec2(Vec2 { x: 0.0, y: 0.0 })", "{e}");+ // the button runs the same command (here with the default reference inside the clip: refused, reported in the status line)+ d.click("lumetri.match.apply");+ let ui = d.ok("ui.inspect", json!({}));+ assert!(ui.to_string().contains("reference frame is inside"), "{ui}");+}diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 065034d25..bd9617bee 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -54,6 +54,18 @@ it shows. Dynamic trimming takes an explicit clock (seconds) so it is determinis{direction, slow?, clock}` (J/L), `trim.tick {clock}`, `trim.shuttleStop {clock?}` (K, one undo step),`trim.cancelDynamic` (Esc), `trim.playAround {clock, loop?}` (Space / Shift+K).+**Colour** (`crates/engine/src/color.rs`): `sequence.colorSettings {workingSpace: rec709|rec2100-pq|+rec2100-hlg, wideGamut, autoToneMap}`, `clip.interpretFootage {items?, colorSpace: auto|<id>}`,+`color.spaces`, `media.colorInfo {item}`; LUTs: `lut.import {path, name?}`, `lut.list`,+`lut.remove {id}`, `lut.export {lut, path, format?}`, `lumetri.setInputLut` / `lumetri.setLook+{clip?, lut: lib:<id>|builtin:<id>|"", path?}`, `lumetri.setSection {clip?, section, on?}`,+`lumetri.applyMatch {clip?, referenceTime|referenceFrame|referenceTimecode, faceDetection?}`. Without+params the menu entries open dialogs (ids `colorDialog.space.<id>`, `colorDialog.working.<id>`,+`colorDialog.wideGamut`, `colorDialog.autoToneMap`, `colorDialog.ok|cancel`). Lumetri panel ids:+`lumetri.input_lut`, `lumetri.look_lut`, `lumetri.switch.<section>`, `lumetri.section.<section>`,+`lumetri.match.*`; HDR scopes: `scopes.hdrWaveform`. `file.exportMedia {sdr: true}` exports an HDR+sequence as tone-mapped SDR.+**Keyboard shortcuts** (`crates/engine/src/shortcuts.rs`): `shortcuts.list {query?, panel?}`,`shortcuts.get`, `shortcuts.set {command, keys, panel?, add?, keepConflicts?}`, `shortcuts.clear`,`shortcuts.undo` / `shortcuts.redo`, `shortcuts.conflicts {platform?}`, `shortcuts.forKey {key}`,diff --git a/docs/testing.md b/docs/testing.mdindex a9fdb4546..32c9d18a0 100644--- a/docs/testing.md+++ b/docs/testing.md@@ -90,7 +90,10 @@ Each codec README has the full fixture matrix and the measured results.projects (demo-generator footage, bars, no media files) at 320×180 and renders one frame of eachthrough the CPU compositor: Motion transform + opacity, four blend modes (Multiply, Screen,Overlay, Difference), Gaussian Blur, Lumetri basic correction, Crop, Cross Dissolve at 50 %, Dip- to Black at 25 %, Wipe at 50 %, and Timecode / Clip Name burn-in text. Each frame is compared+ to Black at 25 %, Wipe at 50 %, Timecode / Clip Name burn-in text, graphic clips, and colour+ management: S-Log3/S-Gamut3.Cine footage interpreted into Rec. 709 (`log_to_rec709`) and+ Rec. 2100 PQ footage tone mapped into Rec. 709 (`hdr_tone_map`; the footage is demo frames+ re-encoded by the test's `Encoded` source). Each frame is comparedwith `crates/golden/goldens/<scene>.png` by `filmcraft_testkit::golden`:**PSNR ≥ 45 dB, max abs ≤ 12, 99th-percentile per-pixel max channel difference ≤ 2** (8-bitsRGB levels; `Tolerance::RENDER`). On failure the actual frame and a ×8 difference image go to@@ -134,6 +137,18 @@ over several frames, release). With `FILMCRAFT_UI_SNAPSHOT_DIR=<dir>` it also reoffscreen through wgpu (`Harness::render`) and writes `mixer-*.png`; this works without a visiblewindow (for example on a locked screen, where `ui.screenshot` cannot capture).+`crates/ui-egui/tests/color_ui.rs` drives colour features the same way (`color-*.png` snapshots):+Lumetri Input/Look LUT menus and section switches, the Interpret Footage ▸ Color Management and+Sequence Color Management dialogs, and the HDR scopes of a PQ sequence.++Colour science tests: `filmcraft-color` (curve round trips and published reference values per+camera log curve, BT.709/BT.2087 matrices, BT.2390 EETF, gamut mapping, LUT tetrahedral vs a+brute-force barycentric reference, `.cube`/`.3dl` round trips), `filmcraft-gpu`+(`gpu_lut_matches_cpu_tetrahedral`: WGSL vs CPU, max |Δ| ≈ 2e-7), `render::colorman`,+`render::color_match`, engine `color_tests.rs`, and `export::tests::hdr_exports_signal_pq_and_hlg`+(PQ/HLG exports read back by our demuxer and by ffprobe: `color_transfer`, `color_primaries`,+`color_space`, mastering display and content light side data).+Not covered headless: `ui.screenshot` (needs a real viewport), the wgpu monitor path (the harnessruns the CPU texture path), audio output, and wall-clock playback advance (kittest frames do notadvance real time). Use `Driver` for new UI regressions: `d.exec(command, params)`,