Skip to main content

euv_core/runtime/streaming/decoder/
impl.rs

1use super::*;
2
3/// Clean worker pool shutdown guaranteeing zero leaked OS threads when `AssetStreamCoordinator` drops.
4impl Drop for AssetStreamCoordinator {
5    /// Signals background worker shutdown and joins all native streaming threads cleanly.
6    fn drop(&mut self) {
7        let Self { queue, .. } = self;
8        queue.request_shutdown();
9        #[cfg(not(target_arch = "wasm32"))]
10        {
11            let Self { workers, .. } = self;
12            for handle in workers.drain(..) {
13                let _: Result<(), Box<dyn Any + Send>> = handle.join();
14            }
15        }
16    }
17}
18
19/// Request scheduling, coalescing, cancellation, hybrid async/cooperative decoding, Clock-LRU residency, spatial prefetch, and GPU upload draining for `AssetStreamCoordinator`.
20impl AssetStreamCoordinator {
21    /// Creates a new `AssetStreamCoordinator` bound to `budget` and an optional mounted `EuvPakArchive`.
22    ///
23    /// # Arguments
24    ///
25    /// - `AssetStreamBudget` - RAM, VRAM, decode time, and GPU upload ceilings.
26    /// - `Option<Arc<EuvPakArchive>>` - Optional mounted `.euvpak` virtual filesystem archive.
27    ///
28    /// # Returns
29    ///
30    /// - `Self` - Initialized `AssetStreamCoordinator`.
31    #[must_use]
32    pub fn new(budget: AssetStreamBudget, vfs: Option<Arc<EuvPakArchive>>) -> Self {
33        #[cfg(not(target_arch = "wasm32"))]
34        {
35            let default_workers: usize = (available_parallelism()
36                .map(usize::from)
37                .unwrap_or(STREAM_DECODER_MIN_WORKERS * 2)
38                / 2)
39            .clamp(STREAM_DECODER_MIN_WORKERS, STREAM_DECODER_MAX_WORKERS);
40            Self::build_internal(
41                budget,
42                vfs,
43                StreamExecutionMode::AsyncWorkers,
44                default_workers,
45            )
46        }
47        #[cfg(target_arch = "wasm32")]
48        {
49            Self::build_internal(budget, vfs, StreamExecutionMode::CooperativeTimeSliced, 0)
50        }
51    }
52
53    /// Creates an `AssetStreamCoordinator` explicitly running in cooperative `<= 1.5 ms/frame` time-sliced decode mode on any platform.
54    ///
55    /// # Arguments
56    ///
57    /// - `AssetStreamBudget` - RAM, VRAM, decode time, and GPU upload ceilings.
58    /// - `Option<Arc<EuvPakArchive>>` - Optional mounted `.euvpak` virtual filesystem archive.
59    ///
60    /// # Returns
61    ///
62    /// - `Self` - Cooperative time-sliced streaming coordinator.
63    #[must_use]
64    pub fn new_cooperative(budget: AssetStreamBudget, vfs: Option<Arc<EuvPakArchive>>) -> Self {
65        Self::build_internal(budget, vfs, StreamExecutionMode::CooperativeTimeSliced, 0)
66    }
67
68    /// Creates an `AssetStreamCoordinator` with an explicit native background worker thread count.
69    ///
70    /// # Arguments
71    ///
72    /// - `AssetStreamBudget` - RAM, VRAM, decode time, and GPU upload ceilings.
73    /// - `Option<Arc<EuvPakArchive>>` - Optional mounted `.euvpak` virtual filesystem archive.
74    /// - `usize` - Background worker thread count (`0` selects cooperative time-sliced mode).
75    ///
76    /// # Returns
77    ///
78    /// - `Self` - Configured streaming coordinator.
79    #[must_use]
80    pub fn with_worker_count(
81        budget: AssetStreamBudget,
82        vfs: Option<Arc<EuvPakArchive>>,
83        worker_count: usize,
84    ) -> Self {
85        let mode: StreamExecutionMode = if worker_count == 0 {
86            StreamExecutionMode::CooperativeTimeSliced
87        } else {
88            StreamExecutionMode::AsyncWorkers
89        };
90        Self::build_internal(budget, vfs, mode, worker_count)
91    }
92
93    /// Internal shared constructor initializing queue, worker context, Clock-LRU residency pool, `ResourceAccountant`, and spatial prefetcher.
94    ///
95    /// # Arguments
96    ///
97    /// - `AssetStreamBudget` - Memory and per-frame ceilings.
98    /// - `Option<Arc<EuvPakArchive>>` - Optional mounted `.euvpak` archive.
99    /// - `StreamExecutionMode` - Async worker threads or cooperative time-sliced mode.
100    /// - `usize` - Target native worker thread count.
101    ///
102    /// # Returns
103    ///
104    /// - `Self` - Constructed `AssetStreamCoordinator`.
105    fn build_internal(
106        budget: AssetStreamBudget,
107        vfs: Option<Arc<EuvPakArchive>>,
108        execution_mode: StreamExecutionMode,
109        worker_count: usize,
110    ) -> Self {
111        let telemetry: Arc<StreamingTelemetryCounters> =
112            Arc::new(StreamingTelemetryCounters::default());
113        let queue: Arc<PriorityStreamQueue> = Arc::new(PriorityStreamQueue::new());
114        #[cfg(not(target_arch = "wasm32"))]
115        let worker_ctx: Arc<StreamWorkerContext> = Arc::new(StreamWorkerContext {
116            queue: Arc::clone(&queue),
117            vfs: Mutex::new(vfs.clone()),
118            completed: Mutex::new(VecDeque::new()),
119            completed_count: AtomicUsize::new(0),
120            in_progress_workers: AtomicUsize::new(0),
121            telemetry: Arc::clone(&telemetry),
122        });
123        let owner: ResourceOwnerId = ResourceOwnerId::new(
124            ResourceOwnerKind::RenderCache,
125            RESIDENCY_DEFAULT_OWNER_ID,
126            1,
127        );
128        let residency: ProgressiveResidencyPool = ProgressiveResidencyPool::new(budget, owner);
129        #[cfg(target_arch = "wasm32")]
130        let _: usize = worker_count;
131        Self {
132            budget,
133            vfs,
134            telemetry,
135            queue,
136            #[cfg(not(target_arch = "wasm32"))]
137            worker_ctx,
138            #[cfg(not(target_arch = "wasm32"))]
139            workers: Vec::new(),
140            #[cfg(not(target_arch = "wasm32"))]
141            target_worker_count: worker_count.clamp(1, STREAM_DECODER_MAX_WORKERS),
142            execution_mode,
143            cooperative_job: None,
144            residency,
145            accountant: ResourceAccountant::default(),
146            spatial_grid: SpatialPrefetchGrid::default(),
147            pending_gpu_uploads: VecDeque::new(),
148            last_prefetch_volume: SpatialPrefetchVolume::default(),
149            next_auto_texture_slot: 1,
150            texture_slots: HashMap::new(),
151            prefetch_scratch: Vec::new(),
152            cancel_scratch: Vec::new(),
153        }
154    }
155
156    /// Lazily spawns dedicated native background I/O & decode threads when `StreamExecutionMode::AsyncWorkers` is active.
157    fn ensure_workers_started(&mut self) {
158        #[cfg(not(target_arch = "wasm32"))]
159        {
160            let Self {
161                execution_mode,
162                workers,
163                target_worker_count,
164                worker_ctx,
165                ..
166            } = self;
167            if *execution_mode != StreamExecutionMode::AsyncWorkers || !workers.is_empty() {
168                return;
169            }
170            for idx in 0..*target_worker_count {
171                let ctx_clone: Arc<StreamWorkerContext> = Arc::clone(worker_ctx);
172                let name: String = format!("{STREAM_DECODER_THREAD_PREFIX}-{idx}");
173                if let Ok(handle) = Builder::new().name(name).spawn(move || {
174                    stream_io_worker_loop(ctx_clone, idx);
175                }) {
176                    workers.push(handle);
177                } else {
178                    break;
179                }
180            }
181        }
182    }
183
184    /// Allocates or retrieves a deterministic GPU bindless texture slot index for `key_hash`.
185    ///
186    /// # Arguments
187    ///
188    /// - `u64` - Asset key hash.
189    ///
190    /// # Returns
191    ///
192    /// - `u32` - Stable bindless texture slot identifier.
193    fn resolve_texture_slot(&mut self, key_hash: u64) -> u32 {
194        let Self {
195            texture_slots,
196            next_auto_texture_slot,
197            ..
198        } = self;
199        if let Some(&existing) = texture_slots.get(&key_hash) {
200            return existing;
201        }
202        let assigned: u32 = *next_auto_texture_slot;
203        *next_auto_texture_slot = next_auto_texture_slot.saturating_add(1);
204        let _: Option<u32> = texture_slots.insert(key_hash, assigned);
205        assigned
206    }
207
208    /// Returns the active streaming budget configuration.
209    ///
210    /// # Returns
211    ///
212    /// - `AssetStreamBudget` - Configured RAM, VRAM, and per-frame ceilings.
213    #[must_use]
214    pub fn budget(&self) -> AssetStreamBudget {
215        let Self { budget, .. } = self;
216        *budget
217    }
218
219    /// Returns the active execution mode (`AsyncWorkers` or `CooperativeTimeSliced`).
220    ///
221    /// # Returns
222    ///
223    /// - `StreamExecutionMode` - Active streaming execution mode.
224    #[must_use]
225    pub fn execution_mode(&self) -> StreamExecutionMode {
226        let Self { execution_mode, .. } = self;
227        *execution_mode
228    }
229
230    /// Replaces the active streaming budget configuration at runtime and immediately enforces new ceilings.
231    ///
232    /// # Arguments
233    ///
234    /// - `AssetStreamBudget` - Updated RAM, VRAM, and per-frame ceilings.
235    pub fn set_budget(&mut self, next_budget: AssetStreamBudget) {
236        let Self {
237            budget,
238            residency,
239            accountant,
240            telemetry,
241            ..
242        } = self;
243        *budget = next_budget;
244        residency.set_budget(next_budget, accountant, telemetry.as_ref());
245    }
246
247    /// Binds every `TextureMipTail` entry from the mounted `.euvpak` Mip-Tail Superblock into `TextureResidencyTier::MipTail` for instant Frame-1 visibility with zero blank pop-in.
248    ///
249    /// # Returns
250    ///
251    /// - `usize` - Number of texture mip-tails bound immediately into VRAM residency.
252    pub fn warm_bind_mip_tail_superblock(&mut self) -> usize {
253        let Some(archive) = ({
254            let Self { vfs, .. } = self;
255            vfs.clone()
256        }) else {
257            return 0;
258        };
259        archive.advise_mip_tails_willneed();
260        let mip_metas: Vec<EuvPakEntryMeta> = archive.mip_tail_entries();
261        let mut bound_count: usize = 0;
262        for meta in mip_metas {
263            let key_hash: u64 = meta.get_path_hash();
264            let slot_id: u32 = self.resolve_texture_slot(key_hash);
265            let Ok(raw_bytes) = archive.read_entry_decoded(key_hash) else {
266                continue;
267            };
268            let Ok(DecodedAssetPayload::Texture {
269                width,
270                height,
271                total_mip_levels,
272                is_srgb,
273                mip_tail_bytes,
274                mid_mip_bytes,
275                full_res_bytes,
276                rgba8,
277                ..
278            }) = decode_texture_payload(
279                raw_bytes.as_slice(),
280                StreamJobKind::TextureMipTail,
281                TextureResidencyTier::MipTail,
282                true,
283            )
284            else {
285                continue;
286            };
287            let spec: TextureMipSpec = TextureMipSpec::new(
288                key_hash,
289                slot_id,
290                [mip_tail_bytes, mid_mip_bytes, full_res_bytes],
291                [width, height],
292                total_mip_levels,
293                is_srgb,
294            );
295            let Self {
296                residency,
297                accountant,
298                telemetry,
299                pending_gpu_uploads,
300                ..
301            } = self;
302            telemetry.add_vfs_syscalls_saved(STREAM_SYSCALLS_SAVED_PER_LOOKUP);
303            if let Ok(upload) =
304                residency.bind_texture_mip_tail(spec, rgba8, accountant, telemetry.as_ref())
305            {
306                pending_gpu_uploads.push_back(upload);
307                bound_count = bound_count.saturating_add(1);
308            }
309        }
310        bound_count
311    }
312
313    /// Requests an asynchronous asset load by 64-bit key hash, coalescing duplicate in-flight requests and escalating priority when needed.
314    ///
315    /// # Arguments
316    ///
317    /// - `u64` - Deterministic 64-bit FNV-1a asset key hash.
318    /// - `StreamPriority` - Requested scheduling priority lane.
319    ///
320    /// # Returns
321    ///
322    /// - `StreamRequestHandle` - Handle referencing the active or coalesced request.
323    pub fn request_asset(
324        &mut self,
325        key_hash: u64,
326        priority: StreamPriority,
327    ) -> StreamRequestHandle {
328        let inferred_kind: StreamJobKind = {
329            let Self { vfs, .. } = self;
330            vfs.as_ref()
331                .and_then(|archive: &Arc<EuvPakArchive>| archive.lookup_hash(key_hash))
332                .map_or(StreamJobKind::RawBytes, |slice: EuvPakSlice<'_>| {
333                    euvpak_kind_to_stream_job_kind(slice.get_kind())
334                })
335        };
336        let target_tier: TextureResidencyTier = match inferred_kind {
337            StreamJobKind::TextureMipTail => TextureResidencyTier::MipTail,
338            StreamJobKind::TextureMip => TextureResidencyTier::FullRes,
339            _ => TextureResidencyTier::Unloaded,
340        };
341        let texture_slot: u32 = if matches!(
342            inferred_kind,
343            StreamJobKind::TextureMip | StreamJobKind::TextureMipTail
344        ) {
345            self.resolve_texture_slot(key_hash)
346        } else {
347            0
348        };
349        self.enqueue_typed_request(
350            key_hash,
351            priority,
352            inferred_kind,
353            target_tier,
354            texture_slot,
355            true,
356        )
357    }
358
359    /// Requests an asynchronous asset load by virtual archive path string.
360    ///
361    /// # Arguments
362    ///
363    /// - `&str` - Virtual asset path inside the mounted `.euvpak`.
364    /// - `StreamPriority` - Requested scheduling priority lane.
365    ///
366    /// # Returns
367    ///
368    /// - `StreamRequestHandle` - Handle referencing the active or coalesced request.
369    pub fn request_path(&mut self, path: &str, priority: StreamPriority) -> StreamRequestHandle {
370        self.request_asset(hash_euvpak_path(path), priority)
371    }
372
373    /// Requests a progressive texture mipmap promotion to `target_tier` on `texture_slot`.
374    ///
375    /// # Arguments
376    ///
377    /// - `u64` - Deterministic 64-bit texture asset key hash.
378    /// - `u32` - Target GPU bindless texture slot index.
379    /// - `TextureResidencyTier` - Desired residency tier (`MipTail`, `MidMip`, or `FullRes`).
380    /// - `StreamPriority` - Scheduling priority lane.
381    /// - `bool` - True when texels use sRGB encoding.
382    ///
383    /// # Returns
384    ///
385    /// - `StreamRequestHandle` - Handle referencing the active or coalesced texture streaming job.
386    pub fn request_texture(
387        &mut self,
388        key_hash: u64,
389        texture_slot: u32,
390        target_tier: TextureResidencyTier,
391        priority: StreamPriority,
392        is_srgb: bool,
393    ) -> StreamRequestHandle {
394        {
395            let Self { texture_slots, .. } = self;
396            let _: Option<u32> = texture_slots.insert(key_hash, texture_slot);
397        }
398        let kind: StreamJobKind = if target_tier == TextureResidencyTier::MipTail {
399            StreamJobKind::TextureMipTail
400        } else {
401            StreamJobKind::TextureMip
402        };
403        self.enqueue_typed_request(key_hash, priority, kind, target_tier, texture_slot, is_srgb)
404    }
405
406    /// Internal typed request entry point handling resident cache hits, VFS syscall accounting, and 4-lane coalescing.
407    ///
408    /// # Arguments
409    ///
410    /// - `u64` - Deterministic 64-bit asset key hash.
411    /// - `StreamPriority` - Priority lane.
412    /// - `StreamJobKind` - Decode job category.
413    /// - `TextureResidencyTier` - Target texture tier.
414    /// - `u32` - GPU texture slot index.
415    /// - `bool` - sRGB color space flag.
416    ///
417    /// # Returns
418    ///
419    /// - `StreamRequestHandle` - Active or coalesced request handle.
420    fn enqueue_typed_request(
421        &mut self,
422        key_hash: u64,
423        priority: StreamPriority,
424        kind: StreamJobKind,
425        target_tier: TextureResidencyTier,
426        texture_slot: u32,
427        is_srgb: bool,
428    ) -> StreamRequestHandle {
429        let already_satisfied: bool = {
430            let Self { residency, .. } = self;
431            if matches!(
432                kind,
433                StreamJobKind::TextureMip | StreamJobKind::TextureMipTail
434            ) {
435                let current_tier: TextureResidencyTier = residency.texture_tier(key_hash);
436                current_tier != TextureResidencyTier::Unloaded
437                    && (current_tier as u8) >= (target_tier as u8)
438            } else {
439                residency.contains(key_hash)
440            }
441        };
442        if already_satisfied {
443            let Self {
444                residency,
445                telemetry,
446                ..
447            } = self;
448            let _: bool = residency.touch(key_hash);
449            telemetry.add_coalesced_hit();
450            return StreamRequestHandle::new(key_hash, priority, CancelToken::new());
451        }
452        self.ensure_workers_started();
453        let Self {
454            vfs,
455            queue,
456            telemetry,
457            ..
458        } = self;
459        let work: StreamWorkItem = StreamWorkItem {
460            key_hash,
461            priority,
462            kind,
463            target_tier,
464            texture_slot,
465            generation: 0,
466            cancel_token: CancelToken::new(),
467            is_srgb,
468        };
469        let (handle, is_new): (StreamRequestHandle, bool) =
470            queue.enqueue_or_coalesce(work, telemetry.as_ref());
471        if is_new
472            && let Some(archive) = vfs.as_ref()
473            && archive.lookup_hash(key_hash).is_some()
474        {
475            telemetry.add_vfs_syscalls_saved(STREAM_SYSCALLS_SAVED_PER_LOOKUP);
476        }
477        handle
478    }
479
480    /// Dynamically reprioritizes an in-flight streaming request onto `new_priority`.
481    ///
482    /// # Arguments
483    ///
484    /// - `u64` - Deterministic 64-bit asset key hash.
485    /// - `StreamPriority` - Updated priority lane.
486    ///
487    /// # Returns
488    ///
489    /// - `bool` - `true` when an active in-flight job was reprioritized.
490    pub fn reprioritize(&mut self, key_hash: u64, new_priority: StreamPriority) -> bool {
491        let Self { queue, .. } = self;
492        queue.reprioritize(key_hash, new_priority)
493    }
494
495    /// Cancels an in-flight asset request by 64-bit key hash.
496    ///
497    /// # Arguments
498    ///
499    /// - `u64` - Deterministic 64-bit asset key hash to cancel.
500    ///
501    /// # Returns
502    ///
503    /// - `bool` - `true` when an active request was found and marked cancelled.
504    pub fn cancel(&mut self, key_hash: u64) -> bool {
505        let Self {
506            queue,
507            telemetry,
508            cooperative_job,
509            spatial_grid,
510            ..
511        } = self;
512        spatial_grid.unmark_prefetched(key_hash);
513        if let Some(in_prog) = cooperative_job.as_ref()
514            && in_prog.work.get_key_hash() == key_hash
515        {
516            in_prog.work.get_cancel_token().cancel();
517            *cooperative_job = None;
518        }
519        queue.cancel(key_hash, telemetry.as_ref())
520    }
521
522    /// Registers a spatial asset anchor for velocity-predicted lookahead prefetching.
523    ///
524    /// # Arguments
525    ///
526    /// - `SpatialAssetAnchor` - World-space bounding sphere and asset key hash.
527    pub fn register_spatial_asset(&mut self, anchor: SpatialAssetAnchor) {
528        let Self { spatial_grid, .. } = self;
529        spatial_grid.register_anchor(anchor);
530    }
531
532    /// Updates screen-space coverage for a texture and automatically schedules promotion when visible coverage demands a higher mip tier.
533    ///
534    /// # Arguments
535    ///
536    /// - `u64` - Deterministic 64-bit texture asset key hash.
537    /// - `f32` - Projected screen-space size in pixels.
538    /// - `f32` - Camera distance in meters.
539    /// - `bool` - Whether the textured surface is currently visible in the frustum.
540    ///
541    /// # Returns
542    ///
543    /// - `TextureResidencyTier` - Target residency tier computed from screen-space coverage.
544    pub fn report_texture_coverage(
545        &mut self,
546        key_hash: u64,
547        screen_coverage_px: f32,
548        camera_distance: f32,
549        visible: bool,
550    ) -> TextureResidencyTier {
551        let (desired_tier, current_tier): (TextureResidencyTier, TextureResidencyTier) = {
552            let Self { residency, .. } = self;
553            let desired: TextureResidencyTier = residency.report_texture_coverage(
554                key_hash,
555                screen_coverage_px,
556                camera_distance,
557                visible,
558            );
559            let current: TextureResidencyTier = residency.texture_tier(key_hash);
560            (desired, current)
561        };
562        if visible && (desired_tier as u8) > (current_tier as u8) {
563            let slot_id: u32 = self.resolve_texture_slot(key_hash);
564            let _: StreamRequestHandle = self.request_texture(
565                key_hash,
566                slot_id,
567                desired_tier,
568                StreamPriority::VisibleHigh,
569                true,
570            );
571        }
572        desired_tier
573    }
574
575    /// Updates the camera velocity-predicted spatial prefetch focus volume, schedules `PrefetchMedium` jobs ahead of arrival, and cancels trailing behind-camera prefetches.
576    ///
577    /// # Arguments
578    ///
579    /// - `[f32; 3]` - Current camera world position.
580    /// - `[f32; 3]` - Current camera world velocity in meters per second.
581    /// - `f32` - Spherical prefetch radius in meters.
582    ///
583    /// # Returns
584    ///
585    /// - `usize` - Number of speculative prefetch requests enqueued for this update.
586    pub fn update_camera_prefetch(
587        &mut self,
588        camera_pos: [f32; 3],
589        camera_vel: [f32; 3],
590        lookahead_radius: f32,
591    ) -> usize {
592        let volume: SpatialPrefetchVolume = SpatialPrefetchVolume::new(
593            camera_pos,
594            camera_vel,
595            PREFETCH_DEFAULT_LOOKAHEAD_SECS,
596            lookahead_radius.max(0.0),
597        );
598        {
599            let Self {
600                last_prefetch_volume,
601                spatial_grid,
602                prefetch_scratch,
603                cancel_scratch,
604                ..
605            } = self;
606            *last_prefetch_volume = volume;
607            spatial_grid.query_lookahead(&volume, prefetch_scratch, cancel_scratch);
608        }
609        let cancel_count: usize = {
610            let Self { cancel_scratch, .. } = self;
611            cancel_scratch.len()
612        };
613        for idx in 0..cancel_count {
614            let key_hash: u64 = {
615                let Self { cancel_scratch, .. } = self;
616                cancel_scratch[idx]
617            };
618            let _: bool = self.cancel(key_hash);
619        }
620        let prefetch_count: usize = {
621            let Self {
622                prefetch_scratch, ..
623            } = self;
624            prefetch_scratch.len()
625        };
626        let mut scheduled: usize = 0;
627        for idx in 0..prefetch_count {
628            let anchor: SpatialAssetAnchor = {
629                let Self {
630                    prefetch_scratch, ..
631                } = self;
632                prefetch_scratch[idx]
633            };
634            let key_hash: u64 = anchor.get_key_hash();
635            let already_resident: bool = {
636                let Self { residency, .. } = self;
637                residency.contains(key_hash)
638            };
639            if already_resident {
640                continue;
641            }
642            let target_tier: TextureResidencyTier = match anchor.get_kind() {
643                StreamJobKind::TextureMipTail => TextureResidencyTier::MipTail,
644                StreamJobKind::TextureMip => TextureResidencyTier::MidMip,
645                _ => TextureResidencyTier::Unloaded,
646            };
647            let slot_id: u32 = if anchor.get_texture_slot() != 0 {
648                anchor.get_texture_slot()
649            } else if matches!(
650                anchor.get_kind(),
651                StreamJobKind::TextureMip | StreamJobKind::TextureMipTail
652            ) {
653                self.resolve_texture_slot(key_hash)
654            } else {
655                0
656            };
657            let _: StreamRequestHandle = self.enqueue_typed_request(
658                key_hash,
659                StreamPriority::PrefetchMedium,
660                anchor.get_kind(),
661                target_tier,
662                slot_id,
663                anchor.get_is_srgb(),
664            );
665            {
666                let Self { spatial_grid, .. } = self;
667                spatial_grid.mark_prefetched(key_hash);
668            }
669            scheduled = scheduled.saturating_add(1);
670        }
671        scheduled
672    }
673
674    /// Admits one decoded `CompletedStreamJob` into `ProgressiveResidencyPool` and queues any resulting GPU mip upload.
675    ///
676    /// # Arguments
677    ///
678    /// - `CompletedStreamJob` - Finished background or cooperative decode result.
679    fn ingest_completed_job(&mut self, job: CompletedStreamJob) {
680        let Self {
681            residency,
682            accountant,
683            telemetry,
684            pending_gpu_uploads,
685            spatial_grid,
686            ..
687        } = self;
688        spatial_grid.unmark_prefetched(job.key_hash);
689        let Ok(payload) = job.payload else {
690            return;
691        };
692        match payload {
693            DecodedAssetPayload::Texture {
694                width,
695                height,
696                total_mip_levels,
697                is_srgb,
698                tier,
699                mip_tail_bytes,
700                mid_mip_bytes,
701                full_res_bytes,
702                rgba8,
703                ..
704            } => {
705                let spec: TextureMipSpec = TextureMipSpec::new(
706                    job.key_hash,
707                    job.texture_slot,
708                    [mip_tail_bytes, mid_mip_bytes, full_res_bytes],
709                    [width, height],
710                    total_mip_levels,
711                    is_srgb,
712                );
713                if let Ok((_, Some(upload))) = residency.promote_texture_tier(
714                    spec,
715                    tier,
716                    rgba8,
717                    accountant,
718                    telemetry.as_ref(),
719                ) {
720                    pending_gpu_uploads.push_back(upload);
721                }
722            }
723            DecodedAssetPayload::Mesh {
724                vram_bytes,
725                raw_bytes,
726            } => {
727                let _: Result<(), String> = residency.admit_asset(
728                    job.key_hash,
729                    ResidencyAssetKind::Mesh,
730                    raw_bytes,
731                    vram_bytes,
732                    accountant,
733                    telemetry.as_ref(),
734                );
735            }
736            DecodedAssetPayload::Raw { kind, bytes } => {
737                let _: Result<(), String> = residency.admit_asset(
738                    job.key_hash,
739                    kind,
740                    bytes,
741                    0,
742                    accountant,
743                    telemetry.as_ref(),
744                );
745            }
746        }
747    }
748
749    /// Advances cooperative chunked time-sliced decoding strictly within `budget_us` microseconds on the calling thread.
750    ///
751    /// # Arguments
752    ///
753    /// - `u64` - Hard CPU decode time ceiling in microseconds (e.g. `1_500` for `1.5 ms/frame`).
754    ///
755    /// # Returns
756    ///
757    /// - `usize` - Number of asset jobs completed during this cooperative slice.
758    pub fn pump_frame_cooperative(&mut self, budget_us: u64) -> usize {
759        let effective_budget_us: u64 = if budget_us == 0 {
760            self.budget().get_max_decode_us_per_frame()
761        } else {
762            budget_us
763        };
764        let frame_start_us: u64 = stream_now_us();
765        let mut completed_count: usize = 0;
766        loop {
767            if stream_now_us().saturating_sub(frame_start_us) >= effective_budget_us {
768                break;
769            }
770            let need_next_job: bool = {
771                let Self {
772                    cooperative_job, ..
773                } = self;
774                cooperative_job.is_none()
775            };
776            if need_next_job {
777                let next_work: Option<StreamWorkItem> = {
778                    let Self { queue, .. } = self;
779                    queue.pop_highest_priority()
780                };
781                let Some(work) = next_work else {
782                    break;
783                };
784                if work.get_cancel_token().is_cancelled() {
785                    continue;
786                }
787                let work_key: u64 = work.get_key_hash();
788                let work_gen: u64 = work.get_generation();
789                let prepared: Option<CooperativeInProgressJob> = {
790                    let Self { vfs, .. } = self;
791                    if let Some(archive) = vfs.as_ref() {
792                        if let Some((meta, payload_crc32, uncompressed_crc32)) =
793                            archive.probe_toc(work_key)
794                        {
795                            let start: usize = meta.get_offset() as usize;
796                            let end: usize =
797                                start.saturating_add(meta.get_compressed_size() as usize);
798                            if let Some(stored) = archive.mapping.as_bytes().get(start..end) {
799                                if euvpak_crc32(stored) != payload_crc32 {
800                                    None
801                                } else if meta.get_is_compressed() {
802                                    Some(CooperativeInProgressJob {
803                                        work,
804                                        accumulated_us: 0,
805                                        uncompressed_crc32,
806                                        running_uncompressed_crc: 0xFFFF_FFFF,
807                                        lz4_decoder: Some(Lz4StreamDecoder::new(
808                                            meta.get_uncompressed_size() as usize,
809                                        )),
810                                        compressed_bytes: stored.to_vec(),
811                                        uncompressed_bytes: None,
812                                    })
813                                } else {
814                                    Some(CooperativeInProgressJob {
815                                        work,
816                                        accumulated_us: 0,
817                                        uncompressed_crc32,
818                                        running_uncompressed_crc: 0xFFFF_FFFF,
819                                        lz4_decoder: None,
820                                        compressed_bytes: Vec::new(),
821                                        uncompressed_bytes: Some(stored.to_vec()),
822                                    })
823                                }
824                            } else {
825                                None
826                            }
827                        } else {
828                            None
829                        }
830                    } else {
831                        None
832                    }
833                };
834                if let Some(job) = prepared {
835                    let Self {
836                        cooperative_job, ..
837                    } = self;
838                    *cooperative_job = Some(job);
839                } else {
840                    let Self {
841                        queue, telemetry, ..
842                    } = self;
843                    let _: bool = queue.mark_completed(work_key, work_gen, telemetry.as_ref());
844                    completed_count = completed_count.saturating_add(1);
845                    continue;
846                }
847            }
848            let step_start_us: u64 = stream_now_us();
849            let finished_job: Option<CompletedStreamJob> = {
850                let Self {
851                    cooperative_job,
852                    queue,
853                    telemetry,
854                    ..
855                } = self;
856                if let Some(in_prog) = cooperative_job.as_mut() {
857                    if in_prog.work.get_cancel_token().is_cancelled() {
858                        *cooperative_job = None;
859                        None
860                    } else if let Some(lz4_dec) = in_prog.lz4_decoder.as_mut() {
861                        let prev_decoded: usize = lz4_dec.decoded_bytes();
862                        let decode_step: Result<bool, String> = lz4_dec.decode_up_to_bytes(
863                            in_prog.compressed_bytes.as_slice(),
864                            STREAM_COOPERATIVE_CHUNK_BYTES,
865                        );
866                        if decode_step.is_ok() {
867                            let newly_decoded: &[u8] = &lz4_dec.decoded_slice()[prev_decoded..];
868                            in_prog.running_uncompressed_crc = euvpak_crc32_update(
869                                in_prog.running_uncompressed_crc,
870                                newly_decoded,
871                            );
872                        }
873                        in_prog.accumulated_us = in_prog
874                            .accumulated_us
875                            .saturating_add(stream_now_us().saturating_sub(step_start_us));
876                        match decode_step {
877                            Ok(true) => {
878                                let finished_dec: Option<Lz4StreamDecoder> =
879                                    in_prog.lz4_decoder.take();
880                                let final_crc: u32 = !in_prog.running_uncompressed_crc;
881                                match finished_dec.map(Lz4StreamDecoder::into_output) {
882                                    Some(Ok(bytes)) if final_crc == in_prog.uncompressed_crc32 => {
883                                        in_prog.uncompressed_bytes = Some(bytes);
884                                        in_prog.compressed_bytes.clear();
885                                        None
886                                    }
887                                    _ => {
888                                        let work: StreamWorkItem = in_prog.work.clone();
889                                        *cooperative_job = None;
890                                        let live: bool = queue.mark_completed(
891                                            work.get_key_hash(),
892                                            work.get_generation(),
893                                            telemetry.as_ref(),
894                                        );
895                                        if live {
896                                            Some(CompletedStreamJob {
897                                                key_hash: work.get_key_hash(),
898                                                texture_slot: work.get_texture_slot(),
899                                                payload: Err(ERR_STREAM_MISSING_ENTRY.to_string()),
900                                            })
901                                        } else {
902                                            None
903                                        }
904                                    }
905                                }
906                            }
907                            Ok(false) => None,
908                            Err(err) => {
909                                let work: StreamWorkItem = in_prog.work.clone();
910                                *cooperative_job = None;
911                                let live: bool = queue.mark_completed(
912                                    work.get_key_hash(),
913                                    work.get_generation(),
914                                    telemetry.as_ref(),
915                                );
916                                if live {
917                                    Some(CompletedStreamJob {
918                                        key_hash: work.get_key_hash(),
919                                        texture_slot: work.get_texture_slot(),
920                                        payload: Err(err),
921                                    })
922                                } else {
923                                    None
924                                }
925                            }
926                        }
927                    } else if let Some(raw_bytes) = in_prog.uncompressed_bytes.take() {
928                        let work: StreamWorkItem = in_prog.work.clone();
929                        let payload_res: Result<DecodedAssetPayload, String> =
930                            decode_uncompressed_asset(
931                                raw_bytes,
932                                work.get_kind(),
933                                work.get_target_tier(),
934                                work.get_is_srgb(),
935                            );
936                        let total_us: u64 = in_prog
937                            .accumulated_us
938                            .saturating_add(stream_now_us().saturating_sub(step_start_us));
939                        *cooperative_job = None;
940                        let live: bool = queue.mark_completed(
941                            work.get_key_hash(),
942                            work.get_generation(),
943                            telemetry.as_ref(),
944                        );
945                        if live {
946                            if payload_res.is_ok() {
947                                telemetry.record_decode_us(total_us);
948                            }
949                            Some(CompletedStreamJob {
950                                key_hash: work.get_key_hash(),
951                                texture_slot: work.get_texture_slot(),
952                                payload: payload_res,
953                            })
954                        } else {
955                            None
956                        }
957                    } else {
958                        *cooperative_job = None;
959                        None
960                    }
961                } else {
962                    None
963                }
964            };
965            if let Some(done_job) = finished_job {
966                self.ingest_completed_job(done_job);
967                completed_count = completed_count.saturating_add(1);
968            }
969        }
970        completed_count
971    }
972
973    /// Pumps completed background decodes (or executes cooperative time-sliced decode work on `wasm32`) strictly within `max_decode_us`.
974    ///
975    /// # Arguments
976    ///
977    /// - `u64` - Maximum main-thread cooperative or ingestion budget in microseconds.
978    ///
979    /// # Returns
980    ///
981    /// - `usize` - Number of asset jobs completed during this pump tick.
982    pub fn pump_frame(&mut self, max_decode_us: u64) -> usize {
983        #[cfg(target_arch = "wasm32")]
984        {
985            self.pump_frame_cooperative(max_decode_us)
986        }
987        #[cfg(not(target_arch = "wasm32"))]
988        {
989            if self.execution_mode() == StreamExecutionMode::CooperativeTimeSliced {
990                return self.pump_frame_cooperative(max_decode_us);
991            }
992            let effective_budget_us: u64 = if max_decode_us == 0 {
993                self.budget().get_max_decode_us_per_frame()
994            } else {
995                max_decode_us
996            };
997            let has_ready: bool = {
998                let Self { worker_ctx, .. } = self;
999                worker_ctx.completed_count.load(Ordering::Acquire) > 0
1000            };
1001            if !has_ready {
1002                return 0;
1003            }
1004            let start_us: u64 = stream_now_us();
1005            let mut ingested: usize = 0;
1006            loop {
1007                let next_job: Option<CompletedStreamJob> = {
1008                    let Self { worker_ctx, .. } = self;
1009                    if let Ok(mut ready) = worker_ctx.completed.lock() {
1010                        let popped: Option<CompletedStreamJob> = ready.pop_front();
1011                        if popped.is_some() {
1012                            let _: usize =
1013                                worker_ctx.completed_count.fetch_sub(1, Ordering::AcqRel);
1014                        }
1015                        popped
1016                    } else {
1017                        None
1018                    }
1019                };
1020                let Some(job) = next_job else {
1021                    break;
1022                };
1023                self.ingest_completed_job(job);
1024                ingested = ingested.saturating_add(1);
1025                if stream_now_us().saturating_sub(start_us) >= effective_budget_us {
1026                    break;
1027                }
1028            }
1029            ingested
1030        }
1031    }
1032
1033    /// Returns `true` when all queued, in-flight, cooperative, and completed streaming work has drained.
1034    ///
1035    /// # Returns
1036    ///
1037    /// - `bool` - Whether the coordinator is completely idle.
1038    #[must_use]
1039    pub fn is_idle(&self) -> bool {
1040        #[cfg(not(target_arch = "wasm32"))]
1041        {
1042            let Self {
1043                queue,
1044                worker_ctx,
1045                cooperative_job,
1046                ..
1047            } = self;
1048            queue.is_empty()
1049                && queue.active_count() == 0
1050                && worker_ctx.in_progress_workers.load(Ordering::Acquire) == 0
1051                && worker_ctx.completed_count.load(Ordering::Acquire) == 0
1052                && cooperative_job.is_none()
1053        }
1054        #[cfg(target_arch = "wasm32")]
1055        {
1056            let Self {
1057                queue,
1058                cooperative_job,
1059                ..
1060            } = self;
1061            queue.is_empty() && queue.active_count() == 0 && cooperative_job.is_none()
1062        }
1063    }
1064
1065    /// Pumps until all queued async or cooperative jobs complete or `max_wait_ms` elapses.
1066    ///
1067    /// # Arguments
1068    ///
1069    /// - `u64` - Maximum wall-clock wait duration in milliseconds.
1070    ///
1071    /// # Returns
1072    ///
1073    /// - `usize` - Total jobs completed while draining.
1074    pub fn pump_until_idle(&mut self, max_wait_ms: u64) -> usize {
1075        let deadline_us: u64 = stream_now_us().saturating_add(max_wait_ms.saturating_mul(1_000));
1076        let mut total_completed: usize = 0;
1077        loop {
1078            let step: usize = self.pump_frame(self.budget().get_max_decode_us_per_frame());
1079            total_completed = total_completed.saturating_add(step);
1080            if self.is_idle() || stream_now_us() >= deadline_us {
1081                break;
1082            }
1083            #[cfg(not(target_arch = "wasm32"))]
1084            if step == 0 {
1085                sleep(Duration::from_micros(250));
1086            }
1087        }
1088        total_completed
1089    }
1090
1091    /// Drains ready incremental GPU texture mipmap uploads into `out` without exceeding `max_bytes` or `max_us`.
1092    ///
1093    /// # Arguments
1094    ///
1095    /// - `usize` - Hard byte budget cap for this frame.
1096    /// - `u64` - Hard CPU time budget cap in microseconds for this frame.
1097    /// - `&mut Vec<GpuTextureMipUpload>` - Destination vector receiving drained mip upload payloads.
1098    ///
1099    /// # Returns
1100    ///
1101    /// - `usize` - Total bytes drained into `out`.
1102    pub fn drain_gpu_uploads(
1103        &mut self,
1104        max_bytes: usize,
1105        max_us: u64,
1106        out: &mut Vec<GpuTextureMipUpload>,
1107    ) -> usize {
1108        let Self {
1109            pending_gpu_uploads,
1110            ..
1111        } = self;
1112        let start_us: u64 = stream_now_us();
1113        let mut consumed: usize = 0;
1114        while let Some(front) = pending_gpu_uploads.front() {
1115            if max_us > 0 && consumed > 0 && stream_now_us().saturating_sub(start_us) >= max_us {
1116                break;
1117            }
1118            let payload_len: usize = front.get_rgba8().len();
1119            if consumed > 0 && consumed.saturating_add(payload_len) > max_bytes {
1120                break;
1121            }
1122            if let Some(upload) = pending_gpu_uploads.pop_front() {
1123                consumed = consumed.saturating_add(payload_len);
1124                out.push(upload);
1125            }
1126        }
1127        consumed
1128    }
1129
1130    /// Returns the number of queued incremental GPU texture mipmap uploads waiting to drain.
1131    ///
1132    /// # Returns
1133    ///
1134    /// - `usize` - Pending GPU upload count.
1135    #[must_use]
1136    pub fn pending_gpu_upload_count(&self) -> usize {
1137        let Self {
1138            pending_gpu_uploads,
1139            ..
1140        } = self;
1141        pending_gpu_uploads.len()
1142    }
1143
1144    /// Returns a shared reference to the O(1) Clock-LRU `ProgressiveResidencyPool`.
1145    ///
1146    /// # Returns
1147    ///
1148    /// - `&ProgressiveResidencyPool` - Active residency pool reference.
1149    #[must_use]
1150    pub fn residency_pool(&self) -> &ProgressiveResidencyPool {
1151        let Self { residency, .. } = self;
1152        residency
1153    }
1154
1155    /// Returns a mutable reference to the O(1) Clock-LRU `ProgressiveResidencyPool`.
1156    ///
1157    /// # Returns
1158    ///
1159    /// - `&mut ProgressiveResidencyPool` - Mutable residency pool reference.
1160    pub fn residency_pool_mut(&mut self) -> &mut ProgressiveResidencyPool {
1161        let Self { residency, .. } = self;
1162        residency
1163    }
1164
1165    /// Returns a shared reference to the authoritative streaming `ResourceAccountant`.
1166    ///
1167    /// # Returns
1168    ///
1169    /// - `&ResourceAccountant` - Resource accountant reference.
1170    #[must_use]
1171    pub fn accountant(&self) -> &ResourceAccountant {
1172        let Self { accountant, .. } = self;
1173        accountant
1174    }
1175
1176    /// Returns a mutable reference to the authoritative streaming `ResourceAccountant`.
1177    ///
1178    /// # Returns
1179    ///
1180    /// - `&mut ResourceAccountant` - Mutable resource accountant reference.
1181    pub fn accountant_mut(&mut self) -> &mut ResourceAccountant {
1182        let Self { accountant, .. } = self;
1183        accountant
1184    }
1185
1186    /// Releases every resident asset from the Clock-LRU residency pool and removes all tracked handles from `ResourceAccountant` with zero leaks.
1187    ///
1188    /// # Returns
1189    ///
1190    /// - `usize` - Number of resident assets released.
1191    pub fn release_all_resident(&mut self) -> usize {
1192        let Self {
1193            residency,
1194            accountant,
1195            telemetry,
1196            pending_gpu_uploads,
1197            ..
1198        } = self;
1199        pending_gpu_uploads.clear();
1200        residency.release_all(accountant, telemetry.as_ref())
1201    }
1202
1203    /// Returns a lock-free snapshot of active streaming telemetry counters.
1204    ///
1205    /// # Returns
1206    ///
1207    /// - `StreamingTelemetrySnapshot` - Current streaming telemetry counters and memory budgets.
1208    #[must_use]
1209    pub fn telemetry_snapshot(&self) -> StreamingTelemetrySnapshot {
1210        let Self {
1211            budget, telemetry, ..
1212        } = self;
1213        telemetry.snapshot(
1214            budget.get_ram_budget_bytes(),
1215            budget.get_vram_budget_bytes(),
1216        )
1217    }
1218}