1use super::*;
2
3impl Drop for AssetStreamCoordinator {
5 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
19impl AssetStreamCoordinator {
21 #[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 #[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 #[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 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 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 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 #[must_use]
214 pub fn budget(&self) -> AssetStreamBudget {
215 let Self { budget, .. } = self;
216 *budget
217 }
218
219 #[must_use]
225 pub fn execution_mode(&self) -> StreamExecutionMode {
226 let Self { execution_mode, .. } = self;
227 *execution_mode
228 }
229
230 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 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 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 pub fn request_path(&mut self, path: &str, priority: StreamPriority) -> StreamRequestHandle {
370 self.request_asset(hash_euvpak_path(path), priority)
371 }
372
373 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 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 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 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 pub fn register_spatial_asset(&mut self, anchor: SpatialAssetAnchor) {
528 let Self { spatial_grid, .. } = self;
529 spatial_grid.register_anchor(anchor);
530 }
531
532 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 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 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 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 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 #[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 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 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 #[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 #[must_use]
1150 pub fn residency_pool(&self) -> &ProgressiveResidencyPool {
1151 let Self { residency, .. } = self;
1152 residency
1153 }
1154
1155 pub fn residency_pool_mut(&mut self) -> &mut ProgressiveResidencyPool {
1161 let Self { residency, .. } = self;
1162 residency
1163 }
1164
1165 #[must_use]
1171 pub fn accountant(&self) -> &ResourceAccountant {
1172 let Self { accountant, .. } = self;
1173 accountant
1174 }
1175
1176 pub fn accountant_mut(&mut self) -> &mut ResourceAccountant {
1182 let Self { accountant, .. } = self;
1183 accountant
1184 }
1185
1186 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 #[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}