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