forge
Explore
Log in

Don't you dare go Hollow

Per-segment color transform core

Browse files at this commit

ac197e573f76e8ab02f7498dc8809157b377d7c9Ahmet Kaan GümüşParent: 8db8298
  • feat
    • per-segment color transform core
Show full message
✨ feat(engine): per-segment color transform core
crates/engine/src/color.rsadded+287 -0
@@ -0,0 +1,287 @@
1+//! Per-segment colour transform, applied engine-side on the decoded YUV samples
2+//! so that playback and export produce the same picture from the same numbers.
3+//!
4+//! The maths lives on YUV rather than RGB because every path already has YUV in
5+//! hand -- the decoders hand back I420 and the encoders take it -- and because
6+//! the four controls are each a straight per-sample affine there:
7+//!
8+//! * brightness and contrast move Y alone (contrast pivots on limited-range mid
9+//! grey, `(16 + 235) / 2`; brightness shifts by a fraction of the 219-code
10+//! luma range, so `1.0` lifts black to white),
11+//! * saturation scales U and V about 128, so `0.0` is exactly grey,
12+//! * tint is a warm/cool *temperature* axis, not a magenta/green one: U carries
13+//! blue-difference and V red-difference, so warm (positive) pushes V up and U
14+//! down by the same amount. A hue rotation would need a 2x2 matrix on (U,V)
15+//! and buys nothing a colourist asks for by name.
16+//!
17+//! Every control therefore collapses into three 256-entry lookup tables built
18+//! once per call, and the pixel loop is a byte indexing a table -- no float per
19+//! pixel, no chance of a `u8` wrap. Identity params short-circuit before the
20+//! tables exist, which is what makes "no colour set" byte-identical rather than
21+//! merely close.
22+
23+/// Limited-range mid grey; contrast pivots here so a change does not also
24+/// shift the picture's overall level.
25+const MID_Y: f32 = 125.5;
26+/// Codes between limited-range black (16) and white (235).
27+const LUMA_RANGE: f32 = 219.0;
28+/// Chroma codes a full-warm or full-cool tint moves U and V by. Picked so the
29+/// extreme is a strong grade rather than a broken picture.
30+const TINT_RANGE: f32 = 32.0;
31+
32+/// One segment's colour setting. Plain data with no invariants: out-of-range or
33+/// non-finite values are clamped where the tables are built, so a deserializer
34+/// can hand this over unchecked.
35+#[derive(Debug, Clone, Copy, PartialEq)]
36+pub struct ColorParams {
37+ /// -1..1, 0 = identity. 1.0 lifts limited-range black to white.
38+ pub brightness: f32,
39+ /// 0..2, 1 = identity. 0 flattens the picture to mid grey.
40+ pub contrast: f32,
41+ /// 0..2, 1 = identity. 0 is greyscale, 2 is doubled chroma.
42+ pub saturation: f32,
43+ /// -1..1, 0 = identity. Positive is warm (more red, less blue).
44+ pub tint: f32,
45+}
46+
47+impl Default for ColorParams {
48+ fn default() -> Self {
49+ Self {
50+ brightness: 0.0,
51+ contrast: 1.0,
52+ saturation: 1.0,
53+ tint: 0.0,
54+ }
55+ }
56+}
57+
58+impl ColorParams {
59+ /// Whether this setting is the do-nothing one. Compared exactly on purpose:
60+ /// anything that is not the identity value goes through the transform, and
61+ /// only a `true` here is allowed to skip it.
62+ pub fn is_identity(&self) -> bool {
63+ self.brightness == 0.0 && self.contrast == 1.0 && self.saturation == 1.0 && self.tint == 0.0
64+ }
65+}
66+
67+/// The three per-plane tables. Built once per frame (768 float ops against ~3 M
68+/// samples at 1080p, so the build never shows up in a measurement).
69+pub(crate) struct Lut {
70+ pub(crate) y: [u8; 256],
71+ pub(crate) u: [u8; 256],
72+ pub(crate) v: [u8; 256],
73+}
74+
75+impl Lut {
76+ pub(crate) fn new(params: &ColorParams) -> Self {
77+ let brightness = sane(params.brightness, 0.0).clamp(-1.0, 1.0) * LUMA_RANGE;
78+ let contrast = sane(params.contrast, 1.0).clamp(0.0, 2.0);
79+ let saturation = sane(params.saturation, 1.0).clamp(0.0, 2.0);
80+ let tint = sane(params.tint, 0.0).clamp(-1.0, 1.0) * TINT_RANGE;
81+
82+ let mut lut = Self {
83+ y: [0; 256],
84+ u: [0; 256],
85+ v: [0; 256],
86+ };
87+ for code in 0..256 {
88+ let f = code as f32;
89+ // Clamped to the full 0..255 swing, not to 16..235: content that is
90+ // already blacker than black or whiter than white keeps whatever a
91+ // grade leaves of it instead of being crushed by this pass.
92+ lut.y[code] = byte((f - MID_Y) * contrast + MID_Y + brightness);
93+ lut.u[code] = byte((f - 128.0) * saturation + 128.0 - tint);
94+ lut.v[code] = byte((f - 128.0) * saturation + 128.0 + tint);
95+ }
96+ lut
97+ }
98+}
99+
100+/// A parameter that survived a file or a UI edit; NaN and infinity fall back to
101+/// the identity value rather than blanking the picture.
102+fn sane(value: f32, fallback: f32) -> f32 {
103+ if value.is_finite() { value } else { fallback }
104+}
105+
106+fn byte(value: f32) -> u8 {
107+ value.round().clamp(0.0, 255.0) as u8
108+}
109+
110+/// Applies `params` in place to one planar 8-bit frame.
111+///
112+/// Per-sample, so the plane layout is free: I420 with `stride == width` (what
113+/// [`crate::convert`] and the export path use) or any other planar 8-bit YUV,
114+/// padding included. Interleaved chroma (NV12) is *not* this function's frame.
115+///
116+/// Identity params return without touching a byte.
117+pub fn apply_yuv(params: &ColorParams, y: &mut [u8], u: &mut [u8], v: &mut [u8]) {
118+ if params.is_identity() {
119+ return;
120+ }
121+ let lut = Lut::new(params);
122+ for s in y.iter_mut() {
123+ *s = lut.y[*s as usize];
124+ }
125+ for s in u.iter_mut() {
126+ *s = lut.u[*s as usize];
127+ }
128+ for s in v.iter_mut() {
129+ *s = lut.v[*s as usize];
130+ }
131+}
132+
133+#[cfg(test)]
134+mod tests {
135+ use super::*;
136+
137+ /// A gradient frame with every luma code and a chroma sweep, so a test that
138+ /// walks it has seen the whole table.
139+ fn frame(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
140+ let y = (0..w * h).map(|i| (i % 256) as u8).collect();
141+ let cw = w.div_ceil(2) * h.div_ceil(2);
142+ let u = (0..cw).map(|i| (i % 256) as u8).collect();
143+ let v = (0..cw).map(|i| (255 - i % 256) as u8).collect();
144+ (y, u, v)
145+ }
146+
147+ /// The charter invariant: no colour set means the exact same bytes, not
148+ /// bytes that round back to the same picture.
149+ #[test]
150+ fn identity_params_leave_every_byte_alone() {
151+ let (y, u, v) = frame(64, 48);
152+ let (mut gy, mut gu, mut gv) = (y.clone(), u.clone(), v.clone());
153+ apply_yuv(&ColorParams::default(), &mut gy, &mut gu, &mut gv);
154+ assert_eq!((gy, gu, gv), (y, u, v));
155+ }
156+
157+ #[test]
158+ fn zero_saturation_is_grey_everywhere() {
159+ let (mut y, mut u, mut v) = frame(64, 48);
160+ let before = y.clone();
161+ apply_yuv(
162+ &ColorParams {
163+ saturation: 0.0,
164+ ..Default::default()
165+ },
166+ &mut y,
167+ &mut u,
168+ &mut v,
169+ );
170+ assert_eq!(y, before, "saturation must not touch luma");
171+ assert!(u.iter().chain(v.iter()).all(|&c| c == 128), "not grey");
172+ }
173+
174+ /// Every extreme, on every code, stays inside `u8` -- a wrap would show as
175+ /// black specks in a blown highlight.
176+ #[test]
177+ fn extremes_clamp_instead_of_wrapping() {
178+ let extremes = [-1.0f32, 1.0, -100.0, 100.0, f32::NAN, f32::INFINITY];
179+ for b in extremes {
180+ for c in [0.0f32, 2.0, 50.0] {
181+ let lut = Lut::new(&ColorParams {
182+ brightness: b,
183+ contrast: c,
184+ saturation: c,
185+ tint: b,
186+ });
187+ // A wrap shows up as a curve that falls: every one of these is
188+ // non-decreasing in the input code, saturated ends included.
189+ assert!(
190+ lut.y.windows(2).all(|w| w[0] <= w[1]),
191+ "Y wrapped at {b}/{c}"
192+ );
193+ assert!(
194+ lut.u.windows(2).all(|w| w[0] <= w[1]),
195+ "U wrapped at {b}/{c}"
196+ );
197+ assert!(
198+ lut.v.windows(2).all(|w| w[0] <= w[1]),
199+ "V wrapped at {b}/{c}"
200+ );
201+ }
202+ }
203+ // The two saturating ends specifically: +219 on code 255 is 474, which
204+ // a wrapping cast would hand back as 218.
205+ let lut = Lut::new(&ColorParams {
206+ brightness: 1.0,
207+ ..Default::default()
208+ });
209+ assert_eq!(lut.y[255], 255, "full brightness must saturate, not wrap");
210+ assert_eq!(lut.y[0], 219, "black lifted by the whole luma range");
211+ let lut = Lut::new(&ColorParams {
212+ brightness: -1.0,
213+ ..Default::default()
214+ });
215+ assert_eq!(lut.y[255], 36, "255 - 219");
216+ }
217+
218+ #[test]
219+ fn brightness_is_monotonic_in_mean_luma() {
220+ let (y0, u0, v0) = frame(64, 48);
221+ let mut last = 0.0;
222+ for step in 0..=8 {
223+ let (mut y, mut u, mut v) = (y0.clone(), u0.clone(), v0.clone());
224+ apply_yuv(
225+ &ColorParams {
226+ brightness: -0.5 + step as f32 * 0.125,
227+ ..Default::default()
228+ },
229+ &mut y,
230+ &mut u,
231+ &mut v,
232+ );
233+ let mean = y.iter().map(|&s| s as f64).sum::<f64>() / y.len() as f64;
234+ assert!(mean >= last, "brighter setting darkened the frame");
235+ last = mean;
236+ }
237+ }
238+
239+ /// The tables are the float maths, sampled: this is what lets the pixel loop
240+ /// be a byte lookup. Same formula, computed per sample, must agree exactly.
241+ #[test]
242+ fn tables_agree_with_the_float_maths() {
243+ let params = ColorParams {
244+ brightness: 0.13,
245+ contrast: 1.4,
246+ saturation: 0.7,
247+ tint: -0.35,
248+ };
249+ let lut = Lut::new(&params);
250+ for code in 0..256 {
251+ let f = code as f32;
252+ let y = ((f - MID_Y) * 1.4 + MID_Y + 0.13 * LUMA_RANGE)
253+ .round()
254+ .clamp(0.0, 255.0) as u8;
255+ let u = ((f - 128.0) * 0.7 + 128.0 + 0.35 * TINT_RANGE)
256+ .round()
257+ .clamp(0.0, 255.0) as u8;
258+ let v = ((f - 128.0) * 0.7 + 128.0 - 0.35 * TINT_RANGE)
259+ .round()
260+ .clamp(0.0, 255.0) as u8;
261+ assert!(lut.y[code].abs_diff(y) <= 1, "Y {code}");
262+ assert!(lut.u[code].abs_diff(u) <= 1, "U {code}");
263+ assert!(lut.v[code].abs_diff(v) <= 1, "V {code}");
264+ }
265+ }
266+
267+ /// Not asserted: a debug build is an order of magnitude off and the number
268+ /// only means something in release. Run with
269+ /// `cargo test -p engine --release color:: -- --nocapture`.
270+ #[test]
271+ fn perf_1080p() {
272+ let (mut y, mut u, mut v) = frame(1920, 1080);
273+ let params = ColorParams {
274+ brightness: 0.1,
275+ contrast: 1.2,
276+ saturation: 1.3,
277+ tint: 0.2,
278+ };
279+ let runs = 30;
280+ let t = std::time::Instant::now();
281+ for _ in 0..runs {
282+ apply_yuv(&params, &mut y, &mut u, &mut v);
283+ }
284+ let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
285+ println!("color::apply_yuv 1920x1080: {ms:.3} ms/frame");
286+ }
287+}
crates/engine/src/convert.rsmodified+125 -0
@@ -29,9 +29,134 @@ pub fn i420_to_bgra(y: &[u8], u: &[u8], v: &[u8], width: usize, height: usize) -
29 out29 out
30 }30 }
31 31
32+/// The same conversion with a segment's colour grade folded in: the grade is
33+/// three table lookups per pixel inside the loop that was reading those samples
34+/// anyway, and measured free: 4.73 ms/frame against 4.74 for the ungraded
35+/// conversion, where grading a scratch copy of the planes first costs a further
36+/// 0.61 (1920x1080, release, `perf_1080p` below).
37+///
38+/// Identity params take the ungraded loop above, byte for byte.
39+pub fn i420_to_bgra_with(
40+ params: &crate::color::ColorParams,
41+ y: &[u8],
42+ u: &[u8],
43+ v: &[u8],
44+ width: usize,
45+ height: usize,
46+) -> Vec<u8> {
47+ if params.is_identity() {
48+ return i420_to_bgra(y, u, v, width, height);
49+ }
50+ let lut = crate::color::Lut::new(params);
51+ let cw = width.div_ceil(2);
52+ let mut out = vec![0u8; width * height * 4];
53+
54+ for row in 0..height {
55+ let y_row = row * width;
56+ let c_row = (row / 2) * cw;
57+ for col in 0..width {
58+ let c = lut.y[y[y_row + col] as usize] as i32 - 16;
59+ let ci = c_row + col / 2;
60+ let d = lut.u[u[ci] as usize] as i32 - 128;
61+ let e = lut.v[v[ci] as usize] as i32 - 128;
62+
63+ let r = ((298 * c + 409 * e + 128) >> 8).clamp(0, 255) as u8;
64+ let g = ((298 * c - 100 * d - 208 * e + 128) >> 8).clamp(0, 255) as u8;
65+ let b = ((298 * c + 516 * d + 128) >> 8).clamp(0, 255) as u8;
66+
67+ let o = (y_row + col) * 4;
68+ out[o] = b;
69+ out[o + 1] = g;
70+ out[o + 2] = r;
71+ out[o + 3] = 255;
72+ }
73+ }
74+ out
75+}
76+
32 #[cfg(test)]77 #[cfg(test)]
33 mod tests {78 mod tests {
34 use super::*;79 use super::*;
80+ use crate::color::ColorParams;
81+
82+ /// The render path's half of the charter invariant: an ungraded segment is
83+ /// the untouched converter, not a grade that happens to round back.
84+ #[test]
85+ fn identity_grade_converts_identically() {
86+ let y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
87+ let u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
88+ let v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
89+ assert_eq!(
90+ i420_to_bgra_with(&ColorParams::default(), &y, &u, &v, 64, 48),
91+ i420_to_bgra(&y, &u, &v, 64, 48)
92+ );
93+ }
94+
95+ /// Fused must equal grading the planes first and converting after -- that is
96+ /// what makes the export path (which grades a scratch copy before the
97+ /// encoder) and the render path show the same picture.
98+ #[test]
99+ fn fused_matches_grade_then_convert() {
100+ let params = ColorParams {
101+ brightness: 0.1,
102+ contrast: 1.3,
103+ saturation: 0.4,
104+ tint: 0.25,
105+ };
106+ let mut y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
107+ let mut u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
108+ let mut v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
109+ let fused = i420_to_bgra_with(&params, &y, &u, &v, 64, 48);
110+ crate::color::apply_yuv(&params, &mut y, &mut u, &mut v);
111+ assert_eq!(fused, i420_to_bgra(&y, &u, &v, 64, 48));
112+ }
113+
114+ /// Not asserted, printed: the numbers in `i420_to_bgra_with`'s docs come
115+ /// from here. `cargo test -p engine --release convert:: -- --nocapture`.
116+ #[test]
117+ fn perf_1080p() {
118+ let (w, h) = (1920usize, 1080usize);
119+ let y: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();
120+ let u: Vec<u8> = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect();
121+ let v: Vec<u8> = (0..w / 2 * h / 2).map(|i| (255 - i % 256) as u8).collect();
122+ let params = ColorParams {
123+ brightness: 0.1,
124+ contrast: 1.2,
125+ saturation: 1.3,
126+ tint: 0.2,
127+ };
128+ let runs = 20;
129+ let bench = |name: &str, mut f: Box<dyn FnMut()>| {
130+ let t = std::time::Instant::now();
131+ for _ in 0..runs {
132+ f();
133+ }
134+ println!(
135+ "{name} 1920x1080: {:.3} ms/frame",
136+ t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs)
137+ );
138+ };
139+ bench(
140+ "i420_to_bgra ",
141+ Box::new(|| {
142+ std::hint::black_box(i420_to_bgra(&y, &u, &v, w, h));
143+ }),
144+ );
145+ bench(
146+ "i420_to_bgra_with ",
147+ Box::new(|| {
148+ std::hint::black_box(i420_to_bgra_with(&params, &y, &u, &v, w, h));
149+ }),
150+ );
151+ bench(
152+ "copy + apply_yuv ",
153+ Box::new(|| {
154+ let (mut y, mut u, mut v) = (y.clone(), u.clone(), v.clone());
155+ crate::color::apply_yuv(&params, &mut y, &mut u, &mut v);
156+ std::hint::black_box((y, u, v));
157+ }),
158+ );
159+ }
35 160
36 #[test]161 #[test]
37 fn known_colors() {162 fn known_colors() {
crates/engine/src/lib.rsmodified+1 -0
@@ -3,6 +3,7 @@
3 pub mod ao;3 pub mod ao;
4 pub mod audio;4 pub mod audio;
5 pub mod clock;5 pub mod clock;
6+pub mod color;
6 pub mod convert;7 pub mod convert;
7 pub mod decode;8 pub mod decode;
8 pub mod demux;9 pub mod demux;