forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

color.rs1092 lines, 44.9 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 /// The RGB grade that runs before the four sliders: wheels, curves, LUT.
46 pub look: Look,
47}
48
49impl Default for ColorParams {
50 fn default() -> Self {
51 Self {
52 brightness: 0.0,
53 contrast: 1.0,
54 saturation: 1.0,
55 tint: 0.0,
56 look: Look::default(),
57 }
58 }
59}
60
61/// The most keys a clip's colour animation may hold ([`crate::project::Clip::color_keys`]).
62pub const MAX_COLOR_KEYS: usize = 256;
63
64/// One point of a clip's colour animation ([`crate::project::Clip::color_keys`]):
65/// the whole grade at source frame `at`, numbered as `in_frame` is. Between two
66/// keys each field moves with the earlier key's ease; the grade is rebuilt per
67/// frame from the interpolated numbers, so a frame between two keys is graded
68/// exactly as a constant grade of those numbers would be.
69#[derive(Debug, Clone, Copy, PartialEq)]
70pub struct ColorKey {
71 /// Source frame of the key.
72 pub at: u32,
73 /// The grade exactly at that frame.
74 pub params: ColorParams,
75 /// The easing of the segment that leaves this key.
76 pub ease: crate::transform::KeyEase,
77}
78
79impl crate::transform::Keyed for ColorKey {
80 fn at(&self) -> u32 {
81 self.at
82 }
83 fn ease(&self) -> crate::transform::KeyEase {
84 self.ease
85 }
86 fn placed(self, at: u32, ease: crate::transform::KeyEase) -> Self {
87 Self { at, ease, ..self }
88 }
89 fn mix(a: &Self, b: &Self, t: f32) -> Self {
90 let l = |x: f32, y: f32| x + (y - x) * t;
91 Self {
92 params: ColorParams {
93 brightness: l(a.params.brightness, b.params.brightness),
94 contrast: l(a.params.contrast, b.params.contrast),
95 saturation: l(a.params.saturation, b.params.saturation),
96 tint: l(a.params.tint, b.params.tint),
97 look: a.params.look,
98 },
99 ..*a
100 }
101 }
102}
103
104/// The grade the keys give at source frame `src`, or `base` with no keys. Keys
105/// animate the four sliders; the clip's [`Look`] (wheels, curves, LUT) is
106/// `base`'s and holds steady under them.
107pub fn evaluate_color(base: ColorParams, keys: &[ColorKey], src: f64) -> ColorParams {
108 crate::transform::sample(keys, src).map_or(base, |k| ColorParams { look: base.look, ..k.params })
109}
110
111impl ColorParams {
112 /// Whether this setting is the do-nothing one. Compared exactly on purpose:
113 /// anything that is not the identity value goes through the transform, and
114 /// only a `true` here is allowed to skip it.
115 pub fn is_identity(&self) -> bool {
116 self.sliders_identity() && self.look.is_identity()
117 }
118
119 /// Whether the four YUV sliders alone are at rest (the look may not be).
120 pub fn sliders_identity(&self) -> bool {
121 self.brightness == 0.0 && self.contrast == 1.0 && self.saturation == 1.0 && self.tint == 0.0
122 }
123}
124
125/// The three per-plane tables. Built once per frame (768 float ops against ~3 M
126/// samples at 1080p, so the build never shows up in a measurement).
127pub(crate) struct Lut {
128 pub(crate) y: [u8; 256],
129 pub(crate) u: [u8; 256],
130 pub(crate) v: [u8; 256],
131}
132
133impl Lut {
134 /// `full_range` says the samples span 0..255 instead of 16..235: the
135 /// sliders' pivot, span and clamp follow it.
136 pub(crate) fn new(params: &ColorParams, full_range: bool) -> Self {
137 let (mid_y, luma_range, lo, hi) = if full_range { (127.5, 255.0, 0.0, 255.0) } else { (MID_Y, LUMA_RANGE, f32::from(CODES.0), f32::from(CODES.1)) };
138 let brightness = sane(params.brightness, 0.0).clamp(-1.0, 1.0) * luma_range;
139 let contrast = sane(params.contrast, 1.0).clamp(0.0, 2.0);
140 let saturation = sane(params.saturation, 1.0).clamp(0.0, 2.0);
141 let tint = sane(params.tint, 0.0).clamp(-1.0, 1.0) * TINT_RANGE * (luma_range / LUMA_RANGE);
142
143 let mut lut = Self {
144 y: [0; 256],
145 u: [0; 256],
146 v: [0; 256],
147 };
148 for code in 0..256 {
149 let f = code as f32;
150 // Clamped to the valid codes 1..254, not to 16..235: content that
151 // is already blacker than black or whiter than white keeps whatever
152 // a grade leaves of it instead of being crushed by this pass, and
153 // nothing lands on 0 or 255, which Rec. 709 reserves for sync.
154 lut.y[code] = byte((f - mid_y) * contrast + mid_y + brightness, lo, hi);
155 lut.u[code] = byte((f - 128.0) * saturation + 128.0 - tint, lo, hi);
156 lut.v[code] = byte((f - 128.0) * saturation + 128.0 + tint, lo, hi);
157 }
158 lut
159 }
160}
161
162/// A parameter that survived a file or a UI edit; NaN and infinity fall back to
163/// the identity value rather than blanking the picture.
164fn sane(value: f32, fallback: f32) -> f32 {
165 if value.is_finite() { value } else { fallback }
166}
167
168/// The lowest and highest valid 8-bit code: 0 and 255 are reserved for sync
169/// (Rec. 709 / BT.1361), so no grade writes them. At 10 bits the reserved codes
170/// are 0..=3 and 1020..=1023 ([`WIDE_CODES`]).
171pub const CODES: (u8, u8) = (1, 254);
172/// [`CODES`] at 10 bits.
173pub const WIDE_CODES: (u16, u16) = (4, 1019);
174
175fn byte(value: f32, lo: f32, hi: f32) -> u8 {
176 value.round().clamp(lo, hi) as u8
177}
178
179/// The 10-bit tables of [`apply_yuv_wide`]: [`Lut::new`]'s arithmetic with every
180/// code-valued constant at four times its 8-bit value, so one grade reads the same
181/// picture at either depth.
182fn wide_tables(params: &ColorParams, full_range: bool) -> ([u16; 1024], [u16; 1024], [u16; 1024]) {
183 const SCALE: f32 = 4.0;
184 // Full range spans 0..=1023 whole; limited is 16..235 at four times 8-bit.
185 let (mid, span, lo, hi) = if full_range {
186 (511.5, 1023.0, 0.0, 1023.0)
187 } else {
188 (MID_Y * SCALE, LUMA_RANGE * SCALE, f32::from(WIDE_CODES.0), f32::from(WIDE_CODES.1))
189 };
190 let brightness = sane(params.brightness, 0.0).clamp(-1.0, 1.0) * span;
191 let contrast = sane(params.contrast, 1.0).clamp(0.0, 2.0);
192 let saturation = sane(params.saturation, 1.0).clamp(0.0, 2.0);
193 let tint = sane(params.tint, 0.0).clamp(-1.0, 1.0) * TINT_RANGE * (span / (LUMA_RANGE * SCALE));
194 let wide_byte = |value: f32| value.round().clamp(lo, hi) as u16;
195 let (mut y, mut u, mut v) = ([0u16; 1024], [0u16; 1024], [0u16; 1024]);
196 for code in 0..1024 {
197 let f = code as f32;
198 y[code] = wide_byte((f - mid) * contrast + mid + brightness);
199 u[code] = wide_byte((f - 512.0) * saturation + 512.0 - tint);
200 v[code] = wide_byte((f - 512.0) * saturation + 512.0 + tint);
201 }
202 (y, u, v)
203}
204
205/// [`apply_yuv`] for one planar 10-bit frame (16-bit samples at 10-bit scale). The
206/// same four controls as the 8-bit path, so a 10-bit export's grade is the grade
207/// the preview shows, at the precision of the file.
208pub fn apply_yuv_wide(params: &ColorParams, y: &mut [u16], u: &mut [u16], v: &mut [u16], width: usize, full_range: bool) {
209 if params.is_identity() {
210 return;
211 }
212 if let Some(stage) = Stage::new(&params.look) {
213 stage.run(y, u, v, width, Codes::new(4.0, 1023, full_range));
214 }
215 if params.sliders_identity() {
216 return;
217 }
218 let (ty, tu, tv) = wide_tables(params, full_range);
219 for s in y.iter_mut() {
220 *s = ty[usize::from(*s).min(1023)];
221 }
222 for s in u.iter_mut() {
223 *s = tu[usize::from(*s).min(1023)];
224 }
225 for s in v.iter_mut() {
226 *s = tv[usize::from(*s).min(1023)];
227 }
228}
229
230/// Applies `params` in place to one planar 8-bit frame.
231///
232/// Planar 8-bit YUV with `stride == width`: 4:2:0 (what [`crate::convert`] and
233/// the export path use), 4:2:2 or 4:4:4, told apart by the chroma planes' size.
234/// Interleaved chroma (NV12) is *not* this function's frame.
235///
236/// Identity params return without touching a byte. `width` is the luma
237/// plane's (stride == width): the look's RGB stage pairs each luma sample with
238/// its chroma, which the four YUV sliders never need.
239pub fn apply_yuv(params: &ColorParams, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize, full_range: bool) {
240 if params.is_identity() {
241 return;
242 }
243 if let Some(stage) = Stage::new(&params.look) {
244 stage.run(y, u, v, width, Codes::new(1.0, 255, full_range));
245 }
246 if params.sliders_identity() {
247 return;
248 }
249 let lut = Lut::new(params, full_range);
250 for s in y.iter_mut() {
251 *s = lut.y[*s as usize];
252 }
253 for s in u.iter_mut() {
254 *s = lut.u[*s as usize];
255 }
256 for s in v.iter_mut() {
257 *s = lut.v[*s as usize];
258 }
259}
260
261// -- the look: lift/gamma/gain wheels, RGB curves and a .cube LUT -------------
262//
263// These three live in R'G'B' rather than YUV, because each is defined per
264// red, green and blue channel. The stage converts a sample to Rec. 709
265// non-linear R'G'B' in 0..1 (limited-range codes, the matrix every SDR export
266// is tagged with), runs wheels -> curves -> LUT, and converts back. The order is
267// the grading suites' own: the wheels balance the picture, the curves shape it,
268// the LUT is the look laid over the balanced shot, and the four YUV sliders
269// after them trim the result.
270//
271// The wheels and curves are both per-channel functions of one value, so they
272// fold into one 4097-entry table per channel built once per frame; only the
273// LUT is evaluated per pixel. A neutral look builds no stage at all, which keeps
274// "nothing set" byte-identical.
275
276/// The most points one curve may hold.
277pub const MAX_CURVE_POINTS: usize = 16;
278
279/// The wheel and curve channels, in the order [`Wheels`] and [`Look::curves`] hold them.
280pub const CHANNELS: [&str; 4] = ["master", "red", "green", "blue"];
281
282/// Lift, gamma and gain: each a master offset and a red, green and blue one, all
283/// -1..1 with 0 neutral. Index 0 is master, then red, green, blue
284/// ([`CHANNELS`]). A channel's amount is its own plus the master's, clamped.
285///
286/// * lift raises (or lowers) the blacks and leaves white where it is: 1.0 puts
287/// black at half grey,
288/// * gamma bends the mid-tones and leaves both ends: 1.0 is an exponent of 0.5
289/// (brighter), -1.0 an exponent of 2 (darker),
290/// * gain scales the whole channel from black: 1.0 doubles it, -1.0 is black.
291#[derive(Debug, Clone, Copy, PartialEq, Default)]
292pub struct Wheels {
293 pub lift: [f32; 4],
294 pub gamma: [f32; 4],
295 pub gain: [f32; 4],
296}
297
298impl Wheels {
299 pub fn is_identity(&self) -> bool {
300 self.lift.iter().chain(&self.gamma).chain(&self.gain).all(|&v| v == 0.0)
301 }
302
303 /// Channel `c` (0 red, 1 green, 2 blue) of `x` through the three wheels.
304 fn eval(&self, c: usize, x: f32) -> f32 {
305 let amt = |w: &[f32; 4]| (sane(w[0], 0.0) + sane(w[c + 1], 0.0)).clamp(-1.0, 1.0);
306 let (lift, gamma, gain) = (amt(&self.lift) * 0.5, amt(&self.gamma), amt(&self.gain));
307 let v = (x + lift * (1.0 - x)) * (1.0 + gain);
308 v.clamp(0.0, 1.0).powf(2f32.powf(-gamma))
309 }
310}
311
312/// One curve: up to [`MAX_CURVE_POINTS`] points (input, output), both 0..1,
313/// inputs strictly increasing, joined by a monotone cubic (Fritsch-Carlson), so
314/// a curve through rising points never dips and never overshoots. Ends the
315/// points leave open are pinned: no point at input 0 means (0, 0) is one, no
316/// point at input 1 means (1, 1) is. No points, or points all on the diagonal,
317/// is the neutral curve.
318#[derive(Debug, Clone, Copy, PartialEq)]
319pub struct Curve {
320 len: u8,
321 pts: [[f32; 2]; MAX_CURVE_POINTS],
322}
323
324impl Default for Curve {
325 fn default() -> Self {
326 Self { len: 0, pts: [[0.0; 2]; MAX_CURVE_POINTS] }
327 }
328}
329
330impl Curve {
331 /// A curve through `points`, or why they cannot be one.
332 pub fn new(points: &[[f32; 2]]) -> Result<Self, String> {
333 if points.len() > MAX_CURVE_POINTS {
334 return Err(format!("a curve holds at most {MAX_CURVE_POINTS} points, not {}", points.len()));
335 }
336 let mut c = Self::default();
337 for (i, p) in points.iter().enumerate() {
338 if !p.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) {
339 return Err(format!("curve point {i} ({}, {}) is outside 0..1", p[0], p[1]));
340 }
341 if i > 0 && p[0] <= points[i - 1][0] {
342 return Err(format!("curve point {i}: inputs must strictly increase"));
343 }
344 c.pts[i] = *p;
345 }
346 c.len = points.len() as u8;
347 Ok(c)
348 }
349
350 pub fn points(&self) -> &[[f32; 2]] {
351 &self.pts[..usize::from(self.len)]
352 }
353
354 pub fn is_identity(&self) -> bool {
355 self.points().iter().all(|p| p[0] == p[1])
356 }
357
358 /// The knots the spline runs through, the pinned ends included.
359 fn knots(&self) -> Vec<[f32; 2]> {
360 let mut k = self.points().to_vec();
361 if k.first().is_none_or(|p| p[0] > 0.0) {
362 k.insert(0, [0.0, 0.0]);
363 }
364 if k.last().is_none_or(|p| p[0] < 1.0) {
365 k.push([1.0, 1.0]);
366 }
367 k
368 }
369
370 /// The curve sampled at `n` evenly spaced inputs over 0..1.
371 pub fn sampled(&self, n: usize) -> Vec<f32> {
372 let k = self.knots();
373 let m = tangents(&k);
374 let mut seg = 0;
375 (0..n)
376 .map(|i| {
377 let x = i as f32 / (n - 1) as f32;
378 while seg + 2 < k.len() && x > k[seg + 1][0] {
379 seg += 1;
380 }
381 let ([x0, y0], [x1, y1]) = (k[seg], k[seg + 1]);
382 let h = x1 - x0;
383 let t = ((x - x0) / h).clamp(0.0, 1.0);
384 let (t2, t3) = (t * t, t * t * t);
385 let y = (2.0 * t3 - 3.0 * t2 + 1.0) * y0
386 + (t3 - 2.0 * t2 + t) * h * m[seg]
387 + (-2.0 * t3 + 3.0 * t2) * y1
388 + (t3 - t2) * h * m[seg + 1];
389 y.clamp(0.0, 1.0)
390 })
391 .collect()
392 }
393}
394
395/// Fritsch-Carlson tangents: the secant average, zeroed at a turn and limited so
396/// no segment overshoots its two knots.
397fn tangents(k: &[[f32; 2]]) -> Vec<f32> {
398 let n = k.len();
399 let d: Vec<f32> = k.windows(2).map(|w| (w[1][1] - w[0][1]) / (w[1][0] - w[0][0])).collect();
400 let mut m = vec![0f32; n];
401 m[0] = d[0];
402 m[n - 1] = d[n - 2];
403 for i in 1..n - 1 {
404 m[i] = if d[i - 1] * d[i] <= 0.0 { 0.0 } else { (d[i - 1] + d[i]) / 2.0 };
405 }
406 for i in 0..n - 1 {
407 if d[i] == 0.0 {
408 m[i] = 0.0;
409 m[i + 1] = 0.0;
410 continue;
411 }
412 let (a, b) = (m[i] / d[i], m[i + 1] / d[i]);
413 let s = a * a + b * b;
414 if s > 9.0 {
415 let t = 3.0 / s.sqrt();
416 m[i] = t * a * d[i];
417 m[i + 1] = t * b * d[i];
418 }
419 }
420 m
421}
422
423/// The RGB part of a grade: wheels, curves and a LUT, in that order.
424#[derive(Debug, Clone, Copy, PartialEq)]
425pub struct Look {
426 pub wheels: Wheels,
427 /// Master, red, green, blue ([`CHANNELS`]). The master runs first, then the
428 /// channel's own.
429 pub curves: [Curve; 4],
430 /// The `.cube` file, if any.
431 pub lut: Option<crate::cube::LutRef>,
432 /// How much of the LUT shows, 0..1: 1 is the LUT's output, 0 the input.
433 pub lut_mix: f32,
434}
435
436impl Default for Look {
437 fn default() -> Self {
438 Self {
439 wheels: Wheels::default(),
440 curves: [Curve::default(); 4],
441 lut: None,
442 lut_mix: 1.0,
443 }
444 }
445}
446
447impl Look {
448 /// Whether this look leaves the picture alone. A LUT at mix 0 does.
449 pub fn is_identity(&self) -> bool {
450 self.wheels.is_identity()
451 && self.curves.iter().all(Curve::is_identity)
452 && (self.lut.is_none() || self.lut_mix == 0.0)
453 }
454}
455
456/// Entries of a channel table: 4096 steps, a quarter of a 10-bit code apart.
457const TABLE_N: usize = 4097;
458
459/// One frame's look, ready to run: a table per channel (`None` when the wheels
460/// and curves are neutral) and the LUT with its mix.
461struct Stage {
462 tables: Option<[Vec<f32>; 3]>,
463 cube: Option<(std::sync::Arc<crate::cube::Cube>, f32)>,
464}
465
466impl Stage {
467 /// `None` for a look that does nothing -- a missing or broken LUT included,
468 /// which plays as no LUT (its handle says why, for the warnings).
469 fn new(look: &Look) -> Option<Self> {
470 let shaped = !look.wheels.is_identity() || !look.curves.iter().all(Curve::is_identity);
471 let mix = sane(look.lut_mix, 1.0).clamp(0.0, 1.0);
472 let cube = look.lut.filter(|_| mix > 0.0).and_then(|r| r.table().ok()).map(|c| (c, mix));
473 if !shaped && cube.is_none() {
474 return None;
475 }
476 let tables = shaped.then(|| {
477 let master = look.curves[0].sampled(TABLE_N);
478 [0, 1, 2].map(|c| {
479 let own = look.curves[c + 1].sampled(TABLE_N);
480 (0..TABLE_N)
481 .map(|i| {
482 let x = look.wheels.eval(c, i as f32 / (TABLE_N - 1) as f32);
483 let x = lerp_table(&master, x);
484 lerp_table(&own, x)
485 })
486 .collect()
487 })
488 });
489 Some(Self { tables, cube })
490 }
491
492 /// One R'G'B' value (0..1) through the stage.
493 ///
494 /// The stage grades the value clamped to 0..1 and adds back what the clamp
495 /// took off: a sample a little outside the gamut (a 4:2:0 edge, a super-white)
496 /// keeps its excess instead of being flattened, so an identity LUT is
497 /// transparent and the final code clamp is the only one.
498 #[inline]
499 pub(crate) fn rgb(&self, p: [f32; 3]) -> [f32; 3] {
500 let mut q = p;
501 if let Some(t) = &self.tables {
502 q = [0, 1, 2].map(|k| {
503 let c = q[k].clamp(0.0, 1.0);
504 lerp_table(&t[k], c) + (q[k] - c)
505 });
506 }
507 if let Some((cube, mix)) = &self.cube {
508 let o = cube.sample(q);
509 q = [0, 1, 2].map(|k| {
510 let held = q[k].clamp(cube.domain_min[k], cube.domain_max[k]);
511 q[k] + (o[k] + (q[k] - held) - q[k]) * mix
512 });
513 }
514 q
515 }
516
517 /// Runs the stage over planar YUV with `stride == width`, on the code span `k`
518 /// (8 or 10 bits, limited range or full). Each chroma
519 /// sample becomes the mean of the graded chroma of the luma samples it
520 /// covers. A plane layout this cannot read is left alone.
521 fn run<T: Sample>(&self, y: &mut [T], u: &mut [T], v: &mut [T], width: usize, k: Codes) {
522 if width == 0 || !y.len().is_multiple_of(width) || u.len() != v.len() {
523 return;
524 }
525 let height = y.len() / width;
526 let (hw, hh) = (width.div_ceil(2), height.div_ceil(2));
527 let (cw, ch) = if u.len() == hw * hh {
528 (hw, hh)
529 } else if u.len() == hw * height {
530 (hw, height)
531 } else if u.len() == width * height {
532 (width, height)
533 } else {
534 return;
535 };
536 let (sx, sy) = (width.div_ceil(cw), height.div_ceil(ch));
537 let lanes = std::thread::available_parallelism().map_or(1, |n| n.get()).min(ch).max(1);
538 let rows = ch.div_ceil(lanes);
539 std::thread::scope(|scope| {
540 let mut ys = &mut y[..];
541 let mut us = &mut u[..];
542 let mut vs = &mut v[..];
543 let mut c0 = 0;
544 while c0 < ch {
545 let c1 = (c0 + rows).min(ch);
546 let ly = ((c1 * sy).min(height) - c0 * sy) * width;
547 let (yc, yr) = ys.split_at_mut(ly);
548 let (uc, ur) = us.split_at_mut((c1 - c0) * cw);
549 let (vc, vr) = vs.split_at_mut((c1 - c0) * cw);
550 (ys, us, vs) = (yr, ur, vr);
551 let k = &k;
552 let rows_here = c1 - c0;
553 let luma_rows = ly / width;
554 scope.spawn(move || {
555 for cy in 0..rows_here {
556 for cx in 0..cw {
557 let ci = cy * cw + cx;
558 let (cb, cr) = (k.chroma(uc[ci].get()), k.chroma(vc[ci].get()));
559 let (mut su, mut sv, mut n) = (0f32, 0f32, 0f32);
560 for dy in 0..sy {
561 let row = cy * sy + dy;
562 if row >= luma_rows {
563 break;
564 }
565 for dx in 0..sx {
566 let col = cx * sx + dx;
567 if col >= width {
568 break;
569 }
570 let at = row * width + col;
571 let l = k.luma(yc[at].get());
572 let p = self.rgb(to_rgb(l, cb, cr));
573 let (l, b, r) = from_rgb(p);
574 yc[at] = T::put(k.luma_code(l));
575 su += b;
576 sv += r;
577 n += 1.0;
578 }
579 }
580 uc[ci] = T::put(k.chroma_code(su / n));
581 vc[ci] = T::put(k.chroma_code(sv / n));
582 }
583 }
584 });
585 c0 = c1;
586 }
587 });
588 }
589}
590
591#[inline]
592fn lerp_table(t: &[f32], x: f32) -> f32 {
593 let p = x.clamp(0.0, 1.0) * (t.len() - 1) as f32;
594 let i = (p as usize).min(t.len() - 2);
595 let d = p - i as f32;
596 t[i] + (t[i + 1] - t[i]) * d
597}
598
599const KR: f32 = 0.2126;
600const KB: f32 = 0.0722;
601const KG: f32 = 1.0 - KR - KB;
602
603#[inline]
604fn to_rgb(y: f32, cb: f32, cr: f32) -> [f32; 3] {
605 let r = y + 2.0 * (1.0 - KR) * cr;
606 let b = y + 2.0 * (1.0 - KB) * cb;
607 let g = (y - KR * r - KB * b) / KG;
608 [r, g, b]
609}
610
611#[inline]
612fn from_rgb([r, g, b]: [f32; 3]) -> (f32, f32, f32) {
613 let y = KR * r + KG * g + KB * b;
614 (y, (b - y) / (2.0 * (1.0 - KB)), (r - y) / (2.0 * (1.0 - KR)))
615}
616
617/// Code arithmetic at one depth, limited range or full.
618struct Codes {
619 black: f32,
620 luma: f32,
621 mid: f32,
622 chroma: f32,
623 min: f32,
624 max: f32,
625}
626
627impl Codes {
628 fn new(scale: f32, max: u16, full_range: bool) -> Self {
629 let max = f32::from(max);
630 if full_range {
631 // Whole span: black is 0, white is `max`, and every code is valid.
632 return Self { black: 0.0, luma: max, mid: 128.0 * scale, chroma: max, min: 0.0, max };
633 }
634 // The valid codes: `scale` up from 0 and down from `max` ([`CODES`]).
635 Self { black: 16.0 * scale, luma: 219.0 * scale, mid: 128.0 * scale, chroma: 224.0 * scale, min: scale, max: max - scale }
636 }
637 #[inline]
638 fn luma(&self, c: u16) -> f32 {
639 (f32::from(c) - self.black) / self.luma
640 }
641 #[inline]
642 fn chroma(&self, c: u16) -> f32 {
643 (f32::from(c) - self.mid) / self.chroma
644 }
645 #[inline]
646 fn luma_code(&self, v: f32) -> u16 {
647 (v * self.luma + self.black).round().clamp(self.min, self.max) as u16
648 }
649 #[inline]
650 fn chroma_code(&self, v: f32) -> u16 {
651 (v * self.chroma + self.mid).round().clamp(self.min, self.max) as u16
652 }
653}
654
655/// A sample of either depth.
656trait Sample: Copy + Send + Sync {
657 fn get(self) -> u16;
658 fn put(v: u16) -> Self;
659}
660
661impl Sample for u8 {
662 fn get(self) -> u16 {
663 u16::from(self)
664 }
665 fn put(v: u16) -> Self {
666 v.min(255) as u8
667 }
668}
669
670impl Sample for u16 {
671 fn get(self) -> u16 {
672 self.min(1023)
673 }
674 fn put(v: u16) -> Self {
675 v
676 }
677}
678
679/// [`Look`]'s RGB stage on one R'G'B' value in 0..1, for tests and tools that
680/// want the maths without a frame.
681pub fn look_rgb(look: &Look, p: [f32; 3]) -> [f32; 3] {
682 Stage::new(look).map_or(p, |s| s.rgb(p))
683}
684
685#[cfg(test)]
686mod tests {
687 use super::*;
688
689 /// No grade writes a reserved sync code (0 and 255 at 8 bits, 0..=3 and
690 /// 1020..=1023 at 10), however hard it pushes, on a frame holding every code
691 /// with chroma at both ends; and a super-white or sub-black sample inside
692 /// the valid codes is kept, not clipped to 16..235.
693 #[test]
694 fn grades_write_only_valid_codes_and_keep_super_white() {
695 let (w, h) = (64usize, 64usize);
696 let y8: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();
697 let u8_: Vec<u8> = (0..w * h / 4).map(|i| if i % 3 == 0 { 0 } else if i % 3 == 1 { 255 } else { (i * 7 % 256) as u8 }).collect();
698 let v8: Vec<u8> = (0..w * h / 4).map(|i| if i % 2 == 0 { 255 } else { (i * 13 % 256) as u8 }).collect();
699 let push = Wheels { lift: [1.0, -1.0, 1.0, -1.0], gamma: [-1.0, 1.0, 0.0, 1.0], gain: [1.0, 1.0, -1.0, 0.5] };
700 let grades = [
701 ColorParams { brightness: 1.0, contrast: 2.0, saturation: 2.0, tint: 1.0, ..Default::default() },
702 ColorParams { brightness: -1.0, contrast: 2.0, saturation: 2.0, tint: -1.0, ..Default::default() },
703 ColorParams { look: Look { wheels: push, ..Default::default() }, ..Default::default() },
704 ColorParams { saturation: 2.0, look: Look { wheels: push, ..Default::default() }, ..Default::default() },
705 ];
706 for params in &grades {
707 let (mut y, mut u, mut v) = (y8.clone(), u8_.clone(), v8.clone());
708 apply_yuv(params, &mut y, &mut u, &mut v, w, false);
709 for s in y.iter().chain(&u).chain(&v) {
710 assert!((CODES.0..=CODES.1).contains(s), "8-bit code {s} from {params:?}");
711 }
712 let wide = |p: &[u8]| p.iter().map(|&c| u16::from(c) * 4 + c as u16 / 64).collect::<Vec<u16>>();
713 let (mut y, mut u, mut v) = (wide(&y8), wide(&u8_), wide(&v8));
714 apply_yuv_wide(params, &mut y, &mut u, &mut v, w, false);
715 for s in y.iter().chain(&u).chain(&v) {
716 assert!((WIDE_CODES.0..=WIDE_CODES.1).contains(s), "10-bit code {s} from {params:?}");
717 }
718 }
719 // A barely-there look on grey chroma: super-white 250 and sub-black 5
720 // come out where they went in, inside the valid codes.
721 let grey = ColorParams {
722 look: Look { wheels: Wheels { gain: [0.001, 0.0, 0.0, 0.0], ..Default::default() }, ..Default::default() },
723 ..Default::default()
724 };
725 let mut y = vec![250u8, 250, 5, 5, 250, 250, 5, 5];
726 let (mut u, mut v) = (vec![128u8; 2], vec![128u8; 2]);
727 apply_yuv(&grey, &mut y, &mut u, &mut v, 4, false);
728 assert!(y.iter().zip([250u8, 250, 5, 5, 250, 250, 5, 5]).all(|(a, b)| a.abs_diff(b) <= 1), "{y:?}");
729 let mut y = vec![1000u16, 1000, 20, 20, 1000, 1000, 20, 20];
730 let (mut u, mut v) = (vec![512u16; 2], vec![512u16; 2]);
731 apply_yuv_wide(&grey, &mut y, &mut u, &mut v, 4, false);
732 assert!(y.iter().zip([1000u16, 1000, 20, 20, 1000, 1000, 20, 20]).all(|(a, b)| a.abs_diff(b) <= 2), "{y:?}");
733 }
734
735 /// A gradient frame with every luma code and a chroma sweep, so a test that
736 /// walks it has seen the whole table.
737 fn frame(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
738 let y = (0..w * h).map(|i| (i % 256) as u8).collect();
739 let cw = w.div_ceil(2) * h.div_ceil(2);
740 let u = (0..cw).map(|i| (i % 256) as u8).collect();
741 let v = (0..cw).map(|i| (255 - i % 256) as u8).collect();
742 (y, u, v)
743 }
744
745 /// The charter invariant: no colour set means the exact same bytes, not
746 /// bytes that round back to the same picture.
747 #[test]
748 fn identity_params_leave_every_byte_alone() {
749 let (y, u, v) = frame(64, 48);
750 let (mut gy, mut gu, mut gv) = (y.clone(), u.clone(), v.clone());
751 apply_yuv(&ColorParams::default(), &mut gy, &mut gu, &mut gv, 64, false);
752 assert_eq!((gy, gu, gv), (y, u, v));
753 }
754
755 #[test]
756 fn zero_saturation_is_grey_everywhere() {
757 let (mut y, mut u, mut v) = frame(64, 48);
758 let before = y.clone();
759 apply_yuv(
760 &ColorParams {
761 saturation: 0.0,
762 ..Default::default()
763 },
764 &mut y,
765 &mut u,
766 &mut v,
767 64, false,
768 );
769 // Untouched but for the reserved sync codes 0 and 255, which no grade
770 // writes ([`CODES`]).
771 let valid: Vec<u8> = before.iter().map(|&c| c.clamp(CODES.0, CODES.1)).collect();
772 assert_eq!(y, valid, "saturation must not touch luma");
773 assert!(u.iter().chain(v.iter()).all(|&c| c == 128), "not grey");
774 }
775
776 /// Every extreme, on every code, stays inside `u8` -- a wrap would show as
777 /// black specks in a blown highlight.
778 #[test]
779 fn extremes_clamp_instead_of_wrapping() {
780 let extremes = [-1.0f32, 1.0, -100.0, 100.0, f32::NAN, f32::INFINITY];
781 for b in extremes {
782 for c in [0.0f32, 2.0, 50.0] {
783 let lut = Lut::new(&ColorParams {
784 brightness: b,
785 contrast: c,
786 saturation: c,
787 tint: b,
788 ..Default::default()
789 }, false);
790 // A wrap shows up as a curve that falls: every one of these is
791 // non-decreasing in the input code, saturated ends included.
792 assert!(
793 lut.y.windows(2).all(|w| w[0] <= w[1]),
794 "Y wrapped at {b}/{c}"
795 );
796 assert!(
797 lut.u.windows(2).all(|w| w[0] <= w[1]),
798 "U wrapped at {b}/{c}"
799 );
800 assert!(
801 lut.v.windows(2).all(|w| w[0] <= w[1]),
802 "V wrapped at {b}/{c}"
803 );
804 }
805 }
806 // The two saturating ends specifically: +219 on code 255 is 474, which
807 // a wrapping cast would hand back as 218.
808 let lut = Lut::new(&ColorParams {
809 brightness: 1.0,
810 ..Default::default()
811 }, false);
812 assert_eq!(lut.y[255], 254, "full brightness must saturate at the last valid code, not wrap");
813 assert_eq!(lut.y[0], 219, "black lifted by the whole luma range");
814 let lut = Lut::new(&ColorParams {
815 brightness: -1.0,
816 ..Default::default()
817 }, false);
818 assert_eq!(lut.y[255], 36, "255 - 219");
819 }
820
821 #[test]
822 fn brightness_is_monotonic_in_mean_luma() {
823 let (y0, u0, v0) = frame(64, 48);
824 let mut last = 0.0;
825 for step in 0..=8 {
826 let (mut y, mut u, mut v) = (y0.clone(), u0.clone(), v0.clone());
827 apply_yuv(
828 &ColorParams {
829 brightness: -0.5 + step as f32 * 0.125,
830 ..Default::default()
831 },
832 &mut y,
833 &mut u,
834 &mut v,
835 64, false,
836 );
837 let mean = y.iter().map(|&s| s as f64).sum::<f64>() / y.len() as f64;
838 assert!(mean >= last, "brighter setting darkened the frame");
839 last = mean;
840 }
841 }
842
843 /// The tables are the float maths, sampled: this is what lets the pixel loop
844 /// be a byte lookup. Same formula, computed per sample, must agree exactly.
845 #[test]
846 fn tables_agree_with_the_float_maths() {
847 let params = ColorParams {
848 brightness: 0.13,
849 contrast: 1.4,
850 saturation: 0.7,
851 tint: -0.35,
852 ..Default::default()
853 };
854 let lut = Lut::new(&params, false);
855 for code in 0..256 {
856 let f = code as f32;
857 let y = ((f - MID_Y) * 1.4 + MID_Y + 0.13 * LUMA_RANGE)
858 .round()
859 .clamp(1.0, 254.0) as u8;
860 let u = ((f - 128.0) * 0.7 + 128.0 + 0.35 * TINT_RANGE)
861 .round()
862 .clamp(1.0, 254.0) as u8;
863 let v = ((f - 128.0) * 0.7 + 128.0 - 0.35 * TINT_RANGE)
864 .round()
865 .clamp(1.0, 254.0) as u8;
866 assert!(lut.y[code].abs_diff(y) <= 1, "Y {code}");
867 assert!(lut.u[code].abs_diff(u) <= 1, "U {code}");
868 assert!(lut.v[code].abs_diff(v) <= 1, "V {code}");
869 }
870 }
871
872 /// Not asserted: a debug build is an order of magnitude off and the number
873 /// only means something in release. Run with
874 /// `cargo test -p engine --release color:: -- --nocapture`.
875 #[test]
876 #[ignore = "perf: run with --ignored"]
877 fn perf_1080p() {
878 let (mut y, mut u, mut v) = frame(1920, 1080);
879 let params = ColorParams {
880 brightness: 0.1,
881 contrast: 1.2,
882 saturation: 1.3,
883 tint: 0.2,
884 ..Default::default()
885 };
886 let runs = 30;
887 let t = std::time::Instant::now();
888 for _ in 0..runs {
889 apply_yuv(&params, &mut y, &mut u, &mut v, 1920, false);
890 }
891 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
892 println!("color::apply_yuv 1920x1080: {ms:.3} ms/frame");
893 }
894
895 fn looked(look: Look) -> ColorParams {
896 ColorParams { look, ..Default::default() }
897 }
898
899 fn warm_cube() -> std::path::PathBuf {
900 let dir = std::env::temp_dir().join(format!("edith-color-{}", std::process::id()));
901 std::fs::create_dir_all(&dir).expect("dir");
902 let path = dir.join("warm.cube");
903 let mut t = String::from("LUT_3D_SIZE 5\n");
904 for b in 0..5 {
905 for g in 0..5 {
906 for r in 0..5 {
907 let (r, g, b) = (r as f32 / 4.0, g as f32 / 4.0, b as f32 / 4.0);
908 t.push_str(&format!("{} {} {}\n", (r * 1.1 + 0.03).min(1.0), g, b * 0.85));
909 }
910 }
911 }
912 std::fs::write(&path, t).expect("write");
913 path
914 }
915
916 /// Neutral wheels, curves whose points sit on the diagonal, and a LUT at mix
917 /// 0 are all "nothing set": the bytes come back as they went in, at both
918 /// depths and through the fused conversion.
919 #[test]
920 fn a_neutral_look_leaves_every_byte_alone() {
921 let diagonal = Curve::new(&[[0.25, 0.25], [0.75, 0.75]]).expect("curve");
922 let look = Look {
923 curves: [diagonal; 4],
924 lut: Some(crate::cube::LutRef::open(&warm_cube())),
925 lut_mix: 0.0,
926 ..Default::default()
927 };
928 let p = looked(look);
929 assert!(p.is_identity());
930 let (y, u, v) = frame(64, 48);
931 let (mut gy, mut gu, mut gv) = (y.clone(), u.clone(), v.clone());
932 apply_yuv(&p, &mut gy, &mut gu, &mut gv, 64, false);
933 assert_eq!((gy, gu, gv), (y.clone(), u.clone(), v.clone()));
934 let w = |s: &[u8]| s.iter().map(|&c| u16::from(c) * 4 + 1).collect::<Vec<u16>>();
935 let (wy, wu, wv) = (w(&y), w(&u), w(&v));
936 let (mut gy, mut gu, mut gv) = (wy.clone(), wu.clone(), wv.clone());
937 apply_yuv_wide(&p, &mut gy, &mut gu, &mut gv, 64, false);
938 assert_eq!((gy, gu, gv), (wy, wu, wv));
939 }
940
941 /// A limited-range grey ramp with neutral chroma, graded through a look.
942 fn graded_grey(look: Look, wide: bool) -> Vec<f32> {
943 let p = looked(look);
944 if wide {
945 let mut y: Vec<u16> = (0..=219).map(|c| (16 + c) * 4).collect();
946 let n = y.len();
947 let (mut u, mut v) = (vec![512u16; n.div_ceil(2)], vec![512u16; n.div_ceil(2)]);
948 apply_yuv_wide(&p, &mut y, &mut u, &mut v, n, false);
949 y.iter().map(|&c| f32::from(c) / 4.0).collect()
950 } else {
951 let mut y: Vec<u8> = (16..=235).collect();
952 let n = y.len();
953 let (mut u, mut v) = (vec![128u8; n.div_ceil(2)], vec![128u8; n.div_ceil(2)]);
954 apply_yuv(&p, &mut y, &mut u, &mut v, n, false);
955 y.iter().map(|&c| f32::from(c)).collect()
956 }
957 }
958
959 #[test]
960 fn wheels_move_the_ends_they_say_at_both_depths() {
961 let lift = Look { wheels: Wheels { lift: [0.5, 0.0, 0.0, 0.0], ..Default::default() }, ..Default::default() };
962 let gain = Look { wheels: Wheels { gain: [-0.5, 0.0, 0.0, 0.0], ..Default::default() }, ..Default::default() };
963 let gamma = Look { wheels: Wheels { gamma: [0.5, 0.0, 0.0, 0.0], ..Default::default() }, ..Default::default() };
964 for wide in [false, true] {
965 let l = graded_grey(lift, wide);
966 assert!((l[0] - (16.0 + 0.25 * 219.0)).abs() <= 1.0, "lift 0.5 puts black at a quarter: {}", l[0]);
967 assert!((l[219] - 235.0).abs() <= 0.5, "lift keeps white");
968 let g = graded_grey(gain, wide);
969 assert!((g[0] - 16.0).abs() <= 0.5 && (g[219] - (16.0 + 0.5 * 219.0)).abs() <= 1.0, "gain halves from black");
970 let m = graded_grey(gamma, wide);
971 assert!(m[110] > 125.0 + 10.0 && (m[0] - 16.0).abs() <= 0.5 && (m[219] - 235.0).abs() <= 0.5, "gamma lifts mids only");
972 assert!(m.windows(2).all(|w| w[1] >= w[0]));
973 }
974 // 8 and 10 bit agree to within an 8-bit code.
975 for look in [lift, gain, gamma] {
976 let (a, b) = (graded_grey(look, false), graded_grey(look, true));
977 assert!(a.iter().zip(&b).all(|(x, y)| (x - y).abs() <= 1.0));
978 }
979 }
980
981 #[test]
982 fn a_red_lift_warms_without_touching_luma_much() {
983 let look = Look { wheels: Wheels { lift: [0.0, 0.3, 0.0, -0.1], ..Default::default() }, ..Default::default() };
984 let out = look_rgb(&look, [0.1, 0.1, 0.1]);
985 assert!(out[0] > 0.2 && (out[1] - 0.1).abs() < 1e-5 && out[2] < 0.1, "{out:?}");
986 }
987
988 #[test]
989 fn curves_are_monotone_and_pass_through_their_points() {
990 let pts = [[0.1, 0.02], [0.3, 0.4], [0.5, 0.45], [0.7, 0.9], [0.9, 0.92]];
991 let c = Curve::new(&pts).expect("curve");
992 let t = c.sampled(1001);
993 assert!(t.windows(2).all(|w| w[1] >= w[0] - 1e-6), "monotone through rising points");
994 for p in pts {
995 assert!((t[(p[0] * 1000.0).round() as usize] - p[1]).abs() < 1e-3, "{p:?}");
996 }
997 assert!((t[0]).abs() < 1e-6 && (t[1000] - 1.0).abs() < 1e-6, "pinned ends");
998 assert!(Curve::new(&[[0.5, 0.5], [0.4, 0.1]]).is_err());
999 assert!(Curve::new(&[[1.5, 0.5]]).is_err());
1000 assert!(Curve::new(&[[f32::NAN, 0.5]]).is_err());
1001 assert!(Curve::new(&[[0.0, 0.0]; 17]).is_err());
1002 // A master S-curve darkens the shadows and brightens the highlights.
1003 let s = Look { curves: [Curve::new(&[[0.25, 0.15], [0.75, 0.85]]).expect("s"), Curve::default(), Curve::default(), Curve::default()], ..Default::default() };
1004 let g = graded_grey(s, false);
1005 assert!(g[55] < 16.0 + 55.0 - 10.0 && g[165] > 16.0 + 165.0 + 10.0);
1006 }
1007
1008 #[test]
1009 fn the_lut_is_mixed_by_intensity_and_a_missing_one_plays_without_it() {
1010 let lut = crate::cube::LutRef::open(&warm_cube());
1011 let full = look_rgb(&Look { lut: Some(lut), ..Default::default() }, [0.5, 0.5, 0.5]);
1012 assert!((full[0] - 0.58).abs() < 1e-4 && (full[2] - 0.425).abs() < 1e-4, "{full:?}");
1013 let half = look_rgb(&Look { lut: Some(lut), lut_mix: 0.5, ..Default::default() }, [0.5, 0.5, 0.5]);
1014 assert!((half[0] - 0.54).abs() < 1e-4, "{half:?}");
1015 let gone = crate::cube::LutRef::open(std::path::Path::new("/nonexistent/edith/x.cube"));
1016 let p = looked(Look { lut: Some(gone), ..Default::default() });
1017 let (y, u, v) = frame(64, 48);
1018 let (mut gy, mut gu, mut gv) = (y.clone(), u.clone(), v.clone());
1019 apply_yuv(&p, &mut gy, &mut gu, &mut gv, 64, false);
1020 assert_eq!((gy, gu, gv), (y, u, v), "a missing LUT is no LUT, never a crash");
1021 }
1022
1023 /// Keys animate the sliders; the look under them is the clip's.
1024 #[test]
1025 fn keys_keep_the_base_look() {
1026 let base = looked(Look { lut_mix: 0.4, wheels: Wheels { gain: [0.2; 4], ..Default::default() }, ..Default::default() });
1027 let key = |at, b| ColorKey { at, params: ColorParams { brightness: b, ..Default::default() }, ease: crate::transform::KeyEase::Linear };
1028 let got = evaluate_color(base, &[key(0, 0.0), key(10, 0.5)], 5.0);
1029 assert!((got.brightness - 0.25).abs() < 1e-6);
1030 assert_eq!(got.look, base.look);
1031 }
1032
1033 /// The look's RGB stage on a 1080p frame, printed. Release:
1034 /// `cargo test -p engine --release color::tests::perf_look -- --nocapture`.
1035 #[test]
1036 #[ignore = "perf: run with --ignored"]
1037 fn perf_look_1080p() {
1038 let (mut y, mut u, mut v) = frame(1920, 1080);
1039 let p = looked(Look {
1040 wheels: Wheels { lift: [0.05, 0.1, 0.0, -0.05], ..Default::default() },
1041 lut: Some(crate::cube::LutRef::open(&warm_cube())),
1042 ..Default::default()
1043 });
1044 let t = std::time::Instant::now();
1045 for _ in 0..10 {
1046 apply_yuv(&p, &mut y, &mut u, &mut v, 1920, false);
1047 }
1048 println!("color look 1920x1080: {:.3} ms/frame", t.elapsed().as_secs_f64() * 100.0);
1049 }
1050
1051 /// A full-range source: identity (sliders and a neutral look) is bit-exact at
1052 /// both depths, and a lift reaches the true ends of 0..255 / 0..1023 where the
1053 /// limited arithmetic would stop at 1 and 254.
1054 #[test]
1055 fn full_range_sources_grade_over_the_whole_span() {
1056 let ramp: Vec<u8> = (0..=255u8).collect();
1057 let (cu, cv) = (vec![128u8; 64], vec![128u8; 64]);
1058 let neutral = ColorParams { look: Look { wheels: Wheels::default(), ..Look::default() }, ..Default::default() };
1059 let (mut y, mut u, mut v) = (ramp.clone(), cu.clone(), cv.clone());
1060 apply_yuv(&neutral, &mut y, &mut u, &mut v, 16, true);
1061 assert_eq!((&y, &u, &v), (&ramp, &cu, &cv));
1062 let wide: Vec<u16> = (0..1024u16).collect();
1063 let (mut y, mut u, mut v) = (wide.clone(), vec![512u16; 256], vec![512u16; 256]);
1064 apply_yuv_wide(&neutral, &mut y, &mut u, &mut v, 32, true);
1065 assert_eq!(y, wide);
1066 assert!(u.iter().all(|&c| c == 512));
1067
1068 // Brightness down then up: the ends of the span are reachable.
1069 let down = ColorParams { brightness: -1.0, ..Default::default() };
1070 let up = ColorParams { brightness: 1.0, ..Default::default() };
1071 let (mut y, mut u, mut v) = (ramp.clone(), cu.clone(), cv.clone());
1072 apply_yuv(&down, &mut y, &mut u, &mut v, 16, true);
1073 assert_eq!(y[255], 0);
1074 let (mut y, mut u, mut v) = (ramp.clone(), cu.clone(), cv.clone());
1075 apply_yuv(&up, &mut y, &mut u, &mut v, 16, true);
1076 assert_eq!((y[0], y[255]), (255, 255));
1077 // A lift wheel on black reaches 0 and 255 through the RGB stage.
1078 let lift = |amount: f32| ColorParams { look: Look { wheels: Wheels { lift: [amount, 0.0, 0.0, 0.0], ..Default::default() }, ..Look::default() }, ..Default::default() };
1079 let (mut y, mut u, mut v) = (vec![0u8, 255, 0, 255], vec![128u8], vec![128u8]);
1080 apply_yuv(&lift(0.0001), &mut y, &mut u, &mut v, 2, true);
1081 assert_eq!((y[0], y[1]), (0, 255), "a negligible lift keeps the true ends");
1082 let (mut y, mut u, mut v) = (vec![0u8; 4], vec![128u8], vec![128u8]);
1083 apply_yuv(&lift(-1.0), &mut y, &mut u, &mut v, 2, true);
1084 assert_eq!(y[0], 0);
1085 let (mut y, mut u, mut v) = (vec![255u8; 4], vec![128u8], vec![128u8]);
1086 apply_yuv(&ColorParams { look: Look { wheels: Wheels { gain: [1.0, 0.0, 0.0, 0.0], ..Default::default() }, ..Look::default() }, ..Default::default() }, &mut y, &mut u, &mut v, 2, true);
1087 assert_eq!(y[0], 255);
1088 let (mut y, mut u, mut v) = (vec![0u16; 4], vec![512u16], vec![512u16]);
1089 apply_yuv_wide(&down, &mut y, &mut u, &mut v, 2, true);
1090 assert_eq!(y[0], 0);
1091 }
1092}