BlueGit

ict rusty-teams

Files

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

luma_effects.rs

luma_effects.rs 13.7 KiB Download Raw
1use std::time::Duration;
2
3use crate::blur::{MASK_HEIGHT, MASK_WIDTH, 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: &[f32], 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 mut cells = Cells { gain: vec![1.; small.len()], bias: vec![0.; small.len()], alpha: vec![0.; small.len()], width: cell_width, height: cell_height };
131 for row in 0..cell_height {
132 let (mask_top, mask_bottom, mask_fraction) = (mask_y.first[row] * MASK_WIDTH, mask_y.second[row] * MASK_WIDTH, mask_y.weight[row]);
133 for column in 0..cell_width {
134 let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);
135 let top = mask[mask_top + left] * (1. - across) + mask[mask_top + right] * across;
136 let bottom = mask[mask_bottom + left] * (1. - across) + mask[mask_bottom + right] * across;
137 let index = row * cell_width + column;
138 let alpha = soft_focus_alpha(strength_percent, inside_person(top * (1. - mask_fraction) + bottom * mask_fraction));
139 (cells.gain[index], cells.bias[index]) = blend_coefficients(alpha, mean_slope[index], mean_offset[index]);
140 cells.alpha[index] = alpha;
141 }
142 }
143 cells
144}
145
146fn neighbor(index: usize, step: usize, last: usize) -> usize {
147 if step < CELL / 2 { index.saturating_sub(1) } else { (index + 1).min(last) }
148}
149
150fn active_columns(cells: &Cells, near_start: usize, far_start: usize, active: &mut [bool]) {
151 let alpha_at = |column: usize| cells.alpha[near_start + column] > 0. || cells.alpha[far_start + column] > 0.;
152 for (column, slot) in active.iter_mut().enumerate() {
153 *slot = alpha_at(column) || alpha_at(column.saturating_sub(1)) || alpha_at((column + 1).min(cells.width - 1));
154 }
155}
156
157fn blend_rows(plane: &mut [u8], stride: usize, first_row: usize, cells: &Cells) {
158 let (mut gain_row, mut bias_row) = (vec![0f32; cells.width], vec![0f32; cells.width]);
159 let mut active = vec![false; cells.width];
160 let last = cells.width - 1;
161 for (offset, line) in plane.chunks_mut(stride).enumerate() {
162 let row = first_row + offset;
163 if row >= cells.height * CELL {
164 break;
165 }
166 let (near, step) = (row / CELL, row % CELL);
167 let far = neighbor(near, step, cells.height - 1);
168 let (near_start, far_start) = (near * cells.width, far * cells.width);
169 active_columns(cells, near_start, far_start, &mut active);
170 if !active.contains(&true) {
171 continue;
172 }
173 let (near_weight, far_weight) = (NEAR_WEIGHTS[step], 1. - NEAR_WEIGHTS[step]);
174 for column in 0..cells.width {
175 gain_row[column] = cells.gain[near_start + column] * near_weight + cells.gain[far_start + column] * far_weight;
176 bias_row[column] = cells.bias[near_start + column] * near_weight + cells.bias[far_start + column] * far_weight;
177 }
178 for (column, group) in line[..cells.width * CELL].as_chunks_mut::<CELL>().0.iter_mut().enumerate() {
179 if !active[column] {
180 continue;
181 }
182 let (before, after) = (column.saturating_sub(1), (column + 1).min(last));
183 let (gain, bias) = (gain_row[column], bias_row[column]);
184 let (gain_before, bias_before, gain_after, bias_after) = (gain_row[before], bias_row[before], gain_row[after], bias_row[after]);
185 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])];
186 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])];
187 for (value, (gain, bias)) in group.iter_mut().zip(gains.into_iter().zip(biases)) {
188 *value = apply_coefficients(*value, gain, bias);
189 }
190 }
191 }
192}
193
194/// Edge-preserving smoothing (fast guided filter, radius about 4) of the luma plane, blended in only inside the person mask.
195pub fn soften_luma(plane: &mut [u8], stride: usize, width: usize, height: usize, mask: &[f32], strength_percent: u8) {
196 if strength_percent == 0 || width < CELL * 2 || height < CELL * 2 {
197 return;
198 }
199 let cells = smoothing_cells(plane, stride, width, height, mask, strength_percent);
200 let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
201 let rows_per_band = height.div_ceil(bands).next_multiple_of(CELL);
202 std::thread::scope(|scope| {
203 for (index, band) in plane[..stride * (height - 1) + width].chunks_mut(rows_per_band * stride).enumerate() {
204 let cells = &cells;
205 scope.spawn(move || blend_rows(band, stride, index * rows_per_band, cells));
206 }
207 });
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213
214 const WIDTH: usize = 64;
215 const HEIGHT: usize = 36;
216
217 #[test]
218 fn the_gamma_follows_the_darkness_and_leaves_bright_frames_alone() {
219 assert_eq!(target_gamma(0.5), 1.);
220 assert_eq!(target_gamma(0.35), 1.);
221 assert!((target_gamma(0.3499) - GAMMA_AT_DARK).abs() < 0.001);
222 assert_eq!(target_gamma(0.05), GAMMA_AT_VERY_DARK);
223 assert_eq!(target_gamma(0.), GAMMA_AT_VERY_DARK);
224 let middle = target_gamma(0.2);
225 assert!(middle < GAMMA_AT_DARK && middle > GAMMA_AT_VERY_DARK);
226 }
227
228 #[test]
229 fn the_gamma_glides_instead_of_jumping() {
230 let step = Duration::from_millis(33);
231 let first = smooth_gamma(1., 0.6, step);
232 assert!(first < 1. && first > 0.95);
233 let mut gamma = 1.;
234 for _ in 0..300 {
235 gamma = smooth_gamma(gamma, 0.6, step);
236 }
237 assert_eq!(gamma, 0.6);
238 }
239
240 #[test]
241 fn the_table_brightens_dark_values_and_keeps_the_ends() {
242 let table = gamma_table(0.6);
243 assert_eq!((table[0], table[255]), (0, 255));
244 assert!(table[40] > 40 && table[128] > 128);
245 assert!(table.windows(2).all(|pair| pair[0] <= pair[1]));
246 assert_eq!(gamma_table(1.), std::array::from_fn(|value| value as u8));
247 let mut plane = vec![40u8; WIDTH * HEIGHT];
248 apply_table(&mut plane, WIDTH, WIDTH, HEIGHT, &table);
249 assert!(plane.iter().all(|&value| value == table[40]));
250 }
251
252 #[test]
253 fn the_mean_luma_is_a_fraction_of_full_scale() {
254 assert_eq!(mean_luma(&vec![255; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT), 1.);
255 assert_eq!(mean_luma(&vec![0; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT), 0.);
256 assert!((mean_luma(&vec![51; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT) - 0.2).abs() < 1e-3);
257 }
258
259 #[test]
260 fn the_blend_only_acts_inside_the_person_and_scales_with_strength() {
261 assert_eq!(soft_focus_alpha(100, 1.), SOFT_FOCUS_MAX_ALPHA);
262 assert_eq!(soft_focus_alpha(50, 1.), 0.35);
263 assert_eq!(soft_focus_alpha(0, 1.), 0.);
264 assert_eq!(soft_focus_alpha(100, 0.), 0.);
265 assert_eq!(inside_person(0.5), 0.);
266 assert_eq!(inside_person(0.2), 0.);
267 assert_eq!(inside_person(1.), 1.);
268 assert_eq!(blend_coefficients(0., 0.3, 40.), (1., 0.));
269 assert_eq!(blend_coefficients(1., 0.3, 40.), (0.3, 40.));
270 let (gain, bias) = blend_coefficients(0.5, 0.2, 100.);
271 assert_eq!(apply_coefficients(100, gain, bias), 110);
272 }
273
274 fn noisy_plane() -> Vec<u8> {
275 (0..WIDTH * HEIGHT)
276 .map(|index| {
277 let (x, y) = (index % WIDTH, index / WIDTH);
278 let base = if x < WIDTH / 2 { 60 } else { 200 };
279 (base + ((x * 7 + y * 13) % 9) as i32 - 4) as u8
280 })
281 .collect()
282 }
283
284 fn roughness(plane: &[u8], y: usize, from: usize, to: usize) -> i32 {
285 (from..to).map(|x| (i32::from(plane[y * WIDTH + x + 1]) - i32::from(plane[y * WIDTH + x])).abs()).sum()
286 }
287
288 #[test]
289 fn soft_focus_smooths_noise_inside_the_mask_keeps_edges_and_spares_the_outside() {
290 let original = noisy_plane();
291 let mut softened = original.clone();
292 let mut mask = vec![0f32; MASK_WIDTH * MASK_HEIGHT];
293 for row in 0..MASK_HEIGHT {
294 mask[row * MASK_WIDTH..][..MASK_WIDTH / 2 + 20].fill(1.);
295 }
296 soften_luma(&mut softened, WIDTH, WIDTH, HEIGHT, &mask, 100);
297 assert!(roughness(&softened, 18, 2, 20) < roughness(&original, 18, 2, 20));
298 assert!(i32::from(softened[18 * WIDTH + WIDTH / 2 + 2]) - i32::from(softened[18 * WIDTH + WIDTH / 2 - 3]) > 100);
299 assert_eq!(softened[18 * WIDTH + WIDTH - 4], original[18 * WIDTH + WIDTH - 4]);
300 let mut untouched = original.clone();
301 soften_luma(&mut untouched, WIDTH, WIDTH, HEIGHT, &mask, 0);
302 assert_eq!(untouched, original);
303 }
304}