1use super::*;
2
3impl RenderBackendCandidate {
5 #[must_use]
15 pub const fn as_str(&self) -> &'static str {
16 match *self {
17 Self::GpuDirect => CANDIDATE_LABEL_GPU_DIRECT,
18 Self::GpuUpload => CANDIDATE_LABEL_GPU_UPLOAD,
19 Self::Hybrid => CANDIDATE_LABEL_HYBRID,
20 Self::Software => CANDIDATE_LABEL_SOFTWARE,
21 Self::Terminal => CANDIDATE_LABEL_TERMINAL,
22 }
23 }
24
25 #[must_use]
35 pub const fn to_render_mode(&self) -> RenderMode {
36 match *self {
37 Self::GpuDirect | Self::GpuUpload => RenderMode::Hardware,
38 Self::Hybrid => RenderMode::Hybrid,
39 Self::Software | Self::Terminal => RenderMode::Software,
40 }
41 }
42
43 #[must_use]
53 pub const fn is_direct_gpu(&self) -> bool {
54 matches!(*self, Self::GpuDirect)
55 }
56}
57
58impl AdaptiveSwitchMode {
60 #[must_use]
70 pub const fn as_str(&self) -> &'static str {
71 match *self {
72 Self::RecommendOnly => SWITCH_MODE_RECOMMEND_ONLY,
73 Self::AutoSwitch => SWITCH_MODE_AUTO_SWITCH,
74 }
75 }
76}
77
78impl FaultEventKind {
80 #[must_use]
90 pub const fn as_str(&self) -> &'static str {
91 match *self {
92 Self::DeviceLost => FAULT_LABEL_DEVICE_LOST,
93 Self::SurfaceDestroyed => FAULT_LABEL_SURFACE_DESTROYED,
94 Self::DriverSuspended => FAULT_LABEL_DRIVER_SUSPENDED,
95 Self::ThermalThrottled => FAULT_LABEL_THERMAL_THROTTLED,
96 }
97 }
98}
99
100impl Default for VisualEquivalenceContract {
102 fn default() -> Self {
108 Self::strict()
109 }
110}
111
112impl VisualEquivalenceContract {
114 #[must_use]
120 pub const fn strict() -> Self {
121 Self {
122 fonts_identical: true,
123 layout_identical: true,
124 color_identical: true,
125 antialiasing_identical: true,
126 shadows_identical: true,
127 blur_identical: true,
128 visible_tiles_identical: true,
129 media_quality_identical: true,
130 }
131 }
132
133 pub const fn check_equivalence(
144 &self,
145 candidate: &Self,
146 ) -> Result<(), VisualEquivalenceFailure> {
147 let Self {
148 fonts_identical,
149 layout_identical,
150 color_identical,
151 antialiasing_identical,
152 shadows_identical,
153 blur_identical,
154 visible_tiles_identical,
155 media_quality_identical,
156 } = *self;
157 if fonts_identical && !candidate.fonts_identical {
158 return Err(VisualEquivalenceFailure::FontMismatch);
159 }
160 if layout_identical && !candidate.layout_identical {
161 return Err(VisualEquivalenceFailure::LayoutMismatch);
162 }
163 if color_identical && !candidate.color_identical {
164 return Err(VisualEquivalenceFailure::ColorSpaceMismatch);
165 }
166 if antialiasing_identical && !candidate.antialiasing_identical {
167 return Err(VisualEquivalenceFailure::AntialiasingMismatch);
168 }
169 if shadows_identical && !candidate.shadows_identical {
170 return Err(VisualEquivalenceFailure::ShadowMismatch);
171 }
172 if blur_identical && !candidate.blur_identical {
173 return Err(VisualEquivalenceFailure::BackdropBlurMismatch);
174 }
175 if visible_tiles_identical && !candidate.visible_tiles_identical {
176 return Err(VisualEquivalenceFailure::VisibleTileMismatch);
177 }
178 if media_quality_identical && !candidate.media_quality_identical {
179 return Err(VisualEquivalenceFailure::MediaQualityMismatch);
180 }
181 Ok(())
182 }
183
184 #[must_use]
195 pub const fn is_equivalent(&self, candidate: &Self) -> bool {
196 self.check_equivalence(candidate).is_ok()
197 }
198}
199
200impl CandidateCapabilities {
202 #[must_use]
214 pub const fn supported_equivalent(
215 candidate: RenderBackendCandidate,
216 graphics_backend: GraphicsBackend,
217 requires_ui_thread_warmup: bool,
218 ) -> Self {
219 Self {
220 candidate,
221 supported: true,
222 visual_contract: VisualEquivalenceContract::strict(),
223 requires_ui_thread_warmup,
224 is_simulated_profile: false,
225 direct_gpu_verified_on_device: matches!(candidate, RenderBackendCandidate::GpuDirect),
226 graphics_backend,
227 }
228 }
229
230 pub fn passes_gate(
241 &self,
242 baseline: &VisualEquivalenceContract,
243 ) -> Result<(), VisualEquivalenceFailure> {
244 if !self.get_supported() {
245 return Err(VisualEquivalenceFailure::BackendUnsupported);
246 }
247 if self.get_candidate() == RenderBackendCandidate::GpuDirect
248 && self.get_is_simulated_profile()
249 && !self.get_direct_gpu_verified_on_device()
250 {
251 return Err(VisualEquivalenceFailure::UnverifiedSimulatedGpu);
252 }
253 let contract: VisualEquivalenceContract = self.get_visual_contract();
254 baseline.check_equivalence(&contract)
255 }
256}
257
258impl Default for HostCapabilityProfile {
260 fn default() -> Self {
266 Self::from_platform(
267 PlatformKind::Headless,
268 PlatformCapabilities::for_platform(PlatformKind::Headless),
269 )
270 }
271}
272
273impl HostCapabilityProfile {
275 #[must_use]
286 pub fn from_platform(platform: PlatformKind, capabilities: PlatformCapabilities) -> Self {
287 let baseline_contract: VisualEquivalenceContract = VisualEquivalenceContract::strict();
288 if matches!(
289 platform,
290 PlatformKind::Terminal
291 | PlatformKind::TerminalCli
292 | PlatformKind::MiniApp
293 | PlatformKind::QuickApp
294 ) {
295 let (cand, backend): (RenderBackendCandidate, GraphicsBackend) =
296 if matches!(platform, PlatformKind::Terminal | PlatformKind::TerminalCli) {
297 (RenderBackendCandidate::Terminal, GraphicsBackend::Headless)
298 } else {
299 (RenderBackendCandidate::Software, GraphicsBackend::Canvas2d)
300 };
301 return Self {
302 platform,
303 candidates: vec![CandidateCapabilities::supported_equivalent(
304 cand, backend, true,
305 )],
306 single_channel_only: true,
307 baseline_contract,
308 };
309 }
310 let default_gpu: GraphicsBackend = platform.default_graphics_backend();
311 let sw_backend: GraphicsBackend = if platform == PlatformKind::Web {
312 GraphicsBackend::Canvas2d
313 } else {
314 GraphicsBackend::SoftwareCpu
315 };
316 let mut candidates: Vec<CandidateCapabilities> = Vec::new();
317 if capabilities.get_hardware_gpu() {
318 let ui_thread_req: bool = matches!(
319 platform,
320 PlatformKind::Web | PlatformKind::MacOs | PlatformKind::Ios | PlatformKind::IpadOs
321 );
322 candidates.push(CandidateCapabilities::supported_equivalent(
323 RenderBackendCandidate::GpuDirect,
324 default_gpu,
325 ui_thread_req,
326 ));
327 candidates.push(CandidateCapabilities::supported_equivalent(
328 RenderBackendCandidate::GpuUpload,
329 default_gpu,
330 ui_thread_req,
331 ));
332 candidates.push(CandidateCapabilities::supported_equivalent(
333 RenderBackendCandidate::Hybrid,
334 default_gpu,
335 ui_thread_req,
336 ));
337 }
338 candidates.push(CandidateCapabilities::supported_equivalent(
339 RenderBackendCandidate::Software,
340 sw_backend,
341 false,
342 ));
343 let single_channel_only: bool = candidates.len() <= 1;
344 Self {
345 platform,
346 candidates,
347 single_channel_only,
348 baseline_contract,
349 }
350 }
351
352 #[must_use]
364 pub fn single_channel(
365 platform: PlatformKind,
366 candidate: RenderBackendCandidate,
367 backend: GraphicsBackend,
368 ) -> Self {
369 Self {
370 platform,
371 candidates: vec![CandidateCapabilities::supported_equivalent(
372 candidate, backend, true,
373 )],
374 single_channel_only: true,
375 baseline_contract: VisualEquivalenceContract::strict(),
376 }
377 }
378
379 #[must_use]
390 pub fn from_host_channel_capabilities(
391 platform: PlatformKind,
392 caps: &HostChannelCapabilities,
393 ) -> Self {
394 let gate: HostVisualEquivalenceGate = caps.get_visual_equivalence();
395 let visual_contract: VisualEquivalenceContract = VisualEquivalenceContract {
396 fonts_identical: gate.get_fonts_equivalent(),
397 layout_identical: gate.get_layout_equivalent(),
398 color_identical: gate.get_color_equivalent(),
399 antialiasing_identical: gate.get_aa_equivalent(),
400 shadows_identical: gate.get_shadow_equivalent(),
401 blur_identical: gate.get_blur_equivalent(),
402 visible_tiles_identical: gate.get_visible_tiles_equivalent(),
403 media_quality_identical: gate.get_media_quality_equivalent(),
404 };
405 let is_sim: bool = caps.get_simulated_profile();
406 let verified_gpu: bool = !is_sim && caps.get_direct_gpu_verified_on_device();
407 let default_gpu: GraphicsBackend = platform.default_graphics_backend();
408 let mut candidates: Vec<CandidateCapabilities> = Vec::new();
409 for channel in caps.get_supported_channels() {
410 let (candidate, graphics_backend): (RenderBackendCandidate, GraphicsBackend) =
411 match *channel {
412 HostRenderChannel::GpuDirect => {
413 (RenderBackendCandidate::GpuDirect, default_gpu)
414 }
415 HostRenderChannel::GpuUpload => {
416 (RenderBackendCandidate::GpuUpload, default_gpu)
417 }
418 HostRenderChannel::SoftwareBuffer => (
419 RenderBackendCandidate::Software,
420 GraphicsBackend::SoftwareCpu,
421 ),
422 HostRenderChannel::Canvas2d => {
423 (RenderBackendCandidate::Software, GraphicsBackend::Canvas2d)
424 }
425 HostRenderChannel::WebGl | HostRenderChannel::WebGl2 => {
426 (RenderBackendCandidate::GpuUpload, GraphicsBackend::WebGl2)
427 }
428 };
429 let direct_verified: bool =
430 candidate == RenderBackendCandidate::GpuDirect && verified_gpu;
431 candidates.push(CandidateCapabilities {
432 candidate,
433 supported: true,
434 visual_contract,
435 requires_ui_thread_warmup: true,
436 is_simulated_profile: is_sim,
437 direct_gpu_verified_on_device: direct_verified,
438 graphics_backend,
439 });
440 }
441 let single_channel_only: bool = caps.get_supported_channels().len() <= 1;
442 Self {
443 platform,
444 candidates,
445 single_channel_only,
446 baseline_contract: VisualEquivalenceContract::strict(),
447 }
448 }
449
450 #[must_use]
460 pub fn is_single_channel(&self) -> bool {
461 if self.get_single_channel_only() {
462 return true;
463 }
464 let eligible: usize = self
465 .get_candidates()
466 .iter()
467 .filter(|cap: &&CandidateCapabilities| {
468 cap.passes_gate(&self.get_baseline_contract()).is_ok()
469 })
470 .count();
471 eligible <= 1
472 }
473
474 pub fn candidate_passes_gate(
485 &self,
486 candidate: RenderBackendCandidate,
487 ) -> Result<(), VisualEquivalenceFailure> {
488 let baseline: VisualEquivalenceContract = self.get_baseline_contract();
489 let found: Option<&CandidateCapabilities> = self
490 .get_candidates()
491 .iter()
492 .find(|cap: &&CandidateCapabilities| cap.get_candidate() == candidate);
493 match found {
494 Some(cap) => cap.passes_gate(&baseline),
495 None => Err(VisualEquivalenceFailure::BackendUnsupported),
496 }
497 }
498
499 #[must_use]
510 pub fn best_available_candidate(
511 &self,
512 exclude: Option<RenderBackendCandidate>,
513 ) -> RenderBackendCandidate {
514 let priority: [RenderBackendCandidate; 5] = [
515 RenderBackendCandidate::GpuDirect,
516 RenderBackendCandidate::GpuUpload,
517 RenderBackendCandidate::Software,
518 RenderBackendCandidate::Hybrid,
519 RenderBackendCandidate::Terminal,
520 ];
521 for cand in priority {
522 if Some(cand) == exclude {
523 continue;
524 }
525 if self.candidate_passes_gate(cand).is_ok() {
526 return cand;
527 }
528 }
529 if self.get_platform() == PlatformKind::Terminal {
530 RenderBackendCandidate::Terminal
531 } else {
532 RenderBackendCandidate::Software
533 }
534 }
535
536 #[must_use]
547 pub fn graphics_backend_for(&self, candidate: RenderBackendCandidate) -> GraphicsBackend {
548 if let Some(cap) = self
549 .get_candidates()
550 .iter()
551 .find(|cap: &&CandidateCapabilities| cap.get_candidate() == candidate)
552 {
553 return cap.get_graphics_backend();
554 }
555 match candidate {
556 RenderBackendCandidate::Software => GraphicsBackend::SoftwareCpu,
557 RenderBackendCandidate::Terminal => GraphicsBackend::Headless,
558 RenderBackendCandidate::GpuDirect
559 | RenderBackendCandidate::GpuUpload
560 | RenderBackendCandidate::Hybrid => self.get_platform().default_graphics_backend(),
561 }
562 }
563}
564
565impl Default for WinnerCache {
567 fn default() -> Self {
573 Self::with_capacity(DEFAULT_WINNER_CACHE_CAPACITY)
574 }
575}
576
577impl WinnerCache {
579 #[must_use]
589 pub fn with_capacity(max_entries: usize) -> Self {
590 let cap: usize = max_entries.max(1);
591 Self {
592 entries: HashMap::with_capacity(cap),
593 max_entries: cap,
594 }
595 }
596
597 #[must_use]
608 pub fn lookup(&self, key: &WinnerCacheKey) -> Option<WinnerCacheEntry> {
609 self.get_entries().get(key).copied()
610 }
611
612 pub fn record(&mut self, key: WinnerCacheKey, entry: WinnerCacheEntry) {
620 let limit: usize = self.get_max_entries();
621 if !self.get_entries().contains_key(&key) && self.get_entries().len() >= limit {
622 let oldest_key: Option<WinnerCacheKey> = self
623 .get_entries()
624 .iter()
625 .min_by_key(|(_, val): &(&WinnerCacheKey, &WinnerCacheEntry)| {
626 val.get_verified_at_ms()
627 })
628 .map(|(k, _): (&WinnerCacheKey, &WinnerCacheEntry)| k.clone());
629 if let Some(evict) = oldest_key {
630 let _: Option<WinnerCacheEntry> = self.get_mut_entries().remove(&evict);
631 }
632 }
633 let _: Option<WinnerCacheEntry> = self.get_mut_entries().insert(key, entry);
634 }
635
636 pub fn invalidate_stale_environment(
650 &mut self,
651 device_id: &str,
652 driver_version: &str,
653 display_mode_hz_millihz: u32,
654 build_id: &str,
655 ) -> usize {
656 let before: usize = self.get_entries().len();
657 self.get_mut_entries()
658 .retain(|k: &WinnerCacheKey, _: &mut WinnerCacheEntry| {
659 if k.get_device_id().as_str() != device_id {
660 return true;
661 }
662 k.get_driver_version().as_str() == driver_version
663 && k.get_display_mode_hz_millihz() == display_mode_hz_millihz
664 && k.get_build_id().as_str() == build_id
665 });
666 before.saturating_sub(self.get_entries().len())
667 }
668
669 #[must_use]
679 pub fn len(&self) -> usize {
680 self.get_entries().len()
681 }
682
683 #[must_use]
693 pub fn is_empty(&self) -> bool {
694 self.get_entries().is_empty()
695 }
696}
697
698impl Default for BoundedTelemetryQueue {
700 fn default() -> Self {
706 Self::with_capacity(DEFAULT_TELEMETRY_QUEUE_CAPACITY)
707 }
708}
709
710impl BoundedTelemetryQueue {
712 #[must_use]
722 pub fn with_capacity(capacity: usize) -> Self {
723 let cap: usize = capacity.max(1);
724 let slots: Vec<TelemetrySample> = vec![TelemetrySample::default(); cap];
725 Self {
726 slots,
727 head: 0,
728 len: 0,
729 capacity: cap,
730 dropped_oldest_count: 0,
731 }
732 }
733
734 pub fn push(&mut self, sample: TelemetrySample) -> bool {
745 let cap: usize = self.get_capacity();
746 let len: usize = self.get_len();
747 let head: usize = self.get_head();
748 if len < cap {
749 let tail: usize = (head + len) % cap;
750 self.get_mut_slots()[tail] = sample;
751 self.set_len(len + 1);
752 true
753 } else {
754 self.get_mut_slots()[head] = sample;
755 self.set_head((head + 1) % cap);
756 let next_drops: u64 = self.get_dropped_oldest_count().saturating_add(1);
757 self.set_dropped_oldest_count(next_drops);
758 false
759 }
760 }
761
762 pub fn drain_into(&mut self, out: &mut Vec<TelemetrySample>) -> usize {
773 let count: usize = self.get_len();
774 let head: usize = self.get_head();
775 let cap: usize = self.get_capacity();
776 for offset in 0..count {
777 let idx: usize = (head + offset) % cap;
778 out.push(self.get_slots()[idx]);
779 }
780 self.set_head(0);
781 self.set_len(0);
782 count
783 }
784
785 pub fn aggregate_and_drain(&mut self) -> AggregatedTelemetryWindow {
795 let mut drained: Vec<TelemetrySample> = Vec::with_capacity(self.get_len());
796 let count: usize = self.drain_into(&mut drained);
797 if count == 0 {
798 return AggregatedTelemetryWindow::default();
799 }
800 let mut present_intervals: Vec<f64> = Vec::with_capacity(count);
801 let mut input_latencies: Vec<f64> = Vec::new();
802 let mut presented: u64 = 0;
803 let mut skipped: u64 = 0;
804 let mut failed: u64 = 0;
805 let mut missed: u64 = 0;
806 let mut compositor_hits: u64 = 0;
807 let last_sample: TelemetrySample = drained[count - 1];
808 for sample in drained.iter() {
809 match sample.get_present_outcome() {
810 SurfacePresentOutcome::Submitted => {
811 presented = presented.saturating_add(1);
812 if sample.get_missed_deadline() {
813 missed = missed.saturating_add(1);
814 }
815 if sample.get_present_interval_ms() > 0.0 {
816 present_intervals.push(sample.get_present_interval_ms());
817 }
818 if sample.get_present_timing_source() == PresentTimingSource::CompositorMeasured
819 {
820 compositor_hits = compositor_hits.saturating_add(1);
821 }
822 }
823 SurfacePresentOutcome::SkippedUnchanged => {
824 skipped = skipped.saturating_add(1);
825 }
826 SurfacePresentOutcome::Failed => {
827 failed = failed.saturating_add(1);
828 }
829 }
830 if sample.get_input_latency_measured() {
831 input_latencies.push(sample.get_input_to_present_ms());
832 }
833 }
834 present_intervals.sort_by(|a: &f64, b: &f64| a.total_cmp(b));
835 input_latencies.sort_by(|a: &f64, b: &f64| a.total_cmp(b));
836 AggregatedTelemetryWindow {
837 sample_count: count as u64,
838 presented_frames: presented,
839 skipped_unchanged_frames: skipped,
840 failed_frames: failed,
841 missed_deadline_frames: missed,
842 present_p50_ms: sorted_percentile_f64(&present_intervals, 0.50),
843 present_p95_ms: sorted_percentile_f64(&present_intervals, 0.95),
844 present_p99_ms: sorted_percentile_f64(&present_intervals, 0.99),
845 input_to_present_p95_ms: sorted_percentile_f64(&input_latencies, 0.95),
846 has_input_latency: !input_latencies.is_empty(),
847 has_compositor_timing: compositor_hits > 0 && compositor_hits == presented,
848 scene_profile: last_sample.get_scene_profile(),
849 display_mode_hz: last_sample.get_display_mode_hz(),
850 candidate: last_sample.get_candidate(),
851 }
852 }
853}
854
855impl CandidateScore {
857 #[must_use]
871 pub const fn from_metrics(
872 candidate: RenderBackendCandidate,
873 scene_profile: SceneProfile,
874 display_mode_hz_millihz: u32,
875 latency: (f64, f64, f64, f64),
876 sample_count: u64,
877 ) -> Self {
878 let (missed_frame_ratio, p95_frame_ms, p99_frame_ms, input_to_present_ms): (
879 f64,
880 f64,
881 f64,
882 f64,
883 ) = latency;
884 Self {
885 candidate,
886 scene_profile,
887 display_mode_hz_millihz,
888 missed_frame_ratio,
889 p95_frame_ms,
890 p99_frame_ms,
891 input_to_present_ms,
892 hybrid_net_gain_ms: 0.0,
893 sample_count,
894 }
895 }
896
897 #[must_use]
908 pub fn with_hybrid_net_gain_ms(mut self, net_gain_ms: f64) -> Self {
909 self.set_hybrid_net_gain_ms(net_gain_ms);
910 self
911 }
912}
913
914impl Default for HandoffBudgetConfig {
916 fn default() -> Self {
922 Self {
923 warmup_steps_required: DEFAULT_HANDOFF_WARMUP_STEPS,
924 per_frame_budget_ms: DEFAULT_HANDOFF_PER_FRAME_BUDGET_MS,
925 max_warmup_timeout_ms: DEFAULT_HANDOFF_TIMEOUT_MS,
926 post_commit_fence_frames: DEFAULT_POST_COMMIT_FENCE_FRAMES,
927 }
928 }
929}
930
931impl RuntimeStateSnapshot {
933 #[must_use]
944 pub fn is_preserved_by(&self, after: &Self) -> bool {
945 self.get_scroll_offset_x().to_bits() == after.get_scroll_offset_x().to_bits()
946 && self.get_scroll_offset_y().to_bits() == after.get_scroll_offset_y().to_bits()
947 && self.get_active_gesture_id() == after.get_active_gesture_id()
948 && self.get_focused_node_id() == after.get_focused_node_id()
949 && self.get_page_state_revision() == after.get_page_state_revision()
950 && self.get_animation_timeline_ns() == after.get_animation_timeline_ns()
951 && after.get_target_refresh_hz() >= self.get_target_refresh_hz()
952 }
953}
954
955impl Default for HandoffCoordinator {
957 fn default() -> Self {
963 Self {
964 stage: HandoffStage::Idle,
965 old_candidate: RenderBackendCandidate::Software,
966 target_candidate: RenderBackendCandidate::Software,
967 target_width: 0,
968 target_height: 0,
969 target_scale_factor: 1.0,
970 target_scene_version: 0,
971 started_at_ms: 0,
972 warmup_steps_completed: 0,
973 budget_config: HandoffBudgetConfig::default(),
974 old_resources_retained: false,
975 commit_fence_id: 0,
976 completed_fence_id: 0,
977 post_handoff_present_confirmed: false,
978 last_abort_reason: None,
979 seamless_success_count: 0,
980 abort_count: 0,
981 preserved_state: RuntimeStateSnapshot::default(),
982 }
983 }
984}
985
986impl HandoffCoordinator {
988 #[must_use]
998 pub fn last_abort_reason_value(&self) -> Option<HandoffAbortReason> {
999 let Self {
1000 last_abort_reason, ..
1001 } = *self;
1002 last_abort_reason
1003 }
1004
1005 #[must_use]
1015 pub fn is_in_flight(&self) -> bool {
1016 matches!(
1017 self.get_stage(),
1018 HandoffStage::WarmingUp
1019 | HandoffStage::ReadyForBoundary
1020 | HandoffStage::AwaitingPresentConfirmation
1021 )
1022 }
1023
1024 pub fn begin_handoff(
1035 &mut self,
1036 old: RenderBackendCandidate,
1037 target: RenderBackendCandidate,
1038 frame_identity: (u32, u32, f32, u64),
1039 now_ms: u64,
1040 state: RuntimeStateSnapshot,
1041 ) {
1042 let (width, height, scale_factor, scene_version): (u32, u32, f32, u64) = frame_identity;
1043 self.set_stage(HandoffStage::WarmingUp);
1044 self.set_old_candidate(old);
1045 self.set_target_candidate(target);
1046 self.set_target_width(width);
1047 self.set_target_height(height);
1048 self.set_target_scale_factor(scale_factor);
1049 self.set_target_scene_version(scene_version);
1050 self.set_started_at_ms(now_ms);
1051 self.set_warmup_steps_completed(0);
1052 self.set_old_resources_retained(true);
1053 self.set_commit_fence_id(0);
1054 self.set_completed_fence_id(0);
1055 self.set_post_handoff_present_confirmed(false);
1056 self.set_last_abort_reason(None);
1057 self.set_preserved_state(state);
1058 }
1059
1060 pub fn step_warmup(
1073 &mut self,
1074 step_elapsed_ms: f64,
1075 step_ok: bool,
1076 now_ms: u64,
1077 ) -> Result<HandoffStage, HandoffAbortReason> {
1078 if self.get_stage() != HandoffStage::WarmingUp {
1079 return Ok(self.get_stage());
1080 }
1081 let budget: HandoffBudgetConfig = self.get_budget_config();
1082 let elapsed_total_ms: u64 = now_ms.saturating_sub(self.get_started_at_ms());
1083 if elapsed_total_ms > budget.get_max_warmup_timeout_ms() {
1084 self.abort_internal(HandoffAbortReason::TimedOut);
1085 return Err(HandoffAbortReason::TimedOut);
1086 }
1087 if !step_ok {
1088 self.abort_internal(HandoffAbortReason::InitFailed);
1089 return Err(HandoffAbortReason::InitFailed);
1090 }
1091 if step_elapsed_ms <= budget.get_per_frame_budget_ms()
1092 || self.get_warmup_steps_completed() == 0
1093 {
1094 let next_steps: u32 = self.get_warmup_steps_completed().saturating_add(1);
1095 self.set_warmup_steps_completed(next_steps);
1096 }
1097 if self.get_warmup_steps_completed() >= budget.get_warmup_steps_required().max(1) {
1098 self.set_stage(HandoffStage::ReadyForBoundary);
1099 }
1100 Ok(self.get_stage())
1101 }
1102
1103 pub fn try_commit_at_frame_boundary(
1117 &mut self,
1118 first_frame: HandoffFrameDescriptor,
1119 current_frame: (u32, u32, f32, u64),
1120 commit_fence_id: u64,
1121 now_ms: u64,
1122 ) -> Result<RenderBackendCandidate, HandoffAbortReason> {
1123 let (cur_w, cur_h, cur_scale, cur_scene_ver): (u32, u32, f32, u64) = current_frame;
1124 let budget: HandoffBudgetConfig = self.get_budget_config();
1125 if now_ms.saturating_sub(self.get_started_at_ms()) > budget.get_max_warmup_timeout_ms() {
1126 self.abort_internal(HandoffAbortReason::TimedOut);
1127 return Err(HandoffAbortReason::TimedOut);
1128 }
1129 if !first_frame.get_first_frame_ok() {
1130 self.abort_internal(HandoffAbortReason::FirstFrameFailed);
1131 return Err(HandoffAbortReason::FirstFrameFailed);
1132 }
1133 if first_frame.get_width() != cur_w
1134 || first_frame.get_height() != cur_h
1135 || first_frame.get_width() != self.get_target_width()
1136 || first_frame.get_height() != self.get_target_height()
1137 {
1138 self.abort_internal(HandoffAbortReason::DimensionMismatch);
1139 return Err(HandoffAbortReason::DimensionMismatch);
1140 }
1141 if (first_frame.get_scale_factor() - cur_scale).abs() > 0.001
1142 || (first_frame.get_scale_factor() - self.get_target_scale_factor()).abs() > 0.001
1143 {
1144 self.abort_internal(HandoffAbortReason::ScaleFactorMismatch);
1145 return Err(HandoffAbortReason::ScaleFactorMismatch);
1146 }
1147 if first_frame.get_scene_version() != cur_scene_ver
1148 || first_frame.get_scene_version() != self.get_target_scene_version()
1149 {
1150 self.abort_internal(HandoffAbortReason::StaleSceneVersion);
1151 return Err(HandoffAbortReason::StaleSceneVersion);
1152 }
1153 if first_frame.get_frame_time_ms() > first_frame.get_deadline_ms() {
1154 self.abort_internal(HandoffAbortReason::MissedDeadline);
1155 return Err(HandoffAbortReason::MissedDeadline);
1156 }
1157 self.set_stage(HandoffStage::AwaitingPresentConfirmation);
1158 self.set_commit_fence_id(commit_fence_id.max(1));
1159 self.set_old_resources_retained(true);
1160 self.set_post_handoff_present_confirmed(false);
1161 Ok(self.get_target_candidate())
1162 }
1163
1164 pub fn confirm_post_handoff_present(
1176 &mut self,
1177 present_confirmed: bool,
1178 completed_fence_id: u64,
1179 ) -> bool {
1180 if self.get_stage() != HandoffStage::AwaitingPresentConfirmation {
1181 return false;
1182 }
1183 if present_confirmed {
1184 self.set_post_handoff_present_confirmed(true);
1185 }
1186 let latest_fence: u64 = self.get_completed_fence_id().max(completed_fence_id);
1187 self.set_completed_fence_id(latest_fence);
1188 if self.get_post_handoff_present_confirmed() && latest_fence >= self.get_commit_fence_id() {
1189 self.set_old_resources_retained(false);
1190 self.set_stage(HandoffStage::Committed);
1191 let next_ok: u64 = self.get_seamless_success_count().saturating_add(1);
1192 self.set_seamless_success_count(next_ok);
1193 true
1194 } else {
1195 false
1196 }
1197 }
1198
1199 pub fn abort_for_fault(&mut self) {
1205 if self.is_in_flight() {
1206 self.abort_internal(HandoffAbortReason::FaultInterrupted);
1207 }
1208 }
1209
1210 fn abort_internal(&mut self, reason: HandoffAbortReason) {
1217 self.set_stage(HandoffStage::Aborted);
1218 self.set_last_abort_reason(Some(reason));
1219 self.set_old_resources_retained(true);
1220 let next_aborts: u64 = self.get_abort_count().saturating_add(1);
1221 self.set_abort_count(next_aborts);
1222 }
1223}
1224
1225impl Default for AdaptiveRouterConfig {
1227 fn default() -> Self {
1233 Self {
1234 switch_mode: AdaptiveSwitchMode::RecommendOnly,
1235 sustained_miss_threshold: DEFAULT_SUSTAINED_MISS_THRESHOLD,
1236 input_latency_degrade_ratio: DEFAULT_INPUT_LATENCY_DEGRADE_RATIO,
1237 consecutive_wins_required: DEFAULT_CONSECUTIVE_WINS_REQUIRED,
1238 switch_cost_ms: DEFAULT_SWITCH_COST_MS,
1239 min_dwell_ms: DEFAULT_MIN_DWELL_MS,
1240 cooldown_ms: DEFAULT_COOLDOWN_MS,
1241 probe_min_headroom_ratio: DEFAULT_PROBE_MIN_HEADROOM_RATIO,
1242 telemetry_queue_capacity: DEFAULT_TELEMETRY_QUEUE_CAPACITY,
1243 }
1244 }
1245}
1246
1247impl AdaptiveDecision {
1249 #[must_use]
1259 pub fn fault_tag_value(&self) -> Option<FaultEventKind> {
1260 let Self { fault_tag, .. } = *self;
1261 fault_tag
1262 }
1263}
1264
1265impl Default for AdaptiveRenderRouter {
1267 fn default() -> Self {
1273 Self::new(
1274 AdaptiveRouterConfig::default(),
1275 HostCapabilityProfile::default(),
1276 60.0,
1277 )
1278 }
1279}
1280
1281impl AdaptiveRenderRouter {
1283 #[must_use]
1295 pub fn new(
1296 config: AdaptiveRouterConfig,
1297 host_profile: HostCapabilityProfile,
1298 display_mode_hz: f64,
1299 ) -> Self {
1300 let initial_candidate: RenderBackendCandidate = host_profile.best_available_candidate(None);
1301 let queue_cap: usize = config.get_telemetry_queue_capacity();
1302 Self {
1303 config,
1304 host_profile,
1305 winner_cache: WinnerCache::default(),
1306 telemetry_queue: BoundedTelemetryQueue::with_capacity(queue_cap),
1307 handoff: HandoffCoordinator::default(),
1308 active_candidate: initial_candidate,
1309 recommended_candidate: initial_candidate,
1310 active_scene_profile: SceneProfile::StaticUi,
1311 display_mode_hz: if display_mode_hz.is_finite() && display_mode_hz > 0.0 {
1312 display_mode_hz
1313 } else {
1314 60.0
1315 },
1316 device_id: DEFAULT_DEVICE_ID.to_string(),
1317 driver_version: DEFAULT_DRIVER_VERSION.to_string(),
1318 build_id: DEFAULT_BUILD_ID.to_string(),
1319 last_switch_ms: 0,
1320 has_switched_once: false,
1321 cooldown_until_ms: 0,
1322 sustained_miss_streak: 0,
1323 input_latency_degraded: false,
1324 streak_candidate: None,
1325 streak_wins: 0,
1326 last_valid_frame_retained: false,
1327 fault_failover_count: 0,
1328 tagged_fault_events: Vec::new(),
1329 probe_runs: 0,
1330 probe_skips_no_headroom: 0,
1331 cache_hits: 0,
1332 recommendations_logged: 0,
1333 last_decision_reason: REASON_KEEP_CURRENT,
1334 }
1335 }
1336
1337 pub fn update_environment(
1351 &mut self,
1352 device_id: &str,
1353 driver_version: &str,
1354 display_mode_hz: f64,
1355 build_id: &str,
1356 ) -> usize {
1357 self.set_device_id(device_id.to_string());
1358 self.set_driver_version(driver_version.to_string());
1359 if display_mode_hz.is_finite() && display_mode_hz > 0.0 {
1360 self.set_display_mode_hz(display_mode_hz);
1361 }
1362 self.set_build_id(build_id.to_string());
1363 let millihz: u32 = hz_to_millihz(self.get_display_mode_hz());
1364 self.get_mut_winner_cache().invalidate_stale_environment(
1365 device_id,
1366 driver_version,
1367 millihz,
1368 build_id,
1369 )
1370 }
1371
1372 #[must_use]
1383 pub fn cache_key_for(&self, scene_profile: SceneProfile) -> WinnerCacheKey {
1384 WinnerCacheKey::new(
1385 self.get_device_id().clone(),
1386 self.get_driver_version().clone(),
1387 hz_to_millihz(self.get_display_mode_hz()),
1388 self.get_build_id().clone(),
1389 scene_profile,
1390 )
1391 }
1392
1393 pub fn select_startup_candidate(&mut self, scene_profile: SceneProfile) -> AdaptiveDecision {
1404 self.set_active_scene_profile(scene_profile);
1405 if self.get_host_profile().is_single_channel() {
1406 let sole: RenderBackendCandidate =
1407 self.get_host_profile().best_available_candidate(None);
1408 self.set_active_candidate(sole);
1409 self.set_recommended_candidate(sole);
1410 self.set_last_decision_reason(REASON_SINGLE_CHANNEL_LOCKED);
1411 return AdaptiveDecision {
1412 kind: AdaptiveDecisionKind::LockedSingleChannel,
1413 active_candidate: sole,
1414 recommended_candidate: sole,
1415 applied: true,
1416 reason: REASON_SINGLE_CHANNEL_LOCKED,
1417 preserve_last_valid_frame: false,
1418 fault_tag: None,
1419 };
1420 }
1421 let key: WinnerCacheKey = self.cache_key_for(scene_profile);
1422 if let Some(entry) = self.get_winner_cache().lookup(&key)
1423 && self
1424 .get_host_profile()
1425 .candidate_passes_gate(entry.get_winner())
1426 .is_ok()
1427 {
1428 let winner: RenderBackendCandidate = entry.get_winner();
1429 let next_hits: u64 = self.get_cache_hits().saturating_add(1);
1430 self.set_cache_hits(next_hits);
1431 self.set_active_candidate(winner);
1432 self.set_recommended_candidate(winner);
1433 self.set_last_decision_reason(REASON_CACHE_HIT_VERIFIED);
1434 return AdaptiveDecision {
1435 kind: AdaptiveDecisionKind::UseCachedWinner,
1436 active_candidate: winner,
1437 recommended_candidate: winner,
1438 applied: true,
1439 reason: REASON_CACHE_HIT_VERIFIED,
1440 preserve_last_valid_frame: false,
1441 fault_tag: None,
1442 };
1443 }
1444 if self
1445 .get_host_profile()
1446 .candidate_passes_gate(RenderBackendCandidate::GpuDirect)
1447 .is_ok()
1448 {
1449 self.set_active_candidate(RenderBackendCandidate::GpuDirect);
1450 self.set_recommended_candidate(RenderBackendCandidate::GpuDirect);
1451 self.set_last_decision_reason(REASON_STARTUP_GPU_DIRECT);
1452 return AdaptiveDecision {
1453 kind: AdaptiveDecisionKind::StartupGpuDirect,
1454 active_candidate: RenderBackendCandidate::GpuDirect,
1455 recommended_candidate: RenderBackendCandidate::GpuDirect,
1456 applied: true,
1457 reason: REASON_STARTUP_GPU_DIRECT,
1458 preserve_last_valid_frame: false,
1459 fault_tag: None,
1460 };
1461 }
1462 let fallback: RenderBackendCandidate =
1463 self.get_host_profile().best_available_candidate(None);
1464 self.set_active_candidate(fallback);
1465 self.set_recommended_candidate(fallback);
1466 self.set_last_decision_reason(REASON_STARTUP_FALLBACK_READY);
1467 AdaptiveDecision {
1468 kind: AdaptiveDecisionKind::KeepCurrent,
1469 active_candidate: fallback,
1470 recommended_candidate: fallback,
1471 applied: true,
1472 reason: REASON_STARTUP_FALLBACK_READY,
1473 preserve_last_valid_frame: false,
1474 fault_tag: None,
1475 }
1476 }
1477
1478 pub fn on_startup_candidate_failed(
1490 &mut self,
1491 failed: RenderBackendCandidate,
1492 now_ms: u64,
1493 ) -> AdaptiveDecision {
1494 let next: RenderBackendCandidate = self
1495 .get_host_profile()
1496 .best_available_candidate(Some(failed));
1497 self.set_active_candidate(next);
1498 self.set_recommended_candidate(next);
1499 self.set_last_switch_ms(now_ms);
1500 self.set_has_switched_once(true);
1501 let cooldown_end: u64 = now_ms.saturating_add(self.get_config().get_cooldown_ms());
1502 self.set_cooldown_until_ms(cooldown_end);
1503 self.set_last_decision_reason(REASON_STARTUP_FAILOVER);
1504 AdaptiveDecision {
1505 kind: AdaptiveDecisionKind::StartupFailover,
1506 active_candidate: next,
1507 recommended_candidate: next,
1508 applied: true,
1509 reason: REASON_STARTUP_FAILOVER,
1510 preserve_last_valid_frame: false,
1511 fault_tag: None,
1512 }
1513 }
1514
1515 pub fn record_runtime_sample(&mut self, sample: TelemetrySample) -> bool {
1526 let target_ms: f64 =
1527 AdaptiveFrameMetrics::target_frame_interval_ms_for_hz(sample.get_display_mode_hz());
1528 if sample.get_present_outcome() == SurfacePresentOutcome::Submitted {
1529 if sample.get_missed_deadline() {
1530 let next_streak: u32 = self.get_sustained_miss_streak().saturating_add(1);
1531 self.set_sustained_miss_streak(next_streak);
1532 } else {
1533 self.set_sustained_miss_streak(0);
1534 }
1535 }
1536 if sample.get_input_latency_measured() {
1537 let degrade_limit: f64 =
1538 target_ms * self.get_config().get_input_latency_degrade_ratio();
1539 self.set_input_latency_degraded(sample.get_input_to_present_ms() > degrade_limit);
1540 }
1541 self.get_mut_telemetry_queue().push(sample)
1542 }
1543
1544 #[must_use]
1557 pub fn has_probe_headroom(
1558 &self,
1559 is_idle: bool,
1560 recent_frame_ms: f64,
1561 target_interval_ms: f64,
1562 ) -> bool {
1563 if is_idle {
1564 return true;
1565 }
1566 if !target_interval_ms.is_finite() || target_interval_ms <= 0.0 {
1567 return false;
1568 }
1569 let remaining_ms: f64 = target_interval_ms - recent_frame_ms.max(0.0);
1570 let required_ms: f64 = target_interval_ms
1571 * self
1572 .get_config()
1573 .get_probe_min_headroom_ratio()
1574 .clamp(0.0, 1.0);
1575 remaining_ms >= required_ms
1576 }
1577
1578 pub fn should_trigger_probe(
1592 &mut self,
1593 is_idle: bool,
1594 recent_frame_ms: f64,
1595 target_interval_ms: f64,
1596 now_ms: u64,
1597 ) -> Result<ProbeTriggerReason, &'static str> {
1598 if self.get_host_profile().is_single_channel() {
1599 self.set_last_decision_reason(REASON_SINGLE_CHANNEL_LOCKED);
1600 return Err(REASON_SINGLE_CHANNEL_LOCKED);
1601 }
1602 if now_ms < self.get_cooldown_until_ms() {
1603 self.set_last_decision_reason(REASON_PROBE_COOLDOWN);
1604 return Err(REASON_PROBE_COOLDOWN);
1605 }
1606 if self.get_handoff().is_in_flight() {
1607 self.set_last_decision_reason(REASON_PROBE_HANDOFF_ACTIVE);
1608 return Err(REASON_PROBE_HANDOFF_ACTIVE);
1609 }
1610 let trigger: Option<ProbeTriggerReason> = if self.get_sustained_miss_streak()
1611 >= self.get_config().get_sustained_miss_threshold()
1612 {
1613 Some(ProbeTriggerReason::SustainedDeadlineMiss)
1614 } else if self.get_input_latency_degraded() {
1615 Some(ProbeTriggerReason::InputLatencyDegraded)
1616 } else {
1617 None
1618 };
1619 let Some(reason) = trigger else {
1620 self.set_last_decision_reason(REASON_PROBE_NO_TRIGGER);
1621 return Err(REASON_PROBE_NO_TRIGGER);
1622 };
1623 if !self.has_probe_headroom(is_idle, recent_frame_ms, target_interval_ms) {
1624 let next_skips: u64 = self.get_probe_skips_no_headroom().saturating_add(1);
1625 self.set_probe_skips_no_headroom(next_skips);
1626 self.set_last_decision_reason(REASON_PROBE_NO_HEADROOM);
1627 return Err(REASON_PROBE_NO_HEADROOM);
1628 }
1629 let next_probes: u64 = self.get_probe_runs().saturating_add(1);
1630 self.set_probe_runs(next_probes);
1631 self.set_last_decision_reason(REASON_PROBE_STARTED);
1632 Ok(reason)
1633 }
1634
1635 pub fn evaluate_candidates(
1648 &mut self,
1649 current: CandidateScore,
1650 candidate: CandidateScore,
1651 now_ms: u64,
1652 ) -> AdaptiveDecision {
1653 let active: RenderBackendCandidate = self.get_active_candidate();
1654 if self.get_host_profile().is_single_channel() {
1655 self.set_last_decision_reason(REASON_SINGLE_CHANNEL_LOCKED);
1656 return AdaptiveDecision {
1657 kind: AdaptiveDecisionKind::LockedSingleChannel,
1658 active_candidate: active,
1659 recommended_candidate: active,
1660 applied: false,
1661 reason: REASON_SINGLE_CHANNEL_LOCKED,
1662 preserve_last_valid_frame: false,
1663 fault_tag: None,
1664 };
1665 }
1666 if candidate.get_candidate() == active {
1667 self.set_streak_candidate(None);
1668 self.set_streak_wins(0);
1669 self.set_last_decision_reason(REASON_KEEP_CURRENT);
1670 return AdaptiveDecision {
1671 kind: AdaptiveDecisionKind::KeepCurrent,
1672 active_candidate: active,
1673 recommended_candidate: active,
1674 applied: false,
1675 reason: REASON_KEEP_CURRENT,
1676 preserve_last_valid_frame: false,
1677 fault_tag: None,
1678 };
1679 }
1680 if self
1681 .get_host_profile()
1682 .candidate_passes_gate(candidate.get_candidate())
1683 .is_err()
1684 {
1685 self.set_streak_candidate(None);
1686 self.set_streak_wins(0);
1687 self.set_last_decision_reason(REASON_VISUAL_GATE_FAILED);
1688 return AdaptiveDecision {
1689 kind: AdaptiveDecisionKind::KeepCurrent,
1690 active_candidate: active,
1691 recommended_candidate: active,
1692 applied: false,
1693 reason: REASON_VISUAL_GATE_FAILED,
1694 preserve_last_valid_frame: false,
1695 fault_tag: None,
1696 };
1697 }
1698 if current.get_scene_profile() != candidate.get_scene_profile()
1699 || current.get_display_mode_hz_millihz() != candidate.get_display_mode_hz_millihz()
1700 {
1701 self.set_last_decision_reason(REASON_CONTEXT_MISMATCH);
1702 return AdaptiveDecision {
1703 kind: AdaptiveDecisionKind::KeepCurrent,
1704 active_candidate: active,
1705 recommended_candidate: active,
1706 applied: false,
1707 reason: REASON_CONTEXT_MISMATCH,
1708 preserve_last_valid_frame: false,
1709 fault_tag: None,
1710 };
1711 }
1712 if candidate.get_candidate() == RenderBackendCandidate::Hybrid
1713 && candidate.get_hybrid_net_gain_ms() <= 0.0
1714 {
1715 self.set_streak_candidate(None);
1716 self.set_streak_wins(0);
1717 self.set_last_decision_reason(REASON_HYBRID_NO_NET_GAIN);
1718 return AdaptiveDecision {
1719 kind: AdaptiveDecisionKind::KeepCurrent,
1720 active_candidate: active,
1721 recommended_candidate: active,
1722 applied: false,
1723 reason: REASON_HYBRID_NO_NET_GAIN,
1724 preserve_last_valid_frame: false,
1725 fault_tag: None,
1726 };
1727 }
1728 let current_cost: f64 = compute_candidate_composite_cost_ms(¤t);
1729 let candidate_cost: f64 = compute_candidate_composite_cost_ms(&candidate);
1730 let gain_ms: f64 = current_cost - candidate_cost;
1731 let is_tie: bool = gain_ms.abs() <= SCORE_TIE_EPSILON_MS;
1732 let prefer_gpu_on_tie: bool = is_tie
1733 && candidate.get_candidate() == RenderBackendCandidate::GpuDirect
1734 && active != RenderBackendCandidate::GpuDirect;
1735 let gpu_wins_tie_stay: bool = is_tie && active == RenderBackendCandidate::GpuDirect;
1736 if gpu_wins_tie_stay {
1737 self.set_streak_candidate(None);
1738 self.set_streak_wins(0);
1739 self.set_last_decision_reason(REASON_TIE_PREFER_GPU_DIRECT);
1740 return AdaptiveDecision {
1741 kind: AdaptiveDecisionKind::KeepCurrent,
1742 active_candidate: active,
1743 recommended_candidate: active,
1744 applied: false,
1745 reason: REASON_TIE_PREFER_GPU_DIRECT,
1746 preserve_last_valid_frame: false,
1747 fault_tag: None,
1748 };
1749 }
1750 let cfg: AdaptiveRouterConfig = self.get_config();
1751 let beats_switch_cost: bool = prefer_gpu_on_tie || gain_ms > cfg.get_switch_cost_ms();
1752 if !beats_switch_cost {
1753 self.set_streak_candidate(None);
1754 self.set_streak_wins(0);
1755 self.set_last_decision_reason(REASON_BELOW_SWITCH_COST);
1756 return AdaptiveDecision {
1757 kind: AdaptiveDecisionKind::KeepCurrent,
1758 active_candidate: active,
1759 recommended_candidate: active,
1760 applied: false,
1761 reason: REASON_BELOW_SWITCH_COST,
1762 preserve_last_valid_frame: false,
1763 fault_tag: None,
1764 };
1765 }
1766 let prev_cand: Option<RenderBackendCandidate> = self.streak_candidate_value();
1767 let next_wins: u32 = if prev_cand == Some(candidate.get_candidate()) {
1768 self.get_streak_wins().saturating_add(1)
1769 } else {
1770 1
1771 };
1772 self.set_streak_candidate(Some(candidate.get_candidate()));
1773 self.set_streak_wins(next_wins);
1774 if next_wins < cfg.get_consecutive_wins_required().max(1) {
1775 self.set_last_decision_reason(REASON_AWAITING_CONSECUTIVE_WINS);
1776 return AdaptiveDecision {
1777 kind: AdaptiveDecisionKind::KeepCurrent,
1778 active_candidate: active,
1779 recommended_candidate: active,
1780 applied: false,
1781 reason: REASON_AWAITING_CONSECUTIVE_WINS,
1782 preserve_last_valid_frame: false,
1783 fault_tag: None,
1784 };
1785 }
1786 let dwell_blocked: bool = self.get_has_switched_once()
1787 && now_ms.saturating_sub(self.get_last_switch_ms()) < cfg.get_min_dwell_ms();
1788 let cooldown_blocked: bool = now_ms < self.get_cooldown_until_ms();
1789 if dwell_blocked || cooldown_blocked {
1790 self.set_last_decision_reason(REASON_DWELL_OR_COOLDOWN_ACTIVE);
1791 return AdaptiveDecision {
1792 kind: AdaptiveDecisionKind::KeepCurrent,
1793 active_candidate: active,
1794 recommended_candidate: candidate.get_candidate(),
1795 applied: false,
1796 reason: REASON_DWELL_OR_COOLDOWN_ACTIVE,
1797 preserve_last_valid_frame: false,
1798 fault_tag: None,
1799 };
1800 }
1801 self.set_recommended_candidate(candidate.get_candidate());
1802 match cfg.get_switch_mode() {
1803 AdaptiveSwitchMode::RecommendOnly => {
1804 let next_recs: u64 = self.get_recommendations_logged().saturating_add(1);
1805 self.set_recommendations_logged(next_recs);
1806 self.set_last_decision_reason(REASON_RECOMMEND_ONLY_SHADOW);
1807 AdaptiveDecision {
1808 kind: AdaptiveDecisionKind::RecommendSwitch,
1809 active_candidate: active,
1810 recommended_candidate: candidate.get_candidate(),
1811 applied: false,
1812 reason: REASON_RECOMMEND_ONLY_SHADOW,
1813 preserve_last_valid_frame: false,
1814 fault_tag: None,
1815 }
1816 }
1817 AdaptiveSwitchMode::AutoSwitch => {
1818 self.set_last_decision_reason(REASON_AUTO_SWITCH_HANDOFF);
1819 AdaptiveDecision {
1820 kind: AdaptiveDecisionKind::BeginHandoff,
1821 active_candidate: active,
1822 recommended_candidate: candidate.get_candidate(),
1823 applied: true,
1824 reason: REASON_AUTO_SWITCH_HANDOFF,
1825 preserve_last_valid_frame: false,
1826 fault_tag: None,
1827 }
1828 }
1829 }
1830 }
1831
1832 pub fn begin_seamless_handoff(
1846 &mut self,
1847 target: RenderBackendCandidate,
1848 frame_identity: (u32, u32, f32, u64),
1849 now_ms: u64,
1850 state: RuntimeStateSnapshot,
1851 ) -> Result<(), VisualEquivalenceFailure> {
1852 self.get_host_profile().candidate_passes_gate(target)?;
1853 let old: RenderBackendCandidate = self.get_active_candidate();
1854 self.get_mut_handoff()
1855 .begin_handoff(old, target, frame_identity, now_ms, state);
1856 Ok(())
1857 }
1858
1859 pub fn commit_handoff_at_boundary(
1874 &mut self,
1875 first_frame: HandoffFrameDescriptor,
1876 current_frame: (u32, u32, f32, u64),
1877 commit_fence_id: u64,
1878 now_ms: u64,
1879 verified_score: CandidateScore,
1880 ) -> AdaptiveDecision {
1881 let old_active: RenderBackendCandidate = self.get_active_candidate();
1882 match self.get_mut_handoff().try_commit_at_frame_boundary(
1883 first_frame,
1884 current_frame,
1885 commit_fence_id,
1886 now_ms,
1887 ) {
1888 Ok(next_candidate) => {
1889 self.set_active_candidate(next_candidate);
1890 self.set_recommended_candidate(next_candidate);
1891 self.set_last_switch_ms(now_ms);
1892 self.set_has_switched_once(true);
1893 let cooldown_end: u64 = now_ms.saturating_add(self.get_config().get_cooldown_ms());
1894 self.set_cooldown_until_ms(cooldown_end);
1895 self.set_streak_candidate(None);
1896 self.set_streak_wins(0);
1897 self.set_sustained_miss_streak(0);
1898 let key: WinnerCacheKey = self.cache_key_for(verified_score.get_scene_profile());
1899 let entry: WinnerCacheEntry = WinnerCacheEntry::new(
1900 next_candidate,
1901 now_ms,
1902 verified_score.get_p95_frame_ms(),
1903 verified_score.get_p99_frame_ms(),
1904 verified_score.get_missed_frame_ratio(),
1905 verified_score.get_input_to_present_ms(),
1906 );
1907 self.get_mut_winner_cache().record(key, entry);
1908 self.set_last_decision_reason(REASON_HANDOFF_COMMITTED);
1909 AdaptiveDecision {
1910 kind: AdaptiveDecisionKind::CommitHandoff,
1911 active_candidate: next_candidate,
1912 recommended_candidate: next_candidate,
1913 applied: true,
1914 reason: REASON_HANDOFF_COMMITTED,
1915 preserve_last_valid_frame: false,
1916 fault_tag: None,
1917 }
1918 }
1919 Err(_) => {
1920 self.set_streak_candidate(None);
1921 self.set_streak_wins(0);
1922 self.set_last_decision_reason(REASON_HANDOFF_ABORTED);
1923 AdaptiveDecision {
1924 kind: AdaptiveDecisionKind::AbortHandoff,
1925 active_candidate: old_active,
1926 recommended_candidate: old_active,
1927 applied: false,
1928 reason: REASON_HANDOFF_ABORTED,
1929 preserve_last_valid_frame: true,
1930 fault_tag: None,
1931 }
1932 }
1933 }
1934 }
1935
1936 pub fn handle_fault(
1949 &mut self,
1950 fault: FaultEventKind,
1951 window_valid: bool,
1952 now_ms: u64,
1953 ) -> AdaptiveDecision {
1954 self.get_mut_handoff().abort_for_fault();
1955 self.get_mut_tagged_fault_events().push((now_ms, fault));
1956 self.set_streak_candidate(None);
1957 self.set_streak_wins(0);
1958 let retain_frame: bool = window_valid && fault != FaultEventKind::SurfaceDestroyed;
1959 self.set_last_valid_frame_retained(retain_frame);
1960 match fault {
1961 FaultEventKind::DeviceLost => {
1962 let current: RenderBackendCandidate = self.get_active_candidate();
1963 let next: RenderBackendCandidate = self
1964 .get_host_profile()
1965 .best_available_candidate(Some(current));
1966 self.set_active_candidate(next);
1967 self.set_recommended_candidate(next);
1968 self.set_last_switch_ms(now_ms);
1969 self.set_has_switched_once(true);
1970 let cooldown_end: u64 = now_ms.saturating_add(self.get_config().get_cooldown_ms());
1971 self.set_cooldown_until_ms(cooldown_end);
1972 let next_faults: u64 = self.get_fault_failover_count().saturating_add(1);
1973 self.set_fault_failover_count(next_faults);
1974 self.set_last_decision_reason(REASON_FAULT_DEVICE_LOST);
1975 AdaptiveDecision {
1976 kind: AdaptiveDecisionKind::FaultFailover,
1977 active_candidate: next,
1978 recommended_candidate: next,
1979 applied: true,
1980 reason: REASON_FAULT_DEVICE_LOST,
1981 preserve_last_valid_frame: retain_frame,
1982 fault_tag: Some(fault),
1983 }
1984 }
1985 FaultEventKind::SurfaceDestroyed
1986 | FaultEventKind::DriverSuspended
1987 | FaultEventKind::ThermalThrottled => {
1988 let active: RenderBackendCandidate = self.get_active_candidate();
1989 let reason: &'static str = match fault {
1990 FaultEventKind::SurfaceDestroyed => REASON_FAULT_SURFACE_DESTROYED,
1991 FaultEventKind::DriverSuspended => REASON_FAULT_DRIVER_SUSPENDED,
1992 FaultEventKind::ThermalThrottled => REASON_FAULT_THERMAL_THROTTLED,
1993 FaultEventKind::DeviceLost => REASON_FAULT_DEVICE_LOST,
1994 };
1995 self.set_last_decision_reason(reason);
1996 AdaptiveDecision {
1997 kind: AdaptiveDecisionKind::FaultFailover,
1998 active_candidate: active,
1999 recommended_candidate: active,
2000 applied: false,
2001 reason,
2002 preserve_last_valid_frame: retain_frame,
2003 fault_tag: Some(fault),
2004 }
2005 }
2006 }
2007 }
2008
2009 #[must_use]
2019 pub fn snapshot(&self) -> AdaptiveRouterSnapshot {
2020 let last_fault: Option<FaultEventKind> = self
2021 .get_tagged_fault_events()
2022 .last()
2023 .map(|(_, kind): &(u64, FaultEventKind)| *kind);
2024 AdaptiveRouterSnapshot {
2025 active_candidate: self.get_active_candidate(),
2026 recommended_candidate: self.get_recommended_candidate(),
2027 switch_mode: self.get_config().get_switch_mode(),
2028 handoff_stage: self.get_handoff().get_stage(),
2029 seamless_handoff_successes: self.get_handoff().get_seamless_success_count(),
2030 handoff_aborts: self.get_handoff().get_abort_count(),
2031 fault_failovers: self.get_fault_failover_count(),
2032 probe_runs: self.get_probe_runs(),
2033 probe_skips_no_headroom: self.get_probe_skips_no_headroom(),
2034 cache_hits: self.get_cache_hits(),
2035 recommendations_logged: self.get_recommendations_logged(),
2036 has_tagged_fault: last_fault.is_some(),
2037 last_fault_kind: last_fault.unwrap_or(FaultEventKind::DeviceLost),
2038 }
2039 }
2040
2041 #[must_use]
2051 pub fn streak_candidate_value(&self) -> Option<RenderBackendCandidate> {
2052 let Self {
2053 streak_candidate, ..
2054 } = *self;
2055 streak_candidate
2056 }
2057}