forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

auto_color.rs172 lines, 6.7 KiBHistoryRawDownload
1//! Auto colour: one correction read off a picture, as the colour card's Auto
2//! button and the `auto_color` edit op set it.
3//!
4//! Two readings, both on the clip as shot (the ungraded frame), so the values
5//! it writes are absolute and a second press lands where the first did:
6//!
7//! * grey-world white balance: each channel's mean is moved to the average of
8//! the three means, by the wheels' per-channel gain (`1 + gain`, so the
9//! correction is a multiplier in R'G'B'),
10//! * a luma stretch: after that balance, the 0.5 % and 99.5 % luma percentiles
11//! are carried to 0.02 and 0.98 by the contrast and brightness sliders. The
12//! sliders pivot on mid grey and move in luma-range units, so a linear stretch
13//! `v' = a v + b` is exactly `contrast = a` with `brightness = b + (a - 1) / 2`.
14//!
15//! Nothing else is touched: saturation, tint, lift, gamma, curves and the LUT
16//! keep what the clip has. A flat frame, one with no luma spread to stretch,
17//! gets no stretch at all.
18
19use crate::color::ColorParams;
20
21/// Luma the low percentile lands on.
22pub const LOW_TARGET: f32 = 0.02;
23/// Luma the high percentile lands on.
24pub const HIGH_TARGET: f32 = 0.98;
25/// Percentiles read off the balanced frame.
26const LOW_PCT: f32 = 0.005;
27const HIGH_PCT: f32 = 0.995;
28/// Pixels read per frame, at most: a strided grid, as the scopes read theirs.
29const MAX_SAMPLES: usize = 65_536;
30/// Bins of the luma histogram the percentiles are read from.
31const BINS: usize = 1024;
32
33/// The correction one frame calls for. Plain numbers, so the card and the MCP
34/// op can both say what they set.
35#[derive(Debug, Clone, Copy, PartialEq)]
36pub struct Correction {
37 /// Red, green and blue wheel gains, -1..1: each channel's own move to meet the grey average.
38 pub gain: [f32; 3],
39 /// The brightness slider, -1..1.
40 pub brightness: f32,
41 /// The contrast slider, 0..2.
42 pub contrast: f32,
43 /// Luma at the low percentile before the stretch, 0..1.
44 pub low: f32,
45 /// Luma at the high percentile before the stretch, 0..1.
46 pub high: f32,
47}
48
49/// Reads the correction off one packed RGB8 frame (`width * height` pixels,
50/// three bytes each). `None` when the buffer does not hold that many pixels or
51/// there are none.
52pub fn analyse(rgb: &[u8], width: usize, height: usize) -> Option<Correction> {
53 let pixels = width.checked_mul(height).filter(|&n| n > 0)?;
54 if rgb.len() != pixels.checked_mul(3)? {
55 return None;
56 }
57 let step = (pixels / MAX_SAMPLES).max(1);
58 let samples: Vec<[f32; 3]> = (0..pixels)
59 .step_by(step)
60 .map(|i| [rgb[3 * i], rgb[3 * i + 1], rgb[3 * i + 2]].map(|c| f32::from(c) / 255.0))
61 .collect();
62
63 // Grey world: every channel's mean goes to the average of the three.
64 let n = samples.len() as f32;
65 let mut mean = [0f32; 3];
66 for s in &samples {
67 for c in 0..3 {
68 mean[c] += s[c] / n;
69 }
70 }
71 let target = (mean[0] + mean[1] + mean[2]) / 3.0;
72 let mut gain = [0f32; 3];
73 for c in 0..3 {
74 if mean[c] > 1e-3 && target > 0.0 {
75 gain[c] = (target / mean[c] - 1.0).clamp(-1.0, 1.0);
76 }
77 }
78
79 // Luma of the balanced frame, counted into bins over 0..1.
80 let mut bins = [0u32; BINS];
81 for s in &samples {
82 let rgb = [0, 1, 2].map(|c| (s[c] * (1.0 + gain[c])).clamp(0.0, 1.0));
83 let luma = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
84 bins[((luma * (BINS - 1) as f32).round() as usize).min(BINS - 1)] += 1;
85 }
86 let low = percentile(&bins, LOW_PCT);
87 let high = percentile(&bins, HIGH_PCT);
88
89 let (brightness, contrast) = if high - low < 1.0 / 256.0 {
90 (0.0, 1.0)
91 } else {
92 let a = ((HIGH_TARGET - LOW_TARGET) / (high - low)).clamp(0.0, 2.0);
93 let b = LOW_TARGET - a * low;
94 ((b + (a - 1.0) / 2.0).clamp(-1.0, 1.0), a)
95 };
96 Some(Correction { gain, brightness, contrast, low, high })
97}
98
99/// The luma at `pct` of the histogram, as 0..1.
100fn percentile(bins: &[u32; BINS], pct: f32) -> f32 {
101 let total: u32 = bins.iter().sum();
102 let want = (pct * total as f32).ceil().max(1.0) as u32;
103 let mut seen = 0;
104 for (i, &count) in bins.iter().enumerate() {
105 seen += count;
106 if seen >= want {
107 return i as f32 / (BINS - 1) as f32;
108 }
109 }
110 1.0
111}
112
113impl Correction {
114 /// `base` with this correction written onto it: the three channel gains
115 /// (the master gain stays where it is, so the channels still meet the
116 /// average once it is added), brightness and contrast. Everything else in
117 /// `base` is kept as it was.
118 pub fn apply(&self, base: ColorParams) -> ColorParams {
119 let mut look = base.look;
120 for c in 0..3 {
121 look.wheels.gain[c + 1] = (self.gain[c] - look.wheels.gain[0]).clamp(-1.0, 1.0);
122 }
123 ColorParams { brightness: self.brightness, contrast: self.contrast, look, ..base }
124 }
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130 use crate::color::look_rgb;
131
132 /// A `w` x `h` frame whose pixel (x, y) is `f(x, y)`.
133 fn frame(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
134 (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| f(x, y)).collect()
135 }
136
137 /// The wheels' part of the correction on one R'G'B' value (the decoder's own
138 /// formulas; the sliders move luma and leave the channels' balance alone).
139 fn balanced(c: &Correction, p: [f32; 3]) -> [f32; 3] {
140 look_rgb(&c.apply(ColorParams::default()).look, p)
141 }
142
143 #[test]
144 fn a_blue_cast_comes_back_neutral() {
145 // A grey ramp with blue lifted by 40 %: a clear cast.
146 let rgb = frame(16, 16, |x, _| {
147 let g = 40 + (x * 12) as u8;
148 [g, g, (f32::from(g) * 1.4).min(255.0) as u8]
149 });
150 let c = analyse(&rgb, 16, 16).expect("a frame");
151 assert!(c.gain[2] < -0.1, "blue must be pulled down: {c:?}");
152 assert!(c.gain[0] > 0.0, "red must come up: {c:?}");
153 let mut sums = [0f32; 3];
154 for px in rgb.chunks(3) {
155 let p = [px[0], px[1], px[2]].map(|v| f32::from(v) / 255.0);
156 let out = balanced(&c, p);
157 for k in 0..3 {
158 sums[k] += out[k] / 256.0;
159 }
160 }
161 let avg = (sums[0] + sums[1] + sums[2]) / 3.0;
162 for k in 0..3 {
163 assert!((sums[k] - avg).abs() < 0.02, "channel {k} off the average: {sums:?}");
164 }
165 // Only the balance and the two slider fields are written; the rest of the grade is kept.
166 let base = ColorParams { saturation: 0.7, tint: 0.2, ..Default::default() };
167 let p = c.apply(base);
168 assert_eq!((p.saturation, p.tint), (0.7, 0.2));
169 assert_eq!((p.brightness, p.contrast), (c.brightness, c.contrast));
170 }
171
172}