diff --git a/Cargo.lock b/Cargo.lock index 758a989..9637fb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -730,7 +730,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "lueur" -version = "0.21.0" +version = "0.22.0" dependencies = [ "anyhow", "axum", diff --git a/GLOSSARY.md b/GLOSSARY.md index d44999c..c8ba6e5 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -76,6 +76,14 @@ _Avoid_: Cache, library A change of shot from one frame to the next, found in a Track when it loads; the Look can fade cuts longer than the rest. _Avoid_: Scene change, transition +**Flash**: +A few frames (an explosion, lightning, a camera flash) much brighter than the frames around them, found in a Track when it loads; the Look's Flash guard tones them down. +_Avoid_: Spike, strobe + +**Black threshold**: +The darkness under which the Look fades colors out instead of showing them dim and muddy; the opposite of the minimum brightness. +_Avoid_: Black level, cutoff + **Look**: The user's color tuning applied at playback: brightness, saturation, smoothing, and how much of the screen each light reads. _Avoid_: Settings, profile diff --git a/apps/server/src/analyze.rs b/apps/server/src/analyze.rs index 08e19be..bd0b765 100644 --- a/apps/server/src/analyze.rs +++ b/apps/server/src/analyze.rs @@ -224,6 +224,7 @@ fn run(video: &Path, opts: &Options, hw: HwAccel) -> Result<(Track, Stats)> { edges, exposure: 1.0, cuts: Vec::new(), + flash_gains: Vec::new(), }; Ok((track, Stats { elapsed: start.elapsed().as_secs_f64(), hwaccel: hw })) } diff --git a/apps/server/src/color.rs b/apps/server/src/color.rs index 816be8d..15d2a8f 100644 --- a/apps/server/src/color.rs +++ b/apps/server/src/color.rs @@ -64,6 +64,14 @@ pub struct Look { pub auto_exposure: bool, /// How much grey, washed-out colors lean to a warm white (0 = none, 1 = fully). pub warm_greys: f32, + /// How much Flashes (a few frames much brighter than around them) are + /// toned down: 0 = as they are, 1 = back to the level around them. + pub flash_guard: f32, + /// Colors darker than this (luminance, linear light, after exposure) fade + /// out instead of showing dim and muddy (0 = off). + pub black_threshold: f32, + /// How fast they fade under the threshold: 1 is linear, higher is darker sooner. + pub black_falloff: f32, } impl Default for Look { @@ -81,6 +89,9 @@ impl Default for Look { centered_smoothing: true, auto_exposure: true, warm_greys: 0.5, + flash_guard: 0.5, + black_threshold: 0.0, + black_falloff: 2.0, } } } @@ -110,6 +121,14 @@ impl Look { for v in &mut c { *v = (l + (*v - l) * self.saturation).max(0.0) * self.brightness; } + // Under the Black threshold, fade out along a curve: 1 at the threshold, 0 at black. + let dim = luminance(c); + if self.black_threshold > 0.0 && dim < self.black_threshold { + let k = (dim / self.black_threshold).powf(self.black_falloff.max(0.1)); + for v in &mut c { + *v *= k; + } + } let max = c[0].max(c[1]).max(c[2]); if max > 1.0 { // Keep the hue instead of clipping each channel separately. @@ -160,4 +179,20 @@ mod tests { let c = look.apply([0.8, 0.4, 0.0]); assert!((c[0] - 1.0).abs() < 1e-6 && (c[1] - 0.5).abs() < 1e-6); } + + #[test] + fn under_the_black_threshold_colors_fade_out_with_no_step() { + let look = + Look { saturation: 1.0, warm_greys: 0.0, black_threshold: 0.02, black_falloff: 2.0, ..Default::default() }; + // Above: untouched. + assert_eq!(look.apply([0.1, 0.05, 0.02]), [0.1, 0.05, 0.02]); + // Across the threshold, no step; under it, darker and darker, down to black. + let lum = |v: f32| luminance(look.apply([v; 3])); + assert!((lum(0.0201) - lum(0.0199)).abs() < 1e-3); + assert!((lum(0.01) - 0.01 * 0.25).abs() < 1e-5, "{}", lum(0.01)); + assert!(lum(0.005) < lum(0.01) && lum(0.0) == 0.0); + // Off: dim colors pass. + let off = Look { black_threshold: 0.0, ..look }; + assert_eq!(off.apply([0.01; 3]), [0.01; 3]); + } } diff --git a/apps/server/src/render.rs b/apps/server/src/render.rs index 9eb5f8e..9f0f7d2 100644 --- a/apps/server/src/render.rs +++ b/apps/server/src/render.rs @@ -62,13 +62,8 @@ impl Renderer { Mapping::new(&self.channels, track.cols, track.rows, look) }); } - let half = smoothing_at(track, t, look); - match (edges, look.centered_smoothing) { - (false, true) => track.sample_centered(t, half, &mut self.grid), - (false, false) => track.sample(t, &mut self.grid), - (true, true) => track.sample_edges_centered(t, half, &mut self.grid), - (true, false) => track.sample_edges(t, &mut self.grid), - } + let half = look.centered_smoothing.then(|| smoothing_at(track, t, look)); + track.sample_for_lights(t, half, edges, look.flash_guard, &mut self.grid); self.mapping.as_ref().unwrap().colors(&self.grid, &mut self.colors); for c in self.colors.iter_mut() { c.1 = look.apply(c.1); @@ -241,6 +236,7 @@ mod tests { edges: Vec::new(), exposure: 1.0, cuts: Vec::new(), + flash_gains: Vec::new(), } } diff --git a/apps/server/src/track.rs b/apps/server/src/track.rs index 35b1097..62c7ea1 100644 --- a/apps/server/src/track.rs +++ b/apps/server/src/track.rs @@ -22,6 +22,12 @@ const VERSION: u8 = 2; const CUT_CHANGE: f32 = 0.08; /// …if it changes this many times more than the frames around it. const CUT_CONTRAST: f32 = 2.5; +/// A Flash lasts at most this long (seconds)… +const FLASH_MAX: f64 = 0.15; +/// …and is at least this many times as bright as the frame before it… +const FLASH_RATIO: f32 = 2.0; +/// …and at least this much brighter (mean linear luminance, 0 to 1). +const FLASH_RISE: f32 = 0.05; #[derive(Debug, Clone)] pub struct Track { @@ -44,6 +50,9 @@ pub struct Track { pub exposure: f32, /// Cuts between two shots, in seconds from the start, sorted; found by `load`. pub cuts: Vec, + /// Per frame, the gain that brings a Flash back to the level around it + /// (1 elsewhere); empty when the film has none. Found by `load`. + pub flash_gains: Vec, } impl Track { @@ -132,6 +141,7 @@ impl Track { edges: Vec::new(), exposure: 1.0, cuts: Vec::new(), + flash_gains: Vec::new(), }; let grids = count * t.frame_len(); if body.len() != grids + count * t.edge_cells() * 3 { @@ -146,6 +156,7 @@ impl Track { } t.exposure = t.measure_exposure(); t.cuts = t.find_cuts(); + t.flash_gains = t.find_flashes(); Ok(t) } @@ -198,6 +209,61 @@ impl Track { .collect() } + /// Flashes (an explosion, lightning, a camera flash): a few frames much + /// brighter than the frames before and after them. Each gets the gain that + /// brings it back to the brighter of those two; a bright scene that lasts + /// is no Flash. Empty when there is none. + fn find_flashes(&self) -> Vec { + let n = self.frame_count(); + let level: Vec = (0..n) + .map(|i| { + let cells = self.frame(i).as_chunks::<3>().0; + let sum: f32 = cells + .iter() + .map(|c| luminance([srgb_to_linear(c[0]), srgb_to_linear(c[1]), srgb_to_linear(c[2])])) + .sum(); + sum / cells.len().max(1) as f32 + }) + .collect(); + let longest = ((FLASH_MAX * self.fps as f64).round() as usize).max(1); + let mut gains = Vec::new(); + let mut i = 1; + while i < n { + let before = level[i - 1]; + let bright = |l: f32| l >= before * FLASH_RATIO && l - before >= FLASH_RISE; + if !bright(level[i]) { + i += 1; + continue; + } + // The Flash's frames, up to the first one back near the level before. + let end = (i..n).find(|&j| !bright(level[j])).unwrap_or(n); + if end < n && end - i <= longest { + if gains.is_empty() { + gains = vec![1.0; n]; + } + let around = before.max(level[end]); + for j in i..end { + gains[j] = (around / level[j]).min(1.0); + } + } + i = end.max(i + 1); + } + gains + } + + /// The cells the lights read at `t`, in linear light: the Edges or the + /// grid, averaged over `t ± half` with triangular weights when `half` is + /// set (a cut becomes a fade centered on it, with no delay), with Flashes toned + /// down by `flash_guard` (0: as they are, 1: back to the level around them). + pub fn sample_for_lights(&self, t: f64, half: Option, edges: bool, flash_guard: f32, out: &mut Vec) { + let (data, cells) = if edges { (&self.edges, self.edge_cells()) } else { (&self.frames, self.cells()) }; + let gains = Gains { gains: &self.flash_gains, guard: flash_guard.clamp(0.0, 1.0) }; + match half { + Some(half) => sample_cells_centered(data, cells, self.fps, t, half, &gains, out), + None => sample_cells(data, cells, self.fps, t, &gains, out), + } + } + /// How far `t` is from the nearest cut (seconds), if the film has any. pub fn to_nearest_cut(&self, t: f64) -> Option { let i = self.cuts.partition_point(|c| *c < t); @@ -243,34 +309,35 @@ impl Track { /// Grid in linear light at time `t` (seconds), interpolated between /// the two nearest analyzed frames. pub fn sample(&self, t: f64, out: &mut Vec) { - sample_cells(&self.frames, self.cells(), self.fps, t, out); + sample_cells(&self.frames, self.cells(), self.fps, t, &Gains::NONE, out); } - /// Like `sample`, for the Edges (empty on a version 1 Track). - pub fn sample_edges(&self, t: f64, out: &mut Vec) { - sample_cells(&self.edges, self.edge_cells(), self.fps, t, out); + pub fn frame(&self, i: usize) -> &[u8] { + let l = self.frame_len(); + &self.frames[i * l..(i + 1) * l] } +} - /// Like `sample`, averaged over `t ± half` seconds with triangular - /// weights: a cut becomes a fade centered on it, with no delay. - pub fn sample_centered(&self, t: f64, half: f64, out: &mut Vec) { - sample_cells_centered(&self.frames, self.cells(), self.fps, t, half, out); - } +/// Per-frame gains (the Flash guard), applied as strongly as `guard` says. +struct Gains<'a> { + gains: &'a [f32], + guard: f32, +} - /// Like `sample_centered`, for the Edges. - pub fn sample_edges_centered(&self, t: f64, half: f64, out: &mut Vec) { - sample_cells_centered(&self.edges, self.edge_cells(), self.fps, t, half, out); - } +impl Gains<'_> { + const NONE: Gains<'static> = Gains { gains: &[], guard: 0.0 }; - pub fn frame(&self, i: usize) -> &[u8] { - let l = self.frame_len(); - &self.frames[i * l..(i + 1) * l] + fn at(&self, frame: usize) -> f32 { + match self.gains.get(frame) { + Some(g) if self.guard > 0.0 => 1.0 - self.guard * (1.0 - g), + _ => 1.0, + } } } /// The cells of `data` (frames of `cells` sRGB colors) at `t`, in linear /// light, interpolated between the two nearest frames. -fn sample_cells(data: &[u8], cells: usize, fps: f32, t: f64, out: &mut Vec) { +fn sample_cells(data: &[u8], cells: usize, fps: f32, t: f64, gains: &Gains, out: &mut Vec) { out.clear(); let len = cells * 3; let n = data.len().checked_div(len).unwrap_or(0); @@ -283,11 +350,12 @@ fn sample_cells(data: &[u8], cells: usize, fps: f32, t: f64, out: &mut Vec) let j = (i + 1).min(n - 1); let k = (f - i as f64) as f32; let (a, b) = (&data[i * len..(i + 1) * len], &data[j * len..(j + 1) * len]); + let (ga, gb) = (gains.at(i), gains.at(j)); for c in 0..cells { let mut px = [0f32; 3]; for ch in 0..3 { - let va = srgb_to_linear(a[c * 3 + ch]); - let vb = srgb_to_linear(b[c * 3 + ch]); + let va = srgb_to_linear(a[c * 3 + ch]) * ga; + let vb = srgb_to_linear(b[c * 3 + ch]) * gb; px[ch] = va + (vb - va) * k; } out.push(px); @@ -297,11 +365,11 @@ fn sample_cells(data: &[u8], cells: usize, fps: f32, t: f64, out: &mut Vec) /// `sample_cells` averaged over `t ± half` seconds with triangular weights, /// down to zero at `± half`: the average changes smoothly with `half`, so a /// wider window shows no jump. -fn sample_cells_centered(data: &[u8], cells: usize, fps: f32, t: f64, half: f64, out: &mut Vec) { +fn sample_cells_centered(data: &[u8], cells: usize, fps: f32, t: f64, half: f64, gains: &Gains, out: &mut Vec) { let step = 1.0 / fps as f64; let m = (half / step).floor() as i32; if m < 1 { - return sample_cells(data, cells, fps, t, out); + return sample_cells(data, cells, fps, t, gains, out); } let mut acc = vec![[0f32; 3]; cells]; let mut total = 0.0; @@ -311,7 +379,7 @@ fn sample_cells_centered(data: &[u8], cells: usize, fps: f32, t: f64, half: f64, if w <= 0.0 { continue; } - sample_cells(data, cells, fps, t + i as f64 * step, &mut g); + sample_cells(data, cells, fps, t + i as f64 * step, gains, &mut g); for (a, c) in acc.iter_mut().zip(&g) { for ch in 0..3 { a[ch] += c[ch] * w; @@ -415,6 +483,7 @@ mod tests { edges: Vec::new(), exposure: 1.0, cuts: Vec::new(), + flash_gains: Vec::new(), }; let p = dir.join("t.lueur"); t.save(&p).unwrap(); @@ -439,11 +508,12 @@ mod tests { edges: Vec::new(), exposure: 1.0, cuts: Vec::new(), + flash_gains: Vec::new(), }; let mut g = Vec::new(); - cut.sample_centered(0.95, 0.3, &mut g); + cut.sample_for_lights(0.95, Some(0.3), false, 0.0, &mut g); assert!((g[0][0] - 0.5).abs() < 0.05, "{:?}", g[0]); - cut.sample_centered(0.75, 0.3, &mut g); + cut.sample_for_lights(0.75, Some(0.3), false, 0.0, &mut g); assert!(g[0][0] > 0.0 && g[0][0] < 0.2, "{:?}", g[0]); // Barcode: black then white. assert_eq!(cut.barcode(2), vec![[0; 3], [255; 3]]); @@ -472,6 +542,7 @@ mod tests { edges: edges.clone(), exposure: 1.0, cuts: Vec::new(), + flash_gains: Vec::new(), }; let p = dir.join("t.lueur"); t.save(&p).unwrap(); @@ -480,7 +551,7 @@ mod tests { assert_eq!(l.frames, t.frames); assert_eq!(l.edges, edges); let mut g = Vec::new(); - l.sample_edges(0.2, &mut g); + l.sample_for_lights(0.2, None, true, 0.0, &mut g); assert_eq!(g.len(), 6); assert!((g[0][0] - srgb_to_linear(100)).abs() < 1e-6, "{:?}", g[0]); @@ -520,6 +591,7 @@ mod tests { edges: Vec::new(), exposure: 1.0, cuts: Vec::new(), + flash_gains: Vec::new(), }; let cuts = t.find_cuts(); assert_eq!(cuts.len(), 2, "{cuts:?}"); @@ -530,4 +602,47 @@ mod tests { assert!((t.to_nearest_cut(0.0).unwrap() - 0.95).abs() < 1e-9); assert_eq!(Track { cuts: Vec::new(), ..t }.to_nearest_cut(1.0), None); } + + #[test] + fn a_short_flash_is_toned_down_a_lasting_bright_scene_is_not() { + // 24 fps, one cell: dark, a 2-frame white flash, dark, then a white scene that lasts. + let mut levels = vec![40u8; 24]; + levels.extend([255, 255]); + levels.extend(vec![40u8; 22]); + levels.extend(vec![255u8; 24]); + let t = Track { + fps: 24.0, + cols: 1, + rows: 1, + source_size: 0, + source: String::new(), + frames: levels.iter().flat_map(|v| [*v; 3]).collect(), + edge_cols: 0, + edge_rows: 0, + edges: Vec::new(), + exposure: 1.0, + cuts: Vec::new(), + flash_gains: Vec::new(), + }; + let gains = t.find_flashes(); + assert_eq!(gains.len(), levels.len()); + assert!(gains[24] < 0.1 && gains[25] < 0.1, "{:?}", &gains[22..28]); + assert!(gains[..24].iter().chain(&gains[26..]).all(|g| *g == 1.0)); + let t = Track { flash_gains: gains, ..t }; + let mut g = Vec::new(); + let dark = srgb_to_linear(40); + // Full guard: the flash is back to the level around it. + t.sample_for_lights(24.5 / 24.0, None, false, 1.0, &mut g); + assert!((g[0][0] - dark).abs() < 1e-3, "{:?}", g[0]); + // Half: halfway; off: the flash as it is. + t.sample_for_lights(24.5 / 24.0, None, false, 0.5, &mut g); + assert!((g[0][0] - (dark + 1.0) / 2.0).abs() < 0.02, "{:?}", g[0]); + t.sample_for_lights(24.5 / 24.0, None, false, 0.0, &mut g); + assert!(g[0][0] > 0.99); + // The lasting white scene stays white. + t.sample_for_lights(3.5, None, false, 1.0, &mut g); + assert!(g[0][0] > 0.99); + // No Flash in a film without any. + assert!(Track { frames: vec![40; 3 * 48], flash_gains: Vec::new(), ..t }.find_flashes().is_empty()); + } } diff --git a/apps/web/src/api.ts b/apps/web/src/api.ts index af76860..0361d93 100644 --- a/apps/web/src/api.ts +++ b/apps/web/src/api.ts @@ -12,6 +12,9 @@ export type Look = { centered_smoothing: boolean; auto_exposure: boolean; warm_greys: number; + flash_guard: number; + black_threshold: number; + black_falloff: number; }; export type SyncConfig = { learn_report_delay: boolean; jump_ms: number; drift_ms: number }; diff --git a/apps/web/src/views/look/index.tsx b/apps/web/src/views/look/index.tsx index 654bb45..9f59d4f 100644 --- a/apps/web/src/views/look/index.tsx +++ b/apps/web/src/views/look/index.tsx @@ -18,6 +18,9 @@ const DEFAULT: Look = { centered_smoothing: true, auto_exposure: true, warm_greys: 0.5, + flash_guard: 0.5, + black_threshold: 0, + black_falloff: 2, }; type NumKey = Exclude; @@ -28,6 +31,9 @@ const specs: Spec[] = [ { key: "brightness", label: "Brightness", hint: "Multiplies every color.", min: 0.1, max: 2, step: 0.05, fmt: (v) => `${Math.round(v * 100)}%` }, { key: "saturation", label: "Saturation", hint: "Above 100% makes colors pop, below washes them out.", min: 0, max: 2, step: 0.05, fmt: (v) => `${Math.round(v * 100)}%` }, { key: "warm_greys", label: "Warm greys", hint: "Grey, washed-out scenes lean to a warm white instead of a cold grey. Colorful scenes are untouched.", min: 0, max: 1, step: 0.05, fmt: (v) => (v ? `${Math.round(v * 100)}%` : "Off") }, + { key: "flash_guard", label: "Flash guard", hint: "Tones down flashes (explosions, lightning, camera flashes): a few frames much brighter than around them. lueur knows the film ahead, so it catches them with no delay. Easier on the eyes.", min: 0, max: 1, step: 0.05, fmt: (v) => (v ? `${Math.round(v * 100)}%` : "Off") }, + { key: "black_threshold", label: "Black threshold", hint: "Very dark colors fade out instead of showing dim and muddy. The opposite of Minimum brightness, which wins if both are set.", min: 0, max: 0.1, step: 0.005, fmt: (v) => (v ? `${(v * 100).toFixed(1)}%` : "Off") }, + { key: "black_falloff", label: "Black falloff", hint: "How fast colors under the Black threshold fade out: 1 is a straight fade, higher goes dark sooner.", min: 1, max: 4, step: 0.25, fmt: (v) => `×${v}` }, { key: "min_brightness", label: "Minimum brightness", hint: "Keeps a soft light during dark scenes instead of going black.", min: 0, max: 0.3, step: 0.01, fmt: (v) => (v ? `${Math.round(v * 100)}%` : "Off") }, { key: "smoothing_ms", label: "Smoothing", hint: "How long a change of color takes. Higher is calmer, lower follows the picture more closely.", min: 0, max: 2000, step: 50, fmt: (v) => (v ? `${v} ms` : "Off") }, { key: "cut_fade_ms", label: "Cut fade", hint: "How long a cut between two shots takes, centered on it. Keep Smoothing low to follow the picture, cuts still fade softly. Below Smoothing, cuts fade like the rest.", min: 0, max: 2000, step: 50, fmt: (v) => (v ? `${v} ms` : "Off") },