BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / luma_effects.rs

luma_effects.rs

luma_effects.rs 13.6 KiB Download Raw
1use std::time::Duration;
2
3use crate::mask::{Mask, axis};
4
5const DARK_LUMA: f32 = 0.35;
6const VERY_DARK_LUMA: f32 = 0.05;
7const GAMMA_AT_DARK: f32 = 0.75;
8const GAMMA_AT_VERY_DARK: f32 = 0.6;
9const GAMMA_TIME_CONSTANT: f32 = 1.0;
10const GAMMA_SETTLED: f32 = 0.005;
11const LUMA_SAMPLE_STEP: usize = 4;
12const SOFT_FOCUS_MAX_ALPHA: f32 = 0.7;
13const CELL: usize = 4;
14const FILTER_RADIUS: usize = 1;
15const FILTER_EPSILON: f32 = 100.;
16const NEAR_WEIGHTS: [f32; CELL] = [0.625, 0.875, 0.875, 0.625];
17const INSIDE_START: f32 = 0.5;
18const MAX_BANDS: usize = 4;
19
20pub fn mean_luma(plane: &[u8], stride: usize, width: usize, height: usize) -> f32 {
21 let (mut sum, mut count) = (0u64, 0u64);
22 for row in (0..height).step_by(LUMA_SAMPLE_STEP) {
23 for &value in plane[row * stride..][..width].iter().step_by(LUMA_SAMPLE_STEP) {
24 sum += u64::from(value);
25 count += 1;
26 }
27 }
28 if count == 0 { 0. } else { sum as f32 / (count as f32 * 255.) }
29}
30
31pub fn target_gamma(mean_luma: f32) -> f32 {
32 if mean_luma >= DARK_LUMA {
33 return 1.;
34 }
35 let darkness = ((DARK_LUMA - mean_luma) / (DARK_LUMA - VERY_DARK_LUMA)).clamp(0., 1.);
36 GAMMA_AT_DARK + (GAMMA_AT_VERY_DARK - GAMMA_AT_DARK) * darkness
37}
38
39pub fn smooth_gamma(current: f32, target: f32, elapsed: Duration) -> f32 {
40 let next = current + (target - current) * (1. - (-elapsed.as_secs_f32() / GAMMA_TIME_CONSTANT).exp());
41 if (next - target).abs() < GAMMA_SETTLED { target } else { next }
42}
43
44pub fn gamma_table(gamma: f32) -> [u8; 256] {
45 std::array::from_fn(|value| (255. * (value as f32 / 255.).powf(gamma)).round() as u8)
46}
47
48pub fn apply_table(plane: &mut [u8], stride: usize, width: usize, height: usize, table: &[u8; 256]) {
49 for row in plane.chunks_mut(stride).take(height) {
50 for value in &mut row[..width] {
51 *value = table[usize::from(*value)];
52 }
53 }
54}
55
56pub fn inside_person(mask_value: f32) -> f32 {
57 ((mask_value - INSIDE_START) / (1. - INSIDE_START)).clamp(0., 1.)
58}
59
60pub fn soft_focus_alpha(strength_percent: u8, inside: f32) -> f32 {
61 f32::from(strength_percent.min(100)) / 100. * SOFT_FOCUS_MAX_ALPHA * inside
62}
63
64pub fn blend_coefficients(alpha: f32, slope: f32, offset: f32) -> (f32, f32) {
65 (1. + alpha * (slope - 1.), alpha * offset)
66}
67
68pub fn apply_coefficients(value: u8, gain: f32, bias: f32) -> u8 {
69 (f32::from(value) * gain + bias + 0.5) as u8
70}
71
72fn box_mean(input: &[f32], width: usize, height: usize) -> Vec<f32> {
73 let mut across = vec![0f32; input.len()];
74 for (line, mean) in input.chunks_exact(width).zip(across.chunks_exact_mut(width)) {
75 for (index, slot) in mean.iter_mut().enumerate() {
76 let (low, high) = (index.saturating_sub(FILTER_RADIUS), (index + FILTER_RADIUS).min(width - 1));
77 *slot = line[low..=high].iter().sum::<f32>() / (high + 1 - low) as f32;
78 }
79 }
80 let mut output = vec![0f32; input.len()];
81 for row in 0..height {
82 let (low, high) = (row.saturating_sub(FILTER_RADIUS), (row + FILTER_RADIUS).min(height - 1));
83 let slot = &mut output[row * width..][..width];
84 for line in low..=high {
85 slot.iter_mut().zip(&across[line * width..][..width]).for_each(|(sum, value)| *sum += value);
86 }
87 let count = (high + 1 - low) as f32;
88 slot.iter_mut().for_each(|sum| *sum /= count);
89 }
90 output
91}
92
93struct Cells {
94 gain: Vec<f32>,
95 bias: Vec<f32>,
96 alpha: Vec<f32>,
97 width: usize,
98 height: usize,
99}
100
101fn cell_means(plane: &[u8], stride: usize, cell_width: usize, cell_height: usize) -> Vec<f32> {
102 let mut means = vec![0f32; cell_width * cell_height];
103 let mut column_sums = vec![0u16; cell_width * CELL];
104 for (row, mean) in means.chunks_exact_mut(cell_width).enumerate() {
105 column_sums.fill(0);
106 for line in 0..CELL {
107 let pixels = &plane[(row * CELL + line) * stride..][..cell_width * CELL];
108 column_sums.iter_mut().zip(pixels).for_each(|(sum, &value)| *sum += u16::from(value));
109 }
110 for (slot, group) in mean.iter_mut().zip(column_sums.as_chunks::<CELL>().0) {
111 *slot = group.iter().map(|&sum| u32::from(sum)).sum::<u32>() as f32 / (CELL * CELL) as f32;
112 }
113 }
114 means
115}
116
117fn smoothing_cells(plane: &[u8], stride: usize, width: usize, height: usize, mask: &Mask, strength_percent: u8) -> Cells {
118 let (cell_width, cell_height) = (width / CELL, height / CELL);
119 let small = cell_means(plane, stride, cell_width, cell_height);
120 let squared: Vec<f32> = small.iter().map(|value| value * value).collect();
121 let mean = box_mean(&small, cell_width, cell_height);
122 let mean_squared = box_mean(&squared, cell_width, cell_height);
123 let slope: Vec<f32> = mean.iter().zip(&mean_squared).map(|(mean, squared)| {
124 let variance = (squared - mean * mean).max(0.);
125 variance / (variance + FILTER_EPSILON)
126 }).collect();
127 let offset: Vec<f32> = mean.iter().zip(&slope).map(|(mean, slope)| mean * (1. - slope)).collect();
128 let (mean_slope, mean_offset) = (box_mean(&slope, cell_width, cell_height), box_mean(&offset, cell_width, cell_height));
129 let (mask_x, mask_y) = (axis(cell_width, mask.width), axis(cell_height, mask.height));
130 let (mask_width, mask) = (mask.width, &mask.values);
131 let mut cells = Cells { gain: vec![1.; small.len()], bias: vec![0.; small.len()], alpha: vec![0.; small.len()], width: cell_width, height: cell_height };
132 for row in 0..cell_height {
133 let (mask_top, mask_bottom, mask_fraction) = (mask_y.first[row] * mask_width, mask_y.second[row] * mask_width, mask_y.weight[row]);
134 for column in 0..cell_width {
135 let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);
136 let top = mask[mask_top + left] * (1. - across) + mask[mask_top + right] * across;
137 let bottom = mask[mask_bottom + left] * (1. - across) + mask[mask_bottom + right] * across;
138 let index = row * cell_width + column;
139 let alpha = soft_focus_alpha(strength_percent, inside_person(top * (1. - mask_fraction) + bottom * mask_fraction));
140 (cells.gain[index], cells.bias[index]) = blend_coefficients(alpha, mean_slope[index], mean_offset[index]);
141 cells.alpha[index] = alpha;
142 }
143 }
144 cells
145}
146
147fn neighbor(index: usize, step: usize, last: usize) -> usize {
148 if step < CELL / 2 { index.saturating_sub(1) } else { (index + 1).min(last) }
149}
150
151fn active_columns(cells: &Cells, near_start: usize, far_start: usize, active: &mut [bool]) {
152 let alpha_at = |column: usize| cells.alpha[near_start + column] > 0. || cells.alpha[far_start + column] > 0.;
153 for (column, slot) in active.iter_mut().enumerate() {
154 *slot = alpha_at(column) || alpha_at(column.saturating_sub(1)) || alpha_at((column + 1).min(cells.width - 1));
155 }
156}
157
158fn blend_rows(plane: &mut [u8], stride: usize, first_row: usize, cells: &Cells) {
159 let (mut gain_row, mut bias_row) = (vec![0f32; cells.width], vec![0f32; cells.width]);
160 let mut active = vec![false; cells.width];
161 let last = cells.width - 1;
162 for (offset, line) in plane.chunks_mut(stride).enumerate() {
163 let row = first_row + offset;
164 if row >= cells.height * CELL {
165 break;
166 }
167 let (near, step) = (row / CELL, row % CELL);
168 let far = neighbor(near, step, cells.height - 1);
169 let (near_start, far_start) = (near * cells.width, far * cells.width);
170 active_columns(cells, near_start, far_start, &mut active);
171 if !active.contains(&true) {
172 continue;
173 }
174 let (near_weight, far_weight) = (NEAR_WEIGHTS[step], 1. - NEAR_WEIGHTS[step]);
175 for column in 0..cells.width {
176 gain_row[column] = cells.gain[near_start + column] * near_weight + cells.gain[far_start + column] * far_weight;
177 bias_row[column] = cells.bias[near_start + column] * near_weight + cells.bias[far_start + column] * far_weight;
178 }
179 for (column, group) in line[..cells.width * CELL].as_chunks_mut::<CELL>().0.iter_mut().enumerate() {
180 if !active[column] {
181 continue;
182 }
183 let (before, after) = (column.saturating_sub(1), (column + 1).min(last));
184 let (gain, bias) = (gain_row[column], bias_row[column]);
185 let (gain_before, bias_before, gain_after, bias_after) = (gain_row[before], bias_row[before], gain_row[after], bias_row[after]);
186 let gains = [gain * NEAR_WEIGHTS[0] + gain_before * (1. - NEAR_WEIGHTS[0]), gain * NEAR_WEIGHTS[1] + gain_before * (1. - NEAR_WEIGHTS[1]), gain * NEAR_WEIGHTS[2] + gain_after * (1. - NEAR_WEIGHTS[2]), gain * NEAR_WEIGHTS[3] + gain_after * (1. - NEAR_WEIGHTS[3])];
187 let biases = [bias * NEAR_WEIGHTS[0] + bias_before * (1. - NEAR_WEIGHTS[0]), bias * NEAR_WEIGHTS[1] + bias_before * (1. - NEAR_WEIGHTS[1]), bias * NEAR_WEIGHTS[2] + bias_after * (1. - NEAR_WEIGHTS[2]), bias * NEAR_WEIGHTS[3] + bias_after * (1. - NEAR_WEIGHTS[3])];
188 for (value, (gain, bias)) in group.iter_mut().zip(gains.into_iter().zip(biases)) {
189 *value = apply_coefficients(*value, gain, bias);
190 }
191 }
192 }
193}
194
195/// Edge-preserving smoothing (fast guided filter, radius about 4) of the luma plane, blended in only inside the person mask.
196pub fn soften_luma(plane: &mut [u8], stride: usize, width: usize, height: usize, mask: &Mask, strength_percent: u8) {
197 if strength_percent == 0 || width < CELL * 2 || height < CELL * 2 {
198 return;
199 }
200 let cells = smoothing_cells(plane, stride, width, height, mask, strength_percent);
201 let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
202 let rows_per_band = height.div_ceil(bands).next_multiple_of(CELL);
203 std::thread::scope(|scope| {
204 for (index, band) in plane[..stride * (height - 1) + width].chunks_mut(rows_per_band * stride).enumerate() {
205 let cells = &cells;
206 scope.spawn(move || blend_rows(band, stride, index * rows_per_band, cells));
207 }
208 });
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 const WIDTH: usize = 64;
216 const HEIGHT: usize = 36;
217
218 #[test]
219 fn the_gamma_follows_the_darkness_and_leaves_bright_frames_alone() {
220 assert_eq!(target_gamma(0.5), 1.);
221 assert_eq!(target_gamma(0.35), 1.);
222 assert!((target_gamma(0.3499) - GAMMA_AT_DARK).abs() < 0.001);
223 assert_eq!(target_gamma(0.05), GAMMA_AT_VERY_DARK);
224 assert_eq!(target_gamma(0.), GAMMA_AT_VERY_DARK);
225 let middle = target_gamma(0.2);
226 assert!(middle < GAMMA_AT_DARK && middle > GAMMA_AT_VERY_DARK);
227 }
228
229 #[test]
230 fn the_gamma_glides_instead_of_jumping() {
231 let step = Duration::from_millis(33);
232 let first = smooth_gamma(1., 0.6, step);
233 assert!(first < 1. && first > 0.95);
234 let mut gamma = 1.;
235 for _ in 0..300 {
236 gamma = smooth_gamma(gamma, 0.6, step);
237 }
238 assert_eq!(gamma, 0.6);
239 }
240
241 #[test]
242 fn the_table_brightens_dark_values_and_keeps_the_ends() {
243 let table = gamma_table(0.6);
244 assert_eq!((table[0], table[255]), (0, 255));
245 assert!(table[40] > 40 && table[128] > 128);
246 assert!(table.windows(2).all(|pair| pair[0] <= pair[1]));
247 assert_eq!(gamma_table(1.), std::array::from_fn(|value| value as u8));
248 let mut plane = vec![40u8; WIDTH * HEIGHT];
249 apply_table(&mut plane, WIDTH, WIDTH, HEIGHT, &table);
250 assert!(plane.iter().all(|&value| value == table[40]));
251 }
252
253 #[test]
254 fn the_mean_luma_is_a_fraction_of_full_scale() {
255 assert_eq!(mean_luma(&vec![255; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT), 1.);
256 assert_eq!(mean_luma(&vec![0; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT), 0.);
257 assert!((mean_luma(&vec![51; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT) - 0.2).abs() < 1e-3);
258 }
259
260 #[test]
261 fn the_blend_only_acts_inside_the_person_and_scales_with_strength() {
262 assert_eq!(soft_focus_alpha(100, 1.), SOFT_FOCUS_MAX_ALPHA);
263 assert_eq!(soft_focus_alpha(50, 1.), 0.35);
264 assert_eq!(soft_focus_alpha(0, 1.), 0.);
265 assert_eq!(soft_focus_alpha(100, 0.), 0.);
266 assert_eq!(inside_person(0.5), 0.);
267 assert_eq!(inside_person(0.2), 0.);
268 assert_eq!(inside_person(1.), 1.);
269 assert_eq!(blend_coefficients(0., 0.3, 40.), (1., 0.));
270 assert_eq!(blend_coefficients(1., 0.3, 40.), (0.3, 40.));
271 let (gain, bias) = blend_coefficients(0.5, 0.2, 100.);
272 assert_eq!(apply_coefficients(100, gain, bias), 110);
273 }
274
275 fn noisy_plane() -> Vec<u8> {
276 (0..WIDTH * HEIGHT)
277 .map(|index| {
278 let (x, y) = (index % WIDTH, index / WIDTH);
279 let base = if x < WIDTH / 2 { 60 } else { 200 };
280 (base + ((x * 7 + y * 13) % 9) as i32 - 4) as u8
281 })
282 .collect()
283 }
284
285 fn roughness(plane: &[u8], y: usize, from: usize, to: usize) -> i32 {
286 (from..to).map(|x| (i32::from(plane[y * WIDTH + x + 1]) - i32::from(plane[y * WIDTH + x])).abs()).sum()
287 }
288
289 #[test]
290 fn soft_focus_smooths_noise_inside_the_mask_keeps_edges_and_spares_the_outside() {
291 let original = noisy_plane();
292 let mut softened = original.clone();
293 let mask = Mask::from_fn(256, 144, |x, _| if x * 256. < 148. { 1. } else { 0. });
294 soften_luma(&mut softened, WIDTH, WIDTH, HEIGHT, &mask, 100);
295 assert!(roughness(&softened, 18, 2, 20) < roughness(&original, 18, 2, 20));
296 assert!(i32::from(softened[18 * WIDTH + WIDTH / 2 + 2]) - i32::from(softened[18 * WIDTH + WIDTH / 2 - 3]) > 100);
297 assert_eq!(softened[18 * WIDTH + WIDTH - 4], original[18 * WIDTH + WIDTH - 4]);
298 let mut untouched = original.clone();
299 soften_luma(&mut untouched, WIDTH, WIDTH, HEIGHT, &mask, 0);
300 assert_eq!(untouched, original);
301 }
302}