| 1 | //! Thread-safe LRU RAM frame cache and cancellable background lookahead pre-fetcher. |
| 2 | //! |
| 3 | //! Designed for real-time 24fps+ playback and instant scrubbing: |
| 4 | //! - `RamFrameCache` stores finished premultiplied RGBA8 frames keyed by |
| 5 | //! `(NodeId, comp.revision, frame, proxy_scale, hiq, use_proxy_clips)` under a hard byte cap. |
| 6 | //! - `cached_frame_ranges` reports contiguous `[start, end]` cached intervals for timeline display. |
| 7 | //! - `RamPrefetcher` runs lookahead evaluation on a background thread with an atomic generation |
| 8 | //! counter so scrubbing or editing cancels stale pre-fetch work immediately. |
| 9 | |
| 10 | #[cfg(not(target_arch = "wasm32"))] |
| 11 | use crate::eval::{Engine, PendingReadback}; |
| 12 | #[cfg(not(target_arch = "wasm32"))] |
| 13 | use model::Comp; |
| 14 | use model::NodeId; |
| 15 | use std::collections::HashMap; |
| 16 | #[cfg(not(target_arch = "wasm32"))] |
| 17 | use std::sync::atomic::AtomicBool; |
| 18 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 19 | use std::sync::{Arc, Mutex}; |
| 20 | #[cfg(not(target_arch = "wasm32"))] |
| 21 | use std::sync::Condvar; |
| 22 | #[cfg(not(target_arch = "wasm32"))] |
| 23 | use std::thread::{self, JoinHandle}; |
| 24 | |
| 25 | /// Fallback RAM frame cache ceiling (1 GiB ≈ 130 full-res 1080p frames or ~520 half-res frames). |
| 26 | pub const DEFAULT_RAM_CACHE_MB: u64 = 1024; |
| 27 | /// Modest VRAM budget for the shared-device background prefetcher `Engine`. |
| 28 | pub const DEFAULT_PREFETCH_VRAM_MB: u64 = 256; |
| 29 | /// Modest media decode cache budget for the shared-device background prefetcher `Engine`. |
| 30 | pub const DEFAULT_PREFETCH_MEDIA_MB: u64 = 128; |
| 31 | |
| 32 | /// Returns total physical system memory in bytes, or a conservative 2 GiB default on `wasm32`. |
| 33 | pub fn system_memory_bytes() -> u64 { |
| 34 | #[cfg(target_arch = "wasm32")] |
| 35 | { |
| 36 | 2 * 1024 * 1024 * 1024 |
| 37 | } |
| 38 | #[cfg(target_os = "macos")] |
| 39 | { |
| 40 | unsafe extern "C" { |
| 41 | fn sysctlbyname( |
| 42 | name: *const std::ffi::c_char, |
| 43 | oldp: *mut std::ffi::c_void, |
| 44 | oldlenp: *mut usize, |
| 45 | newp: *const std::ffi::c_void, |
| 46 | newlen: usize, |
| 47 | ) -> std::ffi::c_int; |
| 48 | } |
| 49 | let mut memsize: u64 = 0; |
| 50 | let mut size = std::mem::size_of::<u64>(); |
| 51 | // SAFETY: `memsize` is a stack u64 and `size` matches its exact byte size. |
| 52 | let rc = unsafe { |
| 53 | sysctlbyname( |
| 54 | c"hw.memsize".as_ptr(), |
| 55 | (&raw mut memsize).cast::<std::ffi::c_void>(), |
| 56 | &raw mut size, |
| 57 | std::ptr::null(), |
| 58 | 0, |
| 59 | ) |
| 60 | }; |
| 61 | if rc == 0 && size == std::mem::size_of::<u64>() && memsize > 0 { |
| 62 | return memsize; |
| 63 | } |
| 64 | 8 * 1024 * 1024 * 1024 |
| 65 | } |
| 66 | #[cfg(target_os = "linux")] |
| 67 | { |
| 68 | if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") { |
| 69 | for line in meminfo.lines() { |
| 70 | if let Some(rest) = line.strip_prefix("MemTotal:") { |
| 71 | if let Some(kb) = rest.split_whitespace().next().and_then(|s| s.parse::<u64>().ok()) { |
| 72 | if kb > 0 { |
| 73 | return kb.saturating_mul(1024); |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | 8 * 1024 * 1024 * 1024 |
| 80 | } |
| 81 | #[cfg(all(not(target_arch = "wasm32"), not(target_os = "macos"), not(target_os = "linux")))] |
| 82 | { |
| 83 | 8 * 1024 * 1024 * 1024 |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | pub(crate) fn ram_cache_budget_mb_for_total_bytes(total_bytes: u64) -> u64 { |
| 88 | let gib = total_bytes / (1024 * 1024 * 1024); |
| 89 | if gib >= 256 { |
| 90 | 32 * 1024 |
| 91 | } else if gib >= 128 { |
| 92 | 16 * 1024 |
| 93 | } else if gib >= 64 { |
| 94 | 8 * 1024 |
| 95 | } else if gib >= 32 { |
| 96 | 4 * 1024 |
| 97 | } else if gib >= 16 { |
| 98 | 2 * 1024 |
| 99 | } else { |
| 100 | DEFAULT_RAM_CACHE_MB |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | /// Returns the default `RamFrameCache` budget in MiB scaled to host physical RAM. |
| 105 | pub fn default_ram_cache_budget_mb() -> u64 { |
| 106 | ram_cache_budget_mb_for_total_bytes(system_memory_bytes()) |
| 107 | } |
| 108 | |
| 109 | fn scaled_prefetch_budget_mb(total_bytes: u64, fallback_mb: u64) -> u64 { |
| 110 | let gib = total_bytes / (1024 * 1024 * 1024); |
| 111 | if gib >= 128 { |
| 112 | 2048 |
| 113 | } else if gib >= 64 { |
| 114 | 1024 |
| 115 | } else if gib >= 32 { |
| 116 | 512 |
| 117 | } else { |
| 118 | fallback_mb |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | pub(crate) fn prefetch_vram_budget_mb_for_total_bytes(total_bytes: u64) -> u64 { |
| 123 | scaled_prefetch_budget_mb(total_bytes, DEFAULT_PREFETCH_VRAM_MB) |
| 124 | } |
| 125 | |
| 126 | pub(crate) fn prefetch_media_budget_mb_for_total_bytes(total_bytes: u64) -> u64 { |
| 127 | scaled_prefetch_budget_mb(total_bytes, DEFAULT_PREFETCH_MEDIA_MB) |
| 128 | } |
| 129 | |
| 130 | /// Returns the default background prefetcher VRAM budget in MiB scaled to host physical RAM. |
| 131 | pub fn default_prefetch_vram_budget_mb() -> u64 { |
| 132 | prefetch_vram_budget_mb_for_total_bytes(system_memory_bytes()) |
| 133 | } |
| 134 | |
| 135 | /// Returns the default background prefetcher media decode cache budget in MiB scaled to host physical RAM. |
| 136 | pub fn default_prefetch_media_budget_mb() -> u64 { |
| 137 | prefetch_media_budget_mb_for_total_bytes(system_memory_bytes()) |
| 138 | } |
| 139 | |
| 140 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 141 | pub struct RamFrameKey { |
| 142 | pub target: NodeId, |
| 143 | pub revision: u64, |
| 144 | pub frame: i64, |
| 145 | pub proxy_scale: u32, |
| 146 | pub hiq: bool, |
| 147 | pub use_proxy_clips: bool, |
| 148 | } |
| 149 | |
| 150 | #[derive(Clone, Debug)] |
| 151 | pub struct RamFrame { |
| 152 | pub size: [u32; 2], |
| 153 | /// Premultiplied RGBA8 pixels, top-down (`size[0] * size[1] * 4` bytes). |
| 154 | pub rgba: Arc<Vec<u8>>, |
| 155 | pub eval_ms: f64, |
| 156 | } |
| 157 | |
| 158 | impl RamFrame { |
| 159 | pub fn byte_size(&self) -> u64 { |
| 160 | self.rgba.len() as u64 |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | struct RamEntry { |
| 165 | frame: RamFrame, |
| 166 | last_used: u64, |
| 167 | } |
| 168 | |
| 169 | struct RamCacheInner { |
| 170 | budget_bytes: u64, |
| 171 | entries: HashMap<RamFrameKey, RamEntry>, |
| 172 | total_bytes: u64, |
| 173 | tick: u64, |
| 174 | evictions: u64, |
| 175 | } |
| 176 | |
| 177 | impl RamCacheInner { |
| 178 | fn evict_over_budget(&mut self) -> usize { |
| 179 | let mut evicted = 0; |
| 180 | while self.total_bytes > self.budget_bytes && !self.entries.is_empty() { |
| 181 | let Some((&oldest_key, _)) = self.entries.iter().min_by_key(|(_, e)| e.last_used) else { |
| 182 | break; |
| 183 | }; |
| 184 | if let Some(removed) = self.entries.remove(&oldest_key) { |
| 185 | self.total_bytes = self.total_bytes.saturating_sub(removed.frame.byte_size()); |
| 186 | self.evictions += 1; |
| 187 | evicted += 1; |
| 188 | } |
| 189 | } |
| 190 | evicted |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | /// Shareable, thread-safe LRU RAM frame cache. |
| 195 | #[derive(Clone)] |
| 196 | pub struct RamFrameCache { |
| 197 | inner: Arc<Mutex<RamCacheInner>>, |
| 198 | cache_epoch: Arc<AtomicU64>, |
| 199 | change_gen: Arc<AtomicU64>, |
| 200 | } |
| 201 | |
| 202 | impl Default for RamFrameCache { |
| 203 | fn default() -> Self { |
| 204 | Self::new(default_ram_cache_budget_mb()) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | impl From<Arc<RamFrameCache>> for RamFrameCache { |
| 209 | fn from(arc: Arc<RamFrameCache>) -> Self { |
| 210 | (*arc).clone() |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | impl RamFrameCache { |
| 215 | pub fn new(budget_mb: u64) -> Self { |
| 216 | Self { |
| 217 | inner: Arc::new(Mutex::new(RamCacheInner { |
| 218 | budget_bytes: budget_mb.saturating_mul(1024 * 1024), |
| 219 | entries: HashMap::new(), |
| 220 | total_bytes: 0, |
| 221 | tick: 0, |
| 222 | evictions: 0, |
| 223 | })), |
| 224 | cache_epoch: Arc::new(AtomicU64::new(1)), |
| 225 | change_gen: Arc::new(AtomicU64::new(1)), |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | pub fn with_budget_mb(budget_mb: u64) -> Self { |
| 230 | Self::new(budget_mb) |
| 231 | } |
| 232 | |
| 233 | pub fn epoch(&self) -> u64 { |
| 234 | self.cache_epoch.load(Ordering::Acquire) |
| 235 | } |
| 236 | |
| 237 | /// Monotonic counter incremented on cache entry insertion, eviction, clear, or invalidation |
| 238 | /// (unchanged on `get` hits), allowing UI callers to skip re-collecting cached frame ranges. |
| 239 | pub fn change_generation(&self) -> u64 { |
| 240 | self.change_gen.load(Ordering::Acquire) |
| 241 | } |
| 242 | |
| 243 | #[cfg(not(target_arch = "wasm32"))] |
| 244 | pub(crate) fn epoch_arc(&self) -> Arc<AtomicU64> { |
| 245 | Arc::clone(&self.cache_epoch) |
| 246 | } |
| 247 | |
| 248 | pub fn set_budget_mb(&self, budget_mb: u64) { |
| 249 | if let Ok(mut guard) = self.inner.lock() { |
| 250 | guard.budget_bytes = budget_mb.saturating_mul(1024 * 1024); |
| 251 | if guard.evict_over_budget() > 0 { |
| 252 | self.change_gen.fetch_add(1, Ordering::AcqRel); |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | pub fn budget_bytes(&self) -> u64 { |
| 258 | self.inner.lock().map(|g| g.budget_bytes).unwrap_or(0) |
| 259 | } |
| 260 | |
| 261 | pub fn budget_mb(&self) -> u64 { |
| 262 | self.budget_bytes() / (1024 * 1024) |
| 263 | } |
| 264 | |
| 265 | pub fn get(&self, key: RamFrameKey) -> Option<RamFrame> { |
| 266 | let mut guard = self.inner.lock().ok()?; |
| 267 | guard.tick += 1; |
| 268 | let tick = guard.tick; |
| 269 | let entry = guard.entries.get_mut(&key)?; |
| 270 | entry.last_used = tick; |
| 271 | Some(entry.frame.clone()) |
| 272 | } |
| 273 | |
| 274 | pub fn contains(&self, key: RamFrameKey) -> bool { |
| 275 | self.inner |
| 276 | .lock() |
| 277 | .map(|g| g.entries.contains_key(&key)) |
| 278 | .unwrap_or(false) |
| 279 | } |
| 280 | |
| 281 | pub fn insert(&self, key: RamFrameKey, frame: RamFrame) { |
| 282 | let Ok(mut guard) = self.inner.lock() else { |
| 283 | return; |
| 284 | }; |
| 285 | if Self::insert_locked(&mut guard, key, frame) { |
| 286 | self.change_gen.fetch_add(1, Ordering::AcqRel); |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | pub fn insert_if_epoch(&self, expected_epoch: u64, key: RamFrameKey, frame: RamFrame) -> bool { |
| 291 | let Ok(mut guard) = self.inner.lock() else { |
| 292 | return false; |
| 293 | }; |
| 294 | if self.cache_epoch.load(Ordering::Acquire) != expected_epoch { |
| 295 | return false; |
| 296 | } |
| 297 | if Self::insert_locked(&mut guard, key, frame) { |
| 298 | self.change_gen.fetch_add(1, Ordering::AcqRel); |
| 299 | } |
| 300 | true |
| 301 | } |
| 302 | |
| 303 | fn insert_locked(guard: &mut RamCacheInner, key: RamFrameKey, frame: RamFrame) -> bool { |
| 304 | let bytes = frame.byte_size(); |
| 305 | if guard.budget_bytes == 0 || bytes > guard.budget_bytes { |
| 306 | return false; |
| 307 | } |
| 308 | guard.tick += 1; |
| 309 | let tick = guard.tick; |
| 310 | if let Some(old) = guard.entries.remove(&key) { |
| 311 | guard.total_bytes = guard.total_bytes.saturating_sub(old.frame.byte_size()); |
| 312 | } |
| 313 | guard.total_bytes += bytes; |
| 314 | guard.entries.insert(key, RamEntry { frame, last_used: tick }); |
| 315 | let _ = guard.evict_over_budget(); |
| 316 | true |
| 317 | } |
| 318 | |
| 319 | pub fn clear(&self) { |
| 320 | if let Ok(mut guard) = self.inner.lock() { |
| 321 | guard.entries.clear(); |
| 322 | guard.total_bytes = 0; |
| 323 | self.cache_epoch.fetch_add(1, Ordering::AcqRel); |
| 324 | self.change_gen.fetch_add(1, Ordering::AcqRel); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | /// Evicts cached frames belonging to older composition revisions. |
| 329 | pub fn invalidate_other_revisions(&self, keep_revision: u64) -> usize { |
| 330 | let Ok(mut guard) = self.inner.lock() else { |
| 331 | return 0; |
| 332 | }; |
| 333 | let stale: Vec<RamFrameKey> = guard |
| 334 | .entries |
| 335 | .keys() |
| 336 | .copied() |
| 337 | .filter(|k| k.revision != keep_revision) |
| 338 | .collect(); |
| 339 | let count = stale.len(); |
| 340 | for k in stale { |
| 341 | if let Some(removed) = guard.entries.remove(&k) { |
| 342 | guard.total_bytes = guard.total_bytes.saturating_sub(removed.frame.byte_size()); |
| 343 | } |
| 344 | } |
| 345 | if count > 0 { |
| 346 | self.change_gen.fetch_add(1, Ordering::AcqRel); |
| 347 | } |
| 348 | count |
| 349 | } |
| 350 | |
| 351 | /// Returns sorted, merged inclusive `[start, end]` frame ranges currently cached |
| 352 | /// for the specified target node, revision, and quality settings. |
| 353 | pub fn cached_frame_ranges( |
| 354 | &self, |
| 355 | target: NodeId, |
| 356 | revision: u64, |
| 357 | proxy_scale: u32, |
| 358 | hiq: bool, |
| 359 | use_proxy_clips: bool, |
| 360 | ) -> Vec<(i64, i64)> { |
| 361 | let Ok(guard) = self.inner.lock() else { |
| 362 | return Vec::new(); |
| 363 | }; |
| 364 | let mut frames: Vec<i64> = guard |
| 365 | .entries |
| 366 | .keys() |
| 367 | .filter(|k| { |
| 368 | k.target == target |
| 369 | && k.revision == revision |
| 370 | && k.proxy_scale == proxy_scale |
| 371 | && k.hiq == hiq |
| 372 | && k.use_proxy_clips == use_proxy_clips |
| 373 | }) |
| 374 | .map(|k| k.frame) |
| 375 | .collect(); |
| 376 | if frames.is_empty() { |
| 377 | return Vec::new(); |
| 378 | } |
| 379 | frames.sort_unstable(); |
| 380 | frames.dedup(); |
| 381 | let mut ranges = Vec::new(); |
| 382 | let mut start = frames[0]; |
| 383 | let mut prev = frames[0]; |
| 384 | for &f in &frames[1..] { |
| 385 | if f == prev + 1 { |
| 386 | prev = f; |
| 387 | } else { |
| 388 | ranges.push((start, prev)); |
| 389 | start = f; |
| 390 | prev = f; |
| 391 | } |
| 392 | } |
| 393 | ranges.push((start, prev)); |
| 394 | ranges |
| 395 | } |
| 396 | |
| 397 | pub fn entry_count(&self) -> usize { |
| 398 | self.inner.lock().map(|g| g.entries.len()).unwrap_or(0) |
| 399 | } |
| 400 | |
| 401 | pub fn total_bytes(&self) -> u64 { |
| 402 | self.inner.lock().map(|g| g.total_bytes).unwrap_or(0) |
| 403 | } |
| 404 | |
| 405 | pub fn total_mb(&self) -> f64 { |
| 406 | self.total_bytes() as f64 / (1024.0 * 1024.0) |
| 407 | } |
| 408 | |
| 409 | pub fn eviction_count(&self) -> u64 { |
| 410 | self.inner.lock().map(|g| g.evictions).unwrap_or(0) |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | /// Parameters for a background lookahead pre-fetch window. |
| 415 | #[cfg(not(target_arch = "wasm32"))] |
| 416 | #[derive(Clone)] |
| 417 | pub struct PrefetchJob { |
| 418 | pub comp: Comp, |
| 419 | pub target: NodeId, |
| 420 | pub center_frame: i64, |
| 421 | pub range: [i64; 2], |
| 422 | pub lookahead: i64, |
| 423 | pub proxy_scale: u32, |
| 424 | pub hiq: bool, |
| 425 | pub use_proxy_clips: bool, |
| 426 | } |
| 427 | |
| 428 | #[cfg(not(target_arch = "wasm32"))] |
| 429 | struct WorkerSlot { |
| 430 | job: Option<(u64, PrefetchJob)>, |
| 431 | shutdown: bool, |
| 432 | } |
| 433 | |
| 434 | /// Background lookahead frame pre-fetcher backed by a background `Engine` (either sharing |
| 435 | /// the host `wgpu::Device`/`wgpu::Queue` or initializing a standalone headless device). |
| 436 | /// |
| 437 | /// Calling `request_lookahead` or `cancel` immediately increments an atomic generation |
| 438 | /// counter so any in-flight lookahead loop aborts before evaluating another frame. |
| 439 | #[cfg(not(target_arch = "wasm32"))] |
| 440 | pub struct RamPrefetcher { |
| 441 | cache: RamFrameCache, |
| 442 | cache_epoch: Arc<AtomicU64>, |
| 443 | shared_device: Option<(Arc<wgpu::Device>, Arc<wgpu::Queue>)>, |
| 444 | vram_budget_mb: u64, |
| 445 | media_budget_mb: u64, |
| 446 | generation: Arc<AtomicU64>, |
| 447 | shutdown: Arc<AtomicBool>, |
| 448 | busy: Arc<AtomicBool>, |
| 449 | completed_frames: Arc<AtomicU64>, |
| 450 | slot: Arc<(Mutex<WorkerSlot>, Condvar)>, |
| 451 | finished: Arc<(Mutex<bool>, Condvar)>, |
| 452 | worker: Option<JoinHandle<()>>, |
| 453 | } |
| 454 | |
| 455 | #[cfg(not(target_arch = "wasm32"))] |
| 456 | fn finish_pending_readback( |
| 457 | pending: Option<(PendingReadback, RamFrameKey, [u32; 2], f64)>, |
| 458 | engine: &Engine, |
| 459 | cache: &RamFrameCache, |
| 460 | completed: &AtomicU64, |
| 461 | job_epoch: u64, |
| 462 | is_cancelled: &impl Fn() -> bool, |
| 463 | ) -> bool { |
| 464 | let Some((rb, key, size, eval_ms)) = pending else { |
| 465 | return true; |
| 466 | }; |
| 467 | if is_cancelled() { |
| 468 | drop(rb); |
| 469 | return false; |
| 470 | } |
| 471 | let Ok(rgba) = rb.finish(engine) else { |
| 472 | return true; |
| 473 | }; |
| 474 | if is_cancelled() { |
| 475 | return false; |
| 476 | } |
| 477 | if cache.insert_if_epoch( |
| 478 | job_epoch, |
| 479 | key, |
| 480 | RamFrame { |
| 481 | size, |
| 482 | rgba: Arc::new(rgba), |
| 483 | eval_ms, |
| 484 | }, |
| 485 | ) { |
| 486 | completed.fetch_add(1, Ordering::AcqRel); |
| 487 | true |
| 488 | } else { |
| 489 | false |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | #[cfg(not(target_arch = "wasm32"))] |
| 494 | impl RamPrefetcher { |
| 495 | pub fn new(cache: RamFrameCache, worker_vram_budget_mb: u64) -> Self { |
| 496 | Self::init( |
| 497 | None, |
| 498 | cache, |
| 499 | worker_vram_budget_mb.max(128), |
| 500 | default_prefetch_media_budget_mb().max(512), |
| 501 | ) |
| 502 | } |
| 503 | |
| 504 | /// Creates a `RamPrefetcher` whose worker `Engine` shares an existing `wgpu::Device` |
| 505 | /// and `wgpu::Queue` with RAM-scaled VRAM and media budgets. |
| 506 | pub fn new_with_device( |
| 507 | device: Arc<wgpu::Device>, |
| 508 | queue: Arc<wgpu::Queue>, |
| 509 | cache: impl Into<RamFrameCache>, |
| 510 | ) -> Self { |
| 511 | Self::init( |
| 512 | Some((device, queue)), |
| 513 | cache.into(), |
| 514 | default_prefetch_vram_budget_mb(), |
| 515 | default_prefetch_media_budget_mb(), |
| 516 | ) |
| 517 | } |
| 518 | |
| 519 | fn init( |
| 520 | shared_device: Option<(Arc<wgpu::Device>, Arc<wgpu::Queue>)>, |
| 521 | cache: RamFrameCache, |
| 522 | vram_budget_mb: u64, |
| 523 | media_budget_mb: u64, |
| 524 | ) -> Self { |
| 525 | let cache_epoch = cache.epoch_arc(); |
| 526 | Self { |
| 527 | cache, |
| 528 | cache_epoch, |
| 529 | shared_device, |
| 530 | vram_budget_mb, |
| 531 | media_budget_mb, |
| 532 | generation: Arc::new(AtomicU64::new(1)), |
| 533 | shutdown: Arc::new(AtomicBool::new(false)), |
| 534 | busy: Arc::new(AtomicBool::new(false)), |
| 535 | completed_frames: Arc::new(AtomicU64::new(0)), |
| 536 | slot: Arc::new(( |
| 537 | Mutex::new(WorkerSlot { |
| 538 | job: None, |
| 539 | shutdown: false, |
| 540 | }), |
| 541 | Condvar::new(), |
| 542 | )), |
| 543 | finished: Arc::new((Mutex::new(false), Condvar::new())), |
| 544 | worker: None, |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | pub fn cache(&self) -> &RamFrameCache { |
| 549 | &self.cache |
| 550 | } |
| 551 | |
| 552 | pub fn is_busy(&self) -> bool { |
| 553 | self.busy.load(Ordering::Acquire) |
| 554 | } |
| 555 | |
| 556 | pub fn completed_frames(&self) -> u64 { |
| 557 | self.completed_frames.load(Ordering::Acquire) |
| 558 | } |
| 559 | |
| 560 | /// Cancels any active lookahead pass immediately without bumping `cache_epoch`, |
| 561 | /// preserving the background worker's `MediaCache` across edits and scrubs. |
| 562 | pub fn cancel(&self) { |
| 563 | self.generation.fetch_add(1, Ordering::AcqRel); |
| 564 | if let Ok(mut guard) = self.slot.0.lock() { |
| 565 | guard.job = None; |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | /// Schedules background lookahead rendering starting at `job.center_frame + 1` |
| 570 | /// through `min(job.range[1], job.center_frame + job.lookahead)`, wrapping around |
| 571 | /// `[range[0], range[1]]` and skipping frames that are already cached. |
| 572 | pub fn request_lookahead(&mut self, job: PrefetchJob) { |
| 573 | self.ensure_worker(); |
| 574 | let job_gen = self.generation.fetch_add(1, Ordering::AcqRel) + 1; |
| 575 | if let Ok(mut guard) = self.slot.0.lock() { |
| 576 | guard.job = Some((job_gen, job)); |
| 577 | self.slot.1.notify_one(); |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | fn ensure_worker(&mut self) { |
| 582 | if self.worker.is_some() { |
| 583 | return; |
| 584 | } |
| 585 | let cache = self.cache.clone(); |
| 586 | let cache_epoch = self.cache_epoch.clone(); |
| 587 | let shared_device = self.shared_device.clone(); |
| 588 | let vram_mb = self.vram_budget_mb; |
| 589 | let media_mb = self.media_budget_mb; |
| 590 | let generation = self.generation.clone(); |
| 591 | let shutdown = self.shutdown.clone(); |
| 592 | let busy = self.busy.clone(); |
| 593 | let completed = self.completed_frames.clone(); |
| 594 | let slot = self.slot.clone(); |
| 595 | let finished = self.finished.clone(); |
| 596 | if let Ok(mut f) = finished.0.lock() { |
| 597 | *f = false; |
| 598 | } |
| 599 | |
| 600 | let handle = thread::Builder::new() |
| 601 | .name("fission-ram-prefetch".to_owned()) |
| 602 | .spawn(move || { |
| 603 | struct FinishGuard(Arc<(Mutex<bool>, Condvar)>); |
| 604 | impl Drop for FinishGuard { |
| 605 | fn drop(&mut self) { |
| 606 | if let Ok(mut f) = self.0.0.lock() { |
| 607 | *f = true; |
| 608 | self.0.1.notify_all(); |
| 609 | } |
| 610 | } |
| 611 | } |
| 612 | let _finish_guard = FinishGuard(finished); |
| 613 | |
| 614 | let mut engine_opt: Option<Engine> = None; |
| 615 | let mut last_comp_rev: Option<u64> = None; |
| 616 | let mut last_cache_epoch: Option<u64> = None; |
| 617 | |
| 618 | loop { |
| 619 | let (job_gen, job) = { |
| 620 | let Ok(mut guard) = slot.0.lock() else { |
| 621 | break; |
| 622 | }; |
| 623 | while !guard.shutdown && guard.job.is_none() { |
| 624 | guard = match slot.1.wait(guard) { |
| 625 | Ok(g) => g, |
| 626 | Err(_) => return, |
| 627 | }; |
| 628 | } |
| 629 | if guard.shutdown || shutdown.load(Ordering::Acquire) { |
| 630 | break; |
| 631 | } |
| 632 | match guard.job.take() { |
| 633 | Some(item) => item, |
| 634 | None => continue, |
| 635 | } |
| 636 | }; |
| 637 | |
| 638 | if shutdown.load(Ordering::Acquire) |
| 639 | || generation.load(Ordering::Acquire) != job_gen |
| 640 | { |
| 641 | continue; |
| 642 | } |
| 643 | |
| 644 | if engine_opt.is_none() { |
| 645 | if let Some((ref dev, ref q)) = shared_device { |
| 646 | engine_opt = Some(Engine::new_with_device( |
| 647 | Arc::clone(dev), |
| 648 | Arc::clone(q), |
| 649 | vram_mb.saturating_mul(1024 * 1024), |
| 650 | media_mb.saturating_mul(1024 * 1024), |
| 651 | )); |
| 652 | } else { |
| 653 | match Engine::new_headless() { |
| 654 | Ok(mut eng) => { |
| 655 | eng.set_vram_budget_mb(vram_mb); |
| 656 | eng.media.set_budget_mb(media_mb); |
| 657 | engine_opt = Some(eng); |
| 658 | } |
| 659 | Err(_) => { |
| 660 | // Headless GPU unavailable; stay idle until shutdown. |
| 661 | continue; |
| 662 | } |
| 663 | } |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | let Some(engine) = engine_opt.as_mut() else { |
| 668 | continue; |
| 669 | }; |
| 670 | |
| 671 | let job_epoch = cache_epoch.load(Ordering::Acquire); |
| 672 | if last_cache_epoch != Some(job_epoch) { |
| 673 | engine.bust_all_caches(); |
| 674 | last_cache_epoch = Some(job_epoch); |
| 675 | last_comp_rev = Some(job.comp.revision); |
| 676 | } else if last_comp_rev != Some(job.comp.revision) { |
| 677 | engine.bust_gpu_cache(); |
| 678 | last_comp_rev = Some(job.comp.revision); |
| 679 | } |
| 680 | engine.proxy_scale = job.proxy_scale.max(1); |
| 681 | engine.hiq = job.hiq; |
| 682 | engine.use_proxy_clips = job.use_proxy_clips; |
| 683 | |
| 684 | if job.target.0 >= job.comp.nodes.len() { |
| 685 | continue; |
| 686 | } |
| 687 | busy.store(true, Ordering::Release); |
| 688 | let start = job.range[0].min(job.range[1]); |
| 689 | let end = job.range[0].max(job.range[1]); |
| 690 | let span = (i128::from(end) - i128::from(start) + 1).max(1); |
| 691 | let count = i128::from(job.lookahead.max(0)).min(span).min(i128::from(i64::MAX)) as i64; |
| 692 | |
| 693 | let is_cancelled = || { |
| 694 | shutdown.load(Ordering::Acquire) |
| 695 | || generation.load(Ordering::Acquire) != job_gen |
| 696 | || cache_epoch.load(Ordering::Acquire) != job_epoch |
| 697 | }; |
| 698 | |
| 699 | // Keep media pre-decode chunks small (2 frames) so edits/scrubs cancel promptly. |
| 700 | const PREFETCH_MEDIA_CHUNK: i64 = 2; |
| 701 | let mut pending: Option<(PendingReadback, RamFrameKey, [u32; 2], f64)> = None; |
| 702 | let mut aborted = false; |
| 703 | let mut chunk_start = 1i64; |
| 704 | 'prefetch: while chunk_start <= count { |
| 705 | if is_cancelled() { |
| 706 | aborted = true; |
| 707 | drop(pending.take()); |
| 708 | break 'prefetch; |
| 709 | } |
| 710 | let chunk_end = (chunk_start + PREFETCH_MEDIA_CHUNK - 1).min(count); |
| 711 | let mut chunk_items = Vec::with_capacity((chunk_end - chunk_start + 1) as usize); |
| 712 | let mut batch_frames = Vec::with_capacity((chunk_end - chunk_start + 1) as usize); |
| 713 | for offset in chunk_start..=chunk_end { |
| 714 | let f_i128 = i128::from(start) |
| 715 | + (i128::from(job.center_frame) - i128::from(start) + i128::from(offset)) |
| 716 | .rem_euclid(span); |
| 717 | let f = f_i128 as i64; |
| 718 | let key = RamFrameKey { |
| 719 | target: job.target, |
| 720 | revision: job.comp.revision, |
| 721 | frame: f, |
| 722 | proxy_scale: engine.proxy_scale, |
| 723 | hiq: engine.hiq, |
| 724 | use_proxy_clips: engine.use_proxy_clips, |
| 725 | }; |
| 726 | if !cache.contains(key) { |
| 727 | chunk_items.push((f, key)); |
| 728 | batch_frames.push(f as f64); |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | if batch_frames.len() > 1 && !is_cancelled() { |
| 733 | engine.media.prefetch_frames_with_proxy( |
| 734 | &job.comp, |
| 735 | job.target, |
| 736 | &batch_frames, |
| 737 | &engine.expr, |
| 738 | job.use_proxy_clips, |
| 739 | ); |
| 740 | } |
| 741 | |
| 742 | for (f, key) in chunk_items { |
| 743 | if is_cancelled() { |
| 744 | aborted = true; |
| 745 | drop(pending.take()); |
| 746 | break 'prefetch; |
| 747 | } |
| 748 | if cache.contains(key) { |
| 749 | continue; |
| 750 | } |
| 751 | let (tex, stats) = engine.evaluate(&job.comp, job.target, f as f64); |
| 752 | if is_cancelled() { |
| 753 | aborted = true; |
| 754 | drop(pending.take()); |
| 755 | break 'prefetch; |
| 756 | } |
| 757 | match engine.begin_readback_rgba(&tex) { |
| 758 | Ok(next_rb) => { |
| 759 | // Overlap frame N+1 GPU eval with frame N async readback. |
| 760 | let prev = pending.replace((next_rb, key, tex.size, stats.eval_ms)); |
| 761 | if !finish_pending_readback( |
| 762 | prev, |
| 763 | engine, |
| 764 | &cache, |
| 765 | &completed, |
| 766 | job_epoch, |
| 767 | &is_cancelled, |
| 768 | ) { |
| 769 | aborted = true; |
| 770 | drop(pending.take()); |
| 771 | break 'prefetch; |
| 772 | } |
| 773 | } |
| 774 | Err(_) => { |
| 775 | if !finish_pending_readback( |
| 776 | pending.take(), |
| 777 | engine, |
| 778 | &cache, |
| 779 | &completed, |
| 780 | job_epoch, |
| 781 | &is_cancelled, |
| 782 | ) { |
| 783 | aborted = true; |
| 784 | break 'prefetch; |
| 785 | } |
| 786 | } |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | chunk_start = chunk_end + 1; |
| 791 | } |
| 792 | if !aborted { |
| 793 | let _ = finish_pending_readback( |
| 794 | pending.take(), |
| 795 | engine, |
| 796 | &cache, |
| 797 | &completed, |
| 798 | job_epoch, |
| 799 | &is_cancelled, |
| 800 | ); |
| 801 | } else { |
| 802 | drop(pending.take()); |
| 803 | } |
| 804 | busy.store(false, Ordering::Release); |
| 805 | } |
| 806 | }) |
| 807 | .ok(); |
| 808 | |
| 809 | self.worker = handle; |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | #[cfg(not(target_arch = "wasm32"))] |
| 814 | impl Drop for RamPrefetcher { |
| 815 | fn drop(&mut self) { |
| 816 | self.shutdown.store(true, Ordering::Release); |
| 817 | self.generation.fetch_add(1, Ordering::AcqRel); |
| 818 | if let Ok(mut guard) = self.slot.0.lock() { |
| 819 | guard.shutdown = true; |
| 820 | guard.job = None; |
| 821 | self.slot.1.notify_all(); |
| 822 | } |
| 823 | if let Some(handle) = self.worker.take() { |
| 824 | let done = if let Ok(guard) = self.finished.0.lock() { |
| 825 | if *guard { |
| 826 | true |
| 827 | } else { |
| 828 | let (g, _) = self |
| 829 | .finished |
| 830 | .1 |
| 831 | .wait_timeout_while(guard, std::time::Duration::from_millis(1500), |f| !*f) |
| 832 | .unwrap_or_else(|e| e.into_inner()); |
| 833 | *g |
| 834 | } |
| 835 | } else { |
| 836 | false |
| 837 | }; |
| 838 | if done { |
| 839 | let _ = handle.join(); |
| 840 | } |
| 841 | } |
| 842 | } |
| 843 | } |
| 844 | |
| 845 | #[cfg(all(test, not(target_arch = "wasm32")))] |
| 846 | mod tests { |
| 847 | use super::*; |
| 848 | use std::time::{Duration, Instant}; |
| 849 | |
| 850 | fn dummy_frame(w: u32, h: u32) -> RamFrame { |
| 851 | RamFrame { |
| 852 | size: [w, h], |
| 853 | rgba: Arc::new(vec![128u8; (w * h * 4) as usize]), |
| 854 | eval_ms: 1.5, |
| 855 | } |
| 856 | } |
| 857 | |
| 858 | #[test] |
| 859 | fn ram_cache_enforces_budget_lru_and_merges_ranges() { |
| 860 | // 4 MB budget -> holds at most 4 frames of 1 MB each (512x512 RGBA8 = 1 MB) |
| 861 | let cache = RamFrameCache::new(4); |
| 862 | let node = NodeId(0); |
| 863 | for f in [10, 11, 12, 14] { |
| 864 | cache.insert( |
| 865 | RamFrameKey { |
| 866 | target: node, |
| 867 | revision: 1, |
| 868 | frame: f, |
| 869 | proxy_scale: 1, |
| 870 | hiq: true, |
| 871 | use_proxy_clips: false, |
| 872 | }, |
| 873 | dummy_frame(512, 512), |
| 874 | ); |
| 875 | } |
| 876 | assert_eq!(cache.entry_count(), 4); |
| 877 | assert_eq!( |
| 878 | cache.cached_frame_ranges(node, 1, 1, true, false), |
| 879 | vec![(10, 12), (14, 14)] |
| 880 | ); |
| 881 | |
| 882 | // Touch frame 10 so frame 11 becomes LRU, then insert frame 15. |
| 883 | assert!(cache |
| 884 | .get(RamFrameKey { |
| 885 | target: node, |
| 886 | revision: 1, |
| 887 | frame: 10, |
| 888 | proxy_scale: 1, |
| 889 | hiq: true, |
| 890 | use_proxy_clips: false, |
| 891 | }) |
| 892 | .is_some()); |
| 893 | cache.insert( |
| 894 | RamFrameKey { |
| 895 | target: node, |
| 896 | revision: 1, |
| 897 | frame: 15, |
| 898 | proxy_scale: 1, |
| 899 | hiq: true, |
| 900 | use_proxy_clips: false, |
| 901 | }, |
| 902 | dummy_frame(512, 512), |
| 903 | ); |
| 904 | assert_eq!(cache.entry_count(), 4); |
| 905 | assert!(cache.eviction_count() >= 1); |
| 906 | assert_eq!( |
| 907 | cache.cached_frame_ranges(node, 1, 1, true, false), |
| 908 | vec![(10, 10), (12, 12), (14, 15)] |
| 909 | ); |
| 910 | |
| 911 | // Revision invalidation drops old revisions cleanly |
| 912 | let evicted = cache.invalidate_other_revisions(2); |
| 913 | assert_eq!(evicted, 4); |
| 914 | assert_eq!(cache.entry_count(), 0); |
| 915 | } |
| 916 | |
| 917 | #[test] |
| 918 | fn ram_prefetcher_renders_lookahead_and_cancels_cleanly() { |
| 919 | let comp_src = r#" |
| 920 | Composition { |
| 921 | CurrentTime = 0, |
| 922 | RenderRange = { 0, 10 }, |
| 923 | GlobalRange = { 0, 10 }, |
| 924 | Tools = ordered() { |
| 925 | BG1 = Background { |
| 926 | Inputs = { |
| 927 | Width = Input { Value = 64, }, |
| 928 | Height = Input { Value = 64, }, |
| 929 | TopLeftRed = Input { Value = 0.5, }, |
| 930 | TopLeftAlpha = Input { Value = 1.0, }, |
| 931 | }, |
| 932 | }, |
| 933 | }, |
| 934 | } |
| 935 | "#; |
| 936 | let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); |
| 937 | let target = comp.find_node("BG1").expect("BG1"); |
| 938 | |
| 939 | let cache = RamFrameCache::new(64); |
| 940 | let mut prefetcher = RamPrefetcher::new(cache.clone(), 128); |
| 941 | prefetcher.request_lookahead(PrefetchJob { |
| 942 | comp: comp.clone(), |
| 943 | target, |
| 944 | center_frame: 0, |
| 945 | range: [0, 10], |
| 946 | lookahead: 4, |
| 947 | proxy_scale: 1, |
| 948 | hiq: true, |
| 949 | use_proxy_clips: false, |
| 950 | }); |
| 951 | |
| 952 | let deadline = Instant::now() + Duration::from_secs(10); |
| 953 | while Instant::now() < deadline { |
| 954 | if cache.cached_frame_ranges(target, comp.revision, 1, true, false) == vec![(1, 4)] { |
| 955 | break; |
| 956 | } |
| 957 | thread::sleep(Duration::from_millis(20)); |
| 958 | } |
| 959 | assert_eq!( |
| 960 | cache.cached_frame_ranges(target, comp.revision, 1, true, false), |
| 961 | vec![(1, 4)] |
| 962 | ); |
| 963 | prefetcher.cancel(); |
| 964 | } |
| 965 | |
| 966 | #[test] |
| 967 | fn ram_prefetcher_loop_wraparound_and_epoch_clear_invalidation() { |
| 968 | let comp_src = r#" |
| 969 | Composition { |
| 970 | CurrentTime = 13, |
| 971 | RenderRange = { 10, 14 }, |
| 972 | GlobalRange = { 10, 14 }, |
| 973 | Tools = ordered() { |
| 974 | BG1 = Background { |
| 975 | Inputs = { |
| 976 | Width = Input { Value = 32, }, |
| 977 | Height = Input { Value = 32, }, |
| 978 | TopLeftRed = Input { Value = 0.25, }, |
| 979 | TopLeftAlpha = Input { Value = 1.0, }, |
| 980 | }, |
| 981 | }, |
| 982 | }, |
| 983 | } |
| 984 | "#; |
| 985 | let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); |
| 986 | let target = comp.find_node("BG1").expect("BG1"); |
| 987 | |
| 988 | let cache = RamFrameCache::new(64); |
| 989 | let initial_epoch = cache.epoch(); |
| 990 | let mut prefetcher = RamPrefetcher::new(cache.clone(), 128); |
| 991 | |
| 992 | // Starting near end of [10, 14] at frame 13 with lookahead 4 must wrap to 14, 10, 11, 12. |
| 993 | prefetcher.request_lookahead(PrefetchJob { |
| 994 | comp: comp.clone(), |
| 995 | target, |
| 996 | center_frame: 13, |
| 997 | range: [10, 14], |
| 998 | lookahead: 4, |
| 999 | proxy_scale: 1, |
| 1000 | hiq: true, |
| 1001 | use_proxy_clips: false, |
| 1002 | }); |
| 1003 | |
| 1004 | let deadline = Instant::now() + Duration::from_secs(10); |
| 1005 | while Instant::now() < deadline { |
| 1006 | if cache.cached_frame_ranges(target, comp.revision, 1, true, false) |
| 1007 | == vec![(10, 12), (14, 14)] |
| 1008 | { |
| 1009 | break; |
| 1010 | } |
| 1011 | thread::sleep(Duration::from_millis(15)); |
| 1012 | } |
| 1013 | assert_eq!( |
| 1014 | cache.cached_frame_ranges(target, comp.revision, 1, true, false), |
| 1015 | vec![(10, 12), (14, 14)] |
| 1016 | ); |
| 1017 | |
| 1018 | // Clearing cache bumps epoch and insert_if_epoch rejects stale pre-clear writes. |
| 1019 | cache.clear(); |
| 1020 | assert!(cache.epoch() > initial_epoch); |
| 1021 | let stale_key = RamFrameKey { |
| 1022 | target, |
| 1023 | revision: comp.revision, |
| 1024 | frame: 13, |
| 1025 | proxy_scale: 1, |
| 1026 | hiq: true, |
| 1027 | use_proxy_clips: false, |
| 1028 | }; |
| 1029 | assert!(!cache.insert_if_epoch(initial_epoch, stale_key, dummy_frame(32, 32))); |
| 1030 | assert_eq!(cache.entry_count(), 0); |
| 1031 | |
| 1032 | // Re-requesting with the SAME comp.revision works after epoch bump (busting worker Engine). |
| 1033 | let after_clear_epoch = cache.epoch(); |
| 1034 | prefetcher.request_lookahead(PrefetchJob { |
| 1035 | comp: comp.clone(), |
| 1036 | target, |
| 1037 | center_frame: 14, |
| 1038 | range: [10, 14], |
| 1039 | lookahead: 5, |
| 1040 | proxy_scale: 1, |
| 1041 | hiq: true, |
| 1042 | use_proxy_clips: false, |
| 1043 | }); |
| 1044 | |
| 1045 | let deadline2 = Instant::now() + Duration::from_secs(10); |
| 1046 | while Instant::now() < deadline2 { |
| 1047 | if cache.cached_frame_ranges(target, comp.revision, 1, true, false) == vec![(10, 14)] { |
| 1048 | break; |
| 1049 | } |
| 1050 | thread::sleep(Duration::from_millis(15)); |
| 1051 | } |
| 1052 | assert_eq!( |
| 1053 | cache.cached_frame_ranges(target, comp.revision, 1, true, false), |
| 1054 | vec![(10, 14)] |
| 1055 | ); |
| 1056 | |
| 1057 | prefetcher.cancel(); |
| 1058 | assert_eq!(cache.epoch(), after_clear_epoch); |
| 1059 | } |
| 1060 | |
| 1061 | #[test] |
| 1062 | fn ram_prefetcher_cancel_does_not_bump_cache_epoch() { |
| 1063 | let comp_src = r#" |
| 1064 | Composition { |
| 1065 | CurrentTime = 0, |
| 1066 | RenderRange = { 0, 4 }, |
| 1067 | GlobalRange = { 0, 4 }, |
| 1068 | Tools = ordered() { |
| 1069 | BG1 = Background { |
| 1070 | Inputs = { |
| 1071 | Width = Input { Value = 32, }, |
| 1072 | Height = Input { Value = 32, }, |
| 1073 | }, |
| 1074 | }, |
| 1075 | }, |
| 1076 | } |
| 1077 | "#; |
| 1078 | let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); |
| 1079 | let target = comp.find_node("BG1").expect("BG1"); |
| 1080 | let cache = RamFrameCache::new(64); |
| 1081 | let mut prefetcher = RamPrefetcher::new(cache.clone(), 128); |
| 1082 | let epoch0 = cache.epoch(); |
| 1083 | |
| 1084 | prefetcher.cancel(); |
| 1085 | assert_eq!(cache.epoch(), epoch0); |
| 1086 | |
| 1087 | prefetcher.request_lookahead(PrefetchJob { |
| 1088 | comp, |
| 1089 | target, |
| 1090 | center_frame: 0, |
| 1091 | range: [0, 4], |
| 1092 | lookahead: 3, |
| 1093 | proxy_scale: 1, |
| 1094 | hiq: true, |
| 1095 | use_proxy_clips: false, |
| 1096 | }); |
| 1097 | prefetcher.cancel(); |
| 1098 | assert_eq!(cache.epoch(), epoch0); |
| 1099 | |
| 1100 | // Only explicit RamFrameCache::clear() bumps the cache epoch. |
| 1101 | cache.clear(); |
| 1102 | assert!(cache.epoch() > epoch0); |
| 1103 | } |
| 1104 | |
| 1105 | #[test] |
| 1106 | fn ram_prefetcher_new_with_device_shares_device_and_renders_lookahead() { |
| 1107 | let host_engine = Engine::new_headless().expect("gpu"); |
| 1108 | let comp_src = r#" |
| 1109 | Composition { |
| 1110 | CurrentTime = 0, |
| 1111 | RenderRange = { 0, 5 }, |
| 1112 | GlobalRange = { 0, 5 }, |
| 1113 | Tools = ordered() { |
| 1114 | BG1 = Background { |
| 1115 | Inputs = { |
| 1116 | Width = Input { Value = 64, }, |
| 1117 | Height = Input { Value = 64, }, |
| 1118 | TopLeftGreen = Input { Value = 0.75, }, |
| 1119 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1120 | }, |
| 1121 | }, |
| 1122 | }, |
| 1123 | } |
| 1124 | "#; |
| 1125 | let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); |
| 1126 | let target = comp.find_node("BG1").expect("BG1"); |
| 1127 | let cache = RamFrameCache::new(64); |
| 1128 | let mut prefetcher = RamPrefetcher::new_with_device( |
| 1129 | host_engine.device_arc(), |
| 1130 | host_engine.queue_arc(), |
| 1131 | cache.clone(), |
| 1132 | ); |
| 1133 | assert_eq!(prefetcher.vram_budget_mb, default_prefetch_vram_budget_mb()); |
| 1134 | assert_eq!(prefetcher.media_budget_mb, default_prefetch_media_budget_mb()); |
| 1135 | |
| 1136 | prefetcher.request_lookahead(PrefetchJob { |
| 1137 | comp: comp.clone(), |
| 1138 | target, |
| 1139 | center_frame: 0, |
| 1140 | range: [0, 5], |
| 1141 | lookahead: 3, |
| 1142 | proxy_scale: 1, |
| 1143 | hiq: true, |
| 1144 | use_proxy_clips: false, |
| 1145 | }); |
| 1146 | |
| 1147 | let deadline = Instant::now() + Duration::from_secs(10); |
| 1148 | while Instant::now() < deadline { |
| 1149 | if cache.cached_frame_ranges(target, comp.revision, 1, true, false) == vec![(1, 3)] { |
| 1150 | break; |
| 1151 | } |
| 1152 | thread::sleep(Duration::from_millis(15)); |
| 1153 | } |
| 1154 | assert_eq!( |
| 1155 | cache.cached_frame_ranges(target, comp.revision, 1, true, false), |
| 1156 | vec![(1, 3)] |
| 1157 | ); |
| 1158 | prefetcher.cancel(); |
| 1159 | } |
| 1160 | |
| 1161 | #[test] |
| 1162 | fn system_memory_and_ram_budget_scaling() { |
| 1163 | const GIB: u64 = 1024 * 1024 * 1024; |
| 1164 | assert!(system_memory_bytes() >= GIB); |
| 1165 | assert_eq!(ram_cache_budget_mb_for_total_bytes(8 * GIB), DEFAULT_RAM_CACHE_MB); |
| 1166 | assert_eq!(ram_cache_budget_mb_for_total_bytes(16 * GIB), 2048); |
| 1167 | assert_eq!(ram_cache_budget_mb_for_total_bytes(32 * GIB), 4096); |
| 1168 | assert_eq!(ram_cache_budget_mb_for_total_bytes(64 * GIB), 8192); |
| 1169 | assert_eq!(ram_cache_budget_mb_for_total_bytes(128 * GIB), 16384); |
| 1170 | assert_eq!(ram_cache_budget_mb_for_total_bytes(256 * GIB), 32768); |
| 1171 | |
| 1172 | let default_cache = RamFrameCache::default(); |
| 1173 | assert_eq!(default_cache.budget_mb(), default_ram_cache_budget_mb()); |
| 1174 | |
| 1175 | let explicit = RamFrameCache::with_budget_mb(32); |
| 1176 | assert_eq!(explicit.budget_mb(), 32); |
| 1177 | assert_eq!(explicit.budget_bytes(), 32 * 1024 * 1024); |
| 1178 | explicit.set_budget_mb(16); |
| 1179 | assert_eq!(explicit.budget_mb(), 16); |
| 1180 | assert_eq!(explicit.budget_bytes(), 16 * 1024 * 1024); |
| 1181 | } |
| 1182 | |
| 1183 | #[test] |
| 1184 | fn prefetch_vram_and_media_budget_scaling() { |
| 1185 | const GIB: u64 = 1024 * 1024 * 1024; |
| 1186 | assert_eq!(prefetch_vram_budget_mb_for_total_bytes(8 * GIB), DEFAULT_PREFETCH_VRAM_MB); |
| 1187 | assert_eq!(prefetch_media_budget_mb_for_total_bytes(8 * GIB), DEFAULT_PREFETCH_MEDIA_MB); |
| 1188 | assert_eq!(prefetch_vram_budget_mb_for_total_bytes(16 * GIB), 256); |
| 1189 | assert_eq!(prefetch_media_budget_mb_for_total_bytes(16 * GIB), 128); |
| 1190 | assert_eq!(prefetch_vram_budget_mb_for_total_bytes(32 * GIB), 512); |
| 1191 | assert_eq!(prefetch_media_budget_mb_for_total_bytes(32 * GIB), 512); |
| 1192 | assert_eq!(prefetch_vram_budget_mb_for_total_bytes(64 * GIB), 1024); |
| 1193 | assert_eq!(prefetch_media_budget_mb_for_total_bytes(64 * GIB), 1024); |
| 1194 | assert_eq!(prefetch_vram_budget_mb_for_total_bytes(128 * GIB), 2048); |
| 1195 | assert_eq!(prefetch_media_budget_mb_for_total_bytes(128 * GIB), 2048); |
| 1196 | assert_eq!(prefetch_vram_budget_mb_for_total_bytes(256 * GIB), 2048); |
| 1197 | assert_eq!(prefetch_media_budget_mb_for_total_bytes(256 * GIB), 2048); |
| 1198 | assert_eq!( |
| 1199 | default_prefetch_vram_budget_mb(), |
| 1200 | prefetch_vram_budget_mb_for_total_bytes(system_memory_bytes()) |
| 1201 | ); |
| 1202 | assert_eq!( |
| 1203 | default_prefetch_media_budget_mb(), |
| 1204 | prefetch_media_budget_mb_for_total_bytes(system_memory_bytes()) |
| 1205 | ); |
| 1206 | } |
| 1207 | |
| 1208 | #[test] |
| 1209 | fn change_generation_tracks_mutations_but_not_reads() { |
| 1210 | let cache = RamFrameCache::new(2); |
| 1211 | let key = |rev, frame| RamFrameKey { |
| 1212 | target: NodeId(0), |
| 1213 | revision: rev, |
| 1214 | frame, |
| 1215 | proxy_scale: 1, |
| 1216 | hiq: true, |
| 1217 | use_proxy_clips: false, |
| 1218 | }; |
| 1219 | let g0 = cache.change_generation(); |
| 1220 | cache.insert(key(1, 0), dummy_frame(512, 512)); |
| 1221 | let g1 = cache.change_generation(); |
| 1222 | assert!(g1 > g0); |
| 1223 | |
| 1224 | // `get` hits update LRU tick only and must NOT bump change_generation. |
| 1225 | assert!(cache.get(key(1, 0)).is_some()); |
| 1226 | assert_eq!(cache.change_generation(), g1); |
| 1227 | |
| 1228 | // Eviction via set_budget_mb bumps change_generation. |
| 1229 | cache.insert(key(1, 1), dummy_frame(512, 512)); |
| 1230 | let g2 = cache.change_generation(); |
| 1231 | assert!(g2 > g1); |
| 1232 | cache.set_budget_mb(1); |
| 1233 | let g3 = cache.change_generation(); |
| 1234 | assert!(g3 > g2); |
| 1235 | |
| 1236 | // Invalidation only bumps when stale entries are actually removed. |
| 1237 | assert_eq!(cache.invalidate_other_revisions(1), 0); |
| 1238 | assert_eq!(cache.change_generation(), g3); |
| 1239 | assert!(cache.invalidate_other_revisions(2) > 0); |
| 1240 | let g4 = cache.change_generation(); |
| 1241 | assert!(g4 > g3); |
| 1242 | |
| 1243 | cache.clear(); |
| 1244 | assert!(cache.change_generation() > g4); |
| 1245 | } |
| 1246 | } |