| 1 | //! GPU dense optical flow (`Dimension.OpticalFlow`) and flow-warped frame interpolation |
| 2 | //! (`TimeStretcher` `InterpolateBetweenFrames = 1` Blend and `= 2` Flow). |
| 3 | |
| 4 | use crate::cache::CachedTexture; |
| 5 | use bytemuck::{Pod, Zeroable}; |
| 6 | use model::BitDepth; |
| 7 | use std::collections::{HashMap, VecDeque}; |
| 8 | use std::collections::hash_map::DefaultHasher; |
| 9 | use std::hash::{Hash, Hasher}; |
| 10 | use std::num::NonZeroU64; |
| 11 | use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; |
| 12 | |
| 13 | fn lock_or_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { |
| 14 | m.lock().unwrap_or_else(|e| e.into_inner()) |
| 15 | } |
| 16 | |
| 17 | fn read_or_recover<T>(rw: &RwLock<T>) -> RwLockReadGuard<'_, T> { |
| 18 | rw.read().unwrap_or_else(|e| e.into_inner()) |
| 19 | } |
| 20 | |
| 21 | fn write_or_recover<T>(rw: &RwLock<T>) -> RwLockWriteGuard<'_, T> { |
| 22 | rw.write().unwrap_or_else(|e| e.into_inner()) |
| 23 | } |
| 24 | |
| 25 | #[repr(C)] |
| 26 | #[derive(Clone, Copy, Pod, Zeroable)] |
| 27 | struct OptFlowUniform { |
| 28 | /// `[dst_w, dst_h, inv_dst_w, inv_dst_h]` |
| 29 | dst_size: [f32; 4], |
| 30 | /// `[scale_x, scale_y, alpha, extra]` |
| 31 | params: [f32; 4], |
| 32 | } |
| 33 | |
| 34 | const OPTFLOW_WGSL: &str = r#" |
| 35 | struct OptFlowUniform { |
| 36 | dst_size: vec4<f32>, |
| 37 | params: vec4<f32>, |
| 38 | }; |
| 39 | |
| 40 | @group(0) @binding(0) var tex_a: texture_2d<f32>; |
| 41 | @group(0) @binding(1) var tex_b: texture_2d<f32>; |
| 42 | @group(0) @binding(2) var tex_c: texture_2d<f32>; |
| 43 | @group(0) @binding(3) var lin_samp: sampler; |
| 44 | @group(0) @binding(4) var<uniform> u: OptFlowUniform; |
| 45 | |
| 46 | struct VsOut { |
| 47 | @builtin(position) pos: vec4<f32>, |
| 48 | @location(0) uv: vec2<f32>, |
| 49 | }; |
| 50 | |
| 51 | @vertex |
| 52 | fn vs_fullscreen(@builtin(vertex_index) vid: u32) -> VsOut { |
| 53 | var positions = array<vec2<f32>, 3>( |
| 54 | vec2<f32>(-1.0, -1.0), |
| 55 | vec2<f32>(3.0, -1.0), |
| 56 | vec2<f32>(-1.0, 3.0), |
| 57 | ); |
| 58 | let p = positions[vid]; |
| 59 | var out: VsOut; |
| 60 | out.pos = vec4<f32>(p, 0.0, 1.0); |
| 61 | out.uv = vec2<f32>(p.x * 0.5 + 0.5, 0.5 - p.y * 0.5); |
| 62 | return out; |
| 63 | } |
| 64 | |
| 65 | // --- 0. Linear cross-dissolve (TimeStretcher InterpolateBetweenFrames = 1 Blend) --- |
| 66 | |
| 67 | @fragment |
| 68 | fn fs_blend(in: VsOut) -> @location(0) vec4<f32> { |
| 69 | let a = textureSampleLevel(tex_a, lin_samp, in.uv, 0.0); |
| 70 | let b = textureSampleLevel(tex_b, lin_samp, in.uv, 0.0); |
| 71 | let alpha = clamp(u.params.z, 0.0, 1.0); |
| 72 | return mix(a, b, alpha); |
| 73 | } |
| 74 | |
| 75 | // --- 1. Feature extraction & anti-aliased pyramid downsample --- |
| 76 | // Stores (luma, R-G chroma, B-Y chroma, alpha) in Rgba16Float so isoluminant colored edges track. |
| 77 | |
| 78 | @fragment |
| 79 | fn fs_extract_features(in: VsOut) -> @location(0) vec4<f32> { |
| 80 | let c = textureSampleLevel(tex_a, lin_samp, in.uv, 0.0); |
| 81 | let luma = dot(c.rgb, vec3<f32>(0.299, 0.587, 0.114)); |
| 82 | let rg = (c.r - c.g) * 0.5; |
| 83 | let by = (c.b - 0.5 * (c.r + c.g)) * 0.5; |
| 84 | return vec4<f32>(luma, rg, by, c.a); |
| 85 | } |
| 86 | |
| 87 | @fragment |
| 88 | fn fs_downsample(in: VsOut) -> @location(0) vec4<f32> { |
| 89 | // 4-tap bilinear box/tent filter at +-0.25 dst texels (~ +-0.5 src texels) |
| 90 | let d = u.dst_size.zw * 0.25; |
| 91 | let c0 = textureSampleLevel(tex_a, lin_samp, in.uv + vec2<f32>(-d.x, -d.y), 0.0); |
| 92 | let c1 = textureSampleLevel(tex_a, lin_samp, in.uv + vec2<f32>( d.x, -d.y), 0.0); |
| 93 | let c2 = textureSampleLevel(tex_a, lin_samp, in.uv + vec2<f32>(-d.x, d.y), 0.0); |
| 94 | let c3 = textureSampleLevel(tex_a, lin_samp, in.uv + vec2<f32>( d.x, d.y), 0.0); |
| 95 | return 0.25 * (c0 + c1 + c2 + c3); |
| 96 | } |
| 97 | |
| 98 | // --- Helper: weighted 3x3 patch SAD between src_tex(uv) and dst_tex(uv + flow_px * inv_size) --- |
| 99 | |
| 100 | fn feat_diff(a: vec4<f32>, b: vec4<f32>) -> f32 { |
| 101 | let d = abs(a - b); |
| 102 | return d.x + 0.85 * (d.y + d.z) + 0.5 * d.w; |
| 103 | } |
| 104 | |
| 105 | fn patch_sad_ab(uv: vec2<f32>, flow_px: vec2<f32>, inv_sz: vec2<f32>) -> f32 { |
| 106 | let uv_t = uv + flow_px * inv_sz; |
| 107 | var cost: f32 = 0.0; |
| 108 | for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { |
| 109 | for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { |
| 110 | let off = vec2<f32>(f32(dx), f32(dy)) * inv_sz; |
| 111 | let w = select(1.0, 2.0, dx == 0 && dy == 0); |
| 112 | let fa = textureSampleLevel(tex_a, lin_samp, uv + off, 0.0); |
| 113 | let fb = textureSampleLevel(tex_b, lin_samp, uv_t + off, 0.0); |
| 114 | cost = cost + w * feat_diff(fa, fb); |
| 115 | } |
| 116 | } |
| 117 | return cost; |
| 118 | } |
| 119 | |
| 120 | fn patch_sad_ba(uv: vec2<f32>, flow_px: vec2<f32>, inv_sz: vec2<f32>) -> f32 { |
| 121 | let uv_t = uv + flow_px * inv_sz; |
| 122 | var cost: f32 = 0.0; |
| 123 | for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { |
| 124 | for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { |
| 125 | let off = vec2<f32>(f32(dx), f32(dy)) * inv_sz; |
| 126 | let w = select(1.0, 2.0, dx == 0 && dy == 0); |
| 127 | let fb = textureSampleLevel(tex_b, lin_samp, uv + off, 0.0); |
| 128 | let fa = textureSampleLevel(tex_a, lin_samp, uv_t + off, 0.0); |
| 129 | cost = cost + w * feat_diff(fb, fa); |
| 130 | } |
| 131 | } |
| 132 | return cost; |
| 133 | } |
| 134 | |
| 135 | fn parabolic_offset(c_neg: f32, c_0: f32, c_pos: f32) -> f32 { |
| 136 | let denom = c_neg - 2.0 * c_0 + c_pos; |
| 137 | if (denom <= 1e-5) { |
| 138 | return 0.0; |
| 139 | } |
| 140 | return clamp(0.5 * (c_neg - c_pos) / denom, -0.5, 0.5); |
| 141 | } |
| 142 | |
| 143 | // --- 2a. Coarsest level (1/8 res): [-4..4] x [-4..4] bidirectional search + parabolic subpixel --- |
| 144 | |
| 145 | @fragment |
| 146 | fn fs_flow_coarse(in: VsOut) -> @location(0) vec4<f32> { |
| 147 | let inv_sz = u.dst_size.zw; |
| 148 | let reg = 0.0004; |
| 149 | |
| 150 | // Forward A -> B |
| 151 | var best_fwd = vec2<f32>(0.0, 0.0); |
| 152 | var best_fwd_cost: f32 = 1e20; |
| 153 | for (var dy: i32 = -4; dy <= 4; dy = dy + 1) { |
| 154 | for (var dx: i32 = -4; dx <= 4; dx = dx + 1) { |
| 155 | let v = vec2<f32>(f32(dx), f32(dy)); |
| 156 | let c = patch_sad_ab(in.uv, v, inv_sz) + reg * dot(v, v); |
| 157 | if (c < best_fwd_cost) { |
| 158 | best_fwd_cost = c; |
| 159 | best_fwd = v; |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | let fc_l = patch_sad_ab(in.uv, best_fwd + vec2<f32>(-1.0, 0.0), inv_sz); |
| 164 | let fc_r = patch_sad_ab(in.uv, best_fwd + vec2<f32>( 1.0, 0.0), inv_sz); |
| 165 | let fc_u = patch_sad_ab(in.uv, best_fwd + vec2<f32>(0.0, -1.0), inv_sz); |
| 166 | let fc_d = patch_sad_ab(in.uv, best_fwd + vec2<f32>(0.0, 1.0), inv_sz); |
| 167 | let fc_0 = patch_sad_ab(in.uv, best_fwd, inv_sz); |
| 168 | let fwd = best_fwd + vec2<f32>( |
| 169 | parabolic_offset(fc_l, fc_0, fc_r), |
| 170 | parabolic_offset(fc_u, fc_0, fc_d), |
| 171 | ); |
| 172 | |
| 173 | // Backward B -> A |
| 174 | var best_bwd = vec2<f32>(0.0, 0.0); |
| 175 | var best_bwd_cost: f32 = 1e20; |
| 176 | for (var dy: i32 = -4; dy <= 4; dy = dy + 1) { |
| 177 | for (var dx: i32 = -4; dx <= 4; dx = dx + 1) { |
| 178 | let v = vec2<f32>(f32(dx), f32(dy)); |
| 179 | let c = patch_sad_ba(in.uv, v, inv_sz) + reg * dot(v, v); |
| 180 | if (c < best_bwd_cost) { |
| 181 | best_bwd_cost = c; |
| 182 | best_bwd = v; |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | let bc_l = patch_sad_ba(in.uv, best_bwd + vec2<f32>(-1.0, 0.0), inv_sz); |
| 187 | let bc_r = patch_sad_ba(in.uv, best_bwd + vec2<f32>( 1.0, 0.0), inv_sz); |
| 188 | let bc_u = patch_sad_ba(in.uv, best_bwd + vec2<f32>(0.0, -1.0), inv_sz); |
| 189 | let bc_d = patch_sad_ba(in.uv, best_bwd + vec2<f32>(0.0, 1.0), inv_sz); |
| 190 | let bc_0 = patch_sad_ba(in.uv, best_bwd, inv_sz); |
| 191 | let bwd = best_bwd + vec2<f32>( |
| 192 | parabolic_offset(bc_l, bc_0, bc_r), |
| 193 | parabolic_offset(bc_u, bc_0, bc_d), |
| 194 | ); |
| 195 | |
| 196 | return vec4<f32>(fwd, bwd); |
| 197 | } |
| 198 | |
| 199 | // --- 2b. Finer levels (1/4, 1/2): upsample x2 + [-2..2] search + 1 iter Lucas-Kanade --- |
| 200 | |
| 201 | fn lk_refine_ab(uv: vec2<f32>, flow_px: vec2<f32>, inv_sz: vec2<f32>) -> vec2<f32> { |
| 202 | let uv_t = uv + flow_px * inv_sz; |
| 203 | var a00: f32 = 0.015; |
| 204 | var a01: f32 = 0.0; |
| 205 | var a11: f32 = 0.015; |
| 206 | var b0: f32 = 0.0; |
| 207 | var b1: f32 = 0.0; |
| 208 | let dx_uv = vec2<f32>(inv_sz.x, 0.0); |
| 209 | let dy_uv = vec2<f32>(0.0, inv_sz.y); |
| 210 | |
| 211 | for (var j: i32 = -1; j <= 1; j = j + 1) { |
| 212 | for (var i: i32 = -1; i <= 1; i = i + 1) { |
| 213 | let off = vec2<f32>(f32(i), f32(j)) * inv_sz; |
| 214 | let p_a = textureSampleLevel(tex_a, lin_samp, uv + off, 0.0); |
| 215 | let p_b = textureSampleLevel(tex_b, lin_samp, uv_t + off, 0.0); |
| 216 | let gx = 0.5 * ( |
| 217 | textureSampleLevel(tex_b, lin_samp, uv_t + off + dx_uv, 0.0) - |
| 218 | textureSampleLevel(tex_b, lin_samp, uv_t + off - dx_uv, 0.0) |
| 219 | ); |
| 220 | let gy = 0.5 * ( |
| 221 | textureSampleLevel(tex_b, lin_samp, uv_t + off + dy_uv, 0.0) - |
| 222 | textureSampleLevel(tex_b, lin_samp, uv_t + off - dy_uv, 0.0) |
| 223 | ); |
| 224 | let it = p_b - p_a; |
| 225 | let w = vec4<f32>(1.0, 0.85, 0.85, 0.5); |
| 226 | a00 = a00 + dot(gx * gx, w); |
| 227 | a01 = a01 + dot(gx * gy, w); |
| 228 | a11 = a11 + dot(gy * gy, w); |
| 229 | b0 = b0 - dot(gx * it, w); |
| 230 | b1 = b1 - dot(gy * it, w); |
| 231 | } |
| 232 | } |
| 233 | let det = a00 * a11 - a01 * a01; |
| 234 | if (abs(det) < 1e-6) { |
| 235 | return flow_px; |
| 236 | } |
| 237 | let delta = vec2<f32>( |
| 238 | (a11 * b0 - a01 * b1) / det, |
| 239 | (-a01 * b0 + a00 * b1) / det, |
| 240 | ); |
| 241 | return flow_px + clamp(delta, vec2<f32>(-1.0), vec2<f32>(1.0)); |
| 242 | } |
| 243 | |
| 244 | fn lk_refine_ba(uv: vec2<f32>, flow_px: vec2<f32>, inv_sz: vec2<f32>) -> vec2<f32> { |
| 245 | let uv_t = uv + flow_px * inv_sz; |
| 246 | var a00: f32 = 0.015; |
| 247 | var a01: f32 = 0.0; |
| 248 | var a11: f32 = 0.015; |
| 249 | var b0: f32 = 0.0; |
| 250 | var b1: f32 = 0.0; |
| 251 | let dx_uv = vec2<f32>(inv_sz.x, 0.0); |
| 252 | let dy_uv = vec2<f32>(0.0, inv_sz.y); |
| 253 | |
| 254 | for (var j: i32 = -1; j <= 1; j = j + 1) { |
| 255 | for (var i: i32 = -1; i <= 1; i = i + 1) { |
| 256 | let off = vec2<f32>(f32(i), f32(j)) * inv_sz; |
| 257 | let p_b = textureSampleLevel(tex_b, lin_samp, uv + off, 0.0); |
| 258 | let p_a = textureSampleLevel(tex_a, lin_samp, uv_t + off, 0.0); |
| 259 | let gx = 0.5 * ( |
| 260 | textureSampleLevel(tex_a, lin_samp, uv_t + off + dx_uv, 0.0) - |
| 261 | textureSampleLevel(tex_a, lin_samp, uv_t + off - dx_uv, 0.0) |
| 262 | ); |
| 263 | let gy = 0.5 * ( |
| 264 | textureSampleLevel(tex_a, lin_samp, uv_t + off + dy_uv, 0.0) - |
| 265 | textureSampleLevel(tex_a, lin_samp, uv_t + off - dy_uv, 0.0) |
| 266 | ); |
| 267 | let it = p_a - p_b; |
| 268 | let w = vec4<f32>(1.0, 0.85, 0.85, 0.5); |
| 269 | a00 = a00 + dot(gx * gx, w); |
| 270 | a01 = a01 + dot(gx * gy, w); |
| 271 | a11 = a11 + dot(gy * gy, w); |
| 272 | b0 = b0 - dot(gx * it, w); |
| 273 | b1 = b1 - dot(gy * it, w); |
| 274 | } |
| 275 | } |
| 276 | let det = a00 * a11 - a01 * a01; |
| 277 | if (abs(det) < 1e-6) { |
| 278 | return flow_px; |
| 279 | } |
| 280 | let delta = vec2<f32>( |
| 281 | (a11 * b0 - a01 * b1) / det, |
| 282 | (-a01 * b0 + a00 * b1) / det, |
| 283 | ); |
| 284 | return flow_px + clamp(delta, vec2<f32>(-1.0), vec2<f32>(1.0)); |
| 285 | } |
| 286 | |
| 287 | @fragment |
| 288 | fn fs_flow_refine(in: VsOut) -> @location(0) vec4<f32> { |
| 289 | let inv_sz = u.dst_size.zw; |
| 290 | let scale = u.params.xy; |
| 291 | let prev = textureSampleLevel(tex_c, lin_samp, in.uv, 0.0); |
| 292 | let base_fwd = prev.xy * scale; |
| 293 | let base_bwd = prev.zw * scale; |
| 294 | let reg = 0.00015; |
| 295 | |
| 296 | // Forward A -> B: local [-2..2] around base_fwd, plus zero-flow candidate for sharp static boundaries |
| 297 | var best_fwd = base_fwd; |
| 298 | var best_fwd_cost = patch_sad_ab(in.uv, base_fwd, inv_sz) + reg * dot(base_fwd, base_fwd); |
| 299 | let zero_fwd_cost = patch_sad_ab(in.uv, vec2<f32>(0.0), inv_sz); |
| 300 | if (zero_fwd_cost < best_fwd_cost) { |
| 301 | best_fwd_cost = zero_fwd_cost; |
| 302 | best_fwd = vec2<f32>(0.0); |
| 303 | } |
| 304 | for (var dy: i32 = -2; dy <= 2; dy = dy + 1) { |
| 305 | for (var dx: i32 = -2; dx <= 2; dx = dx + 1) { |
| 306 | if (dx == 0 && dy == 0) { continue; } |
| 307 | let v = base_fwd + vec2<f32>(f32(dx), f32(dy)); |
| 308 | let c = patch_sad_ab(in.uv, v, inv_sz) + reg * dot(v, v); |
| 309 | if (c < best_fwd_cost) { |
| 310 | best_fwd_cost = c; |
| 311 | best_fwd = v; |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | let fwd = lk_refine_ab(in.uv, best_fwd, inv_sz); |
| 316 | |
| 317 | // Backward B -> A: local [-2..2] around base_bwd, plus zero-flow candidate |
| 318 | var best_bwd = base_bwd; |
| 319 | var best_bwd_cost = patch_sad_ba(in.uv, base_bwd, inv_sz) + reg * dot(base_bwd, base_bwd); |
| 320 | let zero_bwd_cost = patch_sad_ba(in.uv, vec2<f32>(0.0), inv_sz); |
| 321 | if (zero_bwd_cost < best_bwd_cost) { |
| 322 | best_bwd_cost = zero_bwd_cost; |
| 323 | best_bwd = vec2<f32>(0.0); |
| 324 | } |
| 325 | for (var dy: i32 = -2; dy <= 2; dy = dy + 1) { |
| 326 | for (var dx: i32 = -2; dx <= 2; dx = dx + 1) { |
| 327 | if (dx == 0 && dy == 0) { continue; } |
| 328 | let v = base_bwd + vec2<f32>(f32(dx), f32(dy)); |
| 329 | let c = patch_sad_ba(in.uv, v, inv_sz) + reg * dot(v, v); |
| 330 | if (c < best_bwd_cost) { |
| 331 | best_bwd_cost = c; |
| 332 | best_bwd = v; |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | let bwd = lk_refine_ba(in.uv, best_bwd, inv_sz); |
| 337 | |
| 338 | return vec4<f32>(fwd, bwd); |
| 339 | } |
| 340 | |
| 341 | // --- 2c. Edge-preserving 3x3 bilateral flow smoothing --- |
| 342 | // Uses feat_a edges to guide fwd smoothing and feat_b edges to guide bwd smoothing. |
| 343 | |
| 344 | @fragment |
| 345 | fn fs_flow_smooth(in: VsOut) -> @location(0) vec4<f32> { |
| 346 | let inv_sz = u.dst_size.zw; |
| 347 | let center_flow = textureSampleLevel(tex_c, lin_samp, in.uv, 0.0); |
| 348 | let center_fa = textureSampleLevel(tex_a, lin_samp, in.uv, 0.0); |
| 349 | let center_fb = textureSampleLevel(tex_b, lin_samp, in.uv, 0.0); |
| 350 | |
| 351 | var sum_fwd = vec2<f32>(0.0); |
| 352 | var w_fwd: f32 = 0.0; |
| 353 | var sum_bwd = vec2<f32>(0.0); |
| 354 | var w_bwd: f32 = 0.0; |
| 355 | |
| 356 | let inv_2sig_f2 = 1.0 / (2.0 * 0.08 * 0.08); |
| 357 | let inv_2sig_v2 = 1.0 / (2.0 * 1.5 * 1.5); |
| 358 | |
| 359 | for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { |
| 360 | for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { |
| 361 | let off = vec2<f32>(f32(dx), f32(dy)) * inv_sz; |
| 362 | let q_uv = in.uv + off; |
| 363 | let q_flow = textureSampleLevel(tex_c, lin_samp, q_uv, 0.0); |
| 364 | let q_fa = textureSampleLevel(tex_a, lin_samp, q_uv, 0.0); |
| 365 | let q_fb = textureSampleLevel(tex_b, lin_samp, q_uv, 0.0); |
| 366 | |
| 367 | let spatial = select(0.5, 1.0, dx == 0 && dy == 0); |
| 368 | |
| 369 | let dfa = q_fa - center_fa; |
| 370 | let dfv = q_flow.xy - center_flow.xy; |
| 371 | let wf = spatial * exp(-dot(dfa, dfa) * inv_2sig_f2 - dot(dfv, dfv) * inv_2sig_v2); |
| 372 | sum_fwd = sum_fwd + wf * q_flow.xy; |
| 373 | w_fwd = w_fwd + wf; |
| 374 | |
| 375 | let dfb = q_fb - center_fb; |
| 376 | let dbv = q_flow.zw - center_flow.zw; |
| 377 | let wb = spatial * exp(-dot(dfb, dfb) * inv_2sig_f2 - dot(dbv, dbv) * inv_2sig_v2); |
| 378 | sum_bwd = sum_bwd + wb * q_flow.zw; |
| 379 | w_bwd = w_bwd + wb; |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | let out_fwd = select(center_flow.xy, sum_fwd / w_fwd, w_fwd > 1e-5); |
| 384 | let out_bwd = select(center_flow.zw, sum_bwd / w_bwd, w_bwd > 1e-5); |
| 385 | return vec4<f32>(out_fwd, out_bwd); |
| 386 | } |
| 387 | |
| 388 | // --- 3. Bidirectional occlusion-aware warp & blend into target_format --- |
| 389 | |
| 390 | struct WarpCandidate { |
| 391 | col_a: vec4<f32>, |
| 392 | col_b: vec4<f32>, |
| 393 | err_va: f32, |
| 394 | err_vb: f32, |
| 395 | score: f32, |
| 396 | }; |
| 397 | |
| 398 | fn eval_candidate(uv: vec2<f32>, v_px: vec2<f32>, alpha: f32, inv_sz: vec2<f32>, flow_scale: vec2<f32>) -> WarpCandidate { |
| 399 | let v_uv = v_px * inv_sz; |
| 400 | let uv_a = uv - alpha * v_uv; |
| 401 | let uv_b = uv + (1.0 - alpha) * v_uv; |
| 402 | |
| 403 | let col_a = textureSampleLevel(tex_a, lin_samp, uv_a, 0.0); |
| 404 | let col_b = textureSampleLevel(tex_b, lin_samp, uv_b, 0.0); |
| 405 | |
| 406 | let f_at_a = textureSampleLevel(tex_c, lin_samp, uv_a, 0.0).xy * flow_scale; |
| 407 | let f_at_b = -textureSampleLevel(tex_c, lin_samp, uv_b, 0.0).zw * flow_scale; |
| 408 | |
| 409 | let err_va = length(f_at_a - v_px); |
| 410 | let err_vb = length(f_at_b - v_px); |
| 411 | let photo_err = length(col_a - col_b); |
| 412 | |
| 413 | let cost_both = err_va + err_vb + 6.0 * photo_err; |
| 414 | let cost_one = min(err_va, err_vb) + 1.5; |
| 415 | |
| 416 | var out: WarpCandidate; |
| 417 | out.col_a = col_a; |
| 418 | out.col_b = col_b; |
| 419 | out.err_va = err_va; |
| 420 | out.err_vb = err_vb; |
| 421 | out.score = min(cost_both, cost_one); |
| 422 | return out; |
| 423 | } |
| 424 | |
| 425 | @fragment |
| 426 | fn fs_warp_flow(in: VsOut) -> @location(0) vec4<f32> { |
| 427 | let inv_sz = u.dst_size.zw; |
| 428 | let flow_scale = u.params.xy; |
| 429 | let alpha = clamp(u.params.z, 0.0, 1.0); |
| 430 | |
| 431 | if (alpha <= 1e-4) { |
| 432 | return textureSampleLevel(tex_a, lin_samp, in.uv, 0.0); |
| 433 | } |
| 434 | if (alpha >= 1.0 - 1e-4) { |
| 435 | return textureSampleLevel(tex_b, lin_samp, in.uv, 0.0); |
| 436 | } |
| 437 | |
| 438 | let raw_flow = textureSampleLevel(tex_c, lin_samp, in.uv, 0.0); |
| 439 | let v_a = raw_flow.xy * flow_scale; |
| 440 | let v_b = -raw_flow.zw * flow_scale; |
| 441 | |
| 442 | let ca = eval_candidate(in.uv, v_a, alpha, inv_sz, flow_scale); |
| 443 | let cb = eval_candidate(in.uv, v_b, alpha, inv_sz, flow_scale); |
| 444 | |
| 445 | // Pick the physically consistent candidate (forward-origin vs backward-origin) |
| 446 | let use_a = ca.score <= cb.score; |
| 447 | let col_a = select(cb.col_a, ca.col_a, use_a); |
| 448 | let col_b = select(cb.col_b, ca.col_b, use_a); |
| 449 | let err_va = select(cb.err_va, ca.err_va, use_a); |
| 450 | let err_vb = select(cb.err_vb, ca.err_vb, use_a); |
| 451 | |
| 452 | // Occlusion-aware blending weights based on forward-backward self-consistency |
| 453 | let inv_2sig2 = 1.0 / (2.0 * 1.5 * 1.5); |
| 454 | let wa = (1.0 - alpha) * exp(-err_va * err_va * inv_2sig2); |
| 455 | let wb = alpha * exp(-err_vb * err_vb * inv_2sig2); |
| 456 | let wsum = wa + wb; |
| 457 | |
| 458 | if (wsum > 1e-4) { |
| 459 | return (wa * col_a + wb * col_b) / wsum; |
| 460 | } |
| 461 | return mix(col_a, col_b, alpha); |
| 462 | } |
| 463 | "#; |
| 464 | |
| 465 | /// Cached flow fields kept per `OpticalFlowPipelines`; one entry is a single frame pair. |
| 466 | const FLOW_CACHE_CAP: usize = 4; |
| 467 | |
| 468 | /// Uniform slots allocated per ring chunk (`256 * 256 B = 64 KiB` at 256-byte alignment). |
| 469 | const UNIFORM_SLOTS_PER_CHUNK: u32 = 256; |
| 470 | |
| 471 | /// Maximum number of idle `Rgba16Float` pyramid textures retained in [`PyramidScratchPool`]. |
| 472 | const PYRAMID_POOL_MAX_TEXTURES: usize = 32; |
| 473 | /// Maximum total VRAM retained in [`PyramidScratchPool`] (256 MiB). |
| 474 | const PYRAMID_POOL_MAX_BYTES: u64 = 256 * 1024 * 1024; |
| 475 | |
| 476 | /// `(content_hash_a, content_hash_b, full-res size)`. |
| 477 | type FlowKey = (u64, u64, [u32; 2]); |
| 478 | |
| 479 | struct UniformRing { |
| 480 | stride: u32, |
| 481 | chunks: Vec<wgpu::Buffer>, |
| 482 | cursor: u32, |
| 483 | } |
| 484 | |
| 485 | impl UniformRing { |
| 486 | fn new(device: &wgpu::Device) -> Self { |
| 487 | let uniform_size = std::mem::size_of::<OptFlowUniform>() as u32; |
| 488 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); |
| 489 | let stride = uniform_size.div_ceil(min_align) * min_align; |
| 490 | Self { |
| 491 | stride, |
| 492 | chunks: Vec::new(), |
| 493 | cursor: 0, |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | /// Writes `uniform` into the next aligned dynamic-offset slot and returns `(chunk_buffer, offset)`. |
| 498 | /// |
| 499 | /// Lazily appends chunks without wrapping mid-encoder; callers reset the cursor after submit. |
| 500 | fn alloc_slot( |
| 501 | &mut self, |
| 502 | device: &wgpu::Device, |
| 503 | queue: &wgpu::Queue, |
| 504 | uniform: &OptFlowUniform, |
| 505 | ) -> (wgpu::Buffer, u32) { |
| 506 | let slot_global = self.cursor; |
| 507 | let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize; |
| 508 | let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK; |
| 509 | while chunk_idx >= self.chunks.len() { |
| 510 | let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.stride); |
| 511 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 512 | label: Some("optflow-uniform-ring"), |
| 513 | size, |
| 514 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, |
| 515 | mapped_at_creation: false, |
| 516 | }); |
| 517 | self.chunks.push(buf); |
| 518 | } |
| 519 | let offset = slot_in_chunk * self.stride; |
| 520 | queue.write_buffer( |
| 521 | &self.chunks[chunk_idx], |
| 522 | u64::from(offset), |
| 523 | bytemuck::bytes_of(uniform), |
| 524 | ); |
| 525 | self.cursor = slot_global + 1; |
| 526 | (self.chunks[chunk_idx].clone(), offset) |
| 527 | } |
| 528 | |
| 529 | fn reset_cursor(&mut self) { |
| 530 | self.cursor = 0; |
| 531 | } |
| 532 | |
| 533 | fn trim_uniform_chunks(&mut self, keep: usize) { |
| 534 | self.cursor = 0; |
| 535 | if self.chunks.len() > keep { |
| 536 | self.chunks.truncate(keep); |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | fn vram_bytes(&self) -> u64 { |
| 541 | self.chunks.iter().map(wgpu::Buffer::size).sum() |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | struct PooledF16Tex { |
| 546 | size: [u32; 2], |
| 547 | bytes: u64, |
| 548 | tex: wgpu::Texture, |
| 549 | view: wgpu::TextureView, |
| 550 | } |
| 551 | |
| 552 | /// Bounded LRU pool of reusable `Rgba16Float` pyramid/flow scratch textures keyed by `[w, h]`. |
| 553 | #[derive(Default)] |
| 554 | struct PyramidScratchPool { |
| 555 | entries: VecDeque<PooledF16Tex>, |
| 556 | total_bytes: u64, |
| 557 | alloc_count: u64, |
| 558 | reuse_count: u64, |
| 559 | } |
| 560 | |
| 561 | impl PyramidScratchPool { |
| 562 | fn acquire( |
| 563 | &mut self, |
| 564 | device: &wgpu::Device, |
| 565 | size: [u32; 2], |
| 566 | label: &str, |
| 567 | ) -> (wgpu::Texture, wgpu::TextureView) { |
| 568 | let size = [size[0].max(1), size[1].max(1)]; |
| 569 | if let Some(idx) = self.entries.iter().rposition(|e| e.size == size) { |
| 570 | let entry = self.entries.remove(idx).expect("valid pool index"); |
| 571 | self.total_bytes -= entry.bytes; |
| 572 | self.reuse_count += 1; |
| 573 | return (entry.tex, entry.view); |
| 574 | } |
| 575 | self.alloc_count += 1; |
| 576 | alloc_f16_tex(device, size, label) |
| 577 | } |
| 578 | |
| 579 | fn release(&mut self, tex: wgpu::Texture, view: wgpu::TextureView, size: [u32; 2]) { |
| 580 | let size = [size[0].max(1), size[1].max(1)]; |
| 581 | let bytes = u64::from(size[0]) * u64::from(size[1]) * 8; |
| 582 | if bytes > PYRAMID_POOL_MAX_BYTES { |
| 583 | return; |
| 584 | } |
| 585 | while self.entries.len() >= PYRAMID_POOL_MAX_TEXTURES |
| 586 | || self.total_bytes + bytes > PYRAMID_POOL_MAX_BYTES |
| 587 | { |
| 588 | if let Some(evicted) = self.entries.pop_front() { |
| 589 | self.total_bytes -= evicted.bytes; |
| 590 | } else { |
| 591 | break; |
| 592 | } |
| 593 | } |
| 594 | self.total_bytes += bytes; |
| 595 | self.entries.push_back(PooledF16Tex { |
| 596 | size, |
| 597 | bytes, |
| 598 | tex, |
| 599 | view, |
| 600 | }); |
| 601 | } |
| 602 | |
| 603 | fn clear(&mut self) { |
| 604 | self.entries.clear(); |
| 605 | self.total_bytes = 0; |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | /// Self-contained `wgpu` pipelines for GPU optical flow and motion-compensated frame interpolation. |
| 610 | pub struct OpticalFlowPipelines { |
| 611 | shader: wgpu::ShaderModule, |
| 612 | bgl: wgpu::BindGroupLayout, |
| 613 | pipeline_layout: wgpu::PipelineLayout, |
| 614 | sampler: wgpu::Sampler, |
| 615 | extract_features: wgpu::RenderPipeline, |
| 616 | downsample: wgpu::RenderPipeline, |
| 617 | flow_coarse: wgpu::RenderPipeline, |
| 618 | flow_refine: wgpu::RenderPipeline, |
| 619 | flow_smooth: wgpu::RenderPipeline, |
| 620 | blend_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>, |
| 621 | warp_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>, |
| 622 | /// Half-resolution flow fields, least recently used first: `(key, view, texture, size)`. |
| 623 | flow_cache: Mutex<Vec<(FlowKey, wgpu::TextureView, wgpu::Texture, [u32; 2])>>, |
| 624 | uniform_ring: Mutex<UniformRing>, |
| 625 | pyramid_pool: Mutex<PyramidScratchPool>, |
| 626 | } |
| 627 | |
| 628 | impl OpticalFlowPipelines { |
| 629 | pub fn new(device: &wgpu::Device) -> Self { |
| 630 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 631 | label: Some("optflow-shader"), |
| 632 | source: wgpu::ShaderSource::Wgsl(OPTFLOW_WGSL.into()), |
| 633 | }); |
| 634 | |
| 635 | let tex_entry = |binding| wgpu::BindGroupLayoutEntry { |
| 636 | binding, |
| 637 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 638 | ty: wgpu::BindingType::Texture { |
| 639 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, |
| 640 | view_dimension: wgpu::TextureViewDimension::D2, |
| 641 | multisampled: false, |
| 642 | }, |
| 643 | count: None, |
| 644 | }; |
| 645 | |
| 646 | let uniform_size = std::mem::size_of::<OptFlowUniform>() as u64; |
| 647 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 648 | label: Some("optflow-bgl"), |
| 649 | entries: &[ |
| 650 | tex_entry(0), |
| 651 | tex_entry(1), |
| 652 | tex_entry(2), |
| 653 | wgpu::BindGroupLayoutEntry { |
| 654 | binding: 3, |
| 655 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 656 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), |
| 657 | count: None, |
| 658 | }, |
| 659 | wgpu::BindGroupLayoutEntry { |
| 660 | binding: 4, |
| 661 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 662 | ty: wgpu::BindingType::Buffer { |
| 663 | ty: wgpu::BufferBindingType::Uniform, |
| 664 | has_dynamic_offset: true, |
| 665 | min_binding_size: NonZeroU64::new(uniform_size), |
| 666 | }, |
| 667 | count: None, |
| 668 | }, |
| 669 | ], |
| 670 | }); |
| 671 | |
| 672 | let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 673 | label: Some("optflow-pl"), |
| 674 | bind_group_layouts: &[Some(&bgl)], |
| 675 | immediate_size: 0, |
| 676 | }); |
| 677 | |
| 678 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { |
| 679 | label: Some("optflow-linear"), |
| 680 | address_mode_u: wgpu::AddressMode::ClampToEdge, |
| 681 | address_mode_v: wgpu::AddressMode::ClampToEdge, |
| 682 | mag_filter: wgpu::FilterMode::Linear, |
| 683 | min_filter: wgpu::FilterMode::Linear, |
| 684 | mipmap_filter: wgpu::MipmapFilterMode::Nearest, |
| 685 | ..Default::default() |
| 686 | }); |
| 687 | |
| 688 | let f16 = wgpu::TextureFormat::Rgba16Float; |
| 689 | let extract_features = |
| 690 | create_fullscreen_pipeline(device, &shader, &pipeline_layout, "fs_extract_features", f16); |
| 691 | let downsample = |
| 692 | create_fullscreen_pipeline(device, &shader, &pipeline_layout, "fs_downsample", f16); |
| 693 | let flow_coarse = |
| 694 | create_fullscreen_pipeline(device, &shader, &pipeline_layout, "fs_flow_coarse", f16); |
| 695 | let flow_refine = |
| 696 | create_fullscreen_pipeline(device, &shader, &pipeline_layout, "fs_flow_refine", f16); |
| 697 | let flow_smooth = |
| 698 | create_fullscreen_pipeline(device, &shader, &pipeline_layout, "fs_flow_smooth", f16); |
| 699 | |
| 700 | Self { |
| 701 | shader, |
| 702 | bgl, |
| 703 | pipeline_layout, |
| 704 | sampler, |
| 705 | extract_features, |
| 706 | downsample, |
| 707 | flow_coarse, |
| 708 | flow_refine, |
| 709 | flow_smooth, |
| 710 | blend_pipelines: RwLock::new(HashMap::new()), |
| 711 | warp_pipelines: RwLock::new(HashMap::new()), |
| 712 | flow_cache: Mutex::new(Vec::new()), |
| 713 | uniform_ring: Mutex::new(UniformRing::new(device)), |
| 714 | pyramid_pool: Mutex::new(PyramidScratchPool::default()), |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | /// Resets the dynamic uniform ring cursor back to slot `0`. |
| 719 | /// Call only after all prior encoded passes on this pipeline have been submitted. |
| 720 | pub fn reset_uniform_cursor(&self) { |
| 721 | lock_or_recover(&self.uniform_ring).reset_cursor(); |
| 722 | } |
| 723 | |
| 724 | /// Clears cached flow fields and pooled intermediate pyramid textures, and trims uniform ring chunks. |
| 725 | pub fn clear_scratch(&self) { |
| 726 | lock_or_recover(&self.flow_cache).clear(); |
| 727 | lock_or_recover(&self.pyramid_pool).clear(); |
| 728 | lock_or_recover(&self.uniform_ring).trim_uniform_chunks(2); |
| 729 | } |
| 730 | |
| 731 | /// Total resident GPU VRAM bytes currently held across pooled pyramid textures, |
| 732 | /// cached flow-field textures, and dynamic uniform ring buffers. |
| 733 | pub fn vram_bytes(&self) -> u64 { |
| 734 | let pool_bytes = lock_or_recover(&self.pyramid_pool).total_bytes; |
| 735 | let flow_bytes: u64 = lock_or_recover(&self.flow_cache) |
| 736 | .iter() |
| 737 | .map(|(_, _, _, size)| u64::from(size[0].max(1)) * u64::from(size[1].max(1)) * 8) |
| 738 | .sum(); |
| 739 | let ring_bytes = lock_or_recover(&self.uniform_ring).vram_bytes(); |
| 740 | pool_bytes |
| 741 | .saturating_add(flow_bytes) |
| 742 | .saturating_add(ring_bytes) |
| 743 | } |
| 744 | |
| 745 | fn ensure_target_pipeline( |
| 746 | &self, |
| 747 | device: &wgpu::Device, |
| 748 | cache: &RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>, |
| 749 | entry: &str, |
| 750 | format: wgpu::TextureFormat, |
| 751 | ) { |
| 752 | if read_or_recover(cache).contains_key(&format) { |
| 753 | return; |
| 754 | } |
| 755 | let pipe = create_fullscreen_pipeline(device, &self.shader, &self.pipeline_layout, entry, format); |
| 756 | write_or_recover(cache).insert(format, pipe); |
| 757 | } |
| 758 | |
| 759 | #[allow(clippy::too_many_arguments)] |
| 760 | fn run_pass( |
| 761 | &self, |
| 762 | device: &wgpu::Device, |
| 763 | queue: &wgpu::Queue, |
| 764 | enc: &mut wgpu::CommandEncoder, |
| 765 | pipeline: &wgpu::RenderPipeline, |
| 766 | label: &str, |
| 767 | view_a: &wgpu::TextureView, |
| 768 | view_b: &wgpu::TextureView, |
| 769 | view_c: &wgpu::TextureView, |
| 770 | dst_view: &wgpu::TextureView, |
| 771 | dst_size: [u32; 2], |
| 772 | params: [f32; 4], |
| 773 | ) { |
| 774 | let w = dst_size[0].max(1) as f32; |
| 775 | let h = dst_size[1].max(1) as f32; |
| 776 | let uniform = OptFlowUniform { |
| 777 | dst_size: [w, h, 1.0 / w, 1.0 / h], |
| 778 | params, |
| 779 | }; |
| 780 | let (ubuf, dynamic_offset) = { |
| 781 | let mut ring = lock_or_recover(&self.uniform_ring); |
| 782 | ring.alloc_slot(device, queue, &uniform) |
| 783 | }; |
| 784 | |
| 785 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 786 | label: Some(label), |
| 787 | layout: &self.bgl, |
| 788 | entries: &[ |
| 789 | wgpu::BindGroupEntry { |
| 790 | binding: 0, |
| 791 | resource: wgpu::BindingResource::TextureView(view_a), |
| 792 | }, |
| 793 | wgpu::BindGroupEntry { |
| 794 | binding: 1, |
| 795 | resource: wgpu::BindingResource::TextureView(view_b), |
| 796 | }, |
| 797 | wgpu::BindGroupEntry { |
| 798 | binding: 2, |
| 799 | resource: wgpu::BindingResource::TextureView(view_c), |
| 800 | }, |
| 801 | wgpu::BindGroupEntry { |
| 802 | binding: 3, |
| 803 | resource: wgpu::BindingResource::Sampler(&self.sampler), |
| 804 | }, |
| 805 | wgpu::BindGroupEntry { |
| 806 | binding: 4, |
| 807 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 808 | buffer: &ubuf, |
| 809 | offset: 0, |
| 810 | size: NonZeroU64::new(std::mem::size_of::<OptFlowUniform>() as u64), |
| 811 | }), |
| 812 | }, |
| 813 | ], |
| 814 | }); |
| 815 | |
| 816 | let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 817 | label: Some(label), |
| 818 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| 819 | view: dst_view, |
| 820 | depth_slice: None, |
| 821 | resolve_target: None, |
| 822 | ops: wgpu::Operations { |
| 823 | load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), |
| 824 | store: wgpu::StoreOp::Store, |
| 825 | }, |
| 826 | })], |
| 827 | depth_stencil_attachment: None, |
| 828 | timestamp_writes: None, |
| 829 | occlusion_query_set: None, |
| 830 | multiview_mask: None, |
| 831 | }); |
| 832 | rp.set_pipeline(pipeline); |
| 833 | rp.set_bind_group(0, &bg, &[dynamic_offset]); |
| 834 | rp.draw(0..3, 0..1); |
| 835 | } |
| 836 | |
| 837 | /// Linear cross-dissolve `(1 - alpha) * A + alpha * B` for `TimeStretcher` |
| 838 | /// `InterpolateBetweenFrames = 1` (`Blend`). |
| 839 | #[allow(clippy::too_many_arguments)] |
| 840 | pub fn blend_frames( |
| 841 | &self, |
| 842 | device: &wgpu::Device, |
| 843 | queue: &wgpu::Queue, |
| 844 | enc: &mut wgpu::CommandEncoder, |
| 845 | frame_a: &CachedTexture, |
| 846 | frame_b: &CachedTexture, |
| 847 | alpha: f32, |
| 848 | target_format: wgpu::TextureFormat, |
| 849 | ) -> CachedTexture { |
| 850 | self.ensure_target_pipeline(device, &self.blend_pipelines, "fs_blend", target_format); |
| 851 | let key = hash_interp(frame_a.content_hash, frame_b.content_hash, alpha, 1, target_format); |
| 852 | let dst = alloc_output_texture(device, frame_a, target_format, key); |
| 853 | |
| 854 | let guard = read_or_recover(&self.blend_pipelines); |
| 855 | let pipe = guard.get(&target_format).unwrap(); |
| 856 | self.run_pass( |
| 857 | device, |
| 858 | queue, |
| 859 | enc, |
| 860 | pipe, |
| 861 | "optflow-blend", |
| 862 | &frame_a.view, |
| 863 | &frame_b.view, |
| 864 | &frame_a.view, |
| 865 | &dst.view, |
| 866 | dst.size, |
| 867 | [1.0, 1.0, alpha.clamp(0.0, 1.0), 0.0], |
| 868 | ); |
| 869 | dst |
| 870 | } |
| 871 | |
| 872 | /// Multi-scale coarse-to-fine GPU optical flow + bidirectional occlusion-aware warp |
| 873 | /// interpolation for `Dimension.OpticalFlow` and `TimeStretcher` |
| 874 | /// `InterpolateBetweenFrames = 2` (`Flow`). |
| 875 | #[allow(clippy::too_many_arguments)] |
| 876 | pub fn interpolate_flow( |
| 877 | &self, |
| 878 | device: &wgpu::Device, |
| 879 | queue: &wgpu::Queue, |
| 880 | enc: &mut wgpu::CommandEncoder, |
| 881 | frame_a: &CachedTexture, |
| 882 | frame_b: &CachedTexture, |
| 883 | alpha: f32, |
| 884 | target_format: wgpu::TextureFormat, |
| 885 | ) -> CachedTexture { |
| 886 | self.ensure_target_pipeline(device, &self.warp_pipelines, "fs_warp_flow", target_format); |
| 887 | let key = hash_interp(frame_a.content_hash, frame_b.content_hash, alpha, 2, target_format); |
| 888 | let dst = alloc_output_texture(device, frame_a, target_format, key); |
| 889 | |
| 890 | let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)]; |
| 891 | let s1 = half_size(s0); |
| 892 | let unkeyed = frame_a.content_hash == 0 || frame_b.content_hash == 0; |
| 893 | let (flow1_view, uncached_flow): (wgpu::TextureView, Option<wgpu::Texture>) = if unkeyed { |
| 894 | let (flow1_tex, flow1_view) = |
| 895 | self.compute_flow_field(device, queue, enc, frame_a, frame_b); |
| 896 | (flow1_view, Some(flow1_tex)) |
| 897 | } else { |
| 898 | let flow_key = (frame_a.content_hash, frame_b.content_hash, s0); |
| 899 | let cached = { |
| 900 | let mut cache = lock_or_recover(&self.flow_cache); |
| 901 | cache.iter().position(|(k, _, _, _)| *k == flow_key).map(|i| { |
| 902 | let entry = cache.remove(i); |
| 903 | let view = entry.1.clone(); |
| 904 | cache.push(entry); |
| 905 | view |
| 906 | }) |
| 907 | }; |
| 908 | let flow1_view = match cached { |
| 909 | Some(view) => view, |
| 910 | None => { |
| 911 | // Evict the LRU flow field before computing the new one so its backing |
| 912 | // texture can be immediately reused by PyramidScratchPool. |
| 913 | let evicted_before = { |
| 914 | let mut cache = lock_or_recover(&self.flow_cache); |
| 915 | if cache.len() >= FLOW_CACHE_CAP { |
| 916 | Some(cache.remove(0)) |
| 917 | } else { |
| 918 | None |
| 919 | } |
| 920 | }; |
| 921 | if let Some((_, old_view, old_tex, old_size)) = evicted_before { |
| 922 | lock_or_recover(&self.pyramid_pool).release(old_tex, old_view, old_size); |
| 923 | } |
| 924 | |
| 925 | let (flow1_tex, flow1_view) = |
| 926 | self.compute_flow_field(device, queue, enc, frame_a, frame_b); |
| 927 | |
| 928 | let evicted_after = { |
| 929 | let mut cache = lock_or_recover(&self.flow_cache); |
| 930 | let extra = if cache.len() >= FLOW_CACHE_CAP { |
| 931 | Some(cache.remove(0)) |
| 932 | } else { |
| 933 | None |
| 934 | }; |
| 935 | cache.push((flow_key, flow1_view.clone(), flow1_tex, s1)); |
| 936 | extra |
| 937 | }; |
| 938 | if let Some((_, old_view, old_tex, old_size)) = evicted_after { |
| 939 | lock_or_recover(&self.pyramid_pool).release(old_tex, old_view, old_size); |
| 940 | } |
| 941 | flow1_view |
| 942 | } |
| 943 | }; |
| 944 | (flow1_view, None) |
| 945 | }; |
| 946 | |
| 947 | // Full-resolution bidirectional occlusion-aware warp & blend |
| 948 | let scale_1_to_0 = [ |
| 949 | s0[0] as f32 / s1[0] as f32, |
| 950 | s0[1] as f32 / s1[1] as f32, |
| 951 | alpha.clamp(0.0, 1.0), |
| 952 | 0.0, |
| 953 | ]; |
| 954 | { |
| 955 | let guard = read_or_recover(&self.warp_pipelines); |
| 956 | let pipe = guard.get(&target_format).unwrap(); |
| 957 | self.run_pass( |
| 958 | device, queue, enc, pipe, "optflow-warp", |
| 959 | &frame_a.view, &frame_b.view, &flow1_view, &dst.view, s0, scale_1_to_0, |
| 960 | ); |
| 961 | } |
| 962 | if let Some(flow1_tex) = uncached_flow { |
| 963 | lock_or_recover(&self.pyramid_pool).release(flow1_tex, flow1_view, s1); |
| 964 | } |
| 965 | dst |
| 966 | } |
| 967 | |
| 968 | /// Encodes the 4-level (full, 1/2, 1/4, 1/8) coarse-to-fine flow estimate and returns the |
| 969 | /// half-resolution flow field `(texture, view)`. |
| 970 | fn compute_flow_field( |
| 971 | &self, |
| 972 | device: &wgpu::Device, |
| 973 | queue: &wgpu::Queue, |
| 974 | enc: &mut wgpu::CommandEncoder, |
| 975 | frame_a: &CachedTexture, |
| 976 | frame_b: &CachedTexture, |
| 977 | ) -> (wgpu::Texture, wgpu::TextureView) { |
| 978 | let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)]; |
| 979 | let s1 = half_size(s0); |
| 980 | let s2 = half_size(s1); |
| 981 | let s3 = half_size(s2); |
| 982 | |
| 983 | // Acquire all 14 distinct pyramid/feature/flow textures for this call so no texture is |
| 984 | // aliased within the unsubmitted CommandEncoder. |
| 985 | let ( |
| 986 | (fa0_tex, fa0_view), |
| 987 | (fb0_tex, fb0_view), |
| 988 | (fa1_tex, fa1_view), |
| 989 | (fb1_tex, fb1_view), |
| 990 | (fa2_tex, fa2_view), |
| 991 | (fb2_tex, fb2_view), |
| 992 | (fa3_tex, fa3_view), |
| 993 | (fb3_tex, fb3_view), |
| 994 | (flow3_raw_tex, flow3_raw_view), |
| 995 | (flow3_tex, flow3_view), |
| 996 | (flow2_raw_tex, flow2_raw_view), |
| 997 | (flow2_tex, flow2_view), |
| 998 | (flow1_raw_tex, flow1_raw_view), |
| 999 | (flow1_tex, flow1_view), |
| 1000 | ) = { |
| 1001 | let mut pool = lock_or_recover(&self.pyramid_pool); |
| 1002 | ( |
| 1003 | pool.acquire(device, s0, "optflow-fa0"), |
| 1004 | pool.acquire(device, s0, "optflow-fb0"), |
| 1005 | pool.acquire(device, s1, "optflow-fa1"), |
| 1006 | pool.acquire(device, s1, "optflow-fb1"), |
| 1007 | pool.acquire(device, s2, "optflow-fa2"), |
| 1008 | pool.acquire(device, s2, "optflow-fb2"), |
| 1009 | pool.acquire(device, s3, "optflow-fa3"), |
| 1010 | pool.acquire(device, s3, "optflow-fb3"), |
| 1011 | pool.acquire(device, s3, "optflow-f3-raw"), |
| 1012 | pool.acquire(device, s3, "optflow-f3"), |
| 1013 | pool.acquire(device, s2, "optflow-f2-raw"), |
| 1014 | pool.acquire(device, s2, "optflow-f2"), |
| 1015 | pool.acquire(device, s1, "optflow-f1-raw"), |
| 1016 | pool.acquire(device, s1, "optflow-f1"), |
| 1017 | ) |
| 1018 | }; |
| 1019 | |
| 1020 | // 1. Build (luma, R-G, B-Y, alpha) feature pyramids for A and B |
| 1021 | self.run_pass( |
| 1022 | device, queue, enc, &self.extract_features, "optflow-extract-a", |
| 1023 | &frame_a.view, &frame_a.view, &frame_a.view, &fa0_view, s0, [0.0; 4], |
| 1024 | ); |
| 1025 | self.run_pass( |
| 1026 | device, queue, enc, &self.extract_features, "optflow-extract-b", |
| 1027 | &frame_b.view, &frame_b.view, &frame_b.view, &fb0_view, s0, [0.0; 4], |
| 1028 | ); |
| 1029 | |
| 1030 | self.run_pass( |
| 1031 | device, queue, enc, &self.downsample, "optflow-down-a1", |
| 1032 | &fa0_view, &fa0_view, &fa0_view, &fa1_view, s1, [0.0; 4], |
| 1033 | ); |
| 1034 | self.run_pass( |
| 1035 | device, queue, enc, &self.downsample, "optflow-down-b1", |
| 1036 | &fb0_view, &fb0_view, &fb0_view, &fb1_view, s1, [0.0; 4], |
| 1037 | ); |
| 1038 | |
| 1039 | self.run_pass( |
| 1040 | device, queue, enc, &self.downsample, "optflow-down-a2", |
| 1041 | &fa1_view, &fa1_view, &fa1_view, &fa2_view, s2, [0.0; 4], |
| 1042 | ); |
| 1043 | self.run_pass( |
| 1044 | device, queue, enc, &self.downsample, "optflow-down-b2", |
| 1045 | &fb1_view, &fb1_view, &fb1_view, &fb2_view, s2, [0.0; 4], |
| 1046 | ); |
| 1047 | |
| 1048 | self.run_pass( |
| 1049 | device, queue, enc, &self.downsample, "optflow-down-a3", |
| 1050 | &fa2_view, &fa2_view, &fa2_view, &fa3_view, s3, [0.0; 4], |
| 1051 | ); |
| 1052 | self.run_pass( |
| 1053 | device, queue, enc, &self.downsample, "optflow-down-b3", |
| 1054 | &fb2_view, &fb2_view, &fb2_view, &fb3_view, s3, [0.0; 4], |
| 1055 | ); |
| 1056 | |
| 1057 | // 2. Coarse-to-fine bidirectional flow estimation |
| 1058 | // Level 3 (1/8 res): exhaustive [-4..4] search + parabolic subpixel + bilateral smooth |
| 1059 | self.run_pass( |
| 1060 | device, queue, enc, &self.flow_coarse, "optflow-coarse-l3", |
| 1061 | &fa3_view, &fb3_view, &fa3_view, &flow3_raw_view, s3, [0.0; 4], |
| 1062 | ); |
| 1063 | self.run_pass( |
| 1064 | device, queue, enc, &self.flow_smooth, "optflow-smooth-l3", |
| 1065 | &fa3_view, &fb3_view, &flow3_raw_view, &flow3_view, s3, [0.0; 4], |
| 1066 | ); |
| 1067 | |
| 1068 | // Level 2 (1/4 res): upsample + [-2..2] refine + LK + bilateral smooth |
| 1069 | let scale_3_to_2 = [s2[0] as f32 / s3[0] as f32, s2[1] as f32 / s3[1] as f32, 0.0, 0.0]; |
| 1070 | self.run_pass( |
| 1071 | device, queue, enc, &self.flow_refine, "optflow-refine-l2", |
| 1072 | &fa2_view, &fb2_view, &flow3_view, &flow2_raw_view, s2, scale_3_to_2, |
| 1073 | ); |
| 1074 | self.run_pass( |
| 1075 | device, queue, enc, &self.flow_smooth, "optflow-smooth-l2", |
| 1076 | &fa2_view, &fb2_view, &flow2_raw_view, &flow2_view, s2, [0.0; 4], |
| 1077 | ); |
| 1078 | |
| 1079 | // Level 1 (1/2 res): upsample + [-2..2] refine + LK + bilateral smooth |
| 1080 | let scale_2_to_1 = [s1[0] as f32 / s2[0] as f32, s1[1] as f32 / s2[1] as f32, 0.0, 0.0]; |
| 1081 | self.run_pass( |
| 1082 | device, queue, enc, &self.flow_refine, "optflow-refine-l1", |
| 1083 | &fa1_view, &fb1_view, &flow2_view, &flow1_raw_view, s1, scale_2_to_1, |
| 1084 | ); |
| 1085 | self.run_pass( |
| 1086 | device, queue, enc, &self.flow_smooth, "optflow-smooth-l1", |
| 1087 | &fa1_view, &fb1_view, &flow1_raw_view, &flow1_view, s1, [0.0; 4], |
| 1088 | ); |
| 1089 | |
| 1090 | // Return intermediate scratch textures to the pool now that all passes reading/writing them |
| 1091 | // are encoded in strict FIFO order on `enc`. Subsequent calls on the same or future |
| 1092 | // encoders execute strictly after these passes. |
| 1093 | { |
| 1094 | let mut pool = lock_or_recover(&self.pyramid_pool); |
| 1095 | pool.release(fa0_tex, fa0_view, s0); |
| 1096 | pool.release(fb0_tex, fb0_view, s0); |
| 1097 | pool.release(fa1_tex, fa1_view, s1); |
| 1098 | pool.release(fb1_tex, fb1_view, s1); |
| 1099 | pool.release(fa2_tex, fa2_view, s2); |
| 1100 | pool.release(fb2_tex, fb2_view, s2); |
| 1101 | pool.release(fa3_tex, fa3_view, s3); |
| 1102 | pool.release(fb3_tex, fb3_view, s3); |
| 1103 | pool.release(flow3_raw_tex, flow3_raw_view, s3); |
| 1104 | pool.release(flow3_tex, flow3_view, s3); |
| 1105 | pool.release(flow2_raw_tex, flow2_raw_view, s2); |
| 1106 | pool.release(flow2_tex, flow2_view, s2); |
| 1107 | pool.release(flow1_raw_tex, flow1_raw_view, s1); |
| 1108 | } |
| 1109 | |
| 1110 | (flow1_tex, flow1_view) |
| 1111 | } |
| 1112 | } |
| 1113 | |
| 1114 | fn half_size(s: [u32; 2]) -> [u32; 2] { |
| 1115 | [s[0].div_ceil(2).max(1), s[1].div_ceil(2).max(1)] |
| 1116 | } |
| 1117 | |
| 1118 | fn create_fullscreen_pipeline( |
| 1119 | device: &wgpu::Device, |
| 1120 | shader: &wgpu::ShaderModule, |
| 1121 | layout: &wgpu::PipelineLayout, |
| 1122 | frag_entry: &str, |
| 1123 | format: wgpu::TextureFormat, |
| 1124 | ) -> wgpu::RenderPipeline { |
| 1125 | device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { |
| 1126 | label: Some(frag_entry), |
| 1127 | layout: Some(layout), |
| 1128 | vertex: wgpu::VertexState { |
| 1129 | module: shader, |
| 1130 | entry_point: Some("vs_fullscreen"), |
| 1131 | compilation_options: Default::default(), |
| 1132 | buffers: &[], |
| 1133 | }, |
| 1134 | fragment: Some(wgpu::FragmentState { |
| 1135 | module: shader, |
| 1136 | entry_point: Some(frag_entry), |
| 1137 | compilation_options: Default::default(), |
| 1138 | targets: &[Some(wgpu::ColorTargetState { |
| 1139 | format, |
| 1140 | blend: None, |
| 1141 | write_mask: wgpu::ColorWrites::ALL, |
| 1142 | })], |
| 1143 | }), |
| 1144 | primitive: wgpu::PrimitiveState { |
| 1145 | topology: wgpu::PrimitiveTopology::TriangleList, |
| 1146 | ..Default::default() |
| 1147 | }, |
| 1148 | depth_stencil: None, |
| 1149 | multisample: wgpu::MultisampleState::default(), |
| 1150 | multiview_mask: None, |
| 1151 | cache: None, |
| 1152 | }) |
| 1153 | } |
| 1154 | |
| 1155 | fn alloc_f16_tex( |
| 1156 | device: &wgpu::Device, |
| 1157 | size: [u32; 2], |
| 1158 | label: &str, |
| 1159 | ) -> (wgpu::Texture, wgpu::TextureView) { |
| 1160 | let tex = device.create_texture(&wgpu::TextureDescriptor { |
| 1161 | label: Some(label), |
| 1162 | size: wgpu::Extent3d { |
| 1163 | width: size[0].max(1), |
| 1164 | height: size[1].max(1), |
| 1165 | depth_or_array_layers: 1, |
| 1166 | }, |
| 1167 | mip_level_count: 1, |
| 1168 | sample_count: 1, |
| 1169 | dimension: wgpu::TextureDimension::D2, |
| 1170 | format: wgpu::TextureFormat::Rgba16Float, |
| 1171 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 1172 | view_formats: &[], |
| 1173 | }); |
| 1174 | let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); |
| 1175 | (tex, view) |
| 1176 | } |
| 1177 | |
| 1178 | fn alloc_output_texture( |
| 1179 | device: &wgpu::Device, |
| 1180 | reference: &CachedTexture, |
| 1181 | format: wgpu::TextureFormat, |
| 1182 | content_hash: u64, |
| 1183 | ) -> CachedTexture { |
| 1184 | let size = [reference.size[0].max(1), reference.size[1].max(1)]; |
| 1185 | let depth = match format { |
| 1186 | wgpu::TextureFormat::Rgba16Float => BitDepth::Float16, |
| 1187 | wgpu::TextureFormat::Rgba32Float => BitDepth::Float32, |
| 1188 | _ => BitDepth::Int8, |
| 1189 | }; |
| 1190 | let tex = device.create_texture(&wgpu::TextureDescriptor { |
| 1191 | label: Some("optflow-out"), |
| 1192 | size: wgpu::Extent3d { |
| 1193 | width: size[0], |
| 1194 | height: size[1], |
| 1195 | depth_or_array_layers: 1, |
| 1196 | }, |
| 1197 | mip_level_count: 1, |
| 1198 | sample_count: 1, |
| 1199 | dimension: wgpu::TextureDimension::D2, |
| 1200 | format, |
| 1201 | usage: wgpu::TextureUsages::TEXTURE_BINDING |
| 1202 | | wgpu::TextureUsages::STORAGE_BINDING |
| 1203 | | wgpu::TextureUsages::COPY_SRC |
| 1204 | | wgpu::TextureUsages::COPY_DST |
| 1205 | | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 1206 | view_formats: &[], |
| 1207 | }); |
| 1208 | CachedTexture::from_texture_dod_depth( |
| 1209 | tex, |
| 1210 | size, |
| 1211 | reference.origin, |
| 1212 | [reference.canvas_size[0].max(1), reference.canvas_size[1].max(1)], |
| 1213 | depth, |
| 1214 | content_hash, |
| 1215 | ) |
| 1216 | } |
| 1217 | |
| 1218 | fn hash_interp( |
| 1219 | hash_a: u64, |
| 1220 | hash_b: u64, |
| 1221 | alpha: f32, |
| 1222 | mode: u8, |
| 1223 | format: wgpu::TextureFormat, |
| 1224 | ) -> u64 { |
| 1225 | let mut h = DefaultHasher::new(); |
| 1226 | "optflow".hash(&mut h); |
| 1227 | hash_a.hash(&mut h); |
| 1228 | hash_b.hash(&mut h); |
| 1229 | alpha.to_bits().hash(&mut h); |
| 1230 | mode.hash(&mut h); |
| 1231 | format.hash(&mut h); |
| 1232 | h.finish() |
| 1233 | } |
| 1234 | |
| 1235 | #[cfg(test)] |
| 1236 | mod tests { |
| 1237 | use super::*; |
| 1238 | |
| 1239 | fn create_headless_device() -> (wgpu::Device, wgpu::Queue) { |
| 1240 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 1241 | let adapter = pollster::block_on(instance.request_adapter(&Default::default())) |
| 1242 | .expect("no GPU adapter found"); |
| 1243 | let mut req_features = wgpu::Features::empty(); |
| 1244 | if adapter.features().contains(wgpu::Features::FLOAT32_FILTERABLE) { |
| 1245 | req_features |= wgpu::Features::FLOAT32_FILTERABLE; |
| 1246 | } |
| 1247 | pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { |
| 1248 | required_features: req_features, |
| 1249 | ..Default::default() |
| 1250 | })) |
| 1251 | .expect("failed to request GPU device") |
| 1252 | } |
| 1253 | |
| 1254 | /// Renders a 256x144 RGBA8 scene with a subtle static background and a textured/gradient |
| 1255 | /// 48x48 box whose top-left corner is at `(box_x, box_y)`. |
| 1256 | fn render_box_scene(w: u32, h: u32, box_x: i32, box_y: i32) -> Vec<u8> { |
| 1257 | let mut pixels = vec![0u8; (w * h * 4) as usize]; |
| 1258 | let box_size = 48i32; |
| 1259 | for y in 0..h as i32 { |
| 1260 | for x in 0..w as i32 { |
| 1261 | // Static dark-slate subtle background |
| 1262 | let mut r = 24.0 + (x as f32 / w as f32) * 10.0; |
| 1263 | let mut g = 28.0 + (y as f32 / h as f32) * 10.0; |
| 1264 | let mut b = 36.0; |
| 1265 | |
| 1266 | let lx = x - box_x; |
| 1267 | let ly = y - box_y; |
| 1268 | if lx >= 0 && lx < box_size && ly >= 0 && ly < box_size { |
| 1269 | let u = lx as f32 / (box_size - 1) as f32; |
| 1270 | let v = ly as f32 / (box_size - 1) as f32; |
| 1271 | // Rich multi-channel gradient + soft checker inside the box |
| 1272 | let stripe = if ((lx / 8) + (ly / 8)) % 2 == 0 { 35.0 } else { 0.0 }; |
| 1273 | r = (60.0 + 160.0 * u + stripe).min(255.0); |
| 1274 | g = (50.0 + 160.0 * v + stripe * 0.5).min(255.0); |
| 1275 | b = (210.0 - 140.0 * u + 40.0 * v).clamp(0.0, 255.0); |
| 1276 | } |
| 1277 | |
| 1278 | let idx = ((y as u32 * w + x as u32) * 4) as usize; |
| 1279 | pixels[idx] = r.round() as u8; |
| 1280 | pixels[idx + 1] = g.round() as u8; |
| 1281 | pixels[idx + 2] = b.round() as u8; |
| 1282 | pixels[idx + 3] = 255; |
| 1283 | } |
| 1284 | } |
| 1285 | pixels |
| 1286 | } |
| 1287 | |
| 1288 | fn upload_rgba8( |
| 1289 | device: &wgpu::Device, |
| 1290 | queue: &wgpu::Queue, |
| 1291 | w: u32, |
| 1292 | h: u32, |
| 1293 | rgba: &[u8], |
| 1294 | hash: u64, |
| 1295 | ) -> CachedTexture { |
| 1296 | let tex = device.create_texture(&wgpu::TextureDescriptor { |
| 1297 | label: Some("test-rgba8"), |
| 1298 | size: wgpu::Extent3d { |
| 1299 | width: w, |
| 1300 | height: h, |
| 1301 | depth_or_array_layers: 1, |
| 1302 | }, |
| 1303 | mip_level_count: 1, |
| 1304 | sample_count: 1, |
| 1305 | dimension: wgpu::TextureDimension::D2, |
| 1306 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 1307 | usage: wgpu::TextureUsages::TEXTURE_BINDING |
| 1308 | | wgpu::TextureUsages::COPY_DST |
| 1309 | | wgpu::TextureUsages::COPY_SRC |
| 1310 | | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 1311 | view_formats: &[], |
| 1312 | }); |
| 1313 | queue.write_texture( |
| 1314 | tex.as_image_copy(), |
| 1315 | rgba, |
| 1316 | wgpu::TexelCopyBufferLayout { |
| 1317 | offset: 0, |
| 1318 | bytes_per_row: Some(w * 4), |
| 1319 | rows_per_image: Some(h), |
| 1320 | }, |
| 1321 | wgpu::Extent3d { |
| 1322 | width: w, |
| 1323 | height: h, |
| 1324 | depth_or_array_layers: 1, |
| 1325 | }, |
| 1326 | ); |
| 1327 | CachedTexture::from_texture(tex, [w, h], hash) |
| 1328 | } |
| 1329 | |
| 1330 | fn readback_bytes( |
| 1331 | device: &wgpu::Device, |
| 1332 | queue: &wgpu::Queue, |
| 1333 | tex: &CachedTexture, |
| 1334 | bpp: u32, |
| 1335 | ) -> Vec<u8> { |
| 1336 | let [w, h] = tex.size; |
| 1337 | let unpadded_bpr = w * bpp; |
| 1338 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 1339 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 1340 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 1341 | label: Some("test-readback"), |
| 1342 | size: u64::from(padded_bpr) * u64::from(h), |
| 1343 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 1344 | mapped_at_creation: false, |
| 1345 | }); |
| 1346 | let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 1347 | label: Some("test-readback-enc"), |
| 1348 | }); |
| 1349 | enc.copy_texture_to_buffer( |
| 1350 | tex.texture.as_image_copy(), |
| 1351 | wgpu::TexelCopyBufferInfo { |
| 1352 | buffer: &buf, |
| 1353 | layout: wgpu::TexelCopyBufferLayout { |
| 1354 | offset: 0, |
| 1355 | bytes_per_row: Some(padded_bpr), |
| 1356 | rows_per_image: Some(h), |
| 1357 | }, |
| 1358 | }, |
| 1359 | wgpu::Extent3d { |
| 1360 | width: w, |
| 1361 | height: h, |
| 1362 | depth_or_array_layers: 1, |
| 1363 | }, |
| 1364 | ); |
| 1365 | queue.submit(Some(enc.finish())); |
| 1366 | |
| 1367 | let slice = buf.slice(..); |
| 1368 | let (tx, rx) = std::sync::mpsc::channel(); |
| 1369 | slice.map_async(wgpu::MapMode::Read, move |res| { |
| 1370 | let _ = tx.send(res); |
| 1371 | }); |
| 1372 | device |
| 1373 | .poll(wgpu::PollType::Wait { |
| 1374 | submission_index: None, |
| 1375 | timeout: Some(std::time::Duration::from_secs(10)), |
| 1376 | }) |
| 1377 | .expect("device poll failed"); |
| 1378 | rx.recv().expect("channel closed").expect("map_async failed"); |
| 1379 | let data = slice.get_mapped_range().expect("get_mapped_range failed"); |
| 1380 | let mut out = Vec::with_capacity((unpadded_bpr * h) as usize); |
| 1381 | for row in 0..h as usize { |
| 1382 | let start = row * padded_bpr as usize; |
| 1383 | out.extend_from_slice(&data[start..start + unpadded_bpr as usize]); |
| 1384 | } |
| 1385 | drop(data); |
| 1386 | buf.unmap(); |
| 1387 | out |
| 1388 | } |
| 1389 | |
| 1390 | fn f16_to_f32(bits: u16) -> f32 { |
| 1391 | let sign = ((bits >> 15) as u32) << 31; |
| 1392 | let exp = ((bits >> 10) & 0x1f) as u32; |
| 1393 | let frac = (bits & 0x03ff) as u32; |
| 1394 | if exp == 0 { |
| 1395 | if frac == 0 { |
| 1396 | f32::from_bits(sign) |
| 1397 | } else { |
| 1398 | // Subnormal |
| 1399 | let val = (frac as f32) * (2.0f32).powi(-24); |
| 1400 | if sign != 0 { -val } else { val } |
| 1401 | } |
| 1402 | } else if exp == 31 { |
| 1403 | f32::from_bits(sign | 0x7f80_0000 | (frac << 13)) |
| 1404 | } else { |
| 1405 | f32::from_bits(sign | ((exp + 112) << 23) | (frac << 13)) |
| 1406 | } |
| 1407 | } |
| 1408 | |
| 1409 | fn mae_rgba8(a: &[u8], b: &[u8]) -> f64 { |
| 1410 | assert_eq!(a.len(), b.len()); |
| 1411 | let sum: u64 = a |
| 1412 | .iter() |
| 1413 | .zip(b.iter()) |
| 1414 | .map(|(&x, &y)| x.abs_diff(y) as u64) |
| 1415 | .sum(); |
| 1416 | sum as f64 / a.len() as f64 |
| 1417 | } |
| 1418 | |
| 1419 | #[test] |
| 1420 | fn test_optflow_shifts_moving_box_accurately() { |
| 1421 | let (device, queue) = create_headless_device(); |
| 1422 | let pipelines = OpticalFlowPipelines::new(&device); |
| 1423 | |
| 1424 | let (w, h) = (256u32, 144u32); |
| 1425 | let img_a = render_box_scene(w, h, 80, 56); |
| 1426 | let img_b = render_box_scene(w, h, 80 + 16, 56 - 8); |
| 1427 | let img_gt = render_box_scene(w, h, 80 + 8, 56 - 4); |
| 1428 | |
| 1429 | let tex_a = upload_rgba8(&device, &queue, w, h, &img_a, 1); |
| 1430 | let tex_b = upload_rgba8(&device, &queue, w, h, &img_b, 2); |
| 1431 | |
| 1432 | // 1. Rgba8Unorm blend vs optical flow |
| 1433 | let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 1434 | label: Some("optflow-test-rgba8"), |
| 1435 | }); |
| 1436 | let blended = pipelines.blend_frames( |
| 1437 | &device, |
| 1438 | &queue, |
| 1439 | &mut enc, |
| 1440 | &tex_a, |
| 1441 | &tex_b, |
| 1442 | 0.5, |
| 1443 | wgpu::TextureFormat::Rgba8Unorm, |
| 1444 | ); |
| 1445 | let flowed = pipelines.interpolate_flow( |
| 1446 | &device, |
| 1447 | &queue, |
| 1448 | &mut enc, |
| 1449 | &tex_a, |
| 1450 | &tex_b, |
| 1451 | 0.5, |
| 1452 | wgpu::TextureFormat::Rgba8Unorm, |
| 1453 | ); |
| 1454 | queue.submit(Some(enc.finish())); |
| 1455 | |
| 1456 | let blend_bytes = readback_bytes(&device, &queue, &blended, 4); |
| 1457 | let flow_bytes = readback_bytes(&device, &queue, &flowed, 4); |
| 1458 | |
| 1459 | let blend_mae = mae_rgba8(&blend_bytes, &img_gt); |
| 1460 | let optflow_mae = mae_rgba8(&flow_bytes, &img_gt); |
| 1461 | println!("Rgba8Unorm: blend_mae = {blend_mae:.3}, optflow_mae = {optflow_mae:.3}"); |
| 1462 | |
| 1463 | assert!( |
| 1464 | optflow_mae < blend_mae * 0.35, |
| 1465 | "expected optflow_mae ({optflow_mae:.3}) < 0.35 * blend_mae ({:.3})", |
| 1466 | blend_mae * 0.35 |
| 1467 | ); |
| 1468 | assert!( |
| 1469 | optflow_mae < 4.0, |
| 1470 | "expected optflow_mae ({optflow_mae:.3}) < 4.0" |
| 1471 | ); |
| 1472 | |
| 1473 | // 2. Rgba16Float output format verification |
| 1474 | let mut enc_f16 = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 1475 | label: Some("optflow-test-f16"), |
| 1476 | }); |
| 1477 | let flowed_f16 = pipelines.interpolate_flow( |
| 1478 | &device, |
| 1479 | &queue, |
| 1480 | &mut enc_f16, |
| 1481 | &tex_a, |
| 1482 | &tex_b, |
| 1483 | 0.5, |
| 1484 | wgpu::TextureFormat::Rgba16Float, |
| 1485 | ); |
| 1486 | queue.submit(Some(enc_f16.finish())); |
| 1487 | |
| 1488 | assert_eq!(flowed_f16.format, wgpu::TextureFormat::Rgba16Float); |
| 1489 | assert_eq!(flowed_f16.depth, BitDepth::Float16); |
| 1490 | |
| 1491 | let f16_raw = readback_bytes(&device, &queue, &flowed_f16, 8); |
| 1492 | let f16_as_u8: Vec<u8> = f16_raw |
| 1493 | .chunks_exact(2) |
| 1494 | .map(|c| { |
| 1495 | let v = f16_to_f32(u16::from_le_bytes([c[0], c[1]])); |
| 1496 | (v.clamp(0.0, 1.0) * 255.0).round() as u8 |
| 1497 | }) |
| 1498 | .collect(); |
| 1499 | let f16_mae = mae_rgba8(&f16_as_u8, &img_gt); |
| 1500 | println!("Rgba16Float: optflow_mae = {f16_mae:.3}"); |
| 1501 | assert!( |
| 1502 | f16_mae < blend_mae * 0.35 && f16_mae < 4.0, |
| 1503 | "expected Rgba16Float optflow_mae ({f16_mae:.3}) < min(4.0, {:.3})", |
| 1504 | blend_mae * 0.35 |
| 1505 | ); |
| 1506 | } |
| 1507 | |
| 1508 | #[test] |
| 1509 | fn test_flow_field_is_cached_per_frame_pair_and_bounded() { |
| 1510 | let (device, queue) = create_headless_device(); |
| 1511 | let cached = OpticalFlowPipelines::new(&device); |
| 1512 | let fresh = OpticalFlowPipelines::new(&device); |
| 1513 | |
| 1514 | let (w, h) = (128u32, 72u32); |
| 1515 | let frame = |i: i32, hash: u64| { |
| 1516 | upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 20 + 8 * i, 20), hash) |
| 1517 | }; |
| 1518 | let (tex_a, tex_b) = (frame(0, 1), frame(1, 2)); |
| 1519 | let fmt = wgpu::TextureFormat::Rgba8Unorm; |
| 1520 | let interp = |p: &OpticalFlowPipelines, a: &CachedTexture, b: &CachedTexture, alpha: f32| { |
| 1521 | let mut enc = device.create_command_encoder(&Default::default()); |
| 1522 | let out = p.interpolate_flow(&device, &queue, &mut enc, a, b, alpha, fmt); |
| 1523 | queue.submit(Some(enc.finish())); |
| 1524 | readback_bytes(&device, &queue, &out, 4) |
| 1525 | }; |
| 1526 | |
| 1527 | let first = interp(&cached, &tex_a, &tex_b, 0.25); |
| 1528 | let field = lock_or_recover(&cached.flow_cache)[0].1.clone(); |
| 1529 | let second = interp(&cached, &tex_a, &tex_b, 0.75); |
| 1530 | { |
| 1531 | let cache = lock_or_recover(&cached.flow_cache); |
| 1532 | assert_eq!(cache.len(), 1, "second alpha reuses the pair's flow field"); |
| 1533 | assert!(cache[0].1 == field, "second alpha must hit the cached field texture"); |
| 1534 | } |
| 1535 | assert_ne!(first, second, "alpha still drives the warp pass"); |
| 1536 | assert_eq!(second, interp(&fresh, &tex_a, &tex_b, 0.75), "cached field matches a fresh computation"); |
| 1537 | |
| 1538 | for i in 2..8 { |
| 1539 | interp(&cached, &frame(i, 10 + i as u64), &frame(i + 1, 20 + i as u64), 0.5); |
| 1540 | } |
| 1541 | assert_eq!(lock_or_recover(&cached.flow_cache).len(), FLOW_CACHE_CAP); |
| 1542 | } |
| 1543 | |
| 1544 | #[test] |
| 1545 | fn test_optflow_mismatched_sizes_and_rgba32float() { |
| 1546 | let (device, queue) = create_headless_device(); |
| 1547 | let pipelines = OpticalFlowPipelines::new(&device); |
| 1548 | |
| 1549 | let img_a = render_box_scene(128, 72, 40, 20); |
| 1550 | let img_b = render_box_scene(96, 54, 30, 15); |
| 1551 | let tex_a = upload_rgba8(&device, &queue, 128, 72, &img_a, 10); |
| 1552 | let tex_b = upload_rgba8(&device, &queue, 96, 54, &img_b, 11); |
| 1553 | |
| 1554 | let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 1555 | label: Some("optflow-test-f32"), |
| 1556 | }); |
| 1557 | let flowed_f32 = pipelines.interpolate_flow( |
| 1558 | &device, |
| 1559 | &queue, |
| 1560 | &mut enc, |
| 1561 | &tex_a, |
| 1562 | &tex_b, |
| 1563 | 0.5, |
| 1564 | wgpu::TextureFormat::Rgba32Float, |
| 1565 | ); |
| 1566 | let blend_f32 = pipelines.blend_frames( |
| 1567 | &device, |
| 1568 | &queue, |
| 1569 | &mut enc, |
| 1570 | &tex_a, |
| 1571 | &tex_b, |
| 1572 | 0.0, |
| 1573 | wgpu::TextureFormat::Rgba32Float, |
| 1574 | ); |
| 1575 | queue.submit(Some(enc.finish())); |
| 1576 | |
| 1577 | assert_eq!(flowed_f32.size, [128, 72]); |
| 1578 | assert_eq!(flowed_f32.format, wgpu::TextureFormat::Rgba32Float); |
| 1579 | assert_eq!(flowed_f32.depth, BitDepth::Float32); |
| 1580 | |
| 1581 | // Verify blend at alpha=0.0 reproduces frame_a accurately in Rgba32Float |
| 1582 | let raw_f32 = readback_bytes(&device, &queue, &blend_f32, 16); |
| 1583 | let f32_as_u8: Vec<u8> = raw_f32 |
| 1584 | .chunks_exact(4) |
| 1585 | .map(|c| { |
| 1586 | let v = f32::from_le_bytes([c[0], c[1], c[2], c[3]]); |
| 1587 | (v.clamp(0.0, 1.0) * 255.0).round() as u8 |
| 1588 | }) |
| 1589 | .collect(); |
| 1590 | let err = mae_rgba8(&f32_as_u8, &img_a); |
| 1591 | assert!(err < 0.5, "expected alpha=0 blend MAE ({err:.3}) < 0.5"); |
| 1592 | } |
| 1593 | |
| 1594 | #[test] |
| 1595 | fn test_optflow_pyramid_pool_reuses_textures_and_matches_unpooled_bit_for_bit() { |
| 1596 | let (device, queue) = create_headless_device(); |
| 1597 | let pooled = OpticalFlowPipelines::new(&device); |
| 1598 | |
| 1599 | let (w, h) = (192u32, 108u32); |
| 1600 | let fmt = wgpu::TextureFormat::Rgba8Unorm; |
| 1601 | let frames: Vec<CachedTexture> = (0..9) |
| 1602 | .map(|i| { |
| 1603 | let img = render_box_scene(w, h, 24 + i * 10, 20 + i * 4); |
| 1604 | upload_rgba8(&device, &queue, w, h, &img, 500 + i as u64) |
| 1605 | }) |
| 1606 | .collect(); |
| 1607 | |
| 1608 | // 1. Direct compute_flow_field reuse: alloc_count stays flat at 14 after frame 1. |
| 1609 | for i in 0..4 { |
| 1610 | let mut enc = device.create_command_encoder(&Default::default()); |
| 1611 | let (f_tex, f_view) = |
| 1612 | pooled.compute_flow_field(&device, &queue, &mut enc, &frames[i], &frames[i + 1]); |
| 1613 | queue.submit(Some(enc.finish())); |
| 1614 | lock_or_recover(&pooled.pyramid_pool).release(f_tex, f_view, half_size([w, h])); |
| 1615 | assert_eq!( |
| 1616 | lock_or_recover(&pooled.pyramid_pool).alloc_count, |
| 1617 | 14, |
| 1618 | "direct compute_flow_field alloc_count should remain 14 on pair {i}" |
| 1619 | ); |
| 1620 | } |
| 1621 | |
| 1622 | // 2. Full interpolate_flow across 8 distinct frame pairs: |
| 1623 | // - Intermediate pyramid/feature textures reuse from frame 1 (alloc_count only grows by |
| 1624 | // 1 per flow_cache slot up to FLOW_CACHE_CAP, then stays completely flat). |
| 1625 | // - Output matches fresh unpooled OpticalFlowPipelines bit-for-bit. |
| 1626 | pooled.clear_scratch(); |
| 1627 | lock_or_recover(&pooled.pyramid_pool).alloc_count = 0; |
| 1628 | lock_or_recover(&pooled.pyramid_pool).reuse_count = 0; |
| 1629 | |
| 1630 | let mut stable_allocs = 0u64; |
| 1631 | for i in 0..8 { |
| 1632 | let mut enc = device.create_command_encoder(&Default::default()); |
| 1633 | let out_pooled = pooled.interpolate_flow( |
| 1634 | &device, |
| 1635 | &queue, |
| 1636 | &mut enc, |
| 1637 | &frames[i], |
| 1638 | &frames[i + 1], |
| 1639 | 0.5, |
| 1640 | fmt, |
| 1641 | ); |
| 1642 | queue.submit(Some(enc.finish())); |
| 1643 | let pooled_bytes = readback_bytes(&device, &queue, &out_pooled, 4); |
| 1644 | |
| 1645 | let allocs_now = lock_or_recover(&pooled.pyramid_pool).alloc_count; |
| 1646 | if i < FLOW_CACHE_CAP { |
| 1647 | assert_eq!(allocs_now, 14 + i as u64); |
| 1648 | stable_allocs = allocs_now; |
| 1649 | } else { |
| 1650 | assert_eq!( |
| 1651 | allocs_now, stable_allocs, |
| 1652 | "alloc_count must stay flat once flow_cache reaches capacity (pair {i})" |
| 1653 | ); |
| 1654 | } |
| 1655 | |
| 1656 | // Fresh unpooled instance on the exact same pair |
| 1657 | let fresh = OpticalFlowPipelines::new(&device); |
| 1658 | let mut fresh_enc = device.create_command_encoder(&Default::default()); |
| 1659 | let out_fresh = fresh.interpolate_flow( |
| 1660 | &device, |
| 1661 | &queue, |
| 1662 | &mut fresh_enc, |
| 1663 | &frames[i], |
| 1664 | &frames[i + 1], |
| 1665 | 0.5, |
| 1666 | fmt, |
| 1667 | ); |
| 1668 | queue.submit(Some(fresh_enc.finish())); |
| 1669 | let fresh_bytes = readback_bytes(&device, &queue, &out_fresh, 4); |
| 1670 | |
| 1671 | assert_eq!( |
| 1672 | pooled_bytes, fresh_bytes, |
| 1673 | "pooled output must be bit-for-bit identical to unpooled reference (pair {i})" |
| 1674 | ); |
| 1675 | } |
| 1676 | assert!( |
| 1677 | lock_or_recover(&pooled.pyramid_pool).reuse_count >= 7 * 13, |
| 1678 | "expected substantial texture reuse across 8 distinct frame pairs" |
| 1679 | ); |
| 1680 | } |
| 1681 | |
| 1682 | #[test] |
| 1683 | fn test_optflow_uniform_ring_multiple_calls_in_single_encoder() { |
| 1684 | let (device, queue) = create_headless_device(); |
| 1685 | let pipelines = OpticalFlowPipelines::new(&device); |
| 1686 | |
| 1687 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); |
| 1688 | let stride = lock_or_recover(&pipelines.uniform_ring).stride; |
| 1689 | assert_eq!(stride % min_align, 0); |
| 1690 | |
| 1691 | let (w, h) = (64u32, 64u32); |
| 1692 | let solid = |r: u8, g: u8, b: u8| -> Vec<u8> { |
| 1693 | [r, g, b, 255].repeat((w * h) as usize) |
| 1694 | }; |
| 1695 | let tex_black = upload_rgba8(&device, &queue, w, h, &solid(0, 0, 0), 701); |
| 1696 | let tex_white = upload_rgba8(&device, &queue, w, h, &solid(255, 255, 255), 702); |
| 1697 | let box_a = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 8, 8), 703); |
| 1698 | let box_b = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 16, 12), 704); |
| 1699 | |
| 1700 | let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 1701 | label: Some("optflow-ring-single-enc"), |
| 1702 | }); |
| 1703 | |
| 1704 | // Mix blend_frames and interpolate_flow inside a single CommandEncoder, crossing |
| 1705 | // UNIFORM_SLOTS_PER_CHUNK (256) so chunk 0 and chunk 1 are both exercised before submit. |
| 1706 | let blend_first = pipelines.blend_frames( |
| 1707 | &device, |
| 1708 | &queue, |
| 1709 | &mut enc, |
| 1710 | &tex_black, |
| 1711 | &tex_white, |
| 1712 | 0.0, |
| 1713 | wgpu::TextureFormat::Rgba8Unorm, |
| 1714 | ); |
| 1715 | let flow_first = pipelines.interpolate_flow( |
| 1716 | &device, |
| 1717 | &queue, |
| 1718 | &mut enc, |
| 1719 | &box_a, |
| 1720 | &box_b, |
| 1721 | 0.25, |
| 1722 | wgpu::TextureFormat::Rgba8Unorm, |
| 1723 | ); |
| 1724 | |
| 1725 | let mut mid_blends = Vec::new(); |
| 1726 | for i in 0..270 { |
| 1727 | let alpha = if i == 128 { 0.5 } else { 0.8 }; |
| 1728 | let out = pipelines.blend_frames( |
| 1729 | &device, |
| 1730 | &queue, |
| 1731 | &mut enc, |
| 1732 | &tex_black, |
| 1733 | &tex_white, |
| 1734 | alpha, |
| 1735 | wgpu::TextureFormat::Rgba8Unorm, |
| 1736 | ); |
| 1737 | if i == 128 { |
| 1738 | mid_blends.push(out); |
| 1739 | } |
| 1740 | } |
| 1741 | |
| 1742 | let flow_last = pipelines.interpolate_flow( |
| 1743 | &device, |
| 1744 | &queue, |
| 1745 | &mut enc, |
| 1746 | &box_a, |
| 1747 | &box_b, |
| 1748 | 0.75, |
| 1749 | wgpu::TextureFormat::Rgba8Unorm, |
| 1750 | ); |
| 1751 | let blend_last = pipelines.blend_frames( |
| 1752 | &device, |
| 1753 | &queue, |
| 1754 | &mut enc, |
| 1755 | &tex_black, |
| 1756 | &tex_white, |
| 1757 | 1.0, |
| 1758 | wgpu::TextureFormat::Rgba8Unorm, |
| 1759 | ); |
| 1760 | queue.submit(Some(enc.finish())); |
| 1761 | |
| 1762 | assert!( |
| 1763 | lock_or_recover(&pipelines.uniform_ring).chunks.len() >= 2, |
| 1764 | "expected > 256 passes to allocate at least 2 uniform chunks" |
| 1765 | ); |
| 1766 | |
| 1767 | let px_first = readback_bytes(&device, &queue, &blend_first, 4); |
| 1768 | let px_mid = readback_bytes(&device, &queue, &mid_blends[0], 4); |
| 1769 | let px_last = readback_bytes(&device, &queue, &blend_last, 4); |
| 1770 | assert!(px_first[0] <= 1, "first blend (alpha=0) got {}", px_first[0]); |
| 1771 | assert!( |
| 1772 | (126..=129).contains(&px_mid[0]), |
| 1773 | "mid blend (alpha=0.5) got {}", |
| 1774 | px_mid[0] |
| 1775 | ); |
| 1776 | assert!(px_last[0] >= 254, "last blend (alpha=1) got {}", px_last[0]); |
| 1777 | |
| 1778 | let flow_first_px = readback_bytes(&device, &queue, &flow_first, 4); |
| 1779 | let flow_last_px = readback_bytes(&device, &queue, &flow_last, 4); |
| 1780 | assert_ne!( |
| 1781 | flow_first_px, flow_last_px, |
| 1782 | "first (alpha=0.25) and last (alpha=0.75) flow passes must use distinct uniform slots" |
| 1783 | ); |
| 1784 | |
| 1785 | // Verify against standalone fresh runs that neither flow_first nor flow_last was corrupted. |
| 1786 | let ref_p = OpticalFlowPipelines::new(&device); |
| 1787 | let mut ref_enc = device.create_command_encoder(&Default::default()); |
| 1788 | let ref_first = ref_p.interpolate_flow( |
| 1789 | &device, |
| 1790 | &queue, |
| 1791 | &mut ref_enc, |
| 1792 | &box_a, |
| 1793 | &box_b, |
| 1794 | 0.25, |
| 1795 | wgpu::TextureFormat::Rgba8Unorm, |
| 1796 | ); |
| 1797 | let ref_last = ref_p.interpolate_flow( |
| 1798 | &device, |
| 1799 | &queue, |
| 1800 | &mut ref_enc, |
| 1801 | &box_a, |
| 1802 | &box_b, |
| 1803 | 0.75, |
| 1804 | wgpu::TextureFormat::Rgba8Unorm, |
| 1805 | ); |
| 1806 | queue.submit(Some(ref_enc.finish())); |
| 1807 | assert_eq!(flow_first_px, readback_bytes(&device, &queue, &ref_first, 4)); |
| 1808 | assert_eq!(flow_last_px, readback_bytes(&device, &queue, &ref_last, 4)); |
| 1809 | } |
| 1810 | |
| 1811 | #[test] |
| 1812 | fn test_unkeyed_content_hash_zero_bypasses_flow_cache_and_releases_flow1() { |
| 1813 | let (device, queue) = create_headless_device(); |
| 1814 | let pipelines = OpticalFlowPipelines::new(&device); |
| 1815 | let (w, h) = (96u32, 64u32); |
| 1816 | let fmt = wgpu::TextureFormat::Rgba8Unorm; |
| 1817 | |
| 1818 | // Pair 1: both content_hash == 0 (unkeyed scratch textures). |
| 1819 | let a1 = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 8, 8), 0); |
| 1820 | let b1 = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 24, 8), 0); |
| 1821 | let mut enc1 = device.create_command_encoder(&Default::default()); |
| 1822 | let _out1 = pipelines.interpolate_flow(&device, &queue, &mut enc1, &a1, &b1, 0.5, fmt); |
| 1823 | queue.submit(Some(enc1.finish())); |
| 1824 | assert!( |
| 1825 | lock_or_recover(&pipelines.flow_cache).is_empty(), |
| 1826 | "content_hash == 0 must bypass flow_cache" |
| 1827 | ); |
| 1828 | // All 14 textures (13 intermediate + temporary flow1) must be returned to pyramid_pool. |
| 1829 | assert_eq!(lock_or_recover(&pipelines.pyramid_pool).entries.len(), 14); |
| 1830 | |
| 1831 | // Pair 2: completely different box positions, also with content_hash == 0 (or one side 0). |
| 1832 | let a2 = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 40, 12), 0); |
| 1833 | let b2 = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 40, 28), 99); |
| 1834 | let mut enc2 = device.create_command_encoder(&Default::default()); |
| 1835 | let out2 = pipelines.interpolate_flow(&device, &queue, &mut enc2, &a2, &b2, 0.5, fmt); |
| 1836 | queue.submit(Some(enc2.finish())); |
| 1837 | assert!(lock_or_recover(&pipelines.flow_cache).is_empty()); |
| 1838 | |
| 1839 | let fresh = OpticalFlowPipelines::new(&device); |
| 1840 | let mut fresh_enc = device.create_command_encoder(&Default::default()); |
| 1841 | let fresh_out = fresh.interpolate_flow(&device, &queue, &mut fresh_enc, &a2, &b2, 0.5, fmt); |
| 1842 | queue.submit(Some(fresh_enc.finish())); |
| 1843 | assert_eq!( |
| 1844 | readback_bytes(&device, &queue, &out2, 4), |
| 1845 | readback_bytes(&device, &queue, &fresh_out, 4), |
| 1846 | "unkeyed flow computation must not alias any stale cached flow field" |
| 1847 | ); |
| 1848 | } |
| 1849 | |
| 1850 | #[test] |
| 1851 | fn test_optflow_vram_bytes_tracks_memory_and_clears() { |
| 1852 | let (device, queue) = create_headless_device(); |
| 1853 | let pipelines = OpticalFlowPipelines::new(&device); |
| 1854 | assert_eq!(pipelines.vram_bytes(), 0); |
| 1855 | |
| 1856 | let (w, h) = (128u32, 64u32); |
| 1857 | let a = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 16, 16), 11); |
| 1858 | let b = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 32, 16), 12); |
| 1859 | let mut enc = device.create_command_encoder(&Default::default()); |
| 1860 | let _out = pipelines.interpolate_flow( |
| 1861 | &device, |
| 1862 | &queue, |
| 1863 | &mut enc, |
| 1864 | &a, |
| 1865 | &b, |
| 1866 | 0.5, |
| 1867 | wgpu::TextureFormat::Rgba8Unorm, |
| 1868 | ); |
| 1869 | queue.submit(Some(enc.finish())); |
| 1870 | |
| 1871 | let pool_bytes = lock_or_recover(&pipelines.pyramid_pool).total_bytes; |
| 1872 | let flow_bytes = u64::from(w / 2) * u64::from(h / 2) * 8; |
| 1873 | let ring_bytes = lock_or_recover(&pipelines.uniform_ring).vram_bytes(); |
| 1874 | assert!(pool_bytes > 0); |
| 1875 | assert!(ring_bytes > 0); |
| 1876 | assert_eq!(pipelines.vram_bytes(), pool_bytes + flow_bytes + ring_bytes); |
| 1877 | |
| 1878 | // Grow uniform ring beyond 2 chunks so clear_scratch() exercises trim_uniform_chunks(2). |
| 1879 | { |
| 1880 | let mut ring = lock_or_recover(&pipelines.uniform_ring); |
| 1881 | let dummy_u = OptFlowUniform { |
| 1882 | dst_size: [1.0; 4], |
| 1883 | params: [0.0; 4], |
| 1884 | }; |
| 1885 | for _ in 0..(UNIFORM_SLOTS_PER_CHUNK * 3) { |
| 1886 | ring.alloc_slot(&device, &queue, &dummy_u); |
| 1887 | } |
| 1888 | assert!(ring.chunks.len() >= 3); |
| 1889 | } |
| 1890 | assert!(pipelines.vram_bytes() > pool_bytes + flow_bytes + ring_bytes); |
| 1891 | |
| 1892 | pipelines.clear_scratch(); |
| 1893 | assert_eq!(lock_or_recover(&pipelines.pyramid_pool).total_bytes, 0); |
| 1894 | assert!(lock_or_recover(&pipelines.flow_cache).is_empty()); |
| 1895 | assert_eq!(lock_or_recover(&pipelines.uniform_ring).chunks.len(), 2); |
| 1896 | let retained_ring = lock_or_recover(&pipelines.uniform_ring).vram_bytes(); |
| 1897 | assert_eq!(pipelines.vram_bytes(), retained_ring); |
| 1898 | |
| 1899 | lock_or_recover(&pipelines.uniform_ring).trim_uniform_chunks(0); |
| 1900 | assert_eq!(pipelines.vram_bytes(), 0); |
| 1901 | } |
| 1902 | |
| 1903 | #[test] |
| 1904 | fn test_optflow_uniform_ring_grows_dynamically_past_8192_slots_without_wrapping() { |
| 1905 | let (device, queue) = create_headless_device(); |
| 1906 | let mut ring = UniformRing::new(&device); |
| 1907 | let dummy_u = OptFlowUniform { |
| 1908 | dst_size: [64.0, 64.0, 1.0 / 64.0, 1.0 / 64.0], |
| 1909 | params: [1.0, 1.0, 0.5, 0.0], |
| 1910 | }; |
| 1911 | |
| 1912 | // 32 * 256 = 8,192 was the old modulo cap; allocate 8,197 slots without resetting cursor. |
| 1913 | let total = 32 * UNIFORM_SLOTS_PER_CHUNK + 5; |
| 1914 | let mut last = None; |
| 1915 | for _ in 0..total { |
| 1916 | last = Some(ring.alloc_slot(&device, &queue, &dummy_u)); |
| 1917 | } |
| 1918 | let (last_buf, last_offset) = last.expect("allocated slots"); |
| 1919 | assert_eq!(ring.chunks.len(), 33, "must allocate chunk 32 instead of wrapping to 0"); |
| 1920 | assert_eq!(ring.cursor, total); |
| 1921 | assert_eq!(last_buf, ring.chunks[32]); |
| 1922 | assert_eq!(last_offset, 4 * ring.stride); |
| 1923 | |
| 1924 | ring.trim_uniform_chunks(2); |
| 1925 | assert_eq!(ring.chunks.len(), 2); |
| 1926 | assert_eq!(ring.cursor, 0); |
| 1927 | } |
| 1928 | |
| 1929 | #[test] |
| 1930 | #[ignore] |
| 1931 | fn bench_optflow_10_frames_720p_1080p() { |
| 1932 | use std::time::Instant; |
| 1933 | let (device, queue) = create_headless_device(); |
| 1934 | let pipelines = OpticalFlowPipelines::new(&device); |
| 1935 | |
| 1936 | for (label, w, h) in [("720p", 1280u32, 720u32), ("1080p", 1920u32, 1080u32)] { |
| 1937 | let frames: Vec<CachedTexture> = (0..11) |
| 1938 | .map(|i| { |
| 1939 | let img = render_box_scene(w, h, 200 + i * 16, 150 + i * 8); |
| 1940 | upload_rgba8(&device, &queue, w, h, &img, 1000 + i as u64) |
| 1941 | }) |
| 1942 | .collect(); |
| 1943 | |
| 1944 | // Warmup 1 frame with distinct hash so all 10 benchmark frames miss flow_cache |
| 1945 | { |
| 1946 | let warm_a = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 200, 150), 9998); |
| 1947 | let warm_b = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 216, 158), 9999); |
| 1948 | let mut enc = device.create_command_encoder(&Default::default()); |
| 1949 | let _ = pipelines.interpolate_flow( |
| 1950 | &device, |
| 1951 | &queue, |
| 1952 | &mut enc, |
| 1953 | &warm_a, |
| 1954 | &warm_b, |
| 1955 | 0.5, |
| 1956 | wgpu::TextureFormat::Rgba8Unorm, |
| 1957 | ); |
| 1958 | queue.submit(Some(enc.finish())); |
| 1959 | let _ = device.poll(wgpu::PollType::Wait { |
| 1960 | submission_index: None, |
| 1961 | timeout: Some(std::time::Duration::from_secs(10)), |
| 1962 | }); |
| 1963 | } |
| 1964 | |
| 1965 | let t0 = Instant::now(); |
| 1966 | for i in 0..10 { |
| 1967 | let mut enc = device.create_command_encoder(&Default::default()); |
| 1968 | let _out = pipelines.interpolate_flow( |
| 1969 | &device, |
| 1970 | &queue, |
| 1971 | &mut enc, |
| 1972 | &frames[i], |
| 1973 | &frames[i + 1], |
| 1974 | 0.5, |
| 1975 | wgpu::TextureFormat::Rgba8Unorm, |
| 1976 | ); |
| 1977 | queue.submit(Some(enc.finish())); |
| 1978 | let _ = device.poll(wgpu::PollType::Wait { |
| 1979 | submission_index: None, |
| 1980 | timeout: Some(std::time::Duration::from_secs(10)), |
| 1981 | }); |
| 1982 | } |
| 1983 | let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 1984 | println!( |
| 1985 | "BENCH {label} ({w}x{h}) 10 frames: total = {elapsed_ms:.2} ms, per_frame = {:.2} ms", |
| 1986 | elapsed_ms / 10.0 |
| 1987 | ); |
| 1988 | } |
| 1989 | } |
| 1990 | } |