forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

color.rs287 lines, 10.7 KiBHistoryRawDownload
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.
25const MID_Y: f32 = 125.5;
26/// Codes between limited-range black (16) and white (235).
27const 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.
30const 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)]
36pub 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
47impl 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
58impl 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).
69pub(crate) struct Lut {
70 pub(crate) y: [u8; 256],
71 pub(crate) u: [u8; 256],
72 pub(crate) v: [u8; 256],
73}
74
75impl 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.
102fn sane(value: f32, fallback: f32) -> f32 {
103 if value.is_finite() { value } else { fallback }
104}
105
106fn 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.
117pub 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)]
134mod 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}