diff --git a/crates/engine/src/av_decode.m b/crates/engine/src/av_decode.m index 857864382b5f8d8959a34429fc6f7e98ae1ad65e..6e34cfea835898b80820c1b4eca38063382246c4 100644 --- a/crates/engine/src/av_decode.m +++ b/crates/engine/src/av_decode.m @@ -517,21 +517,21 @@ static int copy_nv12_planes( int ok = 0; if (yBase && uvBase && - yW == expectedW && yH == expectedH && - uvW == expectedUvW && uvH == expectedUvH && - yBpr >= yW && uvBpr >= uvRowBytes && + yW >= (size_t)expectedW && yH >= (size_t)expectedH && + uvW >= expectedUvW && uvH >= expectedUvH && + yBpr >= (size_t)expectedW && uvBpr >= uvRowBytes && outYLen >= yRequired && outUvLen >= uvRequired) { - if (yBpr == yW) { + if (yBpr == (size_t)expectedW) { memcpy(outY, yBase, yRequired); } else { - for (size_t r = 0; r < yH; r++) { - memcpy(outY + r * yW, yBase + r * yBpr, yW); + for (size_t r = 0; r < (size_t)expectedH; r++) { + memcpy(outY + r * (size_t)expectedW, yBase + r * yBpr, (size_t)expectedW); } } if (uvBpr == uvRowBytes) { memcpy(outUv, uvBase, uvRequired); } else { - for (size_t r = 0; r < uvH; r++) { + for (size_t r = 0; r < expectedUvH; r++) { memcpy(outUv + r * uvRowBytes, uvBase + r * uvBpr, uvRowBytes); } } diff --git a/crates/engine/src/cache.rs b/crates/engine/src/cache.rs index 81bc8c4b6f19edf1f9adab718e2fd55c12a6b382..59a8fa34f99f22a17ee592ac06ff2efe5c9f8c7c 100644 --- a/crates/engine/src/cache.rs +++ b/crates/engine/src/cache.rs @@ -153,6 +153,14 @@ fn texture_bytes(size: [u32; 2], format: wgpu::TextureFormat) -> u64 { .saturating_mul(bytes_per_pixel(format)) } +fn base_texture_bytes(tex: &CachedTexture) -> u64 { + if tex.bytes == 0 || tex.size[0] == 0 || tex.size[1] == 0 { + 0 + } else { + texture_bytes(tex.size, tex.format) + } +} + /// Clamps `(width, height)` to at least 1 and at most `max_dim` while preserving aspect ratio. /// Returns `(clamped_size, tex_scale)` where `tex_scale = physical / logical` (`1.0` if unclamped). pub(crate) fn clamp_dims_to_limit(width: u32, height: u32, max_dim: u32) -> ([u32; 2], f32) { @@ -372,7 +380,8 @@ impl TexturePool { } fn push(&mut self, tex: &CachedTexture) { - if tex.bytes == 0 || tex.size[0] == 0 || tex.size[1] == 0 { + let base_bytes = base_texture_bytes(tex); + if base_bytes == 0 { return; } let key = TexturePoolKey { @@ -382,13 +391,13 @@ impl TexturePool { usage: tex.texture.usage(), }; self.tick += 1; - self.total_bytes = self.total_bytes.saturating_add(tex.bytes); + self.total_bytes = self.total_bytes.saturating_add(base_bytes); self.pooled_count += 1; self.returns += 1; self.buckets.entry(key).or_default().push_back(PooledTexture { texture: Arc::clone(&tex.texture), view: Arc::clone(&tex.view), - bytes: tex.bytes, + bytes: base_bytes, last_returned: self.tick, }); } @@ -853,18 +862,22 @@ impl NodeCache { self.trim_pool_to_budget(); } - fn defer_to_pool(&mut self, tex: CachedTexture) { - if tex.bytes == 0 || tex.bytes > self.budget_bytes { - if tex.bytes > 0 { + fn defer_to_pool(&mut self, mut tex: CachedTexture) { + let base_bytes = base_texture_bytes(&tex); + if base_bytes == 0 || base_bytes > self.budget_bytes { + if base_bytes > 0 { self.vram_drops.fetch_add(1, Ordering::Relaxed); } return; } - let mut pending_bytes: u64 = self.pending_pool.iter().map(|t| t.bytes).sum(); + // Aux channels are not pooled; drop them immediately so deferred pool entries + // only account for base RGBA texture bytes. + tex.set_aux(None); + let mut pending_bytes: u64 = self.pending_pool.iter().map(base_texture_bytes).sum(); if self .total_bytes .saturating_add(pending_bytes) - .saturating_add(tex.bytes) + .saturating_add(base_bytes) <= self.budget_bytes { self.pending_pool.push_back(tex); @@ -874,19 +887,19 @@ impl NodeCache { if self .total_bytes .saturating_add(pending_bytes) - .saturating_add(tex.bytes) + .saturating_add(base_bytes) <= self.budget_bytes { break; } - pending_bytes = pending_bytes.saturating_sub(dropped.bytes); + pending_bytes = pending_bytes.saturating_sub(base_texture_bytes(dropped)); self.pending_pool.pop_front(); self.vram_drops.fetch_add(1, Ordering::Relaxed); } if self .total_bytes .saturating_add(pending_bytes) - .saturating_add(tex.bytes) + .saturating_add(base_bytes) <= self.budget_bytes { self.pending_pool.push_back(tex); @@ -930,8 +943,9 @@ impl NodeCache { } fn return_to_pool(&self, tex: &CachedTexture) { - if tex.bytes == 0 || tex.bytes > self.budget_bytes { - if tex.bytes > 0 { + let base_bytes = base_texture_bytes(tex); + if base_bytes == 0 || base_bytes > self.budget_bytes { + if base_bytes > 0 { self.vram_drops.fetch_add(1, Ordering::Relaxed); } return; @@ -995,31 +1009,34 @@ impl NodeCache { drained.sort_by_key(|e| e.eviction_priority()); let mut pool = self.pool.lock().expect("texture pool lock"); for tex in recycle_scratch { - if tex.bytes > 0 && tex.bytes <= self.budget_bytes { + let base_bytes = base_texture_bytes(&tex); + if base_bytes > 0 && base_bytes <= self.budget_bytes { pool.push(&tex); - } else if tex.bytes > 0 { + } else if base_bytes > 0 { self.vram_drops.fetch_add(1, Ordering::Relaxed); } } for tex in pending { - if tex.bytes > 0 && tex.bytes <= self.budget_bytes { + let base_bytes = base_texture_bytes(&tex); + if base_bytes > 0 && base_bytes <= self.budget_bytes { pool.push(&tex); - } else if tex.bytes > 0 { + } else if base_bytes > 0 { self.vram_drops.fetch_add(1, Ordering::Relaxed); } } for entry in drained { - if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes { + let base_bytes = base_texture_bytes(&entry.tex); + if base_bytes > 0 && base_bytes <= self.budget_bytes { pool.push(&entry.tex); - } else if entry.tex.bytes > 0 { + } else if base_bytes > 0 { self.vram_drops.fetch_add(1, Ordering::Relaxed); } } self.trim_pool_locked(&mut pool, 0); } else { - let dropped = drained.iter().filter(|e| e.tex.bytes > 0).count() - + pending.iter().filter(|t| t.bytes > 0).count() - + recycle_scratch.iter().filter(|t| t.bytes > 0).count(); + let dropped = drained.iter().filter(|e| base_texture_bytes(&e.tex) > 0).count() + + pending.iter().filter(|t| base_texture_bytes(t) > 0).count() + + recycle_scratch.iter().filter(|t| base_texture_bytes(t) > 0).count(); if dropped > 0 { self.vram_drops.fetch_add(dropped as u64, Ordering::Relaxed); } @@ -1402,4 +1419,66 @@ mod tests { cache.bust_all(); assert!(cache.vram_drops() > before_bust); } + + #[test] + fn pooled_texture_with_aux_drops_aux_bytes_without_phantom_vram_inflation() { + let eng = Engine::new_headless().expect("gpu"); + let device = eng.device(); + let usage = NodeCache::default_texture_usage(); + let mut cache = NodeCache::new(16); + + // 512x512 RGBA8 = 1 MiB base; Z (R32F = 1 MiB) + Normal (RGBA16F = 2 MiB) = 3 MiB aux. + let base_bytes: u64 = 512 * 512 * 4; + let aux_bytes: u64 = 512 * 512 * 4 + 512 * 512 * 8; + let mut t1 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + let ptr1 = Arc::as_ptr(&t1.texture); + assert_eq!(t1.bytes, base_bytes); + let make_aux = || { + Arc::new(AuxChannels { + z: Some(AuxChannelTex::new(device, [512, 512], wgpu::TextureFormat::R32Float, "test-z")), + normal: Some(AuxChannelTex::new(device, [512, 512], wgpu::TextureFormat::Rgba16Float, "test-n")), + ..Default::default() + }) + }; + t1.set_aux(Some(make_aux())); + assert_eq!(t1.bytes, base_bytes + aux_bytes); + + // Live cache includes aux_bytes. + cache.insert(1, t1, NodeId(0), 0); + assert_eq!(cache.live_bytes(), base_bytes + aux_bytes); + assert_eq!(cache.pooled_bytes(), 0); + assert_eq!(cache.total_vram_bytes(), base_bytes + aux_bytes); + + // clear_dynamic drops aux and pools ONLY base RGBA bytes. + assert_eq!(cache.clear_dynamic(), 1); + assert_eq!(cache.live_bytes(), 0); + assert_eq!(cache.pooled_bytes(), base_bytes); + assert_eq!(cache.total_vram_bytes(), base_bytes); + + // Re-acquiring from pool returns exact base RGBA bytes with no aux. + let mut t2 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + assert_eq!(Arc::as_ptr(&t2.texture), ptr1); + assert!(t2.aux.is_none()); + assert_eq!(t2.bytes, base_bytes); + assert_eq!(cache.pooled_bytes(), 0); + assert_eq!(cache.live_bytes(), 0); + assert_eq!(cache.total_vram_bytes(), 0); + + // Re-attach aux, insert, and evict via overwrite (defer_to_pool -> flush_pending_pool). + t2.set_aux(Some(make_aux())); + cache.insert(2, t2, NodeId(1), 0); + let t3 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + cache.insert(2, t3, NodeId(1), 0); + assert_eq!(cache.live_bytes(), base_bytes); + cache.flush_pending_pool(); + assert_eq!(cache.pooled_bytes(), base_bytes); + assert_eq!(cache.total_vram_bytes(), base_bytes * 2); + + // Re-acquire the deferred texture and verify base bytes again. + let t4 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + assert_eq!(t4.bytes, base_bytes); + assert_eq!(cache.pooled_bytes(), 0); + assert_eq!(cache.live_bytes(), base_bytes); + assert_eq!(cache.total_vram_bytes(), base_bytes); + } } diff --git a/crates/engine/src/eval/aux_ops.rs b/crates/engine/src/eval/aux_ops.rs index 0a951c6ff22d795f695956ea4283fb8876820af3..0d085f9eca73fbf9941727ee4c15b1d8eb5d768c 100644 --- a/crates/engine/src/eval/aux_ops.rs +++ b/crates/engine/src/eval/aux_ops.rs @@ -686,18 +686,25 @@ impl Engine { &dst_z, params, ); + let same_dod = dst.size == bg.size && dst.origin == bg.origin; if bg_z.is_some() { - let mut out_aux = bg.aux_cloned(); + let mut out_aux = if same_dod { + bg.aux_cloned() + } else { + AuxChannels::default() + }; out_aux.z = Some(dst_z); dst.set_aux(Some(Arc::new(out_aux))); - } else if bg.aux.is_some() { + } else if bg.aux.is_some() && same_dod { // Preserve any non-Z aux channels on BG, keeping Z = None matching Snow Globe! dst.set_aux(bg.aux.clone()); } } - /// Crops `src.aux` channels from `src.origin` / `src.size` to `src.canvas_size`. - pub(super) fn crop_aux_to_canvas( + /// Re-origins and resizes `src.aux` channels from `(src.origin, src.size)` to + /// `(dst.origin, dst.size)`, padding out-of-bounds Z with `EMPTY_Z_SENTINEL` and + /// out-of-bounds `Rgba16Float` channels with `0.0`. + pub(super) fn reorigin_aux( &self, enc: &mut wgpu::CommandEncoder, src: &CachedTexture, @@ -706,13 +713,17 @@ impl Engine { let Some(src_aux) = src.aux.as_ref() else { return; }; + if src.origin == dst.origin && src.size == dst.size { + dst.set_aux(Some(src_aux.clone())); + return; + } let mut out_aux = AuxChannels::default(); let mut u = UniformParams::default(); u.p[0] = [ - src.origin[0] as f32, - src.origin[1] as f32, - src.canvas_size[0] as f32, - src.canvas_size[1] as f32, + (src.origin[0] - dst.origin[0]) as f32, + (src.origin[1] - dst.origin[1]) as f32, + dst.size[0] as f32, + dst.size[1] as f32, ]; let mut ap = self.aux_pipelines().borrow_mut(); if let Some(z) = src_aux.z.as_ref() { @@ -759,6 +770,16 @@ impl Engine { dst.set_aux(Some(Arc::new(out_aux))); } + /// Crops `src.aux` channels from `src.origin` / `src.size` to `src.canvas_size`. + pub(super) fn crop_aux_to_canvas( + &self, + enc: &mut wgpu::CommandEncoder, + src: &CachedTexture, + dst: &mut CachedTexture, + ) { + self.reorigin_aux(enc, src, dst); + } + /// Evaluates `Dimension.CopyAux` (Mode 0: Aux -> Color with Remap; Mode 1: Color -> Aux). #[allow(clippy::too_many_arguments)] pub(super) fn eval_copy_aux( @@ -1979,4 +2000,265 @@ mod tests { assert!(c_fwd[0] > 2.0, "expected positive forward flow x, got {c_fwd:?}"); assert!(c_bwd[0] < -2.0, "expected negative backward flow x, got {c_bwd:?}"); } + + #[test] + fn depth_merge_transparent_fg_preserves_bg_z_and_non_over_modes_apply_when_bg_closer() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 1 }}, + GlobalRange = {{ 0, 1 }}, + Tools = ordered() {{ + {} + {} + {} + Transparent2D = Background {{ + Inputs = {{ + Width = Input {{ Value = 16, }}, + Height = Input {{ Value = 16, }}, + TopLeftRed = Input {{ Value = 0.0, }}, + TopLeftGreen = Input {{ Value = 0.0, }}, + TopLeftBlue = Input {{ Value = 0.0, }}, + TopLeftAlpha = Input {{ Value = 0.0, }}, + }}, + }}, + -- Transparent 2D FG (no Z -> implicit 0.0) over BG with Z = -5.0 must keep bg_z = -5.0! + M_Trans2D = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "BgFar", Source = "Output", }}, + Foreground = Input {{ SourceOp = "Transparent2D", Source = "Output", }}, + PerformDepthMerge = Input {{ Value = 1, }}, + }}, + }}, + -- Transparent 3D FG (alpha=0, Z = -2.0) over BG with Z = -5.0 must also keep bg_z = -5.0! + M_Trans3D = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "BgFar", Source = "Output", }}, + Foreground = Input {{ SourceOp = "TransNear", Source = "Output", }}, + PerformDepthMerge = Input {{ Value = 1, }}, + }}, + }}, + -- fg_z (-5) < bg_z (-2) with ApplyMode = Screen: Screen(blue, red) -> magenta! + M_Screen = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, + Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, + PerformDepthMerge = Input {{ Value = 1, }}, + ApplyMode = Input {{ Value = FuID {{ "Screen" }}, }}, + }}, + }}, + -- fg_z (-5) < bg_z (-2) with ApplyMode = Multiply: Multiply(blue, red) -> black! + M_Multiply = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, + Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, + PerformDepthMerge = Input {{ Value = 1, }}, + ApplyMode = Input {{ Value = FuID {{ "Multiply" }}, }}, + }}, + }}, + -- fg_z (-5) < bg_z (-2) with Operator = Under: swaps BG behind FG -> blue! + M_Under = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, + Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, + PerformDepthMerge = Input {{ Value = 1, }}, + Operator = Input {{ Value = FuID {{ "Under" }}, }}, + }}, + }}, + -- fg_z (-5) < bg_z (-2) with Operator = Held Out: bg * (1 - fg.a) -> transparent! + M_HeldOut = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, + Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, + PerformDepthMerge = Input {{ Value = 1, }}, + Operator = Input {{ Value = FuID {{ "Held Out" }}, }}, + }}, + }}, + }}, + }}"#, + z_layer_nodes("BgFar", [0.0, 0.0, 1.0, 1.0], -5.0), + z_layer_nodes("FgNear", [1.0, 0.0, 0.0, 1.0], -2.0), + z_layer_nodes("TransNear", [0.0, 0.0, 0.0, 0.0], -2.0), + ); + let comp = Comp::from_fusion_str(&src).expect("parse depth merge regression comp"); + let mut eval_one = |name: &str| -> ([u8; 4], f32) { + let id = comp.find_node(name).unwrap(); + let (tex, _) = eng.evaluate(&comp, id, 0.0); + let px = eng.readback_rgba(&tex).unwrap(); + let c = px_center(&px, tex.size[0], tex.size[1]); + let zt = tex.aux.as_ref().unwrap().z.as_ref().unwrap(); + let zs = readback_r32f(&eng, zt); + (c, zs[(zt.size[1] / 2 * zt.size[0] + zt.size[0] / 2) as usize]) + }; + + let (c_t2d, z_t2d) = eval_one("M_Trans2D"); + assert_eq!(c_t2d, [0, 0, 255, 255]); + assert!((z_t2d - (-5.0)).abs() < 1e-3, "transparent 2D FG must preserve bg_z=-5.0, got {z_t2d}"); + + let (c_t3d, z_t3d) = eval_one("M_Trans3D"); + assert_eq!(c_t3d, [0, 0, 255, 255]); + assert!((z_t3d - (-5.0)).abs() < 1e-3, "transparent 3D FG must preserve bg_z=-5.0, got {z_t3d}"); + + let (c_scr, z_scr) = eval_one("M_Screen"); + assert_eq!(c_scr, [255, 0, 255, 255], "Screen when fg_z < bg_z must blend red+blue -> magenta"); + assert!((z_scr - (-2.0)).abs() < 1e-3); + + let (c_mul, z_mul) = eval_one("M_Multiply"); + assert_eq!(c_mul, [0, 0, 0, 255], "Multiply when fg_z < bg_z must yield black"); + assert!((z_mul - (-2.0)).abs() < 1e-3); + + let (c_und, z_und) = eval_one("M_Under"); + assert_eq!(c_und, [0, 0, 255, 255], "Under when fg_z < bg_z must put BG behind FG -> blue"); + assert!((z_und - (-2.0)).abs() < 1e-3); + + let (c_ho, z_ho) = eval_one("M_HeldOut"); + assert_eq!(c_ho, [0, 0, 0, 0], "Held Out when fg_z < bg_z with opaque FG must yield transparent"); + assert!((z_ho - (-2.0)).abs() < 1e-3); + } + + #[test] + fn copy_aux_mode0_sanitizes_nan_and_inf_pixels() { + let Ok(eng) = Engine::new_headless() else { return }; + let z_tex = AuxChannelTex::new(&eng.device, [4, 1], wgpu::TextureFormat::R32Float, "nan-z"); + let z_vals: [f32; 4] = [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -5.0]; + eng.queue.write_texture( + z_tex.texture.as_image_copy(), + bytemuck::cast_slice(&z_vals), + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(16), + rows_per_image: Some(1), + }, + wgpu::Extent3d { width: 4, height: 1, depth_or_array_layers: 1 }, + ); + let src = eng.alloc_tex([4, 1], BitDepth::Float32, 0); + let dst_remap = eng.alloc_tex([4, 1], BitDepth::Float32, 0); + let dst_raw = eng.alloc_tex([4, 1], BitDepth::Float32, 0); + + let mut u_remap = UniformParams::default(); + u_remap.p[0] = [0.0, 1.0, 0.0, 0.0]; // kind=Z, remap_en=1 + u_remap.p[1] = [-10.0, 0.0, 0.0, 1.0]; // -10..0 -> 0..1 (so 0.0 -> 1.0, -5.0 -> 0.5) + u_remap.p[3] = [1.0, 0.0, 0.0, 0.0]; // blend=1 + + let mut u_raw = UniformParams::default(); + u_raw.p[0] = [0.0, 0.0, 0.0, 0.0]; // kind=Z, remap_en=0 + u_raw.p[3] = [1.0, 0.0, 0.0, 0.0]; // blend=1 + + let mut enc = eng.device.create_command_encoder(&Default::default()); + eng.aux_pipelines().borrow_mut().dispatch_rgba_op( + &eng.device, + &eng.queue, + &mut enc, + false, + &src.view, + &z_tex.view, + &eng.dummy.view, + &dst_remap, + &u_remap, + ); + eng.aux_pipelines().borrow_mut().dispatch_rgba_op( + &eng.device, + &eng.queue, + &mut enc, + false, + &src.view, + &z_tex.view, + &eng.dummy.view, + &dst_raw, + &u_raw, + ); + eng.queue.submit(Some(enc.finish())); + eng.reset_uniform_cursors(); + + let remapped = eng.readback_rgba_f32(&dst_remap).expect("readback remapped"); + for i in 0..3 { + let v = remapped[i * 4]; + assert!(v.is_finite(), "pixel {i} remapped must be finite, got {v}"); + assert!((v - 1.0).abs() < 1e-4, "sanitized 0.0 remapped in [-10..0]->[0..1] should be 1.0, got {v}"); + } + assert!((remapped[12] - 0.5).abs() < 1e-4, "valid -5.0 remapped should be 0.5, got {}", remapped[12]); + + let raw = eng.readback_rgba_f32(&dst_raw).expect("readback raw"); + for i in 0..3 { + assert!(raw[i * 4].is_finite() && raw[i * 4] == 0.0, "pixel {i} raw NaN/Inf must sanitize to 0.0, got {}", raw[i * 4]); + } + assert!((raw[12] - (-5.0)).abs() < 1e-4, "valid -5.0 raw should stay -5.0, got {}", raw[12]); + } + + #[test] + fn motion_blur_expanded_union_dod_pads_aux_z_with_empty_sentinel() { + let Ok(mut eng) = Engine::new_headless() else { return }; + // BgZ and FgZ are both 16x16; MBMerge animates Center.x across 0.25..0.75 with MotionBlur=1, + // Quality=3, ShutterAngle=360 so: + // t=0.5 -> Center.x = 0.375 -> DoD expands left ([-2, 0], 18x16) + // t=1.0 -> Center.x = 0.500 -> center DoD is ([ 0, 0], 16x16) with Z = -1.0 + // t=1.5 -> Center.x = 0.625 -> DoD expands right ([ 0, 0], 18x16) + // Union DoD = ([-2, 0], 20x16); center's 16x16 aux.z must be padded to 20x16 with + // EMPTY_Z_SENTINEL in the 2px OOB margins on left and right. + let src = format!( + r#"Composition {{ + CurrentTime = 1, + RenderRange = {{ 0, 2 }}, + GlobalRange = {{ 0, 2 }}, + Tools = ordered() {{ + {} + {} + MBMerge = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "BgZ", Source = "Output", }}, + Foreground = Input {{ SourceOp = "FgZ", Source = "Output", }}, + PerformDepthMerge = Input {{ Value = 1, }}, + MotionBlur = Input {{ Value = 1, }}, + Quality = Input {{ Value = 3, }}, + ShutterAngle = Input {{ Value = 360.0, }}, + Center = Input {{ + Value = {{ 0.5, 0.5 }}, + Expression = "Point(0.25 + time * 0.25, 0.5)", + }}, + }}, + }}, + -- Downstream zoomed-out Transform ensures Merge does not clip its expanded DoD to canvas! + ZoomOut = Transform {{ + Inputs = {{ + Input = Input {{ SourceOp = "MBMerge", Source = "Output", }}, + Size = Input {{ Value = 0.5, }}, + }}, + }}, + }}, + }}"#, + z_layer_nodes("BgZ", [0.0, 0.0, 1.0, 1.0], -5.0), + z_layer_nodes("FgZ", [1.0, 0.0, 0.0, 1.0], -1.0), + ); + let comp = Comp::from_fusion_str(&src).expect("parse MB DoD aux comp"); + let id = comp.find_node("MBMerge").unwrap(); + + let mut visiting = eng.prepare_frame_scratch(&comp); + let mut stats = EvalStats::default(); + let mut enc = eng.device.create_command_encoder(&Default::default()); + let out = eng.eval_node(&comp, id, 1.0, &mut enc, &mut visiting, &mut stats); + eng.queue.submit(Some(enc.finish())); + eng.reset_uniform_cursors(); + eng.finish_frame_scratch(visiting); + + assert!(out.size[0] > 16 && out.origin[0] < 0, "expected expanded union DoD, got origin={:?} size={:?}", out.origin, out.size); + let aux_z = out + .aux + .as_ref() + .expect("MotionBlur output must carry padded aux") + .z + .as_ref() + .expect("MotionBlur output must carry padded aux.z"); + assert_eq!(aux_z.size, out.size, "padded aux.z size must match out.size"); + + let zs = readback_r32f(&eng, aux_z); + let w = out.size[0] as usize; + let row = (out.size[1] / 2) as usize; + let left_oob = zs[row * w]; + let right_oob = zs[row * w + (w - 1)]; + let center_z = zs[row * w + (w / 2)]; + assert_eq!(left_oob, EMPTY_Z_SENTINEL, "left OOB Z must be EMPTY_Z_SENTINEL, got {left_oob}"); + assert_eq!(right_oob, EMPTY_Z_SENTINEL, "right OOB Z must be EMPTY_Z_SENTINEL, got {right_oob}"); + assert!((center_z - (-1.0)).abs() < 1e-3, "center Z must preserve -1.0, got {center_z}"); + } } diff --git a/crates/engine/src/eval/composite.rs b/crates/engine/src/eval/composite.rs index 01b09862a24a950490fc21b73ed70265b9166a4a..7b67d459fef10cbf2a13451a31e30a6a941aeb42 100644 --- a/crates/engine/src/eval/composite.rs +++ b/crates/engine/src/eval/composite.rs @@ -1166,7 +1166,7 @@ impl Engine { }; let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &fg.view, mv, &dst, &u); - if bg.aux.is_some() && dst.size == bg.size { + if bg.aux.is_some() && dst.size == bg.size && dst.origin == bg.origin { dst.set_aux(bg.aux.clone()); } self.cache.insert(key, dst.clone(), node.id, frame_i); diff --git a/crates/engine/src/eval/fuses.rs b/crates/engine/src/eval/fuses.rs index 7325e2fc0544d56551b82b5bcd42e503f923b194..089324a5092e2773a1a88463387563c314873d5d 100644 --- a/crates/engine/src/eval/fuses.rs +++ b/crates/engine/src/eval/fuses.rs @@ -178,10 +178,11 @@ impl Engine { let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) }; let depth = self.node_depth(comp, node, time, None); + let proxy = self.proxy_scale.max(1) as f32; let hex_size = comp.eval_number(node, "Size", time, 5.0, &self.expr) as f32; let border = comp.eval_number(node, "BorderSize", time, 2.0, &self.expr) as f32; - let xoff = comp.eval_number(node, "XOff", time, 0.0, &self.expr).round() as f32; - let yoff = comp.eval_number(node, "YOff", time, 0.0, &self.expr).round() as f32; + let xoff = comp.eval_number(node, "XOff", time, 0.0, &self.expr).round() as f32 / proxy; + let yoff = comp.eval_number(node, "YOff", time, 0.0, &self.expr).round() as f32 / proxy; let r1 = comp.eval_number(node, "Red1", time, 0.2, &self.expr) as f32; let g1 = comp.eval_number(node, "Green1", time, 0.2, &self.expr) as f32; let b1 = comp.eval_number(node, "Blue1", time, 0.8, &self.expr) as f32; @@ -573,6 +574,52 @@ mod tests { assert!(mask_px.chunks(4).all(|p| p[3] == 128), "Blend=0.5 scales alpha to 0.5"); } + #[test] + fn hexagon_tiles_proxy_scale_scales_xoff_and_yoff_to_match_downsampled_full_res() { + let c = comp( + r#"OffsetHex = Fuse.HexagonTiles { Inputs = { + Width = Input { Value = 192, }, + Height = Input { Value = 108, }, + Size = Input { Value = 16.56, }, + BorderSize = Input { Value = 2.0, }, + XOff = Input { Value = -148, }, + YOff = Input { Value = -37, }, + Red1 = Input { Value = 0, }, + Green1 = Input { Value = 0.495, }, + Blue1 = Input { Value = 0.8, }, + Red2 = Input { Value = 0, }, + Green2 = Input { Value = 0.2, }, + Blue2 = Input { Value = 0.2, }, + }, },"#, + ); + let Ok(mut eng) = Engine::new_headless() else { return }; + let id = c.find_node("OffsetHex").unwrap(); + + eng.proxy_scale = 1; + let (full_tex, _) = eng.evaluate(&c, id, 0.0); + assert_eq!(full_tex.size, [192, 108]); + let full_px = eng.readback_rgba(&full_tex).unwrap(); + + eng.proxy_scale = 2; + let (half_tex, _) = eng.evaluate(&c, id, 0.0); + assert_eq!(half_tex.size, [96, 54]); + let half_px = eng.readback_rgba(&half_tex).unwrap(); + + // Fusion Y-up coordinate fy_half = (54 - 1 - row) maps to fy_full = 2 * fy_half, + // which in top-down rows is row_full = 108 - 1 - 2*(53 - row) = 2*row + 1, col_full = 2*col. + let mut diffs = 0usize; + for row in 0..54u32 { + for col in 0..96u32 { + let h_idx = ((row * 96 + col) * 4) as usize; + let f_idx = (((row * 2 + 1) * 192 + col * 2) * 4) as usize; + if half_px[h_idx..h_idx + 4] != full_px[f_idx..f_idx + 4] { + diffs += 1; + } + } + } + assert!(diffs <= 2, "HexagonTiles proxy_scale=2 diverged from downsampled full-res: {diffs} diffs"); + } + #[test] fn hexagon_tiles_in_30_ground_is_crazy005_evaluates_with_no_unsupported_nodes() { let path = std::path::Path::new("/Volumes/Project/trees/fusion/30_ground_is_crazy005.comp"); @@ -586,12 +633,23 @@ mod tests { assert!(stats.unsupported_nodes.is_empty(), "unexpected unsupported_nodes: {:?}", stats.unsupported_nodes); assert_eq!(tex.size, [1920, 1080]); let gpu_px = eng.readback_rgba(&tex).unwrap(); + let hex_node = comp.node(hex_id); + let c1 = [ + comp.eval_number(hex_node, "Red1", 3107.0, 0.2, &eng.expr), + comp.eval_number(hex_node, "Green1", 3107.0, 0.2, &eng.expr), + comp.eval_number(hex_node, "Blue1", 3107.0, 0.8, &eng.expr), + ]; + let c2 = [ + comp.eval_number(hex_node, "Red2", 3107.0, 0.8, &eng.expr), + comp.eval_number(hex_node, "Green2", 3107.0, 0.2, &eng.expr), + comp.eval_number(hex_node, "Blue2", 3107.0, 0.2, &eng.expr), + ]; let mut diffs = 0usize; for row in 0..1080u32 { for col in 0..1920u32 { let idx = ((row * 1920 + col) * 4) as usize; let g = &gpu_px[idx..idx + 4]; - let (r, h_val) = hexagon_tiles_f64_eval(1920, 1080, col, row, 16.56, 2.0, -148.0, 0.0, [0.0, 0.495, 0.8], [0.0, 0.2, 0.2]); + let (r, h_val) = hexagon_tiles_f64_eval(1920, 1080, col, row, 16.56, 2.0, -148.0, 0.0, c1, c2); if g != r { assert!((h_val - 0.1).abs() < 1e-6, "non-boundary mismatch at ({col}, {row}): h={h_val}, gpu={g:?}, ref={r:?}"); diffs += 1; diff --git a/crates/engine/src/eval/io.rs b/crates/engine/src/eval/io.rs index e359323330048aa8fed964c10eb651e961c8d3bd..22d78d6ee0ba7589eddb8e08d2d9d5fef7c9399a 100644 --- a/crates/engine/src/eval/io.rs +++ b/crates/engine/src/eval/io.rs @@ -4,6 +4,7 @@ use std::sync::{Mutex, OnceLock}; #[path = "nv12.rs"] mod nv12; +pub(crate) use nv12::Nv12Pipelines; static DIMS_CACHE: OnceLock>>> = OnceLock::new(); diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index d47aa98023f1d06e7511ebe5391aa8c5d3686918..9a0ae3ae2c411766bbd4464751c990a9862b3e3d 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -32,6 +32,7 @@ mod output_cache; use dispatch::UniformParams; pub use dispatch::{PendingReadback, create_texture, create_texture_dod, create_texture_dod_fmt}; +pub(crate) use io::Nv12Pipelines; use output_cache::OutputCache; use registry::{ShaderOp, ShaderRegistry}; @@ -317,6 +318,7 @@ impl Engine { if let Some(of) = self.optflow.get() { of.reset_uniform_cursor(); } + self.media.reset_nv12_uniform_cursor(); } fn trim_uniform_chunks(&self) { @@ -324,6 +326,7 @@ impl Engine { if let Some(ap) = self.aux_pipelines.get() { ap.borrow_mut().trim_uniform_chunks(2); } + self.media.trim_nv12_uniform_chunks(2); } pub(super) fn sync_bg_cache_with_vram_drops(&mut self) { @@ -368,6 +371,7 @@ impl Engine { if let Some(of) = self.optflow.get() { of.clear_scratch(); } + self.media.clear_nv12_gpu_state(); #[cfg(not(target_arch = "wasm32"))] self.pipelines.borrow_mut().readback_pool.clear(); self.sprite_cache.clear(); @@ -638,11 +642,15 @@ impl Engine { { return samples.swap_remove(center_idx); } + let center = &samples[center_idx]; let mut hasher = std::collections::hash_map::DefaultHasher::new(); "motion_blur".hash(&mut hasher); id.0.hash(&mut hasher); + self.cache.gpu_salt.hash(&mut hasher); + self.cache.node_salt(id).hash(&mut hasher); cfg.cache_key_bits().hash(&mut hasher); - first.format.hash(&mut hasher); + center.format.hash(&mut hasher); + center.depth.hash(&mut hasher); for s in &samples { s.content_hash.hash(&mut hasher); s.origin.hash(&mut hasher); @@ -653,8 +661,7 @@ impl Engine { stats.cache_hits += 1; return hit; } - let center = &samples[center_idx]; - let out = self.motion_blur.accumulate_samples( + let mut out = self.motion_blur.accumulate_samples( &self.device, &self.queue, enc, @@ -663,6 +670,9 @@ impl Engine { center.format, mb_key, ); + if center.aux.is_some() && (center.origin != out.origin || center.size != out.size) { + self.reorigin_aux(enc, center, &mut out); + } self.cache.insert(mb_key, out.clone(), id, frame_i); out } diff --git a/crates/engine/src/eval/nv12.rs b/crates/engine/src/eval/nv12.rs index 37c3e5dbdf14e5d62ba5cb8ed635ace80a05df72..e8f08b3b1157547901803ee2fbb2182e6f5d1c1b 100644 --- a/crates/engine/src/eval/nv12.rs +++ b/crates/engine/src/eval/nv12.rs @@ -9,7 +9,7 @@ use std::collections::HashMap; use std::num::NonZeroU64; const NV12_WGSL: &str = include_str!("../shaders/nv12_to_rgba.wgsl"); -const NV12_UNIFORM_SLOTS: u32 = 512; +const NV12_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; #[cfg(not(target_arch = "wasm32"))] const MAX_POOLED_PLANE_SIZES: usize = 8; @@ -37,6 +37,8 @@ struct Nv12PlanePair { uv_tex: wgpu::Texture, uv_view: wgpu::TextureView, #[cfg(not(target_arch = "wasm32"))] + bytes: u64, + #[cfg(not(target_arch = "wasm32"))] last_used: u64, } @@ -75,6 +77,10 @@ impl Nv12PlanePair { view_formats: &[], }); let uv_view = uv_tex.create_view(&wgpu::TextureViewDescriptor::default()); + #[cfg(not(target_arch = "wasm32"))] + let bytes = u64::from(raw_w) + .saturating_mul(u64::from(raw_h)) + .saturating_add(u64::from(uv_w).saturating_mul(u64::from(uv_h)).saturating_mul(2)); Self { y_tex, @@ -82,14 +88,16 @@ impl Nv12PlanePair { uv_tex, uv_view, #[cfg(not(target_arch = "wasm32"))] + bytes, + #[cfg(not(target_arch = "wasm32"))] last_used: 0, } } } -pub(super) struct Nv12Pipelines { +pub(crate) struct Nv12Pipelines { sampler: wgpu::Sampler, - uniform_buf: wgpu::Buffer, + uniform_chunks: Vec, uniform_stride: u32, uniform_cursor: u32, pipelines: HashMap, @@ -115,16 +123,10 @@ impl Nv12Pipelines { let align = device.limits().min_uniform_buffer_offset_alignment.max(32); let raw_size = std::mem::size_of::() as u32; let uniform_stride = raw_size.div_ceil(align) * align; - let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("nv12-uniform-ring"), - size: u64::from(uniform_stride) * u64::from(NV12_UNIFORM_SLOTS), - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); Self { sampler, - uniform_buf, + uniform_chunks: Vec::new(), uniform_stride, uniform_cursor: 0, pipelines: HashMap::new(), @@ -135,6 +137,63 @@ impl Nv12Pipelines { } } + pub(crate) fn reset_uniform_cursor(&mut self) { + self.uniform_cursor = 0; + } + + pub(crate) fn trim_uniform_chunks(&mut self, max_chunks: usize) { + self.uniform_cursor = 0; + if self.uniform_chunks.len() > max_chunks { + self.uniform_chunks.truncate(max_chunks); + } + } + + pub(crate) fn vram_bytes(&self) -> u64 { + let uniform_bytes: u64 = self.uniform_chunks.iter().map(wgpu::Buffer::size).sum(); + #[cfg(not(target_arch = "wasm32"))] + let plane_bytes: u64 = self.plane_pool.values().map(|p| p.bytes).sum(); + #[cfg(target_arch = "wasm32")] + let plane_bytes: u64 = 0; + uniform_bytes.saturating_add(plane_bytes) + } + + pub(crate) fn clear_plane_pool(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + { + self.plane_pool.clear(); + self.tick = 0; + } + } + + fn alloc_uniform_slot( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + params: &Nv12UniformParams, + ) -> (usize, u32) { + let slot_global = self.uniform_cursor; + let chunk_idx = (slot_global / NV12_UNIFORM_SLOTS_PER_CHUNK) as usize; + let slot_in_chunk = slot_global % NV12_UNIFORM_SLOTS_PER_CHUNK; + while chunk_idx >= self.uniform_chunks.len() { + let size = u64::from(NV12_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("nv12-uniform-ring"), + size, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + self.uniform_chunks.push(buf); + } + let dyn_offset = slot_in_chunk * self.uniform_stride; + queue.write_buffer( + &self.uniform_chunks[chunk_idx], + u64::from(dyn_offset), + bytemuck::bytes_of(params), + ); + self.uniform_cursor = slot_global + 1; + (chunk_idx, dyn_offset) + } + fn ensure_pipeline(&mut self, device: &wgpu::Device, dst_format: wgpu::TextureFormat) { if self.pipelines.contains_key(&dst_format) { return; @@ -271,9 +330,6 @@ impl Nv12Pipelines { dst: &CachedTexture, ) { self.ensure_pipeline(device, dst.format); - let slot = self.uniform_cursor; - self.uniform_cursor = (self.uniform_cursor + 1) % NV12_UNIFORM_SLOTS; - let dyn_offset = slot * self.uniform_stride; let params = Nv12UniformParams { raw_w: nv12.raw_size[0], @@ -285,11 +341,7 @@ impl Nv12Pipelines { full_range: u32::from(nv12.is_full_range), _pad: 0, }; - queue.write_buffer( - &self.uniform_buf, - u64::from(dyn_offset), - bytemuck::bytes_of(¶ms), - ); + let (chunk_idx, dyn_offset) = self.alloc_uniform_slot(device, queue, ¶ms); let fp = &self.pipelines[&dst.format]; let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { @@ -315,7 +367,7 @@ impl Nv12Pipelines { wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer: &self.uniform_buf, + buffer: &self.uniform_chunks[chunk_idx], offset: 0, size: NonZeroU64::new(std::mem::size_of::() as u64), }), @@ -333,12 +385,6 @@ impl Nv12Pipelines { } } -#[cfg(target_arch = "wasm32")] -thread_local! { - static WASM_NV12_PIPELINES: std::cell::RefCell> = - const { std::cell::RefCell::new(None) }; -} - #[cfg(not(target_arch = "wasm32"))] fn stage_plane_into_buffer( media: &crate::media::MediaCache, @@ -483,87 +529,42 @@ pub(super) fn upload_and_convert_nv12( _ => {} } - // Fallback when staging pool is temporarily exhausted: use fresh textures with + // Fallback when staging pool is temporarily exhausted (or on wasm32): use fresh textures with // `queue.write_texture` so multiple dispatches in one encoder cannot overwrite each other. - let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h); - engine.queue.write_texture( - fresh.y_tex.as_image_copy(), - &nv12.y, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(raw_w), - rows_per_image: Some(raw_h), - }, - wgpu::Extent3d { - width: raw_w, - height: raw_h, - depth_or_array_layers: 1, - }, - ); - engine.queue.write_texture( - fresh.uv_tex.as_image_copy(), - &nv12.uv, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(uv_w * 2), - rows_per_image: Some(uv_h), - }, - wgpu::Extent3d { - width: uv_w, - height: uv_h, - depth_or_array_layers: 1, - }, - ); - engine.media.with_nv12_gpu_state( - || Nv12Pipelines::new(&engine.device), - |pipe| { - pipe.encode_dispatch( - &engine.device, - &engine.queue, - enc, - &fresh.y_view, - &fresh.uv_view, - nv12, - dst, - ); - }, - ); } - #[cfg(target_arch = "wasm32")] - { - let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h); - engine.queue.write_texture( - fresh.y_tex.as_image_copy(), - &nv12.y, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(raw_w), - rows_per_image: Some(raw_h), - }, - wgpu::Extent3d { - width: raw_w, - height: raw_h, - depth_or_array_layers: 1, - }, - ); - engine.queue.write_texture( - fresh.uv_tex.as_image_copy(), - &nv12.uv, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(uv_w * 2), - rows_per_image: Some(uv_h), - }, - wgpu::Extent3d { - width: uv_w, - height: uv_h, - depth_or_array_layers: 1, - }, - ); - WASM_NV12_PIPELINES.with(|cell| { - let mut slot = cell.borrow_mut(); - let pipe = slot.get_or_insert_with(|| Nv12Pipelines::new(&engine.device)); + let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h); + engine.queue.write_texture( + fresh.y_tex.as_image_copy(), + &nv12.y, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(raw_w), + rows_per_image: Some(raw_h), + }, + wgpu::Extent3d { + width: raw_w, + height: raw_h, + depth_or_array_layers: 1, + }, + ); + engine.queue.write_texture( + fresh.uv_tex.as_image_copy(), + &nv12.uv, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(uv_w * 2), + rows_per_image: Some(uv_h), + }, + wgpu::Extent3d { + width: uv_w, + height: uv_h, + depth_or_array_layers: 1, + }, + ); + engine.media.with_nv12_gpu_state( + || Nv12Pipelines::new(&engine.device), + |pipe| { pipe.encode_dispatch( &engine.device, &engine.queue, @@ -573,8 +574,8 @@ pub(super) fn upload_and_convert_nv12( nv12, dst, ); - }); - } + }, + ); } #[cfg(all(test, not(target_arch = "wasm32")))] @@ -823,6 +824,91 @@ mod tests { assert!(b_px[2] > 220 && b_px[0] < 20 && b_px[1] < 20, "second dispatch corrupted: {:?}", &b_px[..4]); } + #[test] + fn nv12_uniform_chunk_ring_grows_past_512_resets_trims_and_tracks_vram() { + let mut engine = Engine::new_headless().expect("headless engine"); + let red_0 = Nv12Frame { + raw_size: [8, 8], + display_size: [8, 8], + rot_deg: 0, + matrix: YuvMatrix::Bt709, + is_full_range: false, + y: vec![63u8; 8 * 8], + uv: [102u8, 240u8].repeat(4 * 4), + }; + let blue_180 = Nv12Frame { + raw_size: [8, 8], + display_size: [8, 8], + rot_deg: 180, + matrix: YuvMatrix::Bt709, + is_full_range: false, + y: vec![32u8; 8 * 8], + uv: [240u8, 118u8].repeat(4 * 4), + }; + + let mut enc = engine + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("nv12-ring-growth-test"), + }); + let dst_first = engine.alloc_tex([8, 8], BitDepth::Int8, 0); + let dst_mid = engine.alloc_tex([8, 8], BitDepth::Int8, 0); + let dst_last = engine.alloc_tex([8, 8], BitDepth::Int8, 0); + + // Dispatch >512 times in a single CommandEncoder so the uniform ring must grow to a 2nd chunk + // without wrapping and clobbering slot 0! + upload_and_convert_nv12(&engine, &mut enc, &red_0, &dst_first); + for _ in 1..NV12_UNIFORM_SLOTS_PER_CHUNK { + upload_and_convert_nv12(&engine, &mut enc, &blue_180, &dst_mid); + } + // Slot 512 (index 0 of chunk 1) + slot 513 (index 1 of chunk 1) + upload_and_convert_nv12(&engine, &mut enc, &blue_180, &dst_mid); + upload_and_convert_nv12(&engine, &mut enc, &blue_180, &dst_last); + + let (chunks_before_trim, cursor_before_reset, vram_before_bust) = + engine.media.with_nv12_gpu_state( + || unreachable!("already initialized"), + |pipe| (pipe.uniform_chunks.len(), pipe.uniform_cursor, pipe.vram_bytes()), + ); + assert_eq!(chunks_before_trim, 2, "expected 2 uniform chunks for 514 dispatches"); + assert_eq!(cursor_before_reset, NV12_UNIFORM_SLOTS_PER_CHUNK + 2); + assert!(vram_before_bust > 0); + assert!(engine.vram_bytes() >= vram_before_bust); + + engine.queue.submit(Some(enc.finish())); + engine.reset_uniform_cursors(); + engine.media.flush_upload_staging_after_submit(&engine.device); + + // Verify slot 0 (red) was NOT clobbered by slot 512 (blue) and slot 513 (blue) is intact! + let first_px = engine.readback_rgba(&dst_first).expect("readback first"); + let last_px = engine.readback_rgba(&dst_last).expect("readback last"); + assert!(first_px[0] > 220 && first_px[2] < 20, "slot 0 clobbered: {:?}", &first_px[..4]); + assert!(last_px[2] > 220 && last_px[0] < 20, "slot 513 corrupted: {:?}", &last_px[..4]); + + let cursor_after_reset = engine.media.with_nv12_gpu_state( + || unreachable!("already initialized"), + |pipe| pipe.uniform_cursor, + ); + assert_eq!(cursor_after_reset, 0); + + // Trim chunks to 1 and verify VRAM drops cleanly; then bust_gpu_cache clears plane pool. + engine.media.trim_nv12_uniform_chunks(1); + let chunks_after_trim = engine.media.with_nv12_gpu_state( + || unreachable!("already initialized"), + |pipe| pipe.uniform_chunks.len(), + ); + assert_eq!(chunks_after_trim, 1); + + let vram_before_clear = engine.media.nv12_vram_bytes(); + engine.bust_gpu_cache(); + let (planes_after_bust, vram_after_bust) = engine.media.with_nv12_gpu_state( + || unreachable!("already initialized"), + |pipe| (pipe.plane_pool.len(), pipe.vram_bytes()), + ); + assert_eq!(planes_after_bust, 0); + assert!(vram_after_bust < vram_before_clear); + } + #[cfg(target_os = "macos")] #[test] fn nv12_synthetic_mp4_decode_and_eval_loader() { diff --git a/crates/engine/src/eval/output_cache.rs b/crates/engine/src/eval/output_cache.rs index dd7a55dfdc2e22f1aac2e6617bcbf23a600efce9..a32fd9a1b9587b57141904abdc34591f68969771 100644 --- a/crates/engine/src/eval/output_cache.rs +++ b/crates/engine/src/eval/output_cache.rs @@ -155,6 +155,7 @@ impl Engine { .saturating_add(self.scene3d.mesh_vram_bytes()) .saturating_add(self.scene3d.uniform_vram_bytes()) .saturating_add(self.optflow.get().map_or(0, |of| of.vram_bytes())) + .saturating_add(self.media.nv12_vram_bytes()) } pub fn vram_mb(&self) -> f64 { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index cdffd9ea59f364da08b348c35d3a6a1e61080e40..b4b9f597f815e09907e7ae6a2a3bd4e3c63b9a09 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -227,21 +227,23 @@ pub(super) fn ensure_parent_dir( fn saver_targets_exr(comp: &Comp, saver: &SaverSpec, out_dir_override: Option<&Path>) -> bool { let node = comp.node(saver.node_id); - if node + if let Some(fmt) = node .static_str("OutputFormat") - .is_some_and(|s| s.eq_ignore_ascii_case("OpenEXRFormat")) + .map(str::trim) + .filter(|s| !s.is_empty()) { - return true; + return fmt.eq_ignore_ascii_case("OpenEXRFormat"); } - if node + if let Some(fmt) = node .raw .get_table("Inputs") .and_then(|i| i.get_table("Clip")) .and_then(|c| c.get_table("Value")) .and_then(|v| v.get_str("FormatID")) - .is_some_and(|s| s.eq_ignore_ascii_case("OpenEXRFormat")) + .map(str::trim) + .filter(|s| !s.is_empty()) { - return true; + return fmt.eq_ignore_ascii_case("OpenEXRFormat"); } resolve_output_path_with_ext(saver, saver.range[0], out_dir_override, "png").is_ok_and(|p| { p.extension() diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index e2dd7e89308009c01656c49c62f6862f3b8f5dca..bdc29c6ce25076dae7b5f2f6e1b1f24fe92892f0 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -1790,3 +1790,51 @@ fn exports_exr_saver_sequence_and_stops_cleanly_on_cancel() { let _ = std::fs::remove_dir_all(&tmp_dir); } + +#[test] +fn saver_output_format_takes_precedence_over_exr_extension() { + let check = |output_format: Option<&str>, format_id: Option<&str>, filename: &str| -> bool { + let of_line = output_format + .map(|f| format!(r#"OutputFormat = Input {{ Value = FuID {{ "{f}" }}, }},"#)) + .unwrap_or_default(); + let fid_line = format_id + .map(|f| format!(r#"FormatID = "{f}","#)) + .unwrap_or_default(); + let src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 0 }}, + GlobalRange = {{ 0, 0 }}, + Tools = ordered() {{ + Saver1 = Saver {{ + Inputs = {{ + {of_line} + Clip = Input {{ + Value = Clip {{ + Filename = "{filename}", + {fid_line} + Saving = true, + }}, + }}, + }}, + }}, + }}, + }}"# + ); + let comp = Comp::from_fusion_str(&src).expect("parse saver comp"); + let saver = select_saver(&comp, None).expect("select saver"); + saver_targets_exr(&comp, &saver, None) + }; + + // Explicit non-EXR OutputFormat overrides .exr filename and even Clip.Value.FormatID. + assert!(!check(Some("PNGFormat"), None, "/tmp/out_0000.exr")); + assert!(!check(Some("PNGFormat"), Some("OpenEXRFormat"), "/tmp/out_0000.exr")); + // Explicit OpenEXRFormat overrides .png filename. + assert!(check(Some("OpenEXRFormat"), None, "/tmp/out_0000.png")); + // Unset OutputFormat with explicit non-EXR FormatID overrides .exr extension. + assert!(!check(None, Some("PNGFormat"), "/tmp/out_0000.exr")); + // Empty OutputFormat and empty/unset FormatID fall back to .exr extension. + assert!(check(None, None, "/tmp/out_0000.exr")); + assert!(check(Some(""), Some(""), "/tmp/out_0000.exr")); + assert!(!check(None, None, "/tmp/out_0000.png")); +} diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 0f422d3506252bb9d83b1043715a9e88daf736ef..37b5a9f4ef967b722e587fb85e20ca0fa26bb2dd 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -683,8 +683,7 @@ pub struct MediaCache { shared: Arc, #[cfg(not(target_arch = "wasm32"))] staging_pool: Mutex, - #[cfg(not(target_arch = "wasm32"))] - nv12_gpu_state: Mutex>>, + nv12_gpu_state: Mutex>, } impl Default for MediaCache { @@ -699,7 +698,6 @@ impl MediaCache { shared: Arc::new(MediaShared::new(budget_mb.saturating_mul(1024 * 1024))), #[cfg(not(target_arch = "wasm32"))] staging_pool: Mutex::new(UploadStagingPool::new(320 * 1024 * 1024)), - #[cfg(not(target_arch = "wasm32"))] nv12_gpu_state: Mutex::new(None), } } @@ -749,26 +747,54 @@ impl MediaCache { if let Ok(mut pool) = self.staging_pool.lock() { pool.clear(); } - #[cfg(not(target_arch = "wasm32"))] if let Ok(mut slot) = self.nv12_gpu_state.lock() { *slot = None; } } - #[cfg(not(target_arch = "wasm32"))] - pub(crate) fn with_nv12_gpu_state( + pub(crate) fn with_nv12_gpu_state( &self, - init: impl FnOnce() -> T, - f: impl FnOnce(&mut T) -> R, + init: impl FnOnce() -> crate::eval::Nv12Pipelines, + f: impl FnOnce(&mut crate::eval::Nv12Pipelines) -> R, ) -> R { let mut slot = self.nv12_gpu_state.lock().unwrap_or_else(|e| e.into_inner()); - let any = slot.get_or_insert_with(|| Box::new(init())); - let state = any - .downcast_mut::() - .expect("nv12_gpu_state type mismatch"); + let state = slot.get_or_insert_with(init); f(state) } + pub(crate) fn reset_nv12_uniform_cursor(&self) { + if let Ok(mut slot) = self.nv12_gpu_state.lock() { + if let Some(pipe) = slot.as_mut() { + pipe.reset_uniform_cursor(); + } + } + } + + pub(crate) fn trim_nv12_uniform_chunks(&self, max_chunks: usize) { + if let Ok(mut slot) = self.nv12_gpu_state.lock() { + if let Some(pipe) = slot.as_mut() { + pipe.trim_uniform_chunks(max_chunks); + } + } + } + + pub(crate) fn nv12_vram_bytes(&self) -> u64 { + self.nv12_gpu_state + .lock() + .ok() + .and_then(|slot| slot.as_ref().map(|pipe| pipe.vram_bytes())) + .unwrap_or(0) + } + + pub(crate) fn clear_nv12_gpu_state(&self) { + if let Ok(mut slot) = self.nv12_gpu_state.lock() { + if let Some(pipe) = slot.as_mut() { + pipe.clear_plane_pool(); + pipe.trim_uniform_chunks(2); + } + } + } + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn acquire_upload_staging(&self, device: &wgpu::Device, needed: u64) -> Option { self.staging_pool diff --git a/crates/engine/src/motion_blur.rs b/crates/engine/src/motion_blur.rs index 5ed6b78f8da488a0272e4f50b6637d21e1bce0da..e82f5daf360c498f58dd902b4b3c3fb9d4ede70c 100644 --- a/crates/engine/src/motion_blur.rs +++ b/crates/engine/src/motion_blur.rs @@ -596,8 +596,12 @@ impl MotionBlurPipelines { ); out.tex_scale = center.tex_scale; out.edge_mode = center.edge_mode; - if let Some(aux) = ¢er.aux { - out.set_aux(Some(aux.clone())); + // Only attach `center.aux` verbatim when the union DoD matches the center sample's DoD; + // otherwise the caller pads/re-origins `center.aux` to `(union_origin, [uw, uh])`. + if center.origin == union_origin && center.size == [uw, uh] { + if let Some(aux) = ¢er.aux { + out.set_aux(Some(aux.clone())); + } } let final_accum_view = if samples.len() % 2 == 1 { @@ -1067,7 +1071,9 @@ mod tests { assert_eq!(tex.canvas_size, [64, 64]); assert_eq!(tex.format, fmt); assert_eq!(tex.depth, depth); - assert!(tex.aux.as_ref().is_some_and(|a| a.z.is_some())); + // Center sample had DoD [0,0] 64x64 != union [-4,-2] 72x68, so `accumulate_samples` + // must NOT attach misaligned aux verbatim (caller pads/re-origins via aux_pipelines). + assert!(tex.aux.is_none()); } // Readback Rgba32Float at row y=32 (local row 32 - (-2) = 34) and verify Snow Globe diff --git a/crates/engine/src/shaders/aux_ops.wgsl b/crates/engine/src/shaders/aux_ops.wgsl index 5ba638e0f3925466402ac1bae029b3fe07295219..a2fef817448c86aa4e6bd2c8c9389fa669ce2fdc 100644 --- a/crates/engine/src/shaders/aux_ops.wgsl +++ b/crates/engine/src/shaders/aux_ops.wgsl @@ -153,11 +153,17 @@ fn aux_cb_apply_op(op: i32, bg_v: f32, fg_v: f32) -> f32 { } } +fn sanitize_finite(x: f32) -> f32 { + return select(0.0, x, x >= -1e38 && x <= 1e38); +} + fn aux_remap(x: f32, fmin: f32, fmax: f32, tmin: f32, tmax: f32, inv: bool) -> f32 { + let sx = sanitize_finite(x); let denom = fmax - fmin; - let t = select(0.0, (x - fmin) / denom, abs(denom) > 1e-12); + let t = select(0.0, (sx - fmin) / denom, abs(denom) > 1e-12); let mapped = t * (tmax - tmin) + tmin; - return select(mapped, tmax + tmin - mapped, inv); + let res = select(mapped, tmax + tmin - mapped, inv); + return sanitize_finite(res); } // @SECTION:DEPTH_MERGE @@ -192,7 +198,7 @@ fn dm_read_mask_uv(uv: vec2, has_mask: f32, invert: f32) -> f32 { return select(m, 1.0 - m, invert > 0.5); } -fn dm_merge_fg_over_bg( +fn dm_composite( bg: vec4, fg: vec4, mode: i32, @@ -200,53 +206,50 @@ fn dm_merge_fg_over_bg( gain: f32, burn_in: f32, sub_add: f32, - eff_blend: f32, ) -> vec4 { if (mode == 0) { let fg_rgb = fg.rgb * mix(fg.a, 1.0, sub_add); let fg_a_eff = fg.a * gain; let fg_occ = fg_a_eff * (1.0 - burn_in); - var comp: vec4; if (op == 1) { let bg_occ = bg.a; - comp = vec4(bg.rgb + fg_rgb * (1.0 - bg_occ), bg.a + fg_a_eff * (1.0 - bg_occ)); + return vec4(bg.rgb + fg_rgb * (1.0 - bg_occ), bg.a + fg_a_eff * (1.0 - bg_occ)); } else if (op == 2) { - comp = vec4(fg_rgb, fg_a_eff) * bg.a; + return vec4(fg_rgb, fg_a_eff) * bg.a; } else if (op == 3) { - comp = vec4(fg_rgb, fg_a_eff) * (1.0 - bg.a); + return vec4(fg_rgb, fg_a_eff) * (1.0 - bg.a); } else if (op == 4) { - comp = vec4(fg_rgb * bg.a + bg.rgb * (1.0 - fg_occ), bg.a); + return vec4(fg_rgb * bg.a + bg.rgb * (1.0 - fg_occ), bg.a); } else if (op == 5) { - comp = vec4(fg_rgb, fg_a_eff) * (1.0 - bg.a) + bg * (1.0 - fg_occ); + return vec4(fg_rgb, fg_a_eff) * (1.0 - bg.a) + bg * (1.0 - fg_occ); } else { let over_rgb = fg_rgb + bg.rgb * (1.0 - fg_occ); let over_a = fg_a_eff + bg.a * (1.0 - fg_a_eff); - comp = vec4(over_rgb, over_a); + return vec4(over_rgb, over_a); } - return mix(bg, comp, eff_blend); } else if (mode == 5) { let fg_ap = fg.a * gain; let comp_rgb = abs(bg.rgb - fg.rgb * gain); let comp_a = bg.a + fg_ap * (1.0 - bg.a); - return mix(bg, vec4(comp_rgb, comp_a), eff_blend); + return vec4(comp_rgb, comp_a); } else if (mode == 11) { let fg_p = fg.rgb * gain; let fg_ap = fg.a * gain; let comp_rgb = clamp(bg.rgb / max(1.0 - fg_p, vec3(1e-5)), vec3(0.0), vec3(1.0)); let comp_a = bg.a + fg_ap * (1.0 - bg.a); - return mix(bg, vec4(comp_rgb, comp_a), eff_blend); + return vec4(comp_rgb, comp_a); } else if (mode == 18) { let fg_p = fg.rgb * gain; let fg_ap = fg.a * gain; let comp_rgb = clamp(1.0 - (1.0 - bg.rgb) / max(1.0 - fg_ap + fg_p, vec3(1e-5)), vec3(0.0), vec3(1.0)); let comp_a = bg.a + fg_ap * (1.0 - bg.a); - return mix(bg, vec4(comp_rgb, comp_a), eff_blend); + return vec4(comp_rgb, comp_a); } else if (mode == 14) { let fg_p = fg.rgb * gain; let fg_ap = fg.a * gain; let comp_rgb = sqrt(max(bg.rgb * bg.rgb + fg_p * fg_p, vec3(0.0))); let comp_a = sqrt(max(bg.a * bg.a + fg_ap * fg_ap, 0.0)); - return mix(bg, vec4(comp_rgb, comp_a), eff_blend); + return vec4(comp_rgb, comp_a); } else if (mode == 20) { let fg_p = fg.rgb * gain; let fg_ap = fg.a * gain; @@ -255,7 +258,7 @@ fn dm_merge_fg_over_bg( let comp_rgb = select(vec3(0.0), (2.0 * bg.rgb * fg_p) / safe_d, denom > vec3(1e-5)); let denom_a = bg.a + fg_ap; let comp_a = select(0.0, (2.0 * bg.a * fg_ap) / max(denom_a, 1e-5), denom_a > 1e-5); - return mix(bg, vec4(comp_rgb, comp_a), eff_blend); + return vec4(comp_rgb, comp_a); } else if (mode == 15 || mode == 16) { let fg_a_eff = fg.a * gain; let over_rgb = fg.rgb + bg.rgb * (1.0 - fg_a_eff); @@ -267,7 +270,7 @@ fn dm_merge_fg_over_bg( ); let comp_rgb = select(bg_branch, over_rgb, pick_over); let comp_a = bg.a + fg_a_eff * (1.0 - bg.a); - return mix(bg, vec4(comp_rgb, comp_a), eff_blend); + return vec4(comp_rgb, comp_a); } else if (mode == 19) { let bg_u = select(vec3(0.0), bg.rgb / max(bg.a, 1e-5), bg.a > 1e-5); let fg_u = select(vec3(0.0), fg.rgb / max(fg.a, 1e-5), fg.a > 1e-5); @@ -275,14 +278,14 @@ fn dm_merge_fg_over_bg( let fg_eff = fg.a * gain; let comp_rgb = fg_eff * bg.a * blended + fg_eff * (1.0 - bg.a) * fg_u + (1.0 - fg_eff) * bg.rgb; let comp_a = bg.a + fg_eff * (1.0 - bg.a); - return mix(bg, vec4(comp_rgb, comp_a), eff_blend); + return vec4(comp_rgb, comp_a); } else { let fg_u = select(vec3(0.0), fg.rgb / max(fg.a, 1e-5), fg.a > 1e-5); let blended = aux_apply_blend_mode(bg.rgb, fg_u, mode); let fg_eff = fg.a * gain; let comp_rgb = fg_eff * blended + (1.0 - fg_eff) * bg.rgb; let comp_a = bg.a + fg_eff * (1.0 - bg.a); - return mix(bg, vec4(comp_rgb, comp_a), eff_blend); + return vec4(comp_rgb, comp_a); } } @@ -414,23 +417,26 @@ fn depth_merge_op(@builtin(global_invocation_id) gid: vec3) { var out_z: f32; if (perform_depth) { if (fg_z >= bg_z) { - out_col = dm_merge_fg_over_bg(bg, fg, mode, op, gain, burn_in, sub_add, eff_blend); - let fg_has_cov = fg_z > EMPTY_Z_THRESH && eff_blend > 0.0; + let comp = dm_composite(bg, fg, mode, op, gain, burn_in, sub_add); + out_col = mix(bg, comp, eff_blend); + let fg_has_cov = fg.a > 0.0 && fg_z > EMPTY_Z_THRESH && eff_blend > 0.0; out_z = select(bg_z, fg_z, fg_has_cov); } else { - // BG is closer than FG: composite BG over FG! - let fg_rgb = fg.rgb * mix(fg.a, 1.0, sub_add); - let fg_a_eff = fg.a * gain; - let bg_over_fg = vec4( - bg.rgb + fg_rgb * (1.0 - bg.a), - bg.a + fg_a_eff * (1.0 - bg.a), - ); - out_col = mix(bg, bg_over_fg, eff_blend); + // BG is closer than FG: swap front/back roles so Operator and ApplyMode apply consistently. + let fg_pre = vec4(fg.rgb * mix(fg.a, 1.0, sub_add), fg.a * gain); + var comp: vec4; + if (mode != 0 && fg_pre.a <= 0.0 && all(fg_pre.rgb == vec3(0.0))) { + comp = bg; + } else { + comp = dm_composite(fg_pre, bg, mode, op, 1.0, burn_in, 1.0); + } + out_col = mix(bg, comp, eff_blend); out_z = bg_z; } } else { - out_col = dm_merge_fg_over_bg(bg, fg, mode, op, gain, burn_in, sub_add, eff_blend); - out_z = select(bg_z, fg_z, fg.a > 0.0 && eff_blend > 0.0); + let comp = dm_composite(bg, fg, mode, op, gain, burn_in, sub_add); + out_col = mix(bg, comp, eff_blend); + out_z = select(bg_z, fg_z, fg.a > 0.0 && fg_z > EMPTY_Z_THRESH && eff_blend > 0.0); } if (mbm) { @@ -497,6 +503,8 @@ fn copy_aux_to_color_op(@builtin(global_invocation_id) gid: vec3) { var v = aux_v.r; if (remap_en) { v = aux_remap(v, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, inv_x); + } else { + v = sanitize_finite(v); } res = vec4(v, v, v, 1.0); } else if (kind == 1) { @@ -507,6 +515,10 @@ fn copy_aux_to_color_op(@builtin(global_invocation_id) gid: vec3) { nx = aux_remap(nx, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, inv_x); ny = aux_remap(ny, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, inv_x); nz = aux_remap(nz, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, inv_x); + } else { + nx = sanitize_finite(nx); + ny = sanitize_finite(ny); + nz = sanitize_finite(nz); } res = vec4(nx, ny, nz, 1.0); } else { @@ -515,6 +527,9 @@ fn copy_aux_to_color_op(@builtin(global_invocation_id) gid: vec3) { if (remap_en) { vx = aux_remap(vx, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, inv_x); vy = aux_remap(vy, u.p[2].x, u.p[2].y, u.p[2].z, u.p[2].w, inv_y); + } else { + vx = sanitize_finite(vx); + vy = sanitize_finite(vy); } res = vec4(vx, vy, 0.0, 1.0); }