| 1 | //! Headless `wgpu` 2D compositor evaluator with Merkle content-hash caching, |
| 2 | //! branch pruning, and surgical cache-busting. |
| 3 | |
| 4 | use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; |
| 5 | use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; |
| 6 | use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port}; |
| 7 | use std::cell::{Cell, OnceCell, RefCell}; |
| 8 | use std::collections::{HashMap, HashSet}; |
| 9 | use std::collections::hash_map::DefaultHasher; |
| 10 | use std::hash::{Hash, Hasher}; |
| 11 | #[cfg(not(target_arch = "wasm32"))] |
| 12 | use std::time::Instant; |
| 13 | #[cfg(target_arch = "wasm32")] |
| 14 | use web_time::Instant; |
| 15 | |
| 16 | mod io; |
| 17 | mod alpha_keyers; |
| 18 | mod aux_ops; |
| 19 | mod color_science; |
| 20 | mod color_lut; |
| 21 | mod depth_optical; |
| 22 | mod composite; |
| 23 | mod transform; |
| 24 | mod color; |
| 25 | mod blur_glow; |
| 26 | mod fuses; |
| 27 | mod keyers; |
| 28 | mod masks; |
| 29 | mod paint; |
| 30 | mod shapes; |
| 31 | mod warps; |
| 32 | mod warps_masks; |
| 33 | mod fx_fuses; |
| 34 | mod archive_fx2; |
| 35 | mod surface_fx; |
| 36 | mod text_3d; |
| 37 | mod registry; |
| 38 | mod dispatch; |
| 39 | mod output_cache; |
| 40 | |
| 41 | use dispatch::UniformParams; |
| 42 | pub use dispatch::{PendingReadback, create_texture, create_texture_dod, create_texture_dod_fmt}; |
| 43 | pub use color_lut::lut_io::export_cube_from_rgba; |
| 44 | pub(crate) use io::Nv12Pipelines; |
| 45 | use output_cache::OutputCache; |
| 46 | use registry::{ShaderOp, ShaderRegistry}; |
| 47 | |
| 48 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 49 | pub struct DisplaySettings { |
| 50 | pub exposure: f32, // stops (0.0 = 1x) |
| 51 | pub gamma: f32, // default 1.0 |
| 52 | pub channel: u32, // 0=RGBA, 1=R, 2=G, 3=B, 4=A |
| 53 | pub checker_bg: bool, |
| 54 | /// False (default) = exact nearest-neighbor pixels ("raw truth" when zooming in); |
| 55 | /// True = bilinear "Smooth Resize". |
| 56 | pub smooth_resize: bool, |
| 57 | /// Visible normalized UV rectangle `[u0, v0, u1, v1]` sampled into the viewer output texture. |
| 58 | pub uv_rect: [f32; 4], |
| 59 | } |
| 60 | |
| 61 | impl Default for DisplaySettings { |
| 62 | fn default() -> Self { |
| 63 | Self { |
| 64 | exposure: 0.0, |
| 65 | gamma: 1.0, |
| 66 | channel: 0, |
| 67 | checker_bg: true, |
| 68 | smooth_resize: false, |
| 69 | uv_rect: [0.0, 0.0, 1.0, 1.0], |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | pub struct Engine { |
| 75 | pub(crate) device: wgpu::Device, |
| 76 | pub(crate) queue: wgpu::Queue, |
| 77 | pipelines: RefCell<ShaderRegistry>, |
| 78 | pipelines_int16: OnceCell<RefCell<ShaderRegistry>>, |
| 79 | pipelines_f16: OnceCell<RefCell<ShaderRegistry>>, |
| 80 | pipelines_f32: OnceCell<RefCell<ShaderRegistry>>, |
| 81 | aux_pipelines: OnceCell<RefCell<aux_ops::AuxPipelines>>, |
| 82 | alpha_keyer_pipelines: OnceCell<RefCell<alpha_keyers::AlphaKeyerPipelines>>, |
| 83 | color_science_pipelines: OnceCell<RefCell<color_science::ColorSciencePipelines>>, |
| 84 | color_lut_pipelines: OnceCell<RefCell<color_lut::ColorLutPipelines>>, |
| 85 | depth_optical_pipelines: OnceCell<RefCell<depth_optical::DepthOpticalPipelines>>, |
| 86 | warps_masks_pipelines: OnceCell<RefCell<warps_masks::WarpsMasksPipelines>>, |
| 87 | fx_fuses_pipelines: OnceCell<RefCell<fx_fuses::FxFusesPipelines>>, |
| 88 | archive_fx2_pipelines: OnceCell<RefCell<archive_fx2::ArchiveFx2Pipelines>>, |
| 89 | pub(crate) surface_fx: OnceCell<RefCell<surface_fx::SurfaceFxPipelines>>, |
| 90 | auto_matte_pipelines: OnceCell<RefCell<crate::auto_matte::AutoMattePipelines>>, |
| 91 | pub auto_matte_cache: crate::auto_matte::AutoMatteCache, |
| 92 | motion_blur: crate::motion_blur::MotionBlurPipelines, |
| 93 | pub(crate) supports_f32_filter: bool, |
| 94 | scene3d: crate::scene3d::Scene3DRenderer, |
| 95 | optflow: std::sync::OnceLock<crate::optflow::OpticalFlowPipelines>, |
| 96 | tracker: std::sync::OnceLock<crate::tracker::TrackerPipelines>, |
| 97 | particles: crate::particles::ParticleCache, |
| 98 | custom_shaders: crate::custom_shader::CustomShaderCache, |
| 99 | pub fuse_registry: crate::fuse_runtime::FuseRegistry, |
| 100 | sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>, |
| 101 | ram_upload_tex: RefCell<Option<CachedTexture>>, |
| 102 | pub(crate) dummy: CachedTexture, |
| 103 | vram_budget_bytes: u64, |
| 104 | last_bg_vram_drops: Cell<u64>, |
| 105 | pub cache: NodeCache, |
| 106 | pub media: MediaCache, |
| 107 | pub expr: ExprEngine, |
| 108 | /// Active evaluation target node (set during `evaluate` / `render_into_viewer`). |
| 109 | pub(super) frame_eval_target: Option<NodeId>, |
| 110 | /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. |
| 111 | frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, |
| 112 | /// Lazily populated downstream adjacency list `(consumer_id, port_name)` for the current comp revision. |
| 113 | frame_consumers: Vec<Vec<(NodeId, String)>>, |
| 114 | /// Comp revision for which `frame_consumers` was built, so steady-state frames skip rebuilding it. |
| 115 | frame_consumers_rev: Option<u64>, |
| 116 | /// Per-evaluation memo of conservative downstream RoI bounds `(node_id, time_bits)`. |
| 117 | frame_roi_memo: HashMap<(NodeId, i64), Option<composite::RoiBox>>, |
| 118 | /// Reusable cycle-detection set for `eval_node` across frames. |
| 119 | frame_visiting: HashSet<(NodeId, i64)>, |
| 120 | /// Active per-`NodeId` cycle-detection set forbidding temporal-lookback re-entrancy across shifted times. |
| 121 | frame_visiting_nodes: HashSet<NodeId>, |
| 122 | output_cache: OutputCache, |
| 123 | /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default |
| 124 | /// to matching the dimensions & aspect ratio of the node they mask!). |
| 125 | mask_target_size: Option<[u32; 2]>, |
| 126 | /// Proxy downscale divisor: 1 = full res, 2 = half res, 4 = quarter res. |
| 127 | pub proxy_scale: u32, |
| 128 | /// When `true`, `Loader` nodes prefer `ProxyFilename` or `Clip.AlternateFilename` if present on disk. |
| 129 | pub use_proxy_clips: bool, |
| 130 | /// High-Quality mode (`true` = exact Fusion bar-for-bar passes & project/ChangeDepth bit depth; |
| 131 | /// `false` = perfmaxxed pyramid blur/glow & fast Rgba8Unorm working textures). |
| 132 | pub hiq: bool, |
| 133 | } |
| 134 | |
| 135 | fn is_video_filename(filename: &str) -> bool { |
| 136 | let Some(ext) = std::path::Path::new(filename) |
| 137 | .extension() |
| 138 | .and_then(|e| e.to_str()) |
| 139 | else { |
| 140 | return false; |
| 141 | }; |
| 142 | matches!( |
| 143 | ext.to_ascii_lowercase().as_str(), |
| 144 | "mov" | "mp4" | "m4v" | "mkv" | "avi" | "webm" | "mxf" |
| 145 | ) |
| 146 | } |
| 147 | |
| 148 | fn is_static_loader_node(node: &Node) -> bool { |
| 149 | let Some(clip) = node.clips.first() else { |
| 150 | return false; |
| 151 | }; |
| 152 | if clip.length.unwrap_or(1) > 1 { |
| 153 | return false; |
| 154 | } |
| 155 | if is_video_filename(&clip.filename) { |
| 156 | return false; |
| 157 | } |
| 158 | if clip |
| 159 | .alternate_filename |
| 160 | .as_deref() |
| 161 | .is_some_and(is_video_filename) |
| 162 | { |
| 163 | return false; |
| 164 | } |
| 165 | if node |
| 166 | .static_str("ProxyFilename") |
| 167 | .is_some_and(is_video_filename) |
| 168 | { |
| 169 | return false; |
| 170 | } |
| 171 | true |
| 172 | } |
| 173 | |
| 174 | impl Engine { |
| 175 | pub fn new(device: wgpu::Device, queue: wgpu::Queue) -> Self { |
| 176 | let supports_f32_filter = device.features().contains(wgpu::Features::FLOAT32_FILTERABLE); |
| 177 | let pipelines = RefCell::new(ShaderRegistry::new(&device, wgpu::TextureFormat::Rgba8Unorm, false)); |
| 178 | let scene3d = crate::scene3d::Scene3DRenderer::new(&device); |
| 179 | let dummy = create_texture(&device, [1, 1], 0); |
| 180 | queue.write_texture( |
| 181 | dummy.texture.as_image_copy(), |
| 182 | &[0, 0, 0, 0], |
| 183 | wgpu::TexelCopyBufferLayout { |
| 184 | offset: 0, |
| 185 | bytes_per_row: Some(4), |
| 186 | rows_per_image: Some(1), |
| 187 | }, |
| 188 | wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, |
| 189 | ); |
| 190 | let default_vram_mb = crate::cache::default_vram_budget_mb(); |
| 191 | Self { |
| 192 | device, |
| 193 | queue, |
| 194 | pipelines, |
| 195 | pipelines_int16: OnceCell::new(), |
| 196 | pipelines_f16: OnceCell::new(), |
| 197 | pipelines_f32: OnceCell::new(), |
| 198 | aux_pipelines: OnceCell::new(), |
| 199 | alpha_keyer_pipelines: OnceCell::new(), |
| 200 | color_science_pipelines: OnceCell::new(), |
| 201 | color_lut_pipelines: OnceCell::new(), |
| 202 | depth_optical_pipelines: OnceCell::new(), |
| 203 | warps_masks_pipelines: OnceCell::new(), |
| 204 | fx_fuses_pipelines: OnceCell::new(), |
| 205 | archive_fx2_pipelines: OnceCell::new(), |
| 206 | surface_fx: OnceCell::new(), |
| 207 | auto_matte_pipelines: OnceCell::new(), |
| 208 | auto_matte_cache: crate::auto_matte::AutoMatteCache::new(), |
| 209 | motion_blur: crate::motion_blur::MotionBlurPipelines::default(), |
| 210 | supports_f32_filter, |
| 211 | scene3d, |
| 212 | optflow: std::sync::OnceLock::new(), |
| 213 | tracker: std::sync::OnceLock::new(), |
| 214 | particles: crate::particles::ParticleCache::default(), |
| 215 | custom_shaders: crate::custom_shader::CustomShaderCache::new(), |
| 216 | fuse_registry: crate::fuse_runtime::FuseRegistry::new(), |
| 217 | sprite_cache: HashMap::new(), |
| 218 | ram_upload_tex: RefCell::new(None), |
| 219 | dummy, |
| 220 | vram_budget_bytes: default_vram_mb.saturating_mul(1024 * 1024), |
| 221 | last_bg_vram_drops: Cell::new(0), |
| 222 | cache: NodeCache::new(default_vram_mb), |
| 223 | media: MediaCache::default(), |
| 224 | expr: ExprEngine::new(), |
| 225 | frame_eval_target: None, |
| 226 | frame_memo: HashMap::new(), |
| 227 | frame_consumers: Vec::new(), |
| 228 | frame_consumers_rev: None, |
| 229 | frame_roi_memo: HashMap::new(), |
| 230 | frame_visiting: HashSet::new(), |
| 231 | frame_visiting_nodes: HashSet::new(), |
| 232 | output_cache: OutputCache::new(), |
| 233 | mask_target_size: None, |
| 234 | proxy_scale: 1, |
| 235 | use_proxy_clips: false, |
| 236 | hiq: true, |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | pub fn new_with_device( |
| 241 | device: std::sync::Arc<wgpu::Device>, |
| 242 | queue: std::sync::Arc<wgpu::Queue>, |
| 243 | vram_budget_bytes: u64, |
| 244 | media_budget_bytes: u64, |
| 245 | ) -> Self { |
| 246 | let mut eng = Self::new((*device).clone(), (*queue).clone()); |
| 247 | eng.vram_budget_bytes = vram_budget_bytes; |
| 248 | eng.cache.budget_bytes = vram_budget_bytes; |
| 249 | let media_mb = if media_budget_bytes == 0 { |
| 250 | 0 |
| 251 | } else { |
| 252 | media_budget_bytes.div_ceil(1024 * 1024) |
| 253 | }; |
| 254 | eng.media.set_budget_mb(media_mb); |
| 255 | eng |
| 256 | } |
| 257 | |
| 258 | pub fn new_headless() -> Result<Self, Box<dyn std::error::Error>> { |
| 259 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 260 | let adapter = pollster::block_on(instance.request_adapter(&Default::default()))?; |
| 261 | let mut req_features = wgpu::Features::empty(); |
| 262 | if adapter.features().contains(wgpu::Features::FLOAT32_FILTERABLE) { |
| 263 | req_features |= wgpu::Features::FLOAT32_FILTERABLE; |
| 264 | } |
| 265 | let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { |
| 266 | required_features: req_features, |
| 267 | ..Default::default() |
| 268 | }))?; |
| 269 | Ok(Self::new(device, queue)) |
| 270 | } |
| 271 | |
| 272 | fn effective_depth(&self, requested: BitDepth) -> BitDepth { |
| 273 | if !self.hiq { |
| 274 | BitDepth::Int8 |
| 275 | } else { |
| 276 | requested |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | pub(crate) fn node_depth(&self, comp: &Comp, node: &Node, time: f64, upstream: Option<BitDepth>) -> BitDepth { |
| 281 | if !self.hiq { |
| 282 | return BitDepth::Int8; |
| 283 | } |
| 284 | let explicit = comp.eval_number(node, "Depth", time, 0.0, &self.expr).round() as i32; |
| 285 | if let Some(d) = BitDepth::from_fusion_depth(explicit) { |
| 286 | return d; |
| 287 | } |
| 288 | upstream.unwrap_or(comp.depth_full) |
| 289 | } |
| 290 | |
| 291 | fn texture_format_for(&self, depth: BitDepth) -> wgpu::TextureFormat { |
| 292 | match depth { |
| 293 | BitDepth::Int8 => wgpu::TextureFormat::Rgba8Unorm, |
| 294 | BitDepth::Int16 | BitDepth::Float16 => wgpu::TextureFormat::Rgba16Float, |
| 295 | BitDepth::Float32 => { |
| 296 | if self.supports_f32_filter { |
| 297 | wgpu::TextureFormat::Rgba32Float |
| 298 | } else { |
| 299 | wgpu::TextureFormat::Rgba16Float |
| 300 | } |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | pub fn device(&self) -> &wgpu::Device { |
| 306 | &self.device |
| 307 | } |
| 308 | |
| 309 | pub fn queue(&self) -> &wgpu::Queue { |
| 310 | &self.queue |
| 311 | } |
| 312 | |
| 313 | pub fn device_arc(&self) -> std::sync::Arc<wgpu::Device> { |
| 314 | std::sync::Arc::new(self.device.clone()) |
| 315 | } |
| 316 | |
| 317 | pub fn queue_arc(&self) -> std::sync::Arc<wgpu::Queue> { |
| 318 | std::sync::Arc::new(self.queue.clone()) |
| 319 | } |
| 320 | |
| 321 | pub fn set_cache_mode(&mut self, mode: CacheMode) { |
| 322 | self.cache.mode = mode; |
| 323 | } |
| 324 | |
| 325 | pub fn set_media_budget_mb(&mut self, budget_mb: u64) { |
| 326 | self.media.set_budget_mb(budget_mb); |
| 327 | } |
| 328 | |
| 329 | fn for_each_registry(&self, mut f: impl FnMut(&mut ShaderRegistry)) { |
| 330 | f(&mut self.pipelines.borrow_mut()); |
| 331 | if let Some(r) = self.pipelines_int16.get() { |
| 332 | f(&mut r.borrow_mut()); |
| 333 | } |
| 334 | if let Some(r) = self.pipelines_f16.get() { |
| 335 | f(&mut r.borrow_mut()); |
| 336 | } |
| 337 | if let Some(r) = self.pipelines_f32.get() { |
| 338 | f(&mut r.borrow_mut()); |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | fn clear_bind_group_caches(&self) { |
| 343 | self.for_each_registry(|r| r.clear_bind_group_cache()); |
| 344 | self.last_bg_vram_drops.set(self.cache.vram_drops()); |
| 345 | } |
| 346 | |
| 347 | pub(super) fn reset_uniform_cursors(&self) { |
| 348 | self.for_each_registry(|r| r.reset_uniform_cursor()); |
| 349 | if let Some(ap) = self.aux_pipelines.get() { |
| 350 | ap.borrow_mut().reset_uniform_cursor(); |
| 351 | } |
| 352 | if let Some(ak) = self.alpha_keyer_pipelines.get() { |
| 353 | ak.borrow_mut().reset_uniform_cursor(); |
| 354 | } |
| 355 | if let Some(cs) = self.color_science_pipelines.get() { |
| 356 | cs.borrow_mut().reset_uniform_cursor(); |
| 357 | } |
| 358 | if let Some(cl) = self.color_lut_pipelines.get() { |
| 359 | cl.borrow_mut().reset_uniform_cursor(); |
| 360 | } |
| 361 | if let Some(dp) = self.depth_optical_pipelines.get() { |
| 362 | dp.borrow_mut().reset_uniform_cursor(); |
| 363 | } |
| 364 | if let Some(wm) = self.warps_masks_pipelines.get() { |
| 365 | wm.borrow_mut().reset_uniform_cursor(); |
| 366 | } |
| 367 | if let Some(ff) = self.fx_fuses_pipelines.get() { |
| 368 | ff.borrow_mut().reset_uniform_cursor(); |
| 369 | } |
| 370 | if let Some(fx2) = self.archive_fx2_pipelines.get() { |
| 371 | fx2.borrow_mut().reset_uniform_cursor(); |
| 372 | } |
| 373 | if let Some(sfx) = self.surface_fx.get() { |
| 374 | sfx.borrow_mut().reset_uniform_cursor(); |
| 375 | } |
| 376 | if let Some(am) = self.auto_matte_pipelines.get() { |
| 377 | am.borrow_mut().reset_uniform_cursor(); |
| 378 | } |
| 379 | if let Some(of) = self.optflow.get() { |
| 380 | of.reset_uniform_cursor(); |
| 381 | } |
| 382 | self.media.reset_nv12_uniform_cursor(); |
| 383 | } |
| 384 | |
| 385 | fn trim_uniform_chunks(&self) { |
| 386 | self.for_each_registry(|r| r.trim_uniform_chunks(2)); |
| 387 | if let Some(ap) = self.aux_pipelines.get() { |
| 388 | ap.borrow_mut().trim_uniform_chunks(2); |
| 389 | } |
| 390 | if let Some(ak) = self.alpha_keyer_pipelines.get() { |
| 391 | ak.borrow_mut().trim_uniform_chunks(2); |
| 392 | } |
| 393 | if let Some(cs) = self.color_science_pipelines.get() { |
| 394 | cs.borrow_mut().trim_uniform_chunks(2); |
| 395 | } |
| 396 | if let Some(cl) = self.color_lut_pipelines.get() { |
| 397 | cl.borrow_mut().trim_uniform_chunks(2); |
| 398 | } |
| 399 | if let Some(dp) = self.depth_optical_pipelines.get() { |
| 400 | dp.borrow_mut().trim_uniform_chunks(2); |
| 401 | } |
| 402 | if let Some(wm) = self.warps_masks_pipelines.get() { |
| 403 | wm.borrow_mut().trim_uniform_chunks(2); |
| 404 | } |
| 405 | if let Some(ff) = self.fx_fuses_pipelines.get() { |
| 406 | ff.borrow_mut().trim_uniform_chunks(2); |
| 407 | } |
| 408 | if let Some(fx2) = self.archive_fx2_pipelines.get() { |
| 409 | fx2.borrow_mut().trim_uniform_chunks(2); |
| 410 | } |
| 411 | if let Some(sfx) = self.surface_fx.get() { |
| 412 | sfx.borrow_mut().trim_uniform_chunks(2); |
| 413 | } |
| 414 | if let Some(am) = self.auto_matte_pipelines.get() { |
| 415 | am.borrow_mut().trim_uniform_chunks(2); |
| 416 | } |
| 417 | self.media.trim_nv12_uniform_chunks(2); |
| 418 | } |
| 419 | |
| 420 | pub(super) fn sync_bg_cache_with_vram_drops(&mut self) { |
| 421 | let drops = self.cache.vram_drops(); |
| 422 | if drops != self.last_bg_vram_drops.get() { |
| 423 | self.custom_shaders.clear_bind_group_cache(); |
| 424 | self.clear_bind_group_caches(); |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | pub fn bust_all_caches(&mut self) { |
| 429 | self.output_cache.clear(); |
| 430 | self.sync_node_cache_budget(); |
| 431 | self.cache.bust_all(); |
| 432 | self.custom_shaders.clear_bind_group_cache(); |
| 433 | self.custom_shaders.trim_uniform_chunks(2); |
| 434 | self.clear_bind_group_caches(); |
| 435 | self.trim_uniform_chunks(); |
| 436 | if let Some(of) = self.optflow.get() { |
| 437 | of.clear_scratch(); |
| 438 | } |
| 439 | if let Some(cl) = self.color_lut_pipelines.get() { |
| 440 | cl.borrow_mut().clear_lut_cache(); |
| 441 | } |
| 442 | #[cfg(not(target_arch = "wasm32"))] |
| 443 | self.pipelines.borrow_mut().readback_pool.clear(); |
| 444 | self.media.clear(); |
| 445 | self.particles.clear(); |
| 446 | self.sprite_cache.clear(); |
| 447 | self.scene3d.clear_shadow_targets(); |
| 448 | self.frame_consumers.clear(); |
| 449 | self.frame_consumers_rev = None; |
| 450 | *self.ram_upload_tex.borrow_mut() = None; |
| 451 | io::clear_dims_cache(); |
| 452 | } |
| 453 | |
| 454 | pub fn bust_gpu_cache(&mut self) { |
| 455 | self.output_cache.clear(); |
| 456 | self.sync_node_cache_budget(); |
| 457 | self.cache.bust_all(); |
| 458 | self.custom_shaders.clear_bind_group_cache(); |
| 459 | self.custom_shaders.trim_uniform_chunks(2); |
| 460 | self.clear_bind_group_caches(); |
| 461 | self.trim_uniform_chunks(); |
| 462 | if let Some(of) = self.optflow.get() { |
| 463 | of.clear_scratch(); |
| 464 | } |
| 465 | if let Some(cl) = self.color_lut_pipelines.get() { |
| 466 | cl.borrow_mut().clear_lut_cache(); |
| 467 | } |
| 468 | self.media.clear_nv12_gpu_state(); |
| 469 | #[cfg(not(target_arch = "wasm32"))] |
| 470 | self.pipelines.borrow_mut().readback_pool.clear(); |
| 471 | self.sprite_cache.clear(); |
| 472 | self.scene3d.clear_shadow_targets(); |
| 473 | *self.ram_upload_tex.borrow_mut() = None; |
| 474 | } |
| 475 | |
| 476 | pub fn bust_frame(&mut self, frame: i64) -> usize { |
| 477 | self.output_cache.clear(); |
| 478 | self.sync_node_cache_budget(); |
| 479 | let busted = self.cache.bust_frame(frame); |
| 480 | self.custom_shaders.clear_bind_group_cache(); |
| 481 | self.clear_bind_group_caches(); |
| 482 | busted |
| 483 | } |
| 484 | |
| 485 | pub fn bust_subtree(&mut self, node: NodeId) -> usize { |
| 486 | self.output_cache.clear(); |
| 487 | self.sync_node_cache_budget(); |
| 488 | let busted = self.cache.bust_subtree(node); |
| 489 | self.custom_shaders.clear_bind_group_cache(); |
| 490 | self.clear_bind_group_caches(); |
| 491 | busted |
| 492 | } |
| 493 | |
| 494 | fn prepare_frame_scratch(&mut self, comp: &Comp) -> HashSet<(NodeId, i64)> { |
| 495 | self.frame_eval_target = None; |
| 496 | self.frame_memo.clear(); |
| 497 | self.frame_roi_memo.clear(); |
| 498 | if self.frame_consumers_rev != Some(comp.revision) |
| 499 | || self.frame_consumers.len() != comp.nodes.len() |
| 500 | { |
| 501 | self.frame_consumers.clear(); |
| 502 | self.frame_consumers_rev = Some(comp.revision); |
| 503 | } |
| 504 | let mut visiting = std::mem::take(&mut self.frame_visiting); |
| 505 | visiting.clear(); |
| 506 | self.frame_visiting_nodes.clear(); |
| 507 | visiting |
| 508 | } |
| 509 | |
| 510 | fn finish_frame_scratch(&mut self, mut visiting: HashSet<(NodeId, i64)>) { |
| 511 | self.frame_eval_target = None; |
| 512 | self.frame_memo.clear(); |
| 513 | self.frame_roi_memo.clear(); |
| 514 | visiting.clear(); |
| 515 | self.frame_visiting = visiting; |
| 516 | self.frame_visiting_nodes.clear(); |
| 517 | } |
| 518 | |
| 519 | /// Evaluates `target` node at `time` and returns its GPU texture + telemetry. |
| 520 | pub fn evaluate( |
| 521 | &mut self, |
| 522 | comp: &Comp, |
| 523 | target: NodeId, |
| 524 | time: f64, |
| 525 | ) -> (CachedTexture, EvalStats) { |
| 526 | let t0 = Instant::now(); |
| 527 | self.sync_bg_cache_with_vram_drops(); |
| 528 | let out_key = self.output_cache_key(comp, target, time) |
| 529 | ^ self.auto_matte_cache.generation().wrapping_mul(0x9e37_79b9_7f4a_7c15); |
| 530 | if let Some((tex, unsupported)) = self.output_cache_get(out_key) { |
| 531 | let stats = EvalStats { |
| 532 | eval_ms: t0.elapsed().as_secs_f64() * 1000.0, |
| 533 | cache_hits: 1, |
| 534 | cached_entries: self.cache.entry_count(), |
| 535 | cached_vram_mb: self.vram_mb(), |
| 536 | media_entries: self.media.entry_count(), |
| 537 | media_mb: self.media.total_mb(), |
| 538 | unsupported_nodes: unsupported, |
| 539 | ..EvalStats::default() |
| 540 | }; |
| 541 | return (tex, stats); |
| 542 | } |
| 543 | let mut stats = EvalStats::default(); |
| 544 | self.media |
| 545 | .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips); |
| 546 | let mut visiting = self.prepare_frame_scratch(comp); |
| 547 | self.frame_eval_target = Some(target); |
| 548 | let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 549 | label: Some("comp-eval"), |
| 550 | }); |
| 551 | |
| 552 | let mut tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); |
| 553 | if tex.has_dod() { |
| 554 | // Crop expanded DoD cleanly back to logical canvas_size for final readback/export |
| 555 | tex = self.crop_to_canvas(&mut encoder, tex); |
| 556 | } |
| 557 | self.queue.submit(Some(encoder.finish())); |
| 558 | self.reset_uniform_cursors(); |
| 559 | self.custom_shaders.reset_uniform_cursor(); |
| 560 | #[cfg(not(target_arch = "wasm32"))] |
| 561 | self.media.flush_upload_staging_after_submit(&self.device); |
| 562 | self.finish_frame_scratch(visiting); |
| 563 | self.cache.flush_pending_pool(); |
| 564 | self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); |
| 565 | self.sync_bg_cache_with_vram_drops(); |
| 566 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 567 | stats.cached_entries = self.cache.entry_count(); |
| 568 | stats.cached_vram_mb = self.vram_mb(); |
| 569 | stats.media_entries = self.media.entry_count(); |
| 570 | stats.media_mb = self.media.total_mb(); |
| 571 | (tex, stats) |
| 572 | } |
| 573 | |
| 574 | /// Zero-copy render straight into a persistent viewer `wgpu::Texture` (premultiplied Rgba8Unorm). |
| 575 | pub fn render_into_viewer( |
| 576 | &mut self, |
| 577 | comp: &Comp, |
| 578 | target: NodeId, |
| 579 | time: f64, |
| 580 | dst_texture: &wgpu::Texture, |
| 581 | display: DisplaySettings, |
| 582 | ) -> EvalStats { |
| 583 | let t0 = Instant::now(); |
| 584 | self.sync_bg_cache_with_vram_drops(); |
| 585 | let out_key = self.output_cache_key(comp, target, time) |
| 586 | ^ self.auto_matte_cache.generation().wrapping_mul(0x9e37_79b9_7f4a_7c15); |
| 587 | let mut stats = EvalStats::default(); |
| 588 | let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 589 | label: Some("comp-viewer-eval"), |
| 590 | }); |
| 591 | |
| 592 | let (tex, visiting_opt) = if let Some((cached, unsupported)) = self.output_cache_get(out_key) { |
| 593 | stats.cache_hits = 1; |
| 594 | stats.unsupported_nodes = unsupported; |
| 595 | (cached, None) |
| 596 | } else { |
| 597 | self.media |
| 598 | .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips); |
| 599 | let mut visiting = self.prepare_frame_scratch(comp); |
| 600 | self.frame_eval_target = Some(target); |
| 601 | let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); |
| 602 | (t, Some(visiting)) |
| 603 | }; |
| 604 | |
| 605 | let dst_size = [dst_texture.width(), dst_texture.height()]; |
| 606 | let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default()); |
| 607 | let mut params = UniformParams::default(); |
| 608 | params.p[0] = [ |
| 609 | 2.0_f32.powf(display.exposure), |
| 610 | display.gamma, |
| 611 | display.channel as f32, |
| 612 | if display.checker_bg { 1.0 } else { 0.0 }, |
| 613 | ]; |
| 614 | params.p[1] = display.uv_rect; |
| 615 | params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0]; |
| 616 | if tex.has_dod() { |
| 617 | params.p[4] = [ |
| 618 | tex.origin[0] as f32, |
| 619 | tex.origin[1] as f32, |
| 620 | tex.canvas_size[0] as f32, |
| 621 | tex.canvas_size[1] as f32, |
| 622 | ]; |
| 623 | } |
| 624 | self.dispatch_to_view_uncached( |
| 625 | &mut encoder, |
| 626 | ShaderOp::DisplayBlit, |
| 627 | &tex.view, |
| 628 | &self.dummy.view, |
| 629 | &self.dummy.view, |
| 630 | &dst_view, |
| 631 | dst_size, |
| 632 | &params, |
| 633 | ); |
| 634 | |
| 635 | self.queue.submit(Some(encoder.finish())); |
| 636 | self.reset_uniform_cursors(); |
| 637 | self.custom_shaders.reset_uniform_cursor(); |
| 638 | #[cfg(not(target_arch = "wasm32"))] |
| 639 | self.media.flush_upload_staging_after_submit(&self.device); |
| 640 | if let Some(visiting) = visiting_opt { |
| 641 | self.finish_frame_scratch(visiting); |
| 642 | self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone()); |
| 643 | } |
| 644 | self.cache.flush_pending_pool(); |
| 645 | self.sync_bg_cache_with_vram_drops(); |
| 646 | |
| 647 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 648 | stats.cached_entries = self.cache.entry_count(); |
| 649 | stats.cached_vram_mb = self.vram_mb(); |
| 650 | stats.media_entries = self.media.entry_count(); |
| 651 | stats.media_mb = self.media.total_mb(); |
| 652 | stats |
| 653 | } |
| 654 | |
| 655 | fn scaled_dims(&self, w: u32, h: u32) -> [u32; 2] { |
| 656 | let s = self.proxy_scale.max(1); |
| 657 | [(w / s).max(1), (h / s).max(1)] |
| 658 | } |
| 659 | |
| 660 | pub(crate) fn eval_node( |
| 661 | &mut self, |
| 662 | comp: &Comp, |
| 663 | id: NodeId, |
| 664 | time: f64, |
| 665 | enc: &mut wgpu::CommandEncoder, |
| 666 | visiting: &mut HashSet<(NodeId, i64)>, |
| 667 | stats: &mut EvalStats, |
| 668 | ) -> CachedTexture { |
| 669 | const MAX_EVAL_DEPTH: usize = 256; |
| 670 | if id.0 >= comp.nodes.len() || visiting.len() >= MAX_EVAL_DEPTH { |
| 671 | return self.dummy.clone(); |
| 672 | } |
| 673 | let frame_i = time.round() as i64; |
| 674 | let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; |
| 675 | let memo_sz = self.mask_target_size; |
| 676 | // Always memoize within a single frame's DAG pass so diamond graphs never explode |
| 677 | // exponentially (even in CacheMode::Bypass, which bypasses the cross-frame cache). |
| 678 | if let Some(hit) = self.frame_memo.get(&(id, time_key, memo_sz)).cloned() { |
| 679 | stats.cache_hits += 1; |
| 680 | return hit; |
| 681 | } |
| 682 | if !self.frame_visiting_nodes.insert(id) { |
| 683 | return self.dummy.clone(); |
| 684 | } |
| 685 | if !visiting.insert((id, time_key)) { |
| 686 | self.frame_visiting_nodes.remove(&id); |
| 687 | return self.dummy.clone(); |
| 688 | } |
| 689 | let mb_cfg = if self.hiq && !comp.node(id).bypassed { |
| 690 | crate::motion_blur::read_motion_blur_config(comp, comp.node(id), time, &self.expr) |
| 691 | } else { |
| 692 | None |
| 693 | }; |
| 694 | let res = if let Some(cfg) = mb_cfg { |
| 695 | self.eval_node_motion_blur(comp, id, time, frame_i, cfg, enc, visiting, stats) |
| 696 | } else { |
| 697 | self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats) |
| 698 | }; |
| 699 | visiting.remove(&(id, time_key)); |
| 700 | self.frame_visiting_nodes.remove(&id); |
| 701 | if res.content_hash != 0 { |
| 702 | let node = comp.node(id); |
| 703 | let sticky = match node.kind.as_str() { |
| 704 | "Loader" | "MediaIn" => is_static_loader_node(node), |
| 705 | "TextPlus" | "Renderer3D" | "pRender" | "PolylineMask" | "BSplineMask" | "MultiPoly" | "TeapotMask" | "WandMask" => true, |
| 706 | _ => false, |
| 707 | }; |
| 708 | if sticky { |
| 709 | self.cache.mark_entry_sticky(res.content_hash); |
| 710 | } |
| 711 | } |
| 712 | self.frame_memo.insert((id, time_key, memo_sz), res.clone()); |
| 713 | res |
| 714 | } |
| 715 | |
| 716 | #[allow(clippy::too_many_arguments)] |
| 717 | fn eval_node_motion_blur( |
| 718 | &mut self, |
| 719 | comp: &Comp, |
| 720 | id: NodeId, |
| 721 | time: f64, |
| 722 | frame_i: i64, |
| 723 | cfg: crate::motion_blur::MotionBlurConfig, |
| 724 | enc: &mut wgpu::CommandEncoder, |
| 725 | visiting: &mut HashSet<(NodeId, i64)>, |
| 726 | stats: &mut EvalStats, |
| 727 | ) -> CachedTexture { |
| 728 | let times = cfg.shutter_times(time); |
| 729 | if times.len() < 2 { |
| 730 | return self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats); |
| 731 | } |
| 732 | let mut samples = Vec::with_capacity(times.len()); |
| 733 | for t_k in times { |
| 734 | let s = self.eval_node_inner(comp, id, t_k, t_k.round() as i64, enc, visiting, stats); |
| 735 | samples.push(s); |
| 736 | } |
| 737 | let center_idx = samples.len() / 2; |
| 738 | let first = &samples[0]; |
| 739 | if first.content_hash != 0 |
| 740 | && samples.iter().all(|s| { |
| 741 | s.content_hash == first.content_hash |
| 742 | && s.origin == first.origin |
| 743 | && s.size == first.size |
| 744 | }) |
| 745 | { |
| 746 | return samples.swap_remove(center_idx); |
| 747 | } |
| 748 | let center = &samples[center_idx]; |
| 749 | let mut hasher = std::collections::hash_map::DefaultHasher::new(); |
| 750 | "motion_blur".hash(&mut hasher); |
| 751 | id.0.hash(&mut hasher); |
| 752 | self.cache.gpu_salt.hash(&mut hasher); |
| 753 | self.cache.node_salt(id).hash(&mut hasher); |
| 754 | cfg.cache_key_bits().hash(&mut hasher); |
| 755 | center.format.hash(&mut hasher); |
| 756 | center.depth.hash(&mut hasher); |
| 757 | for s in &samples { |
| 758 | s.content_hash.hash(&mut hasher); |
| 759 | s.origin.hash(&mut hasher); |
| 760 | s.size.hash(&mut hasher); |
| 761 | } |
| 762 | let mb_key = hasher.finish(); |
| 763 | if let Some(hit) = self.cache.get(mb_key, id, frame_i) { |
| 764 | stats.cache_hits += 1; |
| 765 | return hit; |
| 766 | } |
| 767 | let mut out = self.motion_blur.accumulate_samples( |
| 768 | &self.device, |
| 769 | &self.queue, |
| 770 | enc, |
| 771 | &samples, |
| 772 | center.depth, |
| 773 | center.format, |
| 774 | mb_key, |
| 775 | ); |
| 776 | if center.aux.is_some() && (center.origin != out.origin || center.size != out.size) { |
| 777 | self.reorigin_aux(enc, center, &mut out); |
| 778 | } |
| 779 | self.cache.insert(mb_key, out.clone(), id, frame_i); |
| 780 | out |
| 781 | } |
| 782 | |
| 783 | fn switch_input_port(idx: usize) -> Option<&'static str> { |
| 784 | match idx { |
| 785 | 0 => Some("Input0"), |
| 786 | 1 => Some("Input1"), |
| 787 | 2 => Some("Input2"), |
| 788 | 3 => Some("Input3"), |
| 789 | 4 => Some("Input4"), |
| 790 | 5 => Some("Input5"), |
| 791 | 6 => Some("Input6"), |
| 792 | 7 => Some("Input7"), |
| 793 | 8 => Some("Input8"), |
| 794 | 9 => Some("Input9"), |
| 795 | 10 => Some("Input10"), |
| 796 | 11 => Some("Input11"), |
| 797 | 12 => Some("Input12"), |
| 798 | 13 => Some("Input13"), |
| 799 | 14 => Some("Input14"), |
| 800 | 15 => Some("Input15"), |
| 801 | 16 => Some("Input16"), |
| 802 | _ => None, |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | fn eval_node_inner( |
| 807 | &mut self, |
| 808 | comp: &Comp, |
| 809 | id: NodeId, |
| 810 | time: f64, |
| 811 | frame_i: i64, |
| 812 | enc: &mut wgpu::CommandEncoder, |
| 813 | visiting: &mut HashSet<(NodeId, i64)>, |
| 814 | stats: &mut EvalStats, |
| 815 | ) -> CachedTexture { |
| 816 | let node = comp.node(id); |
| 817 | let comp_dims = self.scaled_dims(comp.width, comp.height); |
| 818 | |
| 819 | // Bypass (`PassThrough`) or passthrough utility nodes |
| 820 | if node.bypassed |
| 821 | || matches!( |
| 822 | node.kind.as_str(), |
| 823 | "Saver" |
| 824 | | "PipeRouter" |
| 825 | | "Fuse.Wireless" |
| 826 | | "Tracker" |
| 827 | ) |
| 828 | { |
| 829 | let port = default_main_input_port(&node.kind); |
| 830 | if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { |
| 831 | return self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 832 | } |
| 833 | return self.dummy.clone(); |
| 834 | } |
| 835 | |
| 836 | // MacroOperator / GroupOperator: seamlessly evaluate the unpacked internal output tool! |
| 837 | if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") { |
| 838 | if let Some(out_id) = node.macro_output { |
| 839 | return self.eval_node(comp, out_id, time, enc, visiting, stats); |
| 840 | } |
| 841 | if let Some(src_id) = node |
| 842 | .connected_node("Input") |
| 843 | .or_else(|| node.connected_node("MainInput1")) |
| 844 | .and_then(|s| comp.find_node(s)) |
| 845 | { |
| 846 | return self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 847 | } |
| 848 | return self.dummy.clone(); |
| 849 | } |
| 850 | |
| 851 | // TimeStretcher / TimeSpeed: remap time BEFORE evaluating upstream! |
| 852 | if matches!(node.kind.as_str(), "TimeStretcher" | "TimeSpeed") { |
| 853 | if let Some(remapped) = self.remap_time_node(comp, node, time) { |
| 854 | return self.eval_time_remapped(comp, node, time, frame_i, remapped, enc, visiting, stats); |
| 855 | } |
| 856 | } |
| 857 | if node.kind == "Switch" || node.kind == "Fuse.Switch" { |
| 858 | let is_native_zero_indexed = node.kind == "Switch" |
| 859 | && (node.inputs.contains_key("Source") |
| 860 | || node.inputs.contains_key("Input0") |
| 861 | || !node.inputs.contains_key("Which")); |
| 862 | let src_name = if is_native_zero_indexed { |
| 863 | let source = comp |
| 864 | .eval_number(node, "Source", time, 0.0, &self.expr) |
| 865 | .round() |
| 866 | .max(0.0) as usize; |
| 867 | if let Some(port) = Self::switch_input_port(source) { |
| 868 | node.connected_node(port) |
| 869 | } else { |
| 870 | let port = format!("Input{source}"); |
| 871 | node.connected_node(&port) |
| 872 | } |
| 873 | .or_else(|| node.connected_node("Input0")) |
| 874 | } else { |
| 875 | let which = comp |
| 876 | .eval_number(node, "Which", time, 1.0, &self.expr) |
| 877 | .round() |
| 878 | .max(1.0) as usize; |
| 879 | if let Some(port) = Self::switch_input_port(which) { |
| 880 | node.connected_node(port) |
| 881 | } else { |
| 882 | let port = format!("Input{which}"); |
| 883 | node.connected_node(&port) |
| 884 | } |
| 885 | .or_else(|| node.connected_node("Input1")) |
| 886 | }; |
| 887 | if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) { |
| 888 | return self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 889 | } |
| 890 | return self.dummy.clone(); |
| 891 | } |
| 892 | |
| 893 | match node.kind.as_str() { |
| 894 | "Loader" => self.eval_loader(comp, node, time, frame_i, enc, visiting, stats), |
| 895 | "MediaIn" => self.eval_media_in(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 896 | "MediaOut" => self.eval_media_out(comp, node, time, enc, visiting, stats), |
| 897 | "Background" => self.eval_background(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 898 | "Merge" => self.eval_merge(comp, node, time, frame_i, enc, visiting, stats), |
| 899 | "MultiMerge" | "Fuse.MultiMerge" => self.eval_multi_merge(comp, node, time, frame_i, enc, visiting, stats), |
| 900 | "Dissolve" => self.eval_dissolve(comp, node, time, frame_i, enc, visiting, stats), |
| 901 | "Transform" => self.eval_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 902 | "CameraShake" => self.eval_camera_shake(comp, node, time, frame_i, enc, visiting, stats), |
| 903 | "CornerPositioner" => self.eval_corner_positioner(comp, node, time, frame_i, enc, visiting, stats), |
| 904 | "PerspectivePositioner" => self.eval_perspective_positioner(comp, node, time, frame_i, enc, visiting, stats), |
| 905 | "DVE" => self.eval_dve(comp, node, time, frame_i, enc, visiting, stats), |
| 906 | "Shadow" => self.eval_shadow(comp, node, time, frame_i, enc, visiting, stats), |
| 907 | "Scale" | "BetterResize" => self.eval_scale(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 908 | "Letterbox" => self.eval_letterbox(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 909 | "Crop" => self.eval_crop(comp, node, time, frame_i, enc, visiting, stats), |
| 910 | "SetDomain" => self.eval_set_domain(comp, node, time, frame_i, enc, visiting, stats), |
| 911 | "ChangeDepth" => { |
| 912 | let mut out = self.eval_change_depth(comp, node, time, frame_i, enc, visiting, stats); |
| 913 | if out.aux.is_none() |
| 914 | && let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) |
| 915 | { |
| 916 | let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; |
| 917 | if let Some(src) = self.frame_memo.get(&(src_id, time_key, self.mask_target_size)) |
| 918 | && src.aux.is_some() |
| 919 | && src.size == out.size |
| 920 | { |
| 921 | out.set_aux(src.aux.clone()); |
| 922 | } |
| 923 | } |
| 924 | out |
| 925 | } |
| 926 | "Dimension.CopyAux" => self.eval_copy_aux(comp, node, time, frame_i, enc, visiting, stats), |
| 927 | "Dimension.OpticalFlow" | "OpticalFlow" => self.eval_optical_flow(comp, node, time, frame_i, enc, visiting, stats), |
| 928 | "VectorMotionBlur" => self.eval_vector_motion_blur(comp, node, time, frame_i, enc, visiting, stats), |
| 929 | "VectorDenoise" => self.eval_vector_denoise(comp, node, time, frame_i, enc, visiting, stats), |
| 930 | "BrightnessContrast" => self.eval_bc(comp, node, time, frame_i, enc, visiting, stats), |
| 931 | "ColorCorrector" => self.eval_cc(comp, node, time, frame_i, enc, visiting, stats), |
| 932 | "ColorGain" => self.eval_color_gain(comp, node, time, frame_i, enc, visiting, stats), |
| 933 | "ColorCurves" => self.eval_color_curves(comp, node, time, frame_i, enc, visiting, stats), |
| 934 | "HueCurves" => self.eval_hue_curves(comp, node, time, frame_i, enc, visiting, stats), |
| 935 | "GamutConvert" => self.eval_gamut_convert(comp, node, time, frame_i, enc, visiting, stats), |
| 936 | "AcesTransform" => self.eval_aces_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 937 | "ColorSpace" => self.eval_color_space(comp, node, time, frame_i, enc, visiting, stats), |
| 938 | "ColorMatrix" => self.eval_color_matrix(comp, node, time, frame_i, enc, visiting, stats), |
| 939 | "CustomColorMatrix" => self.eval_custom_color_matrix(comp, node, time, frame_i, enc, visiting, stats), |
| 940 | "SetCanvasColor" => self.eval_set_canvas_color(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 941 | "ChromaticAdaptation" => self.eval_chromatic_adaptation(comp, node, time, frame_i, enc, visiting, stats), |
| 942 | "ColorSpaceTransform" => self.eval_color_space_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 943 | "GamutLimiter" => self.eval_gamut_limiter(comp, node, time, frame_i, enc, visiting, stats), |
| 944 | "GamutMapping" => self.eval_gamut_mapping(comp, node, time, frame_i, enc, visiting, stats), |
| 945 | "FilmLookCreator" => self.eval_film_look_creator(comp, node, time, frame_i, enc, visiting, stats), |
| 946 | "OCIOCDLTransform" => self.eval_ocio_cdl_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 947 | "FileLUT" => self.eval_file_lut(comp, node, time, frame_i, enc, visiting, stats), |
| 948 | "Fuse.LUTCubeCreator" | "LUTCubeCreator" => self.eval_lut_cube_creator(comp, node, time, frame_i, enc, stats), |
| 949 | "Fuse.LUTCubeApply" | "LUTCubeApply" => self.eval_lut_cube_apply(comp, node, time, frame_i, enc, visiting, stats), |
| 950 | "Fuse.LUTCubeAnalyzer" | "LUTCubeAnalyzer" => self.eval_lut_cube_analyzer(comp, node, time, frame_i, enc, visiting, stats), |
| 951 | "WhiteBalance" => self.eval_white_balance(comp, node, time, frame_i, enc, visiting, stats), |
| 952 | "MatteControl" => self.eval_matte_control(comp, node, time, frame_i, enc, visiting, stats), |
| 953 | "InvertColor" => self.eval_invert(comp, node, time, frame_i, enc, visiting, stats), |
| 954 | "AlphaMultiply" => self.eval_alpha_multiply(comp, node, time, frame_i, enc, visiting, stats), |
| 955 | "AlphaDivide" => self.eval_alpha_divide(comp, node, time, frame_i, enc, visiting, stats), |
| 956 | "PseudoColor" => self.eval_pseudo_color(comp, node, time, frame_i, enc, visiting, stats), |
| 957 | "ChannelBoolean" => self.eval_channel_boolean(comp, node, time, frame_i, enc, visiting, stats), |
| 958 | "LumaKeyer" => self.eval_luma_key(comp, node, time, frame_i, enc, visiting, stats), |
| 959 | "UltraKeyer" => self.eval_ultra_keyer(comp, node, time, frame_i, enc, visiting, stats), |
| 960 | "DeltaKeyer" => self.eval_delta_keyer(comp, node, time, frame_i, enc, visiting, stats), |
| 961 | "DifferenceKeyer" => self.eval_difference_keyer(comp, node, time, frame_i, enc, visiting, stats), |
| 962 | "ChromaKeyer" => self.eval_chroma_keyer(comp, node, time, frame_i, enc, visiting, stats), |
| 963 | "CleanPLate" | "CleanPlate" => self.eval_clean_plate(comp, node, time, frame_i, enc, visiting, stats), |
| 964 | "Blur" => self.eval_blur(comp, node, time, frame_i, enc, visiting, stats), |
| 965 | "Sharpen" => self.eval_sharpen(comp, node, time, frame_i, enc, visiting, stats), |
| 966 | "UnsharpMask" => self.eval_unsharp_mask(comp, node, time, frame_i, enc, visiting, stats), |
| 967 | "Filter" => self.eval_filter(comp, node, time, frame_i, enc, visiting, stats), |
| 968 | "RemoveNoise" => self.eval_remove_noise(comp, node, time, frame_i, enc, visiting, stats), |
| 969 | "VariBlur" => self.eval_vari_blur(comp, node, time, frame_i, enc, visiting, stats), |
| 970 | "DirectionalBlur" => self.eval_dir_blur(comp, node, time, frame_i, enc, visiting, stats), |
| 971 | "Glow" | "SoftGlow" => self.eval_glow(comp, node, time, frame_i, enc, visiting, stats), |
| 972 | "Fuse.XGlow" => self.eval_xglow(comp, node, time, frame_i, enc, visiting, stats), |
| 973 | "DepthBlur" => self.eval_depth_blur(comp, node, time, frame_i, enc, visiting, stats), |
| 974 | "Fog" => self.eval_fog(comp, node, time, frame_i, enc, visiting, stats), |
| 975 | "Highlight" => self.eval_highlight(comp, node, time, frame_i, enc, visiting, stats), |
| 976 | "HotSpot" => self.eval_hot_spot(comp, node, time, frame_i, enc, visiting, stats), |
| 977 | "RankFilter" => self.eval_rank_filter(comp, node, time, frame_i, enc, visiting, stats), |
| 978 | "ErodeDilate" => { |
| 979 | let mut out = self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats); |
| 980 | if self.multiplies_by_mask(comp, node, time) { |
| 981 | let (mask, mask_inv) = self.eval_mask_input_sized( |
| 982 | comp, |
| 983 | node, |
| 984 | time, |
| 985 | Some(out.canvas_size), |
| 986 | enc, |
| 987 | visiting, |
| 988 | stats, |
| 989 | ); |
| 990 | if let Some(m) = mask { |
| 991 | let out_c = self.crop_to_canvas(enc, out); |
| 992 | let key = self.make_key( |
| 993 | node, |
| 994 | "ErodeDilateMBM", |
| 995 | out_c.size, |
| 996 | &[out_c.content_hash, m.content_hash], |
| 997 | &[if mask_inv { 1.0 } else { 0.0 }], |
| 998 | ); |
| 999 | out = if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1000 | hit |
| 1001 | } else { |
| 1002 | let dst = self.alloc_tex(out_c.size, out_c.depth, key); |
| 1003 | let mut u = UniformParams::default(); |
| 1004 | u.p[0][0] = if mask_inv { 1.0 } else { 0.0 }; |
| 1005 | self.dispatch_op( |
| 1006 | enc, |
| 1007 | ShaderOp::MaskApply, |
| 1008 | &out_c.view, |
| 1009 | &self.dummy.view, |
| 1010 | &m.view, |
| 1011 | &dst, |
| 1012 | &u, |
| 1013 | ); |
| 1014 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1015 | dst |
| 1016 | }; |
| 1017 | } |
| 1018 | } |
| 1019 | out |
| 1020 | } |
| 1021 | "FastNoise" => self.eval_fast_noise(comp, node, time, frame_i, comp_dims, enc, stats), |
| 1022 | "Plasma" => self.eval_plasma(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1023 | "DaySky" => self.eval_day_sky(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1024 | "Mandel" => self.eval_mandel(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1025 | "FilmGrain" => self.eval_film_grain(comp, node, time, frame_i, enc, visiting, stats), |
| 1026 | "Displace" => self.eval_displace(comp, node, time, frame_i, enc, visiting, stats), |
| 1027 | "Vortex" => self.eval_vortex(comp, node, time, frame_i, enc, visiting, stats), |
| 1028 | "Drip" => self.eval_drip(comp, node, time, frame_i, enc, visiting, stats), |
| 1029 | "Dent" => self.eval_dent(comp, node, time, frame_i, enc, visiting, stats), |
| 1030 | "GridWarp" => self.eval_grid_warp(comp, node, time, frame_i, enc, visiting, stats), |
| 1031 | "CoordSpace" => self.eval_coord_space(comp, node, time, frame_i, enc, visiting, stats), |
| 1032 | "LensDistort" => self.eval_lens_distort(comp, node, time, frame_i, enc, visiting, stats), |
| 1033 | "Trails" => self.eval_trails(comp, node, time, frame_i, enc, visiting, stats), |
| 1034 | "Fuse.Duplicate" => self.eval_duplicate(comp, node, time, frame_i, enc, visiting, stats), |
| 1035 | "Fuse.KScope" => self.eval_kscope(comp, node, time, frame_i, enc, visiting, stats), |
| 1036 | "Fuse.SwitchElse" => self.eval_switch_else(comp, node, time, enc, visiting, stats), |
| 1037 | "Fuse.CheckerPieceGenerator" => self.eval_checker_piece(comp, node, time, frame_i, enc, stats), |
| 1038 | "Fuse.AlphaWeightedNoise" => self.eval_alpha_weighted_noise(comp, node, time, frame_i, enc, visiting, stats), |
| 1039 | "Fuse.Crystallize" => self.eval_crystallize(comp, node, time, frame_i, enc, visiting, stats), |
| 1040 | "Fuse.HexagonTiles" => self.eval_hexagon_tiles(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1041 | "Fuse.Wipe" => self.eval_fuse_wipe(comp, node, time, frame_i, enc, visiting, stats), |
| 1042 | "Fuse.Null" => self.eval_fuse_null(comp, node, time, enc, visiting, stats), |
| 1043 | "Fuse.SetMetaData" => self.eval_fuse_set_metadata(comp, node, time, enc, visiting, stats), |
| 1044 | "Fuse.Linger" => self.eval_fuse_linger(comp, node, time, frame_i, enc, visiting, stats), |
| 1045 | "Fuse.OCLRays" => self.eval_fuse_ocl_rays(comp, node, time, frame_i, enc, visiting, stats), |
| 1046 | "Fuse.Hexagon" => self.eval_fuse_hexagon(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1047 | "Fuse.Lightning" => self.eval_fuse_lightning(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1048 | "Fuse.VORONOI_DIAGRAM" => self.eval_fuse_voronoi_diagram(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1049 | "Defocus" => self.eval_defocus(comp, node, time, frame_i, enc, visiting, stats), |
| 1050 | "AutoGain" => self.eval_auto_gain(comp, node, time, frame_i, enc, visiting, stats), |
| 1051 | "ColorBalance" => self.eval_color_balance(comp, node, time, frame_i, enc, visiting, stats), |
| 1052 | "SoftClip" => self.eval_soft_clip(comp, node, time, frame_i, enc, visiting, stats), |
| 1053 | "Grain" => self.eval_grain(comp, node, time, frame_i, enc, visiting, stats), |
| 1054 | "Distort" => self.eval_distort(comp, node, time, frame_i, enc, visiting, stats), |
| 1055 | "CreateBumpMap" => self.eval_create_bump_map(comp, node, time, frame_i, enc, visiting, stats), |
| 1056 | "CreateReliefMap" => self.eval_create_relief_map(comp, node, time, frame_i, enc, visiting, stats), |
| 1057 | "CustomFilter" => self.eval_custom_filter(comp, node, time, frame_i, enc, visiting, stats), |
| 1058 | "CineonLog" => self.eval_cineon_log(comp, node, time, frame_i, enc, visiting, stats), |
| 1059 | "LightTrim" => self.eval_light_trim(comp, node, time, frame_i, enc, visiting, stats), |
| 1060 | "MultiPoly" => self.eval_multi_poly(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1061 | "RangesMask" => self.eval_ranges_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1062 | "TeapotMask" => self.eval_teapot_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1063 | "TV" => self.eval_tv(comp, node, time, frame_i, enc, visiting, stats), |
| 1064 | "AutoDomain" => self.eval_auto_domain(comp, node, time, frame_i, enc, visiting, stats), |
| 1065 | "Fuse.FrameAverage" => self.eval_fuse_frame_average(comp, node, time, frame_i, enc, visiting, stats), |
| 1066 | "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1067 | "sNGon" |
| 1068 | | "sRectangle" |
| 1069 | | "sEllipse" |
| 1070 | | "sStar" |
| 1071 | | "sPolygon" |
| 1072 | | "sBSpline" |
| 1073 | | "sChangeStyle" |
| 1074 | | "sText" |
| 1075 | | "sGrid" |
| 1076 | | "sMerge" |
| 1077 | | "sTransform" |
| 1078 | | "sDuplicate" |
| 1079 | | "sJitter" |
| 1080 | | "sExpand" |
| 1081 | | "sOffset" |
| 1082 | | "sBoolean" |
| 1083 | | "sOutline" => self.dummy.clone(), |
| 1084 | "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats), |
| 1085 | "RectangleMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 1, enc, visiting, stats), |
| 1086 | "TriangleMask" => self.eval_triangle_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1087 | "PolylineMask" => self.eval_polyline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1088 | "BSplineMask" => self.eval_bspline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1089 | "Paint" => self.eval_paint(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1090 | "PaintMask" => self.eval_paint_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1091 | "PolylineStroke" | "Multistroke" => self.dummy.clone(), |
| 1092 | "BitmapMask" => self.eval_bitmap_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1093 | "WandMask" => self.eval_wand_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1094 | "TextPlus" => self.eval_text_plus(comp, node, time, frame_i, comp_dims, enc, stats), |
| 1095 | "Fuse.Colorize" => self.eval_colorize(comp, node, time, frame_i, enc, visiting, stats), |
| 1096 | "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats), |
| 1097 | "Fuse.XfChroma" => self.eval_xf_chroma(comp, node, time, frame_i, enc, visiting, stats), |
| 1098 | "Fuse.Cryptomatte" | "Cryptomatte" => self.eval_cryptomatte(comp, node, time, frame_i, enc, visiting, stats), |
| 1099 | "AutoMatte" => self.eval_auto_matte(comp, node, time, frame_i, false, enc, visiting, stats), |
| 1100 | "MagicMask" => self.eval_auto_matte(comp, node, time, frame_i, true, enc, visiting, stats), |
| 1101 | "pRender" => self.eval_p_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1102 | "pEmitter" |
| 1103 | | "pPointForce" |
| 1104 | | "pDirectionalForce" |
| 1105 | | "pTurbulence" |
| 1106 | | "pDrag" |
| 1107 | | "pFriction" |
| 1108 | | "pKill" |
| 1109 | | "pMerge" |
| 1110 | | "pBounce" |
| 1111 | | "pVortex" |
| 1112 | | "pFlock" |
| 1113 | | "pAvoid" |
| 1114 | | "pFollow" |
| 1115 | | "pTangentForce" |
| 1116 | | "pCustom" |
| 1117 | | "pCustomForce" |
| 1118 | | "pImageEmitter" |
| 1119 | | "pSpawn" |
| 1120 | | "pChangeStyle" |
| 1121 | | "pGradientForce" => self.dummy.clone(), |
| 1122 | "Custom" if node.connected_node("Image1").and_then(|s| comp.find_node(s)).is_none() => self.dummy.clone(), |
| 1123 | "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1124 | "SurfaceTracker" => self.eval_surface_tracker(comp, node, time, frame_i, enc, visiting, stats), |
| 1125 | "Dimension.PlanarTransform" | "PlanarTransform" => { |
| 1126 | self.eval_planar_transform(comp, node, time, frame_i, enc, visiting, stats) |
| 1127 | } |
| 1128 | "Dimension.PlanarTracker" | "PlanarTracker" => { |
| 1129 | self.eval_planar_tracker(comp, node, time, frame_i, enc, visiting, stats) |
| 1130 | } |
| 1131 | "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1132 | other => { |
| 1133 | // Dynamically evaluate any registered Fusion Lua / GPU-DCTL `.fuse` tool before |
| 1134 | // falling back to passthrough + unsupported_nodes. |
| 1135 | if other.starts_with("Fuse.") |
| 1136 | && let Some(tex) = self.eval_fuse_runtime( |
| 1137 | comp, node, time, frame_i, comp_dims, enc, visiting, stats, |
| 1138 | ) |
| 1139 | { |
| 1140 | return tex; |
| 1141 | } |
| 1142 | // Graceful passthrough for preserved/unknown image nodes (e.g. SurfaceTracker, MagicMask, |
| 1143 | // Fuse.Cryptomatte, Dimension.OpticalFlow) via standard primary image ports so downstream |
| 1144 | // graphs stay live without mistaking auxiliary sprite/material ports (like pEmitter's |
| 1145 | // ParticleStyleBitmap.DropToolsHere) for a full-frame passthrough. |
| 1146 | if !stats.unsupported_nodes.iter().any(|s| s == other) { |
| 1147 | stats.unsupported_nodes.push(other.to_owned()); |
| 1148 | } |
| 1149 | let port = default_main_input_port(other); |
| 1150 | let primary_src = node |
| 1151 | .connected_node(port) |
| 1152 | .or_else(|| node.connected_node("Input")) |
| 1153 | .or_else(|| node.connected_node("Source")) |
| 1154 | .or_else(|| node.connected_node("MainInput1")) |
| 1155 | .or_else(|| node.connected_node("Image")) |
| 1156 | .or_else(|| node.connected_node("Image1")) |
| 1157 | .or_else(|| node.connected_node("Background")) |
| 1158 | .and_then(|s| comp.find_node(s)); |
| 1159 | if let Some(src_id) = primary_src { |
| 1160 | self.eval_node(comp, src_id, time, enc, visiting, stats) |
| 1161 | } else { |
| 1162 | self.dummy.clone() |
| 1163 | } |
| 1164 | } |
| 1165 | } |
| 1166 | } |
| 1167 | |
| 1168 | /// The node's `EffectMask` after its `MaskChannel` selection and `MaskLow`/`MaskHigh` remap, |
| 1169 | /// pooled and cached; identity settings skip the remap pass. |
| 1170 | #[allow(clippy::too_many_arguments)] |
| 1171 | fn eval_mask_input_sized( |
| 1172 | &mut self, |
| 1173 | comp: &Comp, |
| 1174 | node: &Node, |
| 1175 | time: f64, |
| 1176 | target_size: Option<[u32; 2]>, |
| 1177 | enc: &mut wgpu::CommandEncoder, |
| 1178 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1179 | stats: &mut EvalStats, |
| 1180 | ) -> (Option<CachedTexture>, bool) { |
| 1181 | let invert = comp.eval_number(node, "ApplyMaskInverted", time, 0.0, &self.expr) > 0.5; |
| 1182 | let prev_sz = self.mask_target_size; |
| 1183 | if target_size.is_some() { |
| 1184 | self.mask_target_size = target_size; |
| 1185 | } |
| 1186 | let tex = Self::resolve_effect_mask_id(comp, node).map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats)); |
| 1187 | self.mask_target_size = prev_sz; |
| 1188 | let Some(m) = &tex else { |
| 1189 | return (None, invert); |
| 1190 | }; |
| 1191 | |
| 1192 | let channel = comp.eval_number(node, "MaskChannel", time, 3.0, &self.expr).round().clamp(0.0, 7.0) as usize; |
| 1193 | let low = comp.eval_number(node, "MaskLow", time, 0.0, &self.expr) as f32; |
| 1194 | let high = comp.eval_number(node, "MaskHigh", time, 1.0, &self.expr) as f32; |
| 1195 | if channel == 3 && low == 0.0 && high == 1.0 { |
| 1196 | return (tex, invert); |
| 1197 | } |
| 1198 | // Red, Green, Blue, Alpha, Hue, Luminance, Saturation, Coverage as `BitmapMask` channel ids. |
| 1199 | let bitmap_channel: f32 = [2.0, 3.0, 4.0, 0.0, 7.0, 1.0, 5.0, 8.0][channel]; |
| 1200 | let frame_i = time.round() as i64; |
| 1201 | let key = self.make_key(node, "MaskLevels", m.size, &[m.content_hash], bytemuck::cast_slice(&[bitmap_channel, low, high])); |
| 1202 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1203 | return (Some(hit), invert); |
| 1204 | } |
| 1205 | let out = self.alloc_tex(m.size, m.depth, key); |
| 1206 | let mut u = UniformParams::default(); |
| 1207 | u.p[0] = [bitmap_channel, low, high, 1.0]; |
| 1208 | self.dispatch_op(enc, ShaderOp::BitmapMask, &m.view, &self.dummy.view, &self.dummy.view, &out, &u); |
| 1209 | self.cache.insert(key, out.clone(), node.id, frame_i); |
| 1210 | (Some(out), invert) |
| 1211 | } |
| 1212 | |
| 1213 | /// Computes the remapped source time for `TimeStretcher` or `TimeSpeed`. |
| 1214 | pub(super) fn remap_time_node(&self, comp: &Comp, node: &Node, time: f64) -> Option<f64> { |
| 1215 | match node.kind.as_str() { |
| 1216 | "TimeStretcher" => Some(comp.eval_number(node, "SourceTime", time, 0.0, &self.expr)), |
| 1217 | "TimeSpeed" => { |
| 1218 | let speed = comp.eval_number(node, "Speed", time, 1.0, &self.expr); |
| 1219 | let delay = comp.eval_number(node, "Delay", time, 0.0, &self.expr); |
| 1220 | let g_start = comp.global_range[0] as f64; |
| 1221 | let g_end = comp.global_range[1] as f64; |
| 1222 | let raw = if speed < 0.0 { |
| 1223 | // Fusion plays negative-speed clips backward from (GlobalEnd + 1) anchored at GlobalStart. |
| 1224 | ((g_end + 1.0) + (time - delay - g_start) * speed).min(g_end) |
| 1225 | } else { |
| 1226 | g_start + (time - delay - g_start) * speed |
| 1227 | }; |
| 1228 | Some(raw) |
| 1229 | } |
| 1230 | _ => None, |
| 1231 | } |
| 1232 | } |
| 1233 | |
| 1234 | #[allow(clippy::too_many_arguments)] |
| 1235 | fn eval_time_remapped( |
| 1236 | &mut self, |
| 1237 | comp: &Comp, |
| 1238 | node: &Node, |
| 1239 | time: f64, |
| 1240 | frame_i: i64, |
| 1241 | remapped: f64, |
| 1242 | enc: &mut wgpu::CommandEncoder, |
| 1243 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1244 | stats: &mut EvalStats, |
| 1245 | ) -> CachedTexture { |
| 1246 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 1247 | return self.dummy.clone(); |
| 1248 | }; |
| 1249 | let interp = comp |
| 1250 | .eval_number(node, "InterpolateBetweenFrames", time, 1.0, &self.expr) |
| 1251 | .round() as i32; |
| 1252 | if interp <= 0 { |
| 1253 | let snapped = (remapped + 0.5).floor(); |
| 1254 | return self.eval_node(comp, src_id, snapped, enc, visiting, stats); |
| 1255 | } |
| 1256 | let f0 = remapped.floor(); |
| 1257 | let frac = (remapped - f0) as f32; |
| 1258 | if frac > 1e-3 && frac < 1.0 - 1e-3 { |
| 1259 | let src_node = comp.node(src_id); |
| 1260 | let has_optflow = matches!(src_node.kind.as_str(), "Dimension.OpticalFlow" | "OpticalFlow"); |
| 1261 | let eval_src_id = if has_optflow { |
| 1262 | src_node |
| 1263 | .connected_node("Input") |
| 1264 | .and_then(|s| comp.find_node(s)) |
| 1265 | .unwrap_or(src_id) |
| 1266 | } else { |
| 1267 | src_id |
| 1268 | }; |
| 1269 | let tex_a = self.eval_node(comp, eval_src_id, f0, enc, visiting, stats); |
| 1270 | let tex_b = self.eval_node(comp, eval_src_id, f0 + 1.0, enc, visiting, stats); |
| 1271 | let use_flow = interp == 2 && (has_optflow || self.hiq); |
| 1272 | let dst_depth = self.node_depth(comp, node, time, Some(tex_a.depth.max(tex_b.depth))); |
| 1273 | let mut h = DefaultHasher::new(); |
| 1274 | self.cache.gpu_salt.hash(&mut h); |
| 1275 | self.cache.node_salt(node.id).hash(&mut h); |
| 1276 | "TimeRemapInterp".hash(&mut h); |
| 1277 | use_flow.hash(&mut h); |
| 1278 | tex_a.content_hash.hash(&mut h); |
| 1279 | tex_b.content_hash.hash(&mut h); |
| 1280 | ((frac * 1000.0).round() as i32).hash(&mut h); |
| 1281 | dst_depth.hash(&mut h); |
| 1282 | let key = h.finish(); |
| 1283 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1284 | stats.cache_hits += 1; |
| 1285 | return hit; |
| 1286 | } |
| 1287 | stats.cache_misses += 1; |
| 1288 | stats.nodes_evaluated += 1; |
| 1289 | let fmt = self.texture_format_for(self.effective_depth(dst_depth)); |
| 1290 | let optflow = self.optflow.get_or_init(|| crate::optflow::OpticalFlowPipelines::new(&self.device)); |
| 1291 | let mut out = if use_flow { |
| 1292 | optflow.interpolate_flow(&self.device, &self.queue, enc, &tex_a, &tex_b, frac, fmt) |
| 1293 | } else { |
| 1294 | optflow.blend_frames(&self.device, &self.queue, enc, &tex_a, &tex_b, frac, fmt) |
| 1295 | }; |
| 1296 | out.depth = self.effective_depth(dst_depth); |
| 1297 | out.content_hash = key; |
| 1298 | self.cache.insert(key, out.clone(), node.id, frame_i); |
| 1299 | return out; |
| 1300 | } |
| 1301 | self.eval_node(comp, src_id, remapped, enc, visiting, stats) |
| 1302 | } |
| 1303 | |
| 1304 | fn parse_surface_apply_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> f32 { |
| 1305 | let mode_str = node |
| 1306 | .static_str("OverlayCompositeMode") |
| 1307 | .or_else(|| node.static_str("CompositeMode")) |
| 1308 | .or_else(|| node.static_str("ApplyMode")); |
| 1309 | if let Some(s) = mode_str { |
| 1310 | return match s { |
| 1311 | "Screen" => 1.0, |
| 1312 | "Multiply" => 2.0, |
| 1313 | "Overlay" => 3.0, |
| 1314 | "SoftLight" | "Soft Light" => 4.0, |
| 1315 | "HardLight" | "Hard Light" => 5.0, |
| 1316 | "ColorDodge" | "Color Dodge" => 6.0, |
| 1317 | "Darken" => 7.0, |
| 1318 | "Lighten" => 8.0, |
| 1319 | "Difference" => 9.0, |
| 1320 | "Exclusion" => 10.0, |
| 1321 | "Add" | "LinearDodge" | "Linear Dodge" => 11.0, |
| 1322 | _ => 0.0, |
| 1323 | }; |
| 1324 | } |
| 1325 | let n = comp |
| 1326 | .eval_number(node, "OverlayCompositeMode", time, 0.0, expr) |
| 1327 | .round() as i32; |
| 1328 | match n { |
| 1329 | 1 => 1.0, |
| 1330 | 2 => 2.0, |
| 1331 | 3 => 3.0, |
| 1332 | 4 => 4.0, |
| 1333 | 5 => 5.0, |
| 1334 | _ => 0.0, |
| 1335 | } |
| 1336 | } |
| 1337 | |
| 1338 | #[allow(clippy::too_many_arguments)] |
| 1339 | fn eval_surface_tracker( |
| 1340 | &mut self, |
| 1341 | comp: &Comp, |
| 1342 | node: &Node, |
| 1343 | time: f64, |
| 1344 | frame_i: i64, |
| 1345 | enc: &mut wgpu::CommandEncoder, |
| 1346 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1347 | stats: &mut EvalStats, |
| 1348 | ) -> CachedTexture { |
| 1349 | let Some(bg_id) = node |
| 1350 | .connected_node("Input") |
| 1351 | .or_else(|| node.connected_node("Background")) |
| 1352 | .and_then(|s| comp.find_node(s)) |
| 1353 | else { |
| 1354 | return self.dummy.clone(); |
| 1355 | }; |
| 1356 | let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats); |
| 1357 | |
| 1358 | let stage = comp |
| 1359 | .eval_number(node, "ProcessStage", time, 2.0, &self.expr) |
| 1360 | .round() as i32; |
| 1361 | if stage < 2 { |
| 1362 | return bg; |
| 1363 | } |
| 1364 | |
| 1365 | let Some(overlay_id) = node |
| 1366 | .connected_node("Overlay") |
| 1367 | .or_else(|| node.connected_node("Foreground")) |
| 1368 | .and_then(|s| comp.find_node(s)) |
| 1369 | else { |
| 1370 | return bg; |
| 1371 | }; |
| 1372 | |
| 1373 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 1374 | let opacity = comp.eval_number(node, "OverlayOpacity", time, 1.0, &self.expr) as f32; |
| 1375 | let eff_blend = (blend * opacity).clamp(0.0, 1.0); |
| 1376 | if eff_blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { |
| 1377 | return bg; |
| 1378 | } |
| 1379 | |
| 1380 | let explicit_ref = node |
| 1381 | .inputs |
| 1382 | .contains_key("ReferenceFrame") |
| 1383 | .then(|| comp.eval_number(node, "ReferenceFrame", time, 0.0, &self.expr)); |
| 1384 | let Some((ref_mesh, cur_mesh, ref_frame)) = |
| 1385 | crate::tracker::eval_surface_mesh(comp, node, time, explicit_ref) |
| 1386 | else { |
| 1387 | return bg; |
| 1388 | }; |
| 1389 | |
| 1390 | let overlay_time = match node.static_str("OverlaySource") { |
| 1391 | Some("OverlayFrameRef" | "OverlayFrameReference") => ref_frame, |
| 1392 | Some("OverlayFrameCurrent" | "OverlayFrameFirst") => time, |
| 1393 | _ => time, |
| 1394 | }; |
| 1395 | let overlay = self.eval_node(comp, overlay_id, overlay_time, enc, visiting, stats); |
| 1396 | let bg = self.crop_to_canvas(enc, bg); |
| 1397 | let overlay = self.crop_to_canvas(enc, overlay); |
| 1398 | |
| 1399 | let placement = comp |
| 1400 | .eval_number(node, "OverlayPlacement", time, 1.0, &self.expr) |
| 1401 | .round() as i32; |
| 1402 | let corners = if placement == 0 { |
| 1403 | crate::tracker::extract_warpable_canvas_corners(node) |
| 1404 | .unwrap_or([[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) |
| 1405 | } else { |
| 1406 | crate::tracker::extract_warpable_canvas_corners(node) |
| 1407 | .unwrap_or([[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) |
| 1408 | }; |
| 1409 | let h_inv = crate::tracker::quad_to_unit_homography( |
| 1410 | corners[0], |
| 1411 | corners[1], |
| 1412 | corners[2], |
| 1413 | corners[3], |
| 1414 | ); |
| 1415 | |
| 1416 | let photo_strength = if node.inputs.contains_key("LightingWeight") { |
| 1417 | comp.eval_number(node, "LightingWeight", time, 0.0, &self.expr) as f32 |
| 1418 | } else if node.inputs.contains_key("MatchLighting") { |
| 1419 | comp.eval_number(node, "MatchLighting", time, 0.0, &self.expr) as f32 |
| 1420 | } else { |
| 1421 | 0.0 |
| 1422 | } |
| 1423 | .clamp(0.0, 1.0); |
| 1424 | |
| 1425 | let apply_mode = Self::parse_surface_apply_mode(comp, node, time, &self.expr); |
| 1426 | let (mask, mask_inv) = |
| 1427 | self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); |
| 1428 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 1429 | let mbm = mask.is_some() |
| 1430 | && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; |
| 1431 | let dst_depth = self.node_depth(comp, node, time, Some(bg.depth.max(overlay.depth))); |
| 1432 | |
| 1433 | let ref_hash = ref_mesh.content_hash(); |
| 1434 | let cur_hash = cur_mesh.content_hash(); |
| 1435 | let params_f32: [f32; 14] = [ |
| 1436 | h_inv[0] as f32, |
| 1437 | h_inv[1] as f32, |
| 1438 | h_inv[2] as f32, |
| 1439 | h_inv[3] as f32, |
| 1440 | h_inv[4] as f32, |
| 1441 | h_inv[5] as f32, |
| 1442 | h_inv[6] as f32, |
| 1443 | h_inv[7] as f32, |
| 1444 | h_inv[8] as f32, |
| 1445 | eff_blend, |
| 1446 | apply_mode, |
| 1447 | photo_strength, |
| 1448 | if mask_inv { 1.0 } else { 0.0 }, |
| 1449 | if mbm { 1.0 } else { 0.0 }, |
| 1450 | ]; |
| 1451 | let key = self.make_key( |
| 1452 | node, |
| 1453 | "SurfaceTracker", |
| 1454 | bg.size, |
| 1455 | &[bg.content_hash, overlay.content_hash, mask_hash, ref_hash, cur_hash], |
| 1456 | &params_f32, |
| 1457 | ); |
| 1458 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1459 | stats.cache_hits += 1; |
| 1460 | return hit; |
| 1461 | } |
| 1462 | stats.cache_misses += 1; |
| 1463 | stats.nodes_evaluated += 1; |
| 1464 | |
| 1465 | // WebGPU safety: render mesh exclusively into Rgba8Unorm or Rgba16Float (never Rgba32Float). |
| 1466 | let render_depth = match self.effective_depth(dst_depth) { |
| 1467 | BitDepth::Int8 => BitDepth::Int8, |
| 1468 | _ => BitDepth::Float16, |
| 1469 | }; |
| 1470 | let warped = self.alloc_tex(bg.size, render_depth, key ^ 0x57A1_7EAC); |
| 1471 | let tracker = self |
| 1472 | .tracker |
| 1473 | .get_or_init(|| crate::tracker::TrackerPipelines::new(&self.device)); |
| 1474 | tracker.render_surface_mesh( |
| 1475 | &self.device, |
| 1476 | enc, |
| 1477 | &overlay.view, |
| 1478 | &warped.view, |
| 1479 | warped.format, |
| 1480 | &ref_mesh, |
| 1481 | &cur_mesh, |
| 1482 | h_inv, |
| 1483 | photo_strength, |
| 1484 | ); |
| 1485 | |
| 1486 | let dst = self.alloc_tex(bg.size, dst_depth, key); |
| 1487 | let mut u = UniformParams::default(); |
| 1488 | u.p[0] = [0.5, 0.5, 1.0, 0.0]; |
| 1489 | u.p[1] = [eff_blend, 1.0, apply_mode, 0.0]; |
| 1490 | u.p[2] = [0.0, 0.0, 0.0, 0.0]; |
| 1491 | u.p[3] = [ |
| 1492 | if mask.is_some() { 1.0 } else { 0.0 }, |
| 1493 | if mask_inv { 1.0 } else { 0.0 }, |
| 1494 | bg.size[0] as f32, |
| 1495 | bg.size[1] as f32, |
| 1496 | ]; |
| 1497 | u.p[6] = [0.0, 1.0, 0.0, 0.0]; |
| 1498 | u.p[7] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; |
| 1499 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 1500 | self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &warped.view, mv, &dst, &u); |
| 1501 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1502 | dst |
| 1503 | } |
| 1504 | |
| 1505 | #[allow(clippy::too_many_arguments)] |
| 1506 | fn dispatch_planar_homography( |
| 1507 | &mut self, |
| 1508 | comp: &Comp, |
| 1509 | node: &Node, |
| 1510 | tag: &str, |
| 1511 | src: &CachedTexture, |
| 1512 | dst_size: [u32; 2], |
| 1513 | dst_depth: BitDepth, |
| 1514 | h_inv: [f64; 9], |
| 1515 | blend: f32, |
| 1516 | mask: Option<&CachedTexture>, |
| 1517 | mask_inv: bool, |
| 1518 | mbm: bool, |
| 1519 | time: f64, |
| 1520 | frame_i: i64, |
| 1521 | enc: &mut wgpu::CommandEncoder, |
| 1522 | stats: &mut EvalStats, |
| 1523 | ) -> CachedTexture { |
| 1524 | let mask_hash = mask.map_or(0, |m| m.content_hash); |
| 1525 | let mut u = UniformParams::default(); |
| 1526 | u.p[0] = [h_inv[0] as f32, h_inv[1] as f32, h_inv[2] as f32, h_inv[3] as f32]; |
| 1527 | u.p[1] = [h_inv[4] as f32, h_inv[5] as f32, h_inv[6] as f32, h_inv[7] as f32]; |
| 1528 | u.p[2] = [ |
| 1529 | h_inv[8] as f32, |
| 1530 | blend, |
| 1531 | if mask.is_some() { 1.0 } else { 0.0 }, |
| 1532 | if mask_inv { 1.0 } else { 0.0 }, |
| 1533 | ]; |
| 1534 | u.p[3][1] = if mbm { 1.0 } else { 0.0 }; |
| 1535 | if src.size != dst_size { |
| 1536 | u.p[4] = [0.0, 0.0, dst_size[0] as f32, dst_size[1] as f32]; |
| 1537 | } |
| 1538 | u.p[5] = self.process_skip(comp, node, time); |
| 1539 | let key = self.make_key( |
| 1540 | node, |
| 1541 | tag, |
| 1542 | dst_size, |
| 1543 | &[src.content_hash, mask_hash], |
| 1544 | bytemuck::cast_slice(&u.p[..6]), |
| 1545 | ); |
| 1546 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1547 | stats.cache_hits += 1; |
| 1548 | return hit; |
| 1549 | } |
| 1550 | stats.cache_misses += 1; |
| 1551 | stats.nodes_evaluated += 1; |
| 1552 | let dst = self.alloc_tex(dst_size, dst_depth, key); |
| 1553 | let mv = mask.map_or(&self.dummy.view, |m| &m.view); |
| 1554 | self.dispatch_op(enc, ShaderOp::Homography, &src.view, &self.dummy.view, mv, &dst, &u); |
| 1555 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1556 | dst |
| 1557 | } |
| 1558 | |
| 1559 | #[allow(clippy::too_many_arguments)] |
| 1560 | fn eval_planar_transform( |
| 1561 | &mut self, |
| 1562 | comp: &Comp, |
| 1563 | node: &Node, |
| 1564 | time: f64, |
| 1565 | frame_i: i64, |
| 1566 | enc: &mut wgpu::CommandEncoder, |
| 1567 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1568 | stats: &mut EvalStats, |
| 1569 | ) -> CachedTexture { |
| 1570 | let Some(src_id) = node |
| 1571 | .connected_node("Input") |
| 1572 | .or_else(|| node.connected_node("Background")) |
| 1573 | .and_then(|s| comp.find_node(s)) |
| 1574 | else { |
| 1575 | return self.dummy.clone(); |
| 1576 | }; |
| 1577 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 1578 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 1579 | if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { |
| 1580 | return src; |
| 1581 | } |
| 1582 | let Some(track) = crate::tracker::eval_planar_track(comp, node, "Track", time) else { |
| 1583 | return src; |
| 1584 | }; |
| 1585 | let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) >= 0.5; |
| 1586 | let h_inv = if invert { |
| 1587 | crate::tracker::mat3_invert(&track.to_ref_3x3).unwrap_or(track.to_ref_3x3) |
| 1588 | } else { |
| 1589 | track.to_ref_3x3 |
| 1590 | }; |
| 1591 | let src = self.crop_to_canvas(enc, src); |
| 1592 | let (mask, mask_inv) = |
| 1593 | self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 1594 | let mbm = mask.is_some() |
| 1595 | && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; |
| 1596 | let dst_depth = self.node_depth(comp, node, time, Some(src.depth)); |
| 1597 | self.dispatch_planar_homography( |
| 1598 | comp, |
| 1599 | node, |
| 1600 | "PlanarTransform", |
| 1601 | &src, |
| 1602 | src.size, |
| 1603 | dst_depth, |
| 1604 | h_inv, |
| 1605 | blend, |
| 1606 | mask.as_ref(), |
| 1607 | mask_inv, |
| 1608 | mbm, |
| 1609 | time, |
| 1610 | frame_i, |
| 1611 | enc, |
| 1612 | stats, |
| 1613 | ) |
| 1614 | } |
| 1615 | |
| 1616 | #[allow(clippy::too_many_arguments)] |
| 1617 | fn eval_planar_tracker( |
| 1618 | &mut self, |
| 1619 | comp: &Comp, |
| 1620 | node: &Node, |
| 1621 | time: f64, |
| 1622 | frame_i: i64, |
| 1623 | enc: &mut wgpu::CommandEncoder, |
| 1624 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1625 | stats: &mut EvalStats, |
| 1626 | ) -> CachedTexture { |
| 1627 | let Some(bg_id) = node |
| 1628 | .connected_node("Background") |
| 1629 | .or_else(|| node.connected_node("Input")) |
| 1630 | .and_then(|s| comp.find_node(s)) |
| 1631 | else { |
| 1632 | return self.dummy.clone(); |
| 1633 | }; |
| 1634 | let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats); |
| 1635 | |
| 1636 | // OperationMode: "Track"/0 = passthrough, "CornerPin"/1, "Steady"/2, "Stabilize"/3. |
| 1637 | let op_mode = match node.static_str("OperationMode") { |
| 1638 | Some("CornerPin") => 1, |
| 1639 | Some("Steady") => 2, |
| 1640 | Some("Stabilize") => 3, |
| 1641 | Some(_) => 0, |
| 1642 | None => comp |
| 1643 | .eval_number(node, "OperationMode", time, 0.0, &self.expr) |
| 1644 | .round() as i32, |
| 1645 | }; |
| 1646 | if op_mode == 0 { |
| 1647 | return bg; |
| 1648 | } |
| 1649 | |
| 1650 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 1651 | if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { |
| 1652 | return bg; |
| 1653 | } |
| 1654 | |
| 1655 | if op_mode == 2 || op_mode == 3 { |
| 1656 | // Steady (2) warps Background by inv(ToRef) to lock the plane to RefTime. |
| 1657 | // Stabilize (3) uses StableTrack if valid, falling back to inv(Track.ToRef). |
| 1658 | let mat = if op_mode == 3 { |
| 1659 | crate::tracker::eval_planar_track(comp, node, "StableTrack", time) |
| 1660 | .or_else(|| crate::tracker::eval_planar_track(comp, node, "Track", time)) |
| 1661 | } else { |
| 1662 | crate::tracker::eval_planar_track(comp, node, "Track", time) |
| 1663 | }; |
| 1664 | let Some(track) = mat else { |
| 1665 | return bg; |
| 1666 | }; |
| 1667 | let Some(h_inv) = crate::tracker::mat3_invert(&track.to_ref_3x3) else { |
| 1668 | return bg; |
| 1669 | }; |
| 1670 | let bg = self.crop_to_canvas(enc, bg); |
| 1671 | let (mask, mask_inv) = |
| 1672 | self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); |
| 1673 | let mbm = mask.is_some() |
| 1674 | && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; |
| 1675 | let dst_depth = self.node_depth(comp, node, time, Some(bg.depth)); |
| 1676 | let tag = if op_mode == 3 { "PlanarStabilize" } else { "PlanarSteady" }; |
| 1677 | return self.dispatch_planar_homography( |
| 1678 | comp, |
| 1679 | node, |
| 1680 | tag, |
| 1681 | &bg, |
| 1682 | bg.size, |
| 1683 | dst_depth, |
| 1684 | h_inv, |
| 1685 | blend, |
| 1686 | mask.as_ref(), |
| 1687 | mask_inv, |
| 1688 | mbm, |
| 1689 | time, |
| 1690 | frame_i, |
| 1691 | enc, |
| 1692 | stats, |
| 1693 | ); |
| 1694 | } |
| 1695 | |
| 1696 | // CornerPin (1): warp CornerPin1 / Foreground via CornerPin quad + ToRef over Background. |
| 1697 | let Some(fg_id) = node |
| 1698 | .connected_node("CornerPin1") |
| 1699 | .or_else(|| node.connected_node("Foreground")) |
| 1700 | .or_else(|| node.connected_node("CornerPin")) |
| 1701 | .and_then(|s| comp.find_node(s)) |
| 1702 | else { |
| 1703 | return bg; |
| 1704 | }; |
| 1705 | let fg = self.eval_node(comp, fg_id, time, enc, visiting, stats); |
| 1706 | let bg = self.crop_to_canvas(enc, bg); |
| 1707 | let fg = self.crop_to_canvas(enc, fg); |
| 1708 | |
| 1709 | let read_corner = |primary: &str, alt: &str, default: [f64; 2]| -> [f64; 2] { |
| 1710 | if node.inputs.contains_key(primary) { |
| 1711 | comp.eval_point(node, primary, time, default, &self.expr) |
| 1712 | } else { |
| 1713 | comp.eval_point(node, alt, time, default, &self.expr) |
| 1714 | } |
| 1715 | }; |
| 1716 | let bl = read_corner("CornerPinBottomLeft", "BottomLeft", [0.0, 0.0]); |
| 1717 | let br = read_corner("CornerPinBottomRight", "BottomRight", [1.0, 0.0]); |
| 1718 | let tr = read_corner("CornerPinTopRight", "TopRight", [1.0, 1.0]); |
| 1719 | let tl = read_corner("CornerPinTopLeft", "TopLeft", [0.0, 1.0]); |
| 1720 | let h_pin_inv = crate::tracker::quad_to_unit_homography(tl, tr, br, bl); |
| 1721 | let h_to_ref = crate::tracker::eval_planar_track(comp, node, "Track", time) |
| 1722 | .map_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |m| m.to_ref_3x3); |
| 1723 | let h_combined = crate::tracker::mat3_mul(&h_pin_inv, &h_to_ref); |
| 1724 | |
| 1725 | let dst_depth = self.node_depth(comp, node, time, Some(bg.depth.max(fg.depth))); |
| 1726 | let warped_fg = self.dispatch_planar_homography( |
| 1727 | comp, |
| 1728 | node, |
| 1729 | "PlanarCornerPinWarp", |
| 1730 | &fg, |
| 1731 | bg.size, |
| 1732 | dst_depth, |
| 1733 | h_combined, |
| 1734 | 1.0, |
| 1735 | None, |
| 1736 | false, |
| 1737 | false, |
| 1738 | time, |
| 1739 | frame_i, |
| 1740 | enc, |
| 1741 | stats, |
| 1742 | ); |
| 1743 | |
| 1744 | let (mask, mask_inv) = |
| 1745 | self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); |
| 1746 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 1747 | let mbm = mask.is_some() |
| 1748 | && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; |
| 1749 | let key = self.make_key( |
| 1750 | node, |
| 1751 | "PlanarCornerPinComp", |
| 1752 | bg.size, |
| 1753 | &[bg.content_hash, warped_fg.content_hash, mask_hash], |
| 1754 | &[blend, if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }], |
| 1755 | ); |
| 1756 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1757 | stats.cache_hits += 1; |
| 1758 | return hit; |
| 1759 | } |
| 1760 | stats.cache_misses += 1; |
| 1761 | let dst = self.alloc_tex(bg.size, dst_depth, key); |
| 1762 | let mut u = UniformParams::default(); |
| 1763 | u.p[0] = [0.5, 0.5, 1.0, 0.0]; |
| 1764 | u.p[1] = [blend, 1.0, 0.0, 0.0]; |
| 1765 | u.p[2] = [0.0, 0.0, 0.0, 0.0]; |
| 1766 | u.p[3] = [ |
| 1767 | if mask.is_some() { 1.0 } else { 0.0 }, |
| 1768 | if mask_inv { 1.0 } else { 0.0 }, |
| 1769 | bg.size[0] as f32, |
| 1770 | bg.size[1] as f32, |
| 1771 | ]; |
| 1772 | u.p[6] = [0.0, 1.0, 0.0, 0.0]; |
| 1773 | u.p[7] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; |
| 1774 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 1775 | self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &warped_fg.view, mv, &dst, &u); |
| 1776 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1777 | dst |
| 1778 | } |
| 1779 | |
| 1780 | #[allow(clippy::too_many_arguments)] |
| 1781 | fn eval_auto_matte( |
| 1782 | &mut self, |
| 1783 | comp: &Comp, |
| 1784 | node: &Node, |
| 1785 | time: f64, |
| 1786 | frame_i: i64, |
| 1787 | is_magic_mask: bool, |
| 1788 | enc: &mut wgpu::CommandEncoder, |
| 1789 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1790 | stats: &mut EvalStats, |
| 1791 | ) -> CachedTexture { |
| 1792 | let primary_src = node |
| 1793 | .connected_node("Input") |
| 1794 | .or_else(|| node.connected_node("Image")) |
| 1795 | .or_else(|| node.connected_node("Source")) |
| 1796 | .or_else(|| node.connected_node("Background")) |
| 1797 | .and_then(|s| comp.find_node(s)); |
| 1798 | let Some(src_id) = primary_src else { |
| 1799 | return self.dummy.clone(); |
| 1800 | }; |
| 1801 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 1802 | let params = if is_magic_mask { |
| 1803 | crate::auto_matte::extract_magic_mask_params(comp, node, time, &self.expr) |
| 1804 | } else { |
| 1805 | crate::auto_matte::extract_auto_matte_params(comp, node, time, &self.expr) |
| 1806 | }; |
| 1807 | let mbm = self.multiplies_by_mask(comp, node, time); |
| 1808 | if params.blend <= 1e-6 && !mbm { |
| 1809 | return src; |
| 1810 | } |
| 1811 | let cached_matte = self.auto_matte_cache.get_or_load_frame( |
| 1812 | &node.name, |
| 1813 | frame_i, |
| 1814 | params.cache_dir.as_deref(), |
| 1815 | ); |
| 1816 | // Empty MagicMask / AutoMatte (no strokes/points & no cached neural matte) passes through |
| 1817 | // foreground cleanly with 0.00% MAE regression. |
| 1818 | if cached_matte.is_none() && params.effective_gpu_seeds().is_empty() { |
| 1819 | return src; |
| 1820 | } |
| 1821 | |
| 1822 | let src = self.crop_to_canvas(enc, src); |
| 1823 | let (mask, mask_inv) = |
| 1824 | self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 1825 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 1826 | let matte_hash = cached_matte.as_ref().map_or(0, |m| m.content_hash); |
| 1827 | let skip = self.process_skip(comp, node, time); |
| 1828 | |
| 1829 | let mut ph = DefaultHasher::new(); |
| 1830 | params.hash_into(&mut ph); |
| 1831 | self.proxy_scale.hash(&mut ph); |
| 1832 | mask_inv.hash(&mut ph); |
| 1833 | mbm.hash(&mut ph); |
| 1834 | for s in skip { |
| 1835 | s.to_bits().hash(&mut ph); |
| 1836 | } |
| 1837 | let param_hash = ph.finish(); |
| 1838 | let key = self.make_key( |
| 1839 | node, |
| 1840 | if is_magic_mask { "MagicMask" } else { "AutoMatte" }, |
| 1841 | src.size, |
| 1842 | &[src.content_hash, mask_hash, matte_hash, param_hash], |
| 1843 | &[], |
| 1844 | ); |
| 1845 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1846 | stats.cache_hits += 1; |
| 1847 | return hit; |
| 1848 | } |
| 1849 | stats.cache_misses += 1; |
| 1850 | stats.nodes_evaluated += 1; |
| 1851 | |
| 1852 | let dst = self.alloc_tex(src.size, src.depth, key); |
| 1853 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 1854 | let pipelines = self |
| 1855 | .auto_matte_pipelines |
| 1856 | .get_or_init(|| RefCell::new(crate::auto_matte::AutoMattePipelines::new(&self.device))); |
| 1857 | pipelines.borrow_mut().execute( |
| 1858 | &self.device, |
| 1859 | &self.queue, |
| 1860 | enc, |
| 1861 | &self.cache, |
| 1862 | &self.dummy.view, |
| 1863 | &src, |
| 1864 | mv, |
| 1865 | mask.is_some(), |
| 1866 | mask_inv, |
| 1867 | mbm, |
| 1868 | skip, |
| 1869 | &dst, |
| 1870 | &params, |
| 1871 | cached_matte.as_deref(), |
| 1872 | self.proxy_scale, |
| 1873 | ); |
| 1874 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1875 | dst |
| 1876 | } |
| 1877 | |
| 1878 | fn make_key(&self, node: &Node, tag: &str, size: [u32; 2], upstream: &[u64], params: &[f32]) -> u64 { |
| 1879 | let mut h = DefaultHasher::new(); |
| 1880 | self.cache.gpu_salt.hash(&mut h); |
| 1881 | self.hiq.hash(&mut h); |
| 1882 | self.cache.node_salt(node.id).hash(&mut h); |
| 1883 | tag.hash(&mut h); |
| 1884 | size.hash(&mut h); |
| 1885 | upstream.hash(&mut h); |
| 1886 | for &v in params { |
| 1887 | v.to_bits().hash(&mut h); |
| 1888 | } |
| 1889 | h.finish() |
| 1890 | } |
| 1891 | } |
| 1892 | |
| 1893 | #[cfg(test)] |
| 1894 | mod lazy_shader_verify { |
| 1895 | use super::*; |
| 1896 | |
| 1897 | #[test] |
| 1898 | fn verify_all_43_shader_ops_compile() { |
| 1899 | let eng = Engine::new_headless().expect("gpu"); |
| 1900 | let all_ops = [ |
| 1901 | ShaderOp::Bg, ShaderOp::Merge, ShaderOp::Transform, ShaderOp::Bc, ShaderOp::Cc, |
| 1902 | ShaderOp::ColorGain, ShaderOp::LumaKey, ShaderOp::Blur, ShaderOp::DirBlur, |
| 1903 | ShaderOp::FastNoise, ShaderOp::Displace, ShaderOp::MaskShape, ShaderOp::MaskCombine, |
| 1904 | ShaderOp::MaskApply, ShaderOp::BitmapMask, ShaderOp::Colorize, ShaderOp::ColorCurves, |
| 1905 | ShaderOp::XfChroma, ShaderOp::GamutConvert, ShaderOp::VariBlur, ShaderOp::OutlineTint, |
| 1906 | ShaderOp::OutlineComposite, ShaderOp::CustomWave, ShaderOp::Crop, |
| 1907 | ShaderOp::GlowAdd, ShaderOp::XGlowPrep, ShaderOp::XGlowAccum, ShaderOp::DisplayBlit, |
| 1908 | ShaderOp::Invert, ShaderOp::ChannelBoolean, ShaderOp::Filter, ShaderOp::HueCurves, |
| 1909 | ShaderOp::UltraKeyer, ShaderOp::Dissolve, ShaderOp::Homography, ShaderOp::ShadowComp, |
| 1910 | ShaderOp::Plasma, ShaderOp::FilmGrain, ShaderOp::SetDomain, ShaderOp::ChangeDepth, |
| 1911 | ShaderOp::Vortex, ShaderOp::KScope, ShaderOp::Drip, ShaderOp::Dent, |
| 1912 | ShaderOp::PerspectivePos, ShaderOp::DaySky, ShaderOp::GridWarp, ShaderOp::CheckerPiece, |
| 1913 | ShaderOp::AlphaWeightedNoise, ShaderOp::Crystallize, ShaderOp::HexagonTiles, ShaderOp::RemoveNoise, ShaderOp::DeltaKeyer, |
| 1914 | ]; |
| 1915 | // Verify starts completely empty (lazy!) |
| 1916 | assert_eq!(eng.pipelines.borrow().modules.len(), 0); |
| 1917 | assert_eq!(eng.pipelines.borrow().pipelines.len(), 0); |
| 1918 | for op in all_ops { |
| 1919 | eng.pipelines.borrow_mut().ensure_pipeline(&eng.device, op); |
| 1920 | eng.pipelines_for(BitDepth::Float16).borrow_mut().ensure_pipeline(&eng.device, op); |
| 1921 | } |
| 1922 | assert_eq!(eng.pipelines.borrow().modules.len(), 7); |
| 1923 | assert_eq!(eng.pipelines.borrow().pipelines.len(), 53); |
| 1924 | assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().modules.len(), 7); |
| 1925 | assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().pipelines.len(), 53); |
| 1926 | } |
| 1927 | |
| 1928 | #[test] |
| 1929 | fn switch_supports_native_zero_indexed_source_and_legacy_one_indexed_which() { |
| 1930 | let src = r#" |
| 1931 | Composition { |
| 1932 | CurrentTime = 0, |
| 1933 | RenderRange = { 0, 5 }, |
| 1934 | GlobalRange = { 0, 5 }, |
| 1935 | Tools = ordered() { |
| 1936 | Red = Background { |
| 1937 | Inputs = { |
| 1938 | Width = Input { Value = 16, }, |
| 1939 | Height = Input { Value = 16, }, |
| 1940 | TopLeftRed = Input { Value = 1.0, }, |
| 1941 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1942 | }, |
| 1943 | }, |
| 1944 | Green = Background { |
| 1945 | Inputs = { |
| 1946 | Width = Input { Value = 16, }, |
| 1947 | Height = Input { Value = 16, }, |
| 1948 | TopLeftGreen = Input { Value = 1.0, }, |
| 1949 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1950 | }, |
| 1951 | }, |
| 1952 | Blue = Background { |
| 1953 | Inputs = { |
| 1954 | Width = Input { Value = 16, }, |
| 1955 | Height = Input { Value = 16, }, |
| 1956 | TopLeftBlue = Input { Value = 1.0, }, |
| 1957 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1958 | }, |
| 1959 | }, |
| 1960 | SwNative0 = Switch { |
| 1961 | Inputs = { |
| 1962 | Source = Input { Value = 0, }, |
| 1963 | Input0 = Input { SourceOp = "Red", Source = "Output", }, |
| 1964 | Input1 = Input { SourceOp = "Green", Source = "Output", }, |
| 1965 | }, |
| 1966 | }, |
| 1967 | SwNative1 = Switch { |
| 1968 | Inputs = { |
| 1969 | Source = Input { Value = 1, }, |
| 1970 | Input0 = Input { SourceOp = "Red", Source = "Output", }, |
| 1971 | Input1 = Input { SourceOp = "Green", Source = "Output", }, |
| 1972 | }, |
| 1973 | }, |
| 1974 | SwNativeOmittedSource = Switch { |
| 1975 | Inputs = { |
| 1976 | Input0 = Input { SourceOp = "Red", Source = "Output", }, |
| 1977 | Input1 = Input { SourceOp = "Green", Source = "Output", }, |
| 1978 | }, |
| 1979 | }, |
| 1980 | SwFuse2 = Fuse.Switch { |
| 1981 | Inputs = { |
| 1982 | Which = Input { Value = 2, }, |
| 1983 | Input1 = Input { SourceOp = "Red", Source = "Output", }, |
| 1984 | Input2 = Input { SourceOp = "Blue", Source = "Output", }, |
| 1985 | }, |
| 1986 | }, |
| 1987 | SwLegacy2 = Switch { |
| 1988 | Inputs = { |
| 1989 | Which = Input { Value = 2, }, |
| 1990 | Input1 = Input { SourceOp = "Red", Source = "Output", }, |
| 1991 | Input2 = Input { SourceOp = "Blue", Source = "Output", }, |
| 1992 | }, |
| 1993 | }, |
| 1994 | }, |
| 1995 | } |
| 1996 | "#; |
| 1997 | let comp = Comp::from_fusion_str(src).expect("parse switch comp"); |
| 1998 | let mut eng = Engine::new_headless().expect("gpu"); |
| 1999 | |
| 2000 | let (t0, _) = eng.evaluate(&comp, comp.find_node("SwNative0").unwrap(), 0.0); |
| 2001 | let p0 = eng.readback_rgba(&t0).unwrap(); |
| 2002 | assert!(p0[0] > 240 && p0[1] < 15 && p0[2] < 15, "SwNative0 expected red, got {:?}", &p0[..4]); |
| 2003 | |
| 2004 | let (t1, _) = eng.evaluate(&comp, comp.find_node("SwNative1").unwrap(), 0.0); |
| 2005 | let p1 = eng.readback_rgba(&t1).unwrap(); |
| 2006 | assert!(p1[1] > 240 && p1[0] < 15 && p1[2] < 15, "SwNative1 expected green, got {:?}", &p1[..4]); |
| 2007 | |
| 2008 | let (to, _) = eng.evaluate(&comp, comp.find_node("SwNativeOmittedSource").unwrap(), 0.0); |
| 2009 | let po = eng.readback_rgba(&to).unwrap(); |
| 2010 | assert!(po[0] > 240 && po[1] < 15 && po[2] < 15, "SwNativeOmittedSource expected red, got {:?}", &po[..4]); |
| 2011 | |
| 2012 | let (tf, _) = eng.evaluate(&comp, comp.find_node("SwFuse2").unwrap(), 0.0); |
| 2013 | let pf = eng.readback_rgba(&tf).unwrap(); |
| 2014 | assert!(pf[2] > 240 && pf[0] < 15 && pf[1] < 15, "SwFuse2 expected blue, got {:?}", &pf[..4]); |
| 2015 | |
| 2016 | let (tl, _) = eng.evaluate(&comp, comp.find_node("SwLegacy2").unwrap(), 0.0); |
| 2017 | let pl = eng.readback_rgba(&tl).unwrap(); |
| 2018 | assert!(pl[2] > 240 && pl[0] < 15 && pl[1] < 15, "SwLegacy2 expected blue, got {:?}", &pl[..4]); |
| 2019 | } |
| 2020 | |
| 2021 | #[test] |
| 2022 | fn custom_without_image1_renders_nothing() { |
| 2023 | let src = r#" |
| 2024 | Composition { |
| 2025 | CurrentTime = 0, |
| 2026 | RenderRange = { 0, 0 }, |
| 2027 | GlobalRange = { 0, 0 }, |
| 2028 | Tools = ordered() { |
| 2029 | Unwired = Custom { |
| 2030 | Inputs = { |
| 2031 | RedExpression = Input { Value = "0.7", }, |
| 2032 | AlphaExpression = Input { Value = "1", }, |
| 2033 | }, |
| 2034 | }, |
| 2035 | Dangling = Custom { |
| 2036 | Inputs = { |
| 2037 | Image1 = Input { SourceOp = "NoSuchTool", Source = "Output", }, |
| 2038 | RedExpression = Input { Value = "0.7", }, |
| 2039 | AlphaExpression = Input { Value = "1", }, |
| 2040 | }, |
| 2041 | }, |
| 2042 | }, |
| 2043 | } |
| 2044 | "#; |
| 2045 | let comp = Comp::from_fusion_str(src).expect("parse custom comp"); |
| 2046 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2047 | for name in ["Unwired", "Dangling"] { |
| 2048 | let (t, _) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0); |
| 2049 | let px = eng.readback_rgba(&t).unwrap(); |
| 2050 | assert_eq!(&px[..4], &[0, 0, 0, 0], "{name} must be transparent without Image1"); |
| 2051 | } |
| 2052 | } |
| 2053 | |
| 2054 | #[test] |
| 2055 | fn frame_memo_distinguishes_subframe_times_within_same_rounded_frame() { |
| 2056 | // BG1 animates TopLeftRed from 0.0 at t=9.0 to 1.0 at t=10.0. |
| 2057 | // At t=10.0: BG1 is evaluated directly (red=1.0). |
| 2058 | // At t=9.6 (via TimeSpeed Speed=0.96, Delay=0.0): time.round() is ALSO 10, |
| 2059 | // so frame_memo keyed by rounded frame would wrongly return t=10.0's red=1.0! |
| 2060 | let src = r#" |
| 2061 | Composition { |
| 2062 | CurrentTime = 10, |
| 2063 | RenderRange = { 0, 20 }, |
| 2064 | GlobalRange = { 0, 20 }, |
| 2065 | Tools = ordered() { |
| 2066 | AnimRed = BezierSpline { |
| 2067 | KeyFrames = { |
| 2068 | [9] = { 0.0, Flags = { Linear = true } }, |
| 2069 | [10] = { 1.0, Flags = { Linear = true } }, |
| 2070 | }, |
| 2071 | }, |
| 2072 | BG1 = Background { |
| 2073 | Inputs = { |
| 2074 | Width = Input { Value = 32, }, |
| 2075 | Height = Input { Value = 32, }, |
| 2076 | TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, |
| 2077 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2078 | }, |
| 2079 | }, |
| 2080 | TS = TimeSpeed { |
| 2081 | Inputs = { |
| 2082 | Speed = Input { Value = 0.96, }, |
| 2083 | Input = Input { SourceOp = "BG1", Source = "Output", }, |
| 2084 | }, |
| 2085 | }, |
| 2086 | Out = Merge { |
| 2087 | Inputs = { |
| 2088 | Background = Input { SourceOp = "BG1", Source = "Output", }, |
| 2089 | Foreground = Input { SourceOp = "TS", Source = "Output", }, |
| 2090 | Size = Input { Value = 0.5, }, |
| 2091 | }, |
| 2092 | }, |
| 2093 | }, |
| 2094 | } |
| 2095 | "#; |
| 2096 | let comp = Comp::from_fusion_str(src).expect("parse subframe comp"); |
| 2097 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2098 | let out_id = comp.find_node("Out").unwrap(); |
| 2099 | let (tex, _) = eng.evaluate(&comp, out_id, 10.0); |
| 2100 | assert_eq!(tex.size, [32, 32]); |
| 2101 | let rgba = eng.readback_rgba(&tex).unwrap(); |
| 2102 | // Corner pixel (0, 0) is BG1 at t=10.0 -> red ~255. |
| 2103 | assert!(rgba[0] > 240, "corner pixel (BG1 @10.0) expected ~255, got {}", rgba[0]); |
| 2104 | // Center pixel (16, 16) is TS (BG1 @9.6) -> red ~0.6 * 255 = 153! |
| 2105 | let mid_idx = (16 * 32 + 16) * 4; |
| 2106 | assert!( |
| 2107 | (rgba[mid_idx] as i32 - 153).abs() <= 6, |
| 2108 | "center pixel (BG1 @9.6) expected ~153, got {}", |
| 2109 | rgba[mid_idx] |
| 2110 | ); |
| 2111 | // Also verify frame_memo was cleared after evaluate. |
| 2112 | assert!(eng.frame_memo.is_empty()); |
| 2113 | } |
| 2114 | |
| 2115 | #[test] |
| 2116 | fn frame_memo_includes_mask_target_size_and_new_with_device_sets_budgets() { |
| 2117 | let eng0 = Engine::new_headless().expect("gpu"); |
| 2118 | let mut eng = Engine::new_with_device( |
| 2119 | std::sync::Arc::new(eng0.device().clone()), |
| 2120 | std::sync::Arc::new(eng0.queue().clone()), |
| 2121 | 64 * 1024 * 1024, |
| 2122 | 32 * 1024 * 1024, |
| 2123 | ); |
| 2124 | assert_eq!(eng.vram_budget_mb(), 64); |
| 2125 | |
| 2126 | let src = r#" |
| 2127 | Composition { |
| 2128 | CurrentTime = 0, |
| 2129 | RenderRange = { 0, 1 }, |
| 2130 | GlobalRange = { 0, 1 }, |
| 2131 | Tools = ordered() { |
| 2132 | MaskImg = Background { |
| 2133 | Inputs = { |
| 2134 | Width = Input { Value = 64, }, |
| 2135 | Height = Input { Value = 64, }, |
| 2136 | TopLeftRed = Input { Value = 1.0, }, |
| 2137 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2138 | }, |
| 2139 | }, |
| 2140 | BM = BitmapMask { |
| 2141 | Inputs = { |
| 2142 | Image = Input { SourceOp = "MaskImg", Source = "Output", }, |
| 2143 | }, |
| 2144 | }, |
| 2145 | SmallBG = Background { |
| 2146 | Inputs = { |
| 2147 | Width = Input { Value = 32, }, |
| 2148 | Height = Input { Value = 32, }, |
| 2149 | TopLeftGreen = Input { Value = 1.0, }, |
| 2150 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2151 | EffectMask = Input { SourceOp = "BM", Source = "Mask", }, |
| 2152 | }, |
| 2153 | }, |
| 2154 | LargeBG = Background { |
| 2155 | Inputs = { |
| 2156 | Width = Input { Value = 64, }, |
| 2157 | Height = Input { Value = 64, }, |
| 2158 | TopLeftBlue = Input { Value = 1.0, }, |
| 2159 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2160 | EffectMask = Input { SourceOp = "BM", Source = "Mask", }, |
| 2161 | }, |
| 2162 | }, |
| 2163 | Out = Merge { |
| 2164 | Inputs = { |
| 2165 | Background = Input { SourceOp = "LargeBG", Source = "Output", }, |
| 2166 | Foreground = Input { SourceOp = "SmallBG", Source = "Output", }, |
| 2167 | }, |
| 2168 | }, |
| 2169 | }, |
| 2170 | } |
| 2171 | "#; |
| 2172 | let comp = Comp::from_fusion_str(src).expect("parse mask target size comp"); |
| 2173 | let out_id = comp.find_node("Out").unwrap(); |
| 2174 | let (tex, _) = eng.evaluate(&comp, out_id, 0.0); |
| 2175 | assert_eq!(tex.size, [64, 64]); |
| 2176 | assert!(eng.frame_memo.is_empty()); |
| 2177 | } |
| 2178 | |
| 2179 | #[test] |
| 2180 | fn display_blit_preserves_hdr_highlights_and_negatives_across_scale_and_crop() { |
| 2181 | let src = r#" |
| 2182 | Composition { |
| 2183 | CurrentTime = 0, |
| 2184 | RenderRange = { 0, 1 }, |
| 2185 | GlobalRange = { 0, 1 }, |
| 2186 | Prefs = { Comp = { FrameFormat = { Width = 8, Height = 8, DepthFull = 4 } } }, |
| 2187 | Tools = ordered() { |
| 2188 | BG1 = Background { |
| 2189 | Inputs = { |
| 2190 | Width = Input { Value = 8, }, |
| 2191 | Height = Input { Value = 8, }, |
| 2192 | Depth = Input { Value = 4, }, |
| 2193 | TopLeftRed = Input { Value = 3.5, }, |
| 2194 | TopLeftGreen = Input { Value = -0.25, }, |
| 2195 | TopLeftBlue = Input { Value = 0.5, }, |
| 2196 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2197 | }, |
| 2198 | }, |
| 2199 | SC = Scale { |
| 2200 | Inputs = { |
| 2201 | Input = Input { SourceOp = "BG1", Source = "Output", }, |
| 2202 | XSize = Input { Value = 0.5, }, |
| 2203 | YSize = Input { Value = 0.5, }, |
| 2204 | }, |
| 2205 | }, |
| 2206 | }, |
| 2207 | } |
| 2208 | "#; |
| 2209 | let comp = Comp::from_fusion_str(src).expect("parse hdr scale comp"); |
| 2210 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2211 | let sc_id = comp.find_node("SC").unwrap(); |
| 2212 | let (tex, _) = eng.evaluate(&comp, sc_id, 0.0); |
| 2213 | assert!(tex.depth.is_float()); |
| 2214 | |
| 2215 | // Read raw float pixels from tex (Float32 or Float16) to verify > 1.0 and < 0.0 survived Scale's DisplayBlit! |
| 2216 | let [w, h] = tex.size; |
| 2217 | let bpp = if tex.format == wgpu::TextureFormat::Rgba32Float { 16u32 } else { 8u32 }; |
| 2218 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 2219 | let padded_bpr = (w * bpp).div_ceil(align) * align; |
| 2220 | let buf = eng.device.create_buffer(&wgpu::BufferDescriptor { |
| 2221 | label: Some("hdr-readback"), |
| 2222 | size: u64::from(padded_bpr) * u64::from(h), |
| 2223 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 2224 | mapped_at_creation: false, |
| 2225 | }); |
| 2226 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 2227 | enc.copy_texture_to_buffer( |
| 2228 | tex.texture.as_image_copy(), |
| 2229 | wgpu::TexelCopyBufferInfo { |
| 2230 | buffer: &buf, |
| 2231 | layout: wgpu::TexelCopyBufferLayout { |
| 2232 | offset: 0, |
| 2233 | bytes_per_row: Some(padded_bpr), |
| 2234 | rows_per_image: Some(h), |
| 2235 | }, |
| 2236 | }, |
| 2237 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 2238 | ); |
| 2239 | eng.queue.submit(Some(enc.finish())); |
| 2240 | let slice = buf.slice(..); |
| 2241 | let (tx, rx) = std::sync::mpsc::channel(); |
| 2242 | slice.map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); }); |
| 2243 | eng.device.poll(wgpu::PollType::Wait { |
| 2244 | submission_index: None, |
| 2245 | timeout: Some(std::time::Duration::from_secs(5)), |
| 2246 | }).unwrap(); |
| 2247 | rx.recv().unwrap().unwrap(); |
| 2248 | let data = slice.get_mapped_range().unwrap(); |
| 2249 | let f16_to_f32 = |h: u16| -> f32 { |
| 2250 | let sign = u32::from(h >> 15) << 31; |
| 2251 | let exp = u32::from((h >> 10) & 0x1F); |
| 2252 | let mant = u32::from(h & 0x3FF); |
| 2253 | if exp == 0 { |
| 2254 | if mant == 0 { |
| 2255 | f32::from_bits(sign) |
| 2256 | } else { |
| 2257 | let mut m = mant; |
| 2258 | let mut e = 127 - 14; |
| 2259 | while (m & 0x400) == 0 { |
| 2260 | m <<= 1; |
| 2261 | e -= 1; |
| 2262 | } |
| 2263 | f32::from_bits(sign | (e << 23) | ((m & 0x3FF) << 13)) |
| 2264 | } |
| 2265 | } else if exp == 31 { |
| 2266 | f32::from_bits(sign | 0x7F80_0000 | (mant << 13)) |
| 2267 | } else { |
| 2268 | f32::from_bits(sign | ((exp + 112) << 23) | (mant << 13)) |
| 2269 | } |
| 2270 | }; |
| 2271 | let (r, g, b) = if tex.format == wgpu::TextureFormat::Rgba32Float { |
| 2272 | let px: &[f32] = bytemuck::cast_slice(&data[..16]); |
| 2273 | (px[0], px[1], px[2]) |
| 2274 | } else { |
| 2275 | let px: &[u16] = bytemuck::cast_slice(&data[..8]); |
| 2276 | (f16_to_f32(px[0]), f16_to_f32(px[1]), f16_to_f32(px[2])) |
| 2277 | }; |
| 2278 | assert!((r - 3.5).abs() < 0.05, "expected HDR red ~3.5, got {r}"); |
| 2279 | assert!((g - (-0.25)).abs() < 0.05, "expected negative HDR green ~-0.25, got {g}"); |
| 2280 | assert!((b - 0.5).abs() < 0.05, "expected blue ~0.5, got {b}"); |
| 2281 | } |
| 2282 | |
| 2283 | #[test] |
| 2284 | fn output_cache_enforces_byte_budget_and_reports_in_vram_bytes() { |
| 2285 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2286 | // 64 MiB total VRAM budget -> output_cache cap is 64 / 4 = 16 MiB. |
| 2287 | eng.set_vram_budget_mb(64); |
| 2288 | assert_eq!(eng.output_cache_budget_bytes(), 16 * 1024 * 1024); |
| 2289 | |
| 2290 | // 2048x1024 RGBA8 = 8 MiB per frame (so 16 MiB cap fits 2 frames, evicting the 3rd). |
| 2291 | let src = r#" |
| 2292 | Composition { |
| 2293 | CurrentTime = 0, |
| 2294 | RenderRange = { 0, 5 }, |
| 2295 | GlobalRange = { 0, 5 }, |
| 2296 | Tools = ordered() { |
| 2297 | AnimRed = BezierSpline { |
| 2298 | KeyFrames = { |
| 2299 | [0] = { 0.1 }, |
| 2300 | [5] = { 0.9 }, |
| 2301 | }, |
| 2302 | }, |
| 2303 | BG = Background { |
| 2304 | Inputs = { |
| 2305 | Width = Input { Value = 2048, }, |
| 2306 | Height = Input { Value = 1024, }, |
| 2307 | TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, |
| 2308 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2309 | }, |
| 2310 | }, |
| 2311 | }, |
| 2312 | } |
| 2313 | "#; |
| 2314 | let comp = Comp::from_fusion_str(src).expect("parse output_cache test comp"); |
| 2315 | let bg = comp.find_node("BG").unwrap(); |
| 2316 | |
| 2317 | let (_, s0) = eng.evaluate(&comp, bg, 0.0); |
| 2318 | assert_eq!(eng.output_cache.len(), 1); |
| 2319 | assert_eq!(eng.output_cache_bytes(), 8 * 1024 * 1024); |
| 2320 | assert!(eng.vram_bytes() >= eng.output_cache_bytes()); |
| 2321 | assert!(eng.vram_bytes() <= 64 * 1024 * 1024); |
| 2322 | assert!((s0.cached_vram_mb - eng.vram_mb()).abs() < 0.01); |
| 2323 | |
| 2324 | let (_, _) = eng.evaluate(&comp, bg, 1.0); |
| 2325 | assert_eq!(eng.output_cache.len(), 2); |
| 2326 | assert_eq!(eng.output_cache_bytes(), 16 * 1024 * 1024); |
| 2327 | assert!(eng.vram_bytes() <= 64 * 1024 * 1024); |
| 2328 | |
| 2329 | // Touch frame 0 so frame 1 becomes LRU, then evaluate frame 2 -> frame 1 evicted. |
| 2330 | let (_, warm0) = eng.evaluate(&comp, bg, 0.0); |
| 2331 | assert_eq!(warm0.cache_hits, 1); |
| 2332 | |
| 2333 | let (_, _) = eng.evaluate(&comp, bg, 2.0); |
| 2334 | assert_eq!(eng.output_cache.len(), 2); |
| 2335 | assert_eq!(eng.output_cache_bytes(), 16 * 1024 * 1024); |
| 2336 | assert!(eng.vram_bytes() <= 64 * 1024 * 1024); |
| 2337 | |
| 2338 | // Frame 1 was evicted, so evaluating frame 1 misses output_cache; frame 2 hits. |
| 2339 | let k1 = eng.output_cache_key(&comp, bg, 1.0); |
| 2340 | let k2 = eng.output_cache_key(&comp, bg, 2.0); |
| 2341 | assert!(eng.output_cache_get(k1).is_none(), "LRU frame 1 should have been evicted"); |
| 2342 | assert!(eng.output_cache_get(k2).is_some(), "recent frame 2 should still be cached"); |
| 2343 | |
| 2344 | // Even a single frame exceeding the byte cap (e.g., 4096x2048 RGBA8 = 32 MiB > 16 MiB) |
| 2345 | // must always keep at least the most recent frame in output_cache. |
| 2346 | let big_tex = create_texture(&eng.device, [4096, 2048], 0); |
| 2347 | assert_eq!(big_tex.bytes, 32 * 1024 * 1024); |
| 2348 | eng.output_cache_insert(999_999, big_tex, Vec::new()); |
| 2349 | assert_eq!(eng.output_cache.len(), 1); |
| 2350 | assert_eq!(eng.output_cache_bytes(), 32 * 1024 * 1024); |
| 2351 | } |
| 2352 | |
| 2353 | #[test] |
| 2354 | fn output_cache_does_not_double_count_shared_node_cache_textures() { |
| 2355 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2356 | eng.set_vram_budget_mb(64); |
| 2357 | |
| 2358 | let src = r#" |
| 2359 | Composition { |
| 2360 | CurrentTime = 0, |
| 2361 | RenderRange = { 0, 1 }, |
| 2362 | GlobalRange = { 0, 1 }, |
| 2363 | Tools = ordered() { |
| 2364 | BG = Background { |
| 2365 | Inputs = { |
| 2366 | Width = Input { Value = 2048, }, |
| 2367 | Height = Input { Value = 1024, }, |
| 2368 | TopLeftRed = Input { Value = 0.5, }, |
| 2369 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2370 | }, |
| 2371 | }, |
| 2372 | }, |
| 2373 | } |
| 2374 | "#; |
| 2375 | let comp = Comp::from_fusion_str(src).expect("parse shared vram comp"); |
| 2376 | let bg = comp.find_node("BG").unwrap(); |
| 2377 | |
| 2378 | let (tex, _) = eng.evaluate(&comp, bg, 0.0); |
| 2379 | assert_eq!(tex.bytes, 8 * 1024 * 1024); |
| 2380 | drop(tex); |
| 2381 | |
| 2382 | // Texture is held in both NodeCache and output_cache (Arc::strong_count >= 2). |
| 2383 | // vram_bytes() must count the 8 MiB allocation once, not 16 MiB, and NodeCache's |
| 2384 | // budget must remain at the full 64 MiB. |
| 2385 | assert_eq!(eng.output_cache.unshared_bytes(), 0); |
| 2386 | assert_eq!(eng.vram_bytes(), eng.cache.total_vram_bytes()); |
| 2387 | assert_eq!(eng.vram_bytes(), 8 * 1024 * 1024); |
| 2388 | assert_eq!(eng.cache.budget_bytes, 64 * 1024 * 1024); |
| 2389 | |
| 2390 | // If an unshared texture (strong_count == 1) is in output_cache, it IS counted |
| 2391 | // in vram_bytes() and subtracted from NodeCache's budget. |
| 2392 | let unshared = create_texture(&eng.device, [2048, 1024], 42); |
| 2393 | assert_eq!(std::sync::Arc::strong_count(&unshared.texture), 1); |
| 2394 | eng.output_cache_insert(123_456, unshared, Vec::new()); |
| 2395 | assert_eq!(eng.output_cache.unshared_bytes(), 8 * 1024 * 1024); |
| 2396 | assert_eq!(eng.vram_bytes(), 16 * 1024 * 1024); |
| 2397 | assert_eq!(eng.cache.budget_bytes, 56 * 1024 * 1024); |
| 2398 | } |
| 2399 | |
| 2400 | #[test] |
| 2401 | fn time_speed_and_time_stretcher_match_fusion_global_range_and_defaults() { |
| 2402 | let src = r#" |
| 2403 | Composition { |
| 2404 | CurrentTime = 0, |
| 2405 | RenderRange = { 0, 10 }, |
| 2406 | GlobalRange = { -10, 40 }, |
| 2407 | Tools = ordered() { |
| 2408 | TimeR = BezierSpline { |
| 2409 | KeyFrames = { |
| 2410 | [-10] = { 0.0, Flags = { Linear = true } }, |
| 2411 | [40] = { 1.0, Flags = { Linear = true } }, |
| 2412 | }, |
| 2413 | }, |
| 2414 | BG = Background { |
| 2415 | Inputs = { |
| 2416 | Width = Input { Value = 16, }, |
| 2417 | Height = Input { Value = 16, }, |
| 2418 | TopLeftRed = Input { SourceOp = "TimeR", Source = "Value", }, |
| 2419 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2420 | }, |
| 2421 | }, |
| 2422 | TSNeg = TimeSpeed { |
| 2423 | Inputs = { |
| 2424 | Speed = Input { Value = -0.5, }, |
| 2425 | Delay = Input { Value = 2.0, }, |
| 2426 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2427 | }, |
| 2428 | }, |
| 2429 | TSPos = TimeSpeed { |
| 2430 | Inputs = { |
| 2431 | Speed = Input { Value = 0.5, }, |
| 2432 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2433 | }, |
| 2434 | }, |
| 2435 | StrDef = TimeStretcher { |
| 2436 | Inputs = { |
| 2437 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2438 | }, |
| 2439 | }, |
| 2440 | StrSnap = TimeStretcher { |
| 2441 | Inputs = { |
| 2442 | SourceTime = Input { Value = 13.5, }, |
| 2443 | InterpolateBetweenFrames = Input { Value = 0, }, |
| 2444 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2445 | }, |
| 2446 | }, |
| 2447 | }, |
| 2448 | } |
| 2449 | "#; |
| 2450 | let comp = Comp::from_fusion_str(src).expect("parse time remap comp"); |
| 2451 | let Ok(mut eng) = Engine::new_headless() else { |
| 2452 | return; |
| 2453 | }; |
| 2454 | let red_at = |e: &mut Engine, name: &str, t: f64| -> u8 { |
| 2455 | let (tex, _) = e.evaluate(&comp, comp.find_node(name).unwrap(), t); |
| 2456 | e.readback_rgba(&tex).unwrap()[0] |
| 2457 | }; |
| 2458 | // Negative speed at t=4, delay=2, GlobalRange=[-10, 40]: |
| 2459 | // (40 + 1) + (4 - 2 - (-10)) * (-0.5) = 41 - 6 = 35 -> (35 - (-10))/50 = 0.90 -> 230 |
| 2460 | assert!((red_at(&mut eng, "TSNeg", 4.0) as i32 - 230).abs() <= 2); |
| 2461 | // Positive speed at t=4, delay=0, GlobalRange=[-10, 40]: |
| 2462 | // -10 + (4 - (-10)) * 0.5 = -3 -> (-3 - (-10))/50 = 0.14 -> 36 |
| 2463 | assert!((red_at(&mut eng, "TSPos", 4.0) as i32 - 36).abs() <= 2); |
| 2464 | // Omitted SourceTime defaults to 0.0 even at t=6 -> (0 - (-10))/50 = 0.20 -> 51 |
| 2465 | assert!((red_at(&mut eng, "StrDef", 6.0) as i32 - 51).abs() <= 2); |
| 2466 | // InterpolateBetweenFrames=0 rounds half-up via floor(x + 0.5): 13.5 -> 14 -> (14 - (-10))/50 = 0.48 -> 122 |
| 2467 | assert!((red_at(&mut eng, "StrSnap", 0.0) as i32 - 122).abs() <= 2); |
| 2468 | } |
| 2469 | |
| 2470 | #[test] |
| 2471 | fn frame_consumers_persist_within_revision_and_rebuild_on_edit() { |
| 2472 | let src = r#" |
| 2473 | Composition { |
| 2474 | CurrentTime = 0, |
| 2475 | RenderRange = { 0, 2 }, |
| 2476 | GlobalRange = { 0, 2 }, |
| 2477 | Tools = ordered() { |
| 2478 | BG = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, |
| 2479 | FG = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftRed = Input { Value = 1.0, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, |
| 2480 | FG2 = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, |
| 2481 | M = Merge { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Foreground = Input { SourceOp = "FG", Source = "Output", }, }, }, |
| 2482 | }, |
| 2483 | } |
| 2484 | "#; |
| 2485 | let mut comp = Comp::from_fusion_str(src).expect("parse merge comp"); |
| 2486 | let Ok(mut eng) = Engine::new_headless() else { |
| 2487 | return; |
| 2488 | }; |
| 2489 | let m_id = comp.find_node("M").unwrap(); |
| 2490 | let fg_id = comp.find_node("FG").unwrap(); |
| 2491 | let fg2_id = comp.find_node("FG2").unwrap(); |
| 2492 | |
| 2493 | let _ = eng.evaluate(&comp, m_id, 0.0); |
| 2494 | assert_eq!(eng.frame_consumers_rev, Some(comp.revision)); |
| 2495 | assert_eq!(eng.frame_consumers.len(), comp.nodes.len()); |
| 2496 | assert!(eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); |
| 2497 | |
| 2498 | // Second frame at same revision keeps the cached adjacency table instead of clearing it. |
| 2499 | let _ = eng.evaluate(&comp, m_id, 1.0); |
| 2500 | assert_eq!(eng.frame_consumers_rev, Some(comp.revision)); |
| 2501 | assert_eq!(eng.frame_consumers.len(), comp.nodes.len()); |
| 2502 | assert!(eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); |
| 2503 | |
| 2504 | // Mutating the comp increments comp.revision and refreshes frame_consumers on next eval. |
| 2505 | comp.connect_output(fg2_id, "Output", m_id, "Foreground").unwrap(); |
| 2506 | let _ = eng.evaluate(&comp, m_id, 1.0); |
| 2507 | assert_eq!(eng.frame_consumers_rev, Some(comp.revision)); |
| 2508 | assert_eq!(eng.frame_consumers.len(), comp.nodes.len()); |
| 2509 | assert!(!eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); |
| 2510 | assert!(eng.frame_consumers[fg2_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); |
| 2511 | } |
| 2512 | |
| 2513 | #[test] |
| 2514 | fn vram_drops_clear_bind_groups_and_viewer_blit_bypasses_bg_cache() { |
| 2515 | let Ok(mut eng) = Engine::new_headless() else { |
| 2516 | return; |
| 2517 | }; |
| 2518 | // Default Engine::new wires RAM-scaled MediaCache::default(). |
| 2519 | assert!(crate::media::default_media_cache_budget_mb() >= 512); |
| 2520 | |
| 2521 | // Tight 8 MiB VRAM budget: 1024x1024 RGBA8 = 4 MiB per texture. |
| 2522 | eng.set_vram_budget_mb(8); |
| 2523 | |
| 2524 | let src = r#" |
| 2525 | Composition { |
| 2526 | CurrentTime = 0, |
| 2527 | RenderRange = { 0, 10 }, |
| 2528 | GlobalRange = { 0, 10 }, |
| 2529 | Tools = ordered() { |
| 2530 | AnimRed = BezierSpline { |
| 2531 | KeyFrames = { |
| 2532 | [0] = { 0.1 }, |
| 2533 | [10] = { 0.9 }, |
| 2534 | }, |
| 2535 | }, |
| 2536 | BG = Background { |
| 2537 | Inputs = { |
| 2538 | Width = Input { Value = 1024, }, |
| 2539 | Height = Input { Value = 1024, }, |
| 2540 | TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, |
| 2541 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2542 | }, |
| 2543 | }, |
| 2544 | BC = BrightnessContrast { |
| 2545 | Inputs = { |
| 2546 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2547 | Gain = Input { Value = 1.2, }, |
| 2548 | }, |
| 2549 | }, |
| 2550 | }, |
| 2551 | } |
| 2552 | "#; |
| 2553 | let comp = Comp::from_fusion_str(src).expect("parse vram bg test comp"); |
| 2554 | let bc = comp.find_node("BC").unwrap(); |
| 2555 | |
| 2556 | // Evaluate frame 0 -> uniform_cursor resets to 0 after submit, bg_cache populated. |
| 2557 | let _ = eng.evaluate(&comp, bc, 0.0); |
| 2558 | assert!(eng.frame_eval_target.is_none()); |
| 2559 | assert_eq!(eng.pipelines.borrow().uniform_chunks.len(), 1); |
| 2560 | // Next uniform slot allocated must start at chunk 0, offset 0 (cursor was reset post-submit). |
| 2561 | { |
| 2562 | let mut reg = eng.pipelines.borrow_mut(); |
| 2563 | let slot = reg.alloc_uniform_slot(&eng.device, &eng.queue, &UniformParams::default()); |
| 2564 | assert_eq!(slot, (0, 0)); |
| 2565 | reg.reset_uniform_cursor(); |
| 2566 | } |
| 2567 | assert!(eng.pipelines.borrow().bg_entry_count() > 0); |
| 2568 | |
| 2569 | // Render into ephemeral viewer textures on frame 0 (output_cache hit): must not grow bg_cache! |
| 2570 | let bg_before_viewer = eng.pipelines.borrow().bg_entry_count(); |
| 2571 | let misses_before_viewer = eng.pipelines.borrow().bg_misses; |
| 2572 | let viewer_tex_a = create_texture(&eng.device, [512, 512], 0); |
| 2573 | let viewer_tex_b = create_texture(&eng.device, [640, 360], 0); |
| 2574 | let _ = eng.render_into_viewer(&comp, bc, 0.0, &viewer_tex_a.texture, DisplaySettings::default()); |
| 2575 | let _ = eng.render_into_viewer(&comp, bc, 0.0, &viewer_tex_b.texture, DisplaySettings::default()); |
| 2576 | assert_eq!(eng.pipelines.borrow().bg_entry_count(), bg_before_viewer); |
| 2577 | assert_eq!(eng.pipelines.borrow().bg_misses, misses_before_viewer); |
| 2578 | |
| 2579 | // Evaluate frames 1..=3 under 8 MiB budget -> organic eviction increments vram_drops |
| 2580 | // and sync_bg_cache_with_vram_drops clears bg_cache so evicted textures aren't pinned. |
| 2581 | for f in 1..=3 { |
| 2582 | let _ = eng.evaluate(&comp, bc, f as f64); |
| 2583 | } |
| 2584 | assert!(eng.cache.vram_drops() > 0); |
| 2585 | assert_eq!(eng.last_bg_vram_drops.get(), eng.cache.vram_drops()); |
| 2586 | } |
| 2587 | |
| 2588 | #[test] |
| 2589 | fn static_still_loader_is_sticky_while_video_and_sequence_loaders_are_not() { |
| 2590 | let dir = std::env::temp_dir().join("fission_sticky_loader_tiering_test"); |
| 2591 | let _ = std::fs::remove_dir_all(&dir); |
| 2592 | std::fs::create_dir_all(&dir).unwrap(); |
| 2593 | |
| 2594 | let still_path = dir.join("still.png"); |
| 2595 | image::RgbaImage::from_pixel(32, 32, image::Rgba([200, 100, 50, 255])) |
| 2596 | .save(&still_path) |
| 2597 | .unwrap(); |
| 2598 | |
| 2599 | for i in 0..3 { |
| 2600 | let seq_path = dir.join(format!("seq_{i:04}.png")); |
| 2601 | image::RgbaImage::from_pixel(32, 32, image::Rgba([40 * i as u8, 120, 200, 255])) |
| 2602 | .save(&seq_path) |
| 2603 | .unwrap(); |
| 2604 | } |
| 2605 | let seq_first = dir.join("seq_0000.png"); |
| 2606 | |
| 2607 | let video_path = dir.join("anim.mp4"); |
| 2608 | let has_video = std::process::Command::new("ffmpeg") |
| 2609 | .args([ |
| 2610 | "-y", |
| 2611 | "-v", |
| 2612 | "error", |
| 2613 | "-f", |
| 2614 | "lavfi", |
| 2615 | "-i", |
| 2616 | "testsrc2=size=64x64:rate=24:duration=0.5", |
| 2617 | "-c:v", |
| 2618 | "libx264", |
| 2619 | "-pix_fmt", |
| 2620 | "yuv420p", |
| 2621 | ]) |
| 2622 | .arg(&video_path) |
| 2623 | .status() |
| 2624 | .is_ok_and(|s| s.success()); |
| 2625 | |
| 2626 | let video_tool = if has_video { |
| 2627 | format!( |
| 2628 | r#" |
| 2629 | VidLoader = Loader {{ |
| 2630 | Clips = {{ |
| 2631 | Clip {{ |
| 2632 | ID = "Clip1", |
| 2633 | Filename = "{}", |
| 2634 | FormatID = "QuickTimeMovies", |
| 2635 | Length = 12, |
| 2636 | TrimIn = 0, |
| 2637 | TrimOut = 11, |
| 2638 | GlobalStart = 0, |
| 2639 | GlobalEnd = 11, |
| 2640 | }}, |
| 2641 | }}, |
| 2642 | }},"#, |
| 2643 | video_path.to_string_lossy().replace('\\', "/") |
| 2644 | ) |
| 2645 | } else { |
| 2646 | String::new() |
| 2647 | }; |
| 2648 | |
| 2649 | let src = format!( |
| 2650 | r#" |
| 2651 | Composition {{ |
| 2652 | CurrentTime = 0, |
| 2653 | RenderRange = {{ 0, 5 }}, |
| 2654 | GlobalRange = {{ 0, 5 }}, |
| 2655 | Tools = ordered() {{ |
| 2656 | StillLoader = Loader {{ |
| 2657 | Clips = {{ |
| 2658 | Clip {{ |
| 2659 | ID = "Clip1", |
| 2660 | Filename = "{}", |
| 2661 | FormatID = "PNGFormat", |
| 2662 | StartFrame = -1, |
| 2663 | GlobalStart = 0, |
| 2664 | GlobalEnd = 10, |
| 2665 | }}, |
| 2666 | }}, |
| 2667 | }}, |
| 2668 | SeqLoader = Loader {{ |
| 2669 | Clips = {{ |
| 2670 | Clip {{ |
| 2671 | ID = "Clip1", |
| 2672 | Filename = "{}", |
| 2673 | FormatID = "PNGFormat", |
| 2674 | StartFrame = 0, |
| 2675 | Length = 3, |
| 2676 | TrimIn = 0, |
| 2677 | TrimOut = 2, |
| 2678 | GlobalStart = 0, |
| 2679 | GlobalEnd = 2, |
| 2680 | }}, |
| 2681 | }}, |
| 2682 | }},{video_tool} |
| 2683 | }}, |
| 2684 | }} |
| 2685 | "#, |
| 2686 | still_path.to_string_lossy().replace('\\', "/"), |
| 2687 | seq_first.to_string_lossy().replace('\\', "/"), |
| 2688 | ); |
| 2689 | |
| 2690 | let comp = Comp::from_fusion_str(&src).expect("parse loader tiering comp"); |
| 2691 | let still_id = comp.find_node("StillLoader").unwrap(); |
| 2692 | let seq_id = comp.find_node("SeqLoader").unwrap(); |
| 2693 | assert!(is_static_loader_node(comp.node(still_id))); |
| 2694 | assert!(!is_static_loader_node(comp.node(seq_id))); |
| 2695 | if has_video { |
| 2696 | let vid_id = comp.find_node("VidLoader").unwrap(); |
| 2697 | assert!(!is_static_loader_node(comp.node(vid_id))); |
| 2698 | } |
| 2699 | |
| 2700 | let Ok(mut eng) = Engine::new_headless() else { |
| 2701 | let _ = std::fs::remove_dir_all(&dir); |
| 2702 | return; |
| 2703 | }; |
| 2704 | |
| 2705 | let (still_tex, _) = eng.evaluate(&comp, still_id, 0.0); |
| 2706 | assert_ne!(still_tex.content_hash, 0); |
| 2707 | assert!( |
| 2708 | eng.cache.is_entry_sticky(still_tex.content_hash), |
| 2709 | "static still Loader must be marked sticky" |
| 2710 | ); |
| 2711 | |
| 2712 | let (seq_tex, _) = eng.evaluate(&comp, seq_id, 0.0); |
| 2713 | assert_ne!(seq_tex.content_hash, 0); |
| 2714 | assert!( |
| 2715 | !eng.cache.is_entry_sticky(seq_tex.content_hash), |
| 2716 | "multi-frame image-sequence Loader must NOT be sticky" |
| 2717 | ); |
| 2718 | |
| 2719 | if has_video { |
| 2720 | let vid_id = comp.find_node("VidLoader").unwrap(); |
| 2721 | let (vid_tex, _) = eng.evaluate(&comp, vid_id, 0.0); |
| 2722 | assert_ne!(vid_tex.content_hash, 0); |
| 2723 | assert!( |
| 2724 | !eng.cache.is_entry_sticky(vid_tex.content_hash), |
| 2725 | "video Loader must NOT be sticky" |
| 2726 | ); |
| 2727 | |
| 2728 | // Also verify lazy EOF frame-hold in video decoder works cleanly past EOF. |
| 2729 | let mut dec = crate::media::open_video_decoder(&video_path).expect("open video decoder"); |
| 2730 | let nb = dec.info().nb_frames; |
| 2731 | assert!(nb >= 6); |
| 2732 | let near_eof = dec.decode_frame(nb - 2).expect("decode near EOF"); |
| 2733 | let past_eof = dec.decode_frame(nb + 1).expect("hold frame past EOF"); |
| 2734 | assert_eq!(near_eof.len(), past_eof.len()); |
| 2735 | } |
| 2736 | |
| 2737 | let _ = std::fs::remove_dir_all(&dir); |
| 2738 | } |
| 2739 | } |