Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / camera / src / main / rust / src / luma.rs
luma.rs177 lines · 6.4 KiBRaw
| 1 | //! Zero-copy Y-plane luma statistics: the native half of the contract in |
| 2 | //! Kotlin's `LumaPlaneMath`. The JNI entry takes a *direct* `ByteBuffer` |
| 3 | //! (as delivered by `Image` planes / `ImageReader`) and reads it in place — |
| 4 | //! no byte-array copy crosses JNI. The Kotlin fallback computes the same |
| 5 | //! statistics from any buffer; tests prove the two agree on synthetic |
| 6 | //! planes, padded strides included. |
| 7 | //! |
| 8 | //! Mean: samples every 16th pixel in raster order, summed as integers, so |
| 9 | //! both sides agree exactly before the final division. Grid: at most 96 |
| 10 | //! samples per side, every `strideX`/`strideY`-th pixel. |
| 11 | |
| 12 | use jni_bridge::jni_fn; |
| 13 | |
| 14 | /// Pixels between mean samples, in raster order. |
| 15 | pub const LUMA_SAMPLE_STEP: usize = 16; |
| 16 | /// Longest side of the downsampled grid. |
| 17 | pub const GRID_MAX_SIDE: usize = 96; |
| 18 | |
| 19 | /// Statistics for one Y plane: `(mean, grid, grid_width, grid_height)`. |
| 20 | pub type LumaStats = (f64, Vec<f32>, usize, usize); |
| 21 | |
| 22 | fn readable(len: usize, row_stride: usize, pixel_stride: usize, w: usize, h: usize) -> bool { |
| 23 | if w == 0 || h == 0 || row_stride == 0 || pixel_stride == 0 { |
| 24 | return false; |
| 25 | } |
| 26 | match (h - 1).checked_mul(row_stride).and_then(|v| v.checked_add((w - 1) * pixel_stride)) { |
| 27 | Some(last) => last < len, |
| 28 | None => false, |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | /// Computes the shared statistics over `data`, or `None` when unreadable. |
| 33 | pub fn luma_stats( |
| 34 | data: &[u8], |
| 35 | width: usize, |
| 36 | height: usize, |
| 37 | row_stride: usize, |
| 38 | pixel_stride: usize, |
| 39 | ) -> Option<LumaStats> { |
| 40 | if !readable(data.len(), row_stride, pixel_stride, width, height) { |
| 41 | return None; |
| 42 | } |
| 43 | let stride_x = (width / GRID_MAX_SIDE).max(1); |
| 44 | let stride_y = (height / GRID_MAX_SIDE).max(1); |
| 45 | let grid_width = width.div_ceil(stride_x); |
| 46 | let grid_height = height.div_ceil(stride_y); |
| 47 | let mut grid = vec![0f32; grid_width * grid_height]; |
| 48 | let mut out = 0usize; |
| 49 | let mut y = 0usize; |
| 50 | while y < height { |
| 51 | let row_start = y * row_stride; |
| 52 | let mut x = 0usize; |
| 53 | while x < width { |
| 54 | grid[out] = data[row_start + x * pixel_stride] as f32; |
| 55 | out += 1; |
| 56 | x += stride_x; |
| 57 | } |
| 58 | y += stride_y; |
| 59 | } |
| 60 | let mut sum: u64 = 0; |
| 61 | let mut count: u64 = 0; |
| 62 | let mut n: usize = 0; |
| 63 | let total = width * height; |
| 64 | while n < total { |
| 65 | let x = n % width; |
| 66 | let yy = n / width; |
| 67 | sum += data[yy * row_stride + x * pixel_stride] as u64; |
| 68 | count += 1; |
| 69 | n += LUMA_SAMPLE_STEP; |
| 70 | } |
| 71 | if count == 0 { |
| 72 | return None; |
| 73 | } |
| 74 | Some((sum as f64 / count as f64, grid, grid_width, grid_height)) |
| 75 | } |
| 76 | |
| 77 | #[cfg(test)] |
| 78 | mod luma_tests { |
| 79 | use super::luma_stats; |
| 80 | |
| 81 | fn plane(w: usize, h: usize, row_stride: usize, pixel_stride: usize) -> Vec<u8> { |
| 82 | // Padding bytes are poisoned with 0xEE: stats must never read them |
| 83 | // as pixels, so a stride bug changes the result and fails the test. |
| 84 | let mut data = vec![0xEEu8; row_stride * h]; |
| 85 | for y in 0..h { |
| 86 | for x in 0..w { |
| 87 | data[y * row_stride + x * pixel_stride] = ((x * 7 + y * 13) % 251) as u8; |
| 88 | } |
| 89 | } |
| 90 | data |
| 91 | } |
| 92 | |
| 93 | #[test] |
| 94 | fn flat_plane_mean_and_grid() { |
| 95 | let data = vec![100u8; 64 * 48]; |
| 96 | let (mean, grid, gw, gh) = luma_stats(&data, 64, 48, 64, 1).expect("stats"); |
| 97 | assert_eq!(mean, 100.0); |
| 98 | assert_eq!((gw, gh), (64, 48)); |
| 99 | assert!(grid.iter().all(|v| *v == 100.0)); |
| 100 | } |
| 101 | |
| 102 | #[test] |
| 103 | fn padded_strides_ignore_padding() { |
| 104 | let data = plane(37, 23, 48, 1); |
| 105 | let (mean, grid, gw, _) = luma_stats(&data, 37, 23, 48, 1).expect("stats"); |
| 106 | // Independent recomputation straight from pixel coordinates. |
| 107 | let mut sum = 0u64; |
| 108 | let mut count = 0u64; |
| 109 | let mut n = 0usize; |
| 110 | while n < 37 * 23 { |
| 111 | sum += ((n % 37 * 7 + n / 37 * 13) % 251) as u64; |
| 112 | count += 1; |
| 113 | n += 16; |
| 114 | } |
| 115 | assert_eq!(mean, sum as f64 / count as f64); |
| 116 | assert_eq!(gw, 37); |
| 117 | assert_eq!(grid[0], 0.0); |
| 118 | } |
| 119 | |
| 120 | #[test] |
| 121 | fn rejects_unreadable_planes() { |
| 122 | assert!(luma_stats(&[], 0, 0, 0, 1).is_none()); |
| 123 | assert!(luma_stats(&[0u8; 10], 64, 48, 64, 1).is_none()); |
| 124 | assert!(luma_stats(&[0u8; 64 * 48], 64, 48, 0, 1).is_none()); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | jni_fn! { /// JNI entry for `StitchNative.lumaStatsFromYPlane`: direct Y-plane buffer |
| 129 | /// in, `[mean, gridWidth, gridHeight, grid...]` float array out, null on any |
| 130 | /// failure (non-direct buffer, bad strides, undersized buffer) so Kotlin |
| 131 | /// falls back to its own identical computation. |
| 132 | Java_com_vayunmathur_camera_platform_StitchNative_lumaStatsFromYPlane -> jni::sys::jfloatArray; (_class: jni::objects::JClass<'l>, buffer: jni::objects::JByteBuffer<'l>, width: jni::sys::jint, height: jni::sys::jint, row_stride: jni::sys::jint, pixel_stride: jni::sys::jint) |env| { |
| 133 | let null = std::ptr::null_mut(); |
| 134 | if width <= 0 || height <= 0 || row_stride <= 0 || pixel_stride <= 0 { |
| 135 | return Ok(null); |
| 136 | } |
| 137 | let address = match env.get_direct_buffer_address(&buffer) { |
| 138 | Ok(a) => a, |
| 139 | Err(_) => return Ok(null), |
| 140 | }; |
| 141 | if address.is_null() { |
| 142 | return Ok(null); |
| 143 | } |
| 144 | let capacity = match env.get_direct_buffer_capacity(&buffer) { |
| 145 | Ok(c) => c, |
| 146 | Err(_) => return Ok(null), |
| 147 | }; |
| 148 | // The buffer is a live local reference for the whole call, so the |
| 149 | // address stays valid while the slice is read; nothing is retained. |
| 150 | let data = unsafe { std::slice::from_raw_parts(address, capacity) }; |
| 151 | let stats = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 152 | luma_stats( |
| 153 | data, |
| 154 | width as usize, |
| 155 | height as usize, |
| 156 | row_stride as usize, |
| 157 | pixel_stride as usize, |
| 158 | ) |
| 159 | })) |
| 160 | .unwrap_or(None); |
| 161 | let Some((mean, grid, grid_width, grid_height)) = stats else { |
| 162 | return Ok(null); |
| 163 | }; |
| 164 | let mut out = Vec::with_capacity(3 + grid.len()); |
| 165 | out.push(mean as f32); |
| 166 | out.push(grid_width as f32); |
| 167 | out.push(grid_height as f32); |
| 168 | out.extend_from_slice(&grid); |
| 169 | let arr = match env.new_float_array(out.len()) { |
| 170 | Ok(a) => a, |
| 171 | Err(_) => return Ok(null), |
| 172 | }; |
| 173 | match arr.set_region(env, 0, &out) { |
| 174 | Ok(()) => Ok(arr.into_raw()), |
| 175 | Err(_) => Ok(null), |
| 176 | } |
| 177 | } } |