Skip to main content

euv_core/render/telemetry/
impl.rs

1use super::*;
2
3/// Default unobservable state ensuring missing metrics never initialize as fake zero.
4impl<T> Default for ObservableMetric<T> {
5    /// Creates an explicitly unobservable metric placeholder.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - `ObservableMetric::Unobservable(UNOBSERVABLE_NOT_COLLECTED)`.
10    fn default() -> Self {
11        Self::Unobservable(UNOBSERVABLE_NOT_COLLECTED)
12    }
13}
14
15/// Truthful JSON serialization emitting explicit `status`, `value` (`null` when unobservable), and `reason`.
16impl<T> Serialize for ObservableMetric<T>
17where
18    T: Serialize,
19{
20    /// Serializes this metric without ever replacing unobservable data with fake zero.
21    ///
22    /// # Arguments
23    ///
24    /// - `&Self` - Metric reference.
25    /// - `S` - Active serializer.
26    ///
27    /// # Returns
28    ///
29    /// - `Result<S::Ok, S::Error>` - Serialized object representation.
30    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
31    where
32        S: Serializer,
33    {
34        let mut state: S::SerializeStruct = serializer.serialize_struct(METRIC_STRUCT_NAME, 3)?;
35        match self {
36            Self::Measured(val) => {
37                state.serialize_field(METRIC_FIELD_STATUS, METRIC_STATUS_MEASURED)?;
38                state.serialize_field(METRIC_FIELD_VALUE, val)?;
39                let none_reason: Option<&str> = None;
40                state.serialize_field(METRIC_FIELD_REASON, &none_reason)?;
41            }
42            Self::Proxy(val) => {
43                state.serialize_field(METRIC_FIELD_STATUS, METRIC_STATUS_PROXY)?;
44                state.serialize_field(METRIC_FIELD_VALUE, val)?;
45                let none_reason: Option<&str> = None;
46                state.serialize_field(METRIC_FIELD_REASON, &none_reason)?;
47            }
48            Self::Unobservable(reason) => {
49                state.serialize_field(METRIC_FIELD_STATUS, METRIC_STATUS_UNOBSERVABLE)?;
50                let none_value: Option<&T> = None;
51                state.serialize_field(METRIC_FIELD_VALUE, &none_value)?;
52                state.serialize_field(METRIC_FIELD_REASON, reason)?;
53            }
54        }
55        state.end()
56    }
57}
58
59/// Inspection helpers for `ObservableMetric<T>`.
60impl<T> ObservableMetric<T> {
61    /// Returns `true` when this metric holds a directly measured sample.
62    ///
63    /// # Arguments
64    ///
65    /// - `&Self` - Metric reference.
66    ///
67    /// # Returns
68    ///
69    /// - `bool` - `true` only for `Measured`.
70    #[must_use]
71    pub const fn is_measured(&self) -> bool {
72        matches!(*self, Self::Measured(_))
73    }
74
75    /// Returns `true` when this metric holds a proxy estimate.
76    ///
77    /// # Arguments
78    ///
79    /// - `&Self` - Metric reference.
80    ///
81    /// # Returns
82    ///
83    /// - `bool` - `true` only for `Proxy`.
84    #[must_use]
85    pub const fn is_proxy(&self) -> bool {
86        matches!(*self, Self::Proxy(_))
87    }
88
89    /// Returns `true` when this metric is explicitly unobservable.
90    ///
91    /// # Arguments
92    ///
93    /// - `&Self` - Metric reference.
94    ///
95    /// # Returns
96    ///
97    /// - `bool` - `true` only for `Unobservable`.
98    #[must_use]
99    pub const fn is_unobservable(&self) -> bool {
100        matches!(*self, Self::Unobservable(_))
101    }
102
103    /// Returns the canonical wire status string (`"measured"`, `"proxy"`, or `"unobservable"`).
104    ///
105    /// # Arguments
106    ///
107    /// - `&Self` - Metric reference.
108    ///
109    /// # Returns
110    ///
111    /// - `&'static str` - Canonical metric status tag.
112    #[must_use]
113    pub const fn status_str(&self) -> &'static str {
114        match *self {
115            Self::Measured(_) => METRIC_STATUS_MEASURED,
116            Self::Proxy(_) => METRIC_STATUS_PROXY,
117            Self::Unobservable(_) => METRIC_STATUS_UNOBSERVABLE,
118        }
119    }
120
121    /// Returns a reference to the underlying value when `Measured` or `Proxy`, or `None` when `Unobservable`.
122    ///
123    /// # Arguments
124    ///
125    /// - `&Self` - Metric reference.
126    ///
127    /// # Returns
128    ///
129    /// - `Option<&T>` - Inner value reference when available.
130    #[must_use]
131    pub const fn value_ref(&self) -> Option<&T> {
132        match self {
133            Self::Measured(val) | Self::Proxy(val) => Some(val),
134            Self::Unobservable(_) => None,
135        }
136    }
137
138    /// Returns a reference to the directly measured value only (`None` for `Proxy` or `Unobservable`).
139    ///
140    /// # Arguments
141    ///
142    /// - `&Self` - Metric reference.
143    ///
144    /// # Returns
145    ///
146    /// - `Option<&T>` - Directly measured value reference.
147    #[must_use]
148    pub const fn measured_ref(&self) -> Option<&T> {
149        match self {
150            Self::Measured(val) => Some(val),
151            Self::Proxy(_) | Self::Unobservable(_) => None,
152        }
153    }
154
155    /// Returns the diagnostic reason when this metric is `Unobservable`.
156    ///
157    /// # Arguments
158    ///
159    /// - `&Self` - Metric reference.
160    ///
161    /// # Returns
162    ///
163    /// - `Option<&'static str>` - Unobservability reason if unavailable.
164    #[must_use]
165    pub const fn unobservable_reason(&self) -> Option<&'static str> {
166        match *self {
167            Self::Unobservable(reason) => Some(reason),
168            Self::Measured(_) | Self::Proxy(_) => None,
169        }
170    }
171}
172
173/// Wire-label helpers for `PresentTimingSource`.
174impl PresentTimingSource {
175    /// Returns the canonical snake_case wire label for this timing source.
176    ///
177    /// # Arguments
178    ///
179    /// - `&Self` - Timing source reference.
180    ///
181    /// # Returns
182    ///
183    /// - `&'static str` - Canonical wire label.
184    #[must_use]
185    pub const fn as_str(&self) -> &'static str {
186        match *self {
187            Self::CompositorMeasured => TIMING_SOURCE_COMPOSITOR,
188            Self::SubmissionProxy => TIMING_SOURCE_PROXY,
189            Self::Unobservable => TIMING_SOURCE_UNOBSERVABLE,
190        }
191    }
192
193    /// Converts a mobile presentation timing source into the unified `PresentTimingSource`.
194    ///
195    /// # Arguments
196    ///
197    /// - `MobilePresentTimingSource` - Mobile timing provenance.
198    ///
199    /// # Returns
200    ///
201    /// - `Self` - Mapped unified `PresentTimingSource`.
202    #[must_use]
203    pub const fn from_mobile_timing_source(source: MobilePresentTimingSource) -> Self {
204        match source {
205            MobilePresentTimingSource::CompositorMeasured => Self::CompositorMeasured,
206            MobilePresentTimingSource::SubmissionProxy => Self::SubmissionProxy,
207            MobilePresentTimingSource::Unobservable => Self::Unobservable,
208        }
209    }
210}
211
212/// Wire-label and cross-module strategy conversion helpers for `UploadStrategy`.
213impl UploadStrategy {
214    /// Returns the canonical snake_case wire label for this upload strategy.
215    ///
216    /// # Arguments
217    ///
218    /// - `&Self` - Upload strategy reference.
219    ///
220    /// # Returns
221    ///
222    /// - `&'static str` - Canonical wire label.
223    #[must_use]
224    pub const fn as_str(&self) -> &'static str {
225        match *self {
226            Self::DirectGpu => UPLOAD_STRATEGY_DIRECT_GPU,
227            Self::MultiRect => UPLOAD_STRATEGY_MULTI_RECT,
228            Self::MergedBbox => UPLOAD_STRATEGY_MERGED_BBOX,
229            Self::FullFrame => UPLOAD_STRATEGY_FULL_FRAME,
230            Self::None => UPLOAD_STRATEGY_NONE,
231        }
232    }
233
234    /// Bridges a scene `DirtyRectStrategy` into the unified telemetry `UploadStrategy`.
235    ///
236    /// # Arguments
237    ///
238    /// - `DirtyRectStrategy` - Dirty-rectangle strategy computed by `DirtyRectSet`.
239    ///
240    /// # Returns
241    ///
242    /// - `Self` - Corresponding telemetry upload strategy.
243    #[must_use]
244    pub const fn from_dirty_rect_strategy(strategy: DirtyRectStrategy) -> Self {
245        match strategy {
246            DirtyRectStrategy::Empty => Self::None,
247            DirtyRectStrategy::MultiRect => Self::MultiRect,
248            DirtyRectStrategy::MergedBbox => Self::MergedBbox,
249            DirtyRectStrategy::FullFrame => Self::FullFrame,
250        }
251    }
252
253    /// Bridges a `MobileUploadStrategy` into the unified telemetry `UploadStrategy`.
254    ///
255    /// # Arguments
256    ///
257    /// - `MobileUploadStrategy` - Mobile upload strategy selected for Android/iOS.
258    ///
259    /// # Returns
260    ///
261    /// - `Self` - Corresponding unified upload strategy.
262    #[must_use]
263    pub const fn from_mobile_upload_strategy(strategy: MobileUploadStrategy) -> Self {
264        match strategy {
265            MobileUploadStrategy::DirectGpu => Self::DirectGpu,
266            MobileUploadStrategy::MultiRect => Self::MultiRect,
267            MobileUploadStrategy::MergedBbox => Self::MergedBbox,
268            MobileUploadStrategy::FullFrame => Self::FullFrame,
269            MobileUploadStrategy::None => Self::None,
270        }
271    }
272
273    /// Converts this unified `UploadStrategy` into the matching `MobileUploadStrategy`.
274    ///
275    /// # Arguments
276    ///
277    /// - `&Self` - Upload strategy reference.
278    ///
279    /// # Returns
280    ///
281    /// - `MobileUploadStrategy` - Corresponding mobile upload strategy.
282    #[must_use]
283    pub const fn to_mobile_upload_strategy(&self) -> MobileUploadStrategy {
284        match *self {
285            Self::DirectGpu => MobileUploadStrategy::DirectGpu,
286            Self::MultiRect => MobileUploadStrategy::MultiRect,
287            Self::MergedBbox => MobileUploadStrategy::MergedBbox,
288            Self::FullFrame => MobileUploadStrategy::FullFrame,
289            Self::None => MobileUploadStrategy::None,
290        }
291    }
292}
293
294/// Lossless conversion from `DirtyRectStrategy` into `UploadStrategy`.
295impl From<DirtyRectStrategy> for UploadStrategy {
296    /// Converts `strategy` into `UploadStrategy`.
297    ///
298    /// # Arguments
299    ///
300    /// - `DirtyRectStrategy` - Scene dirty-rect strategy.
301    ///
302    /// # Returns
303    ///
304    /// - `Self` - Unified `UploadStrategy`.
305    fn from(strategy: DirtyRectStrategy) -> Self {
306        Self::from_dirty_rect_strategy(strategy)
307    }
308}
309
310/// Lossless conversion from `MobileUploadStrategy` into `UploadStrategy`.
311impl From<MobileUploadStrategy> for UploadStrategy {
312    /// Converts `strategy` into `UploadStrategy`.
313    ///
314    /// # Arguments
315    ///
316    /// - `MobileUploadStrategy` - Mobile upload strategy.
317    ///
318    /// # Returns
319    ///
320    /// - `Self` - Unified `UploadStrategy`.
321    fn from(strategy: MobileUploadStrategy) -> Self {
322        Self::from_mobile_upload_strategy(strategy)
323    }
324}
325
326/// Conversion and query helpers for `SurfacePresentOutcome`.
327impl SurfacePresentOutcome {
328    /// Returns the canonical snake_case wire label for this surface presentation outcome.
329    ///
330    /// # Arguments
331    ///
332    /// - `&Self` - Outcome reference.
333    ///
334    /// # Returns
335    ///
336    /// - `&'static str` - Canonical wire label.
337    #[must_use]
338    pub const fn as_str(&self) -> &'static str {
339        match *self {
340            Self::Submitted => SURFACE_OUTCOME_SUBMITTED,
341            Self::SkippedUnchanged => SURFACE_OUTCOME_SKIPPED,
342            Self::Failed => SURFACE_OUTCOME_FAILED,
343        }
344    }
345
346    /// Converts a runtime `PresentOutcome` into a truthful `SurfacePresentOutcome`.
347    ///
348    /// # Arguments
349    ///
350    /// - `PresentOutcome` - Detailed runtime presentation outcome.
351    ///
352    /// # Returns
353    ///
354    /// - `Self` - Mapped `SurfacePresentOutcome`.
355    #[must_use]
356    pub const fn from_present_outcome(outcome: PresentOutcome) -> Self {
357        match outcome {
358            PresentOutcome::Presented => Self::Submitted,
359            PresentOutcome::SkippedNoDamage | PresentOutcome::WaitInFlight => {
360                Self::SkippedUnchanged
361            }
362            PresentOutcome::PresentFailedRetry => Self::Failed,
363        }
364    }
365
366    /// Converts a legacy `FrameSubmitOutcome` into a truthful `SurfacePresentOutcome`.
367    ///
368    /// # Arguments
369    ///
370    /// - `FrameSubmitOutcome` - Frame submission outcome.
371    ///
372    /// # Returns
373    ///
374    /// - `Self` - Mapped `SurfacePresentOutcome`.
375    #[must_use]
376    pub const fn from_submit_outcome(outcome: FrameSubmitOutcome) -> Self {
377        match outcome {
378            FrameSubmitOutcome::Submitted => Self::Submitted,
379            FrameSubmitOutcome::SkippedNoDamage => Self::SkippedUnchanged,
380            FrameSubmitOutcome::SubmitFailed => Self::Failed,
381        }
382    }
383
384    /// Maps this `SurfacePresentOutcome` back to `PresentOutcome`.
385    ///
386    /// # Arguments
387    ///
388    /// - `&Self` - Outcome reference.
389    ///
390    /// # Returns
391    ///
392    /// - `PresentOutcome` - Corresponding runtime presentation outcome.
393    #[must_use]
394    pub const fn to_present_outcome(&self) -> PresentOutcome {
395        match *self {
396            Self::Submitted => PresentOutcome::Presented,
397            Self::SkippedUnchanged => PresentOutcome::SkippedNoDamage,
398            Self::Failed => PresentOutcome::PresentFailedRetry,
399        }
400    }
401}
402
403/// Lossless conversion from `PresentOutcome` into `SurfacePresentOutcome`.
404impl From<PresentOutcome> for SurfacePresentOutcome {
405    /// Converts `outcome` into `SurfacePresentOutcome`.
406    ///
407    /// # Arguments
408    ///
409    /// - `PresentOutcome` - Runtime present outcome.
410    ///
411    /// # Returns
412    ///
413    /// - `Self` - Mapped surface outcome.
414    fn from(outcome: PresentOutcome) -> Self {
415        Self::from_present_outcome(outcome)
416    }
417}
418
419/// Lossless conversion from `FrameSubmitOutcome` into `SurfacePresentOutcome`.
420impl From<FrameSubmitOutcome> for SurfacePresentOutcome {
421    /// Converts `outcome` into `SurfacePresentOutcome`.
422    ///
423    /// # Arguments
424    ///
425    /// - `FrameSubmitOutcome` - Frame submission outcome.
426    ///
427    /// # Returns
428    ///
429    /// - `Self` - Mapped surface outcome.
430    fn from(outcome: FrameSubmitOutcome) -> Self {
431        Self::from_submit_outcome(outcome)
432    }
433}
434
435/// Default truthful initialization where all uncollected timing metrics start explicitly `Unobservable`.
436impl Default for AdaptiveFrameMetrics {
437    /// Creates an honest default `AdaptiveFrameMetrics` with zero fake zeros on uncollected metrics.
438    ///
439    /// # Returns
440    ///
441    /// - `Self` - Default truthful metrics snapshot.
442    fn default() -> Self {
443        Self {
444            display_mode_hz: ObservableMetric::Unobservable(UNOBSERVABLE_NOT_COLLECTED),
445            frame_callback_count: 0,
446            frame_callback_interval_ms: ObservableMetric::Unobservable(UNOBSERVABLE_NOT_COLLECTED),
447            actual_presented_new_frames: ObservableMetric::Unobservable(
448                UNOBSERVABLE_NO_COMPOSITOR_TIMING,
449            ),
450            actual_present_interval_p50_ms: ObservableMetric::Unobservable(
451                UNOBSERVABLE_NO_COMPOSITOR_TIMING,
452            ),
453            actual_present_interval_p95_ms: ObservableMetric::Unobservable(
454                UNOBSERVABLE_NO_COMPOSITOR_TIMING,
455            ),
456            actual_present_interval_p99_ms: ObservableMetric::Unobservable(
457                UNOBSERVABLE_NO_COMPOSITOR_TIMING,
458            ),
459            present_timing_source: PresentTimingSource::Unobservable,
460            present_outcome: SurfacePresentOutcome::SkippedUnchanged,
461            present_submit_failures: 0,
462            present_failures: 0,
463            cpu_raster_ms: ObservableMetric::Unobservable(UNOBSERVABLE_NO_CPU_RASTER_TIMING),
464            cpu_mirror_active: false,
465            texture_upload_bytes: 0,
466            upload_strategy: UploadStrategy::None,
467            gpu_exec_ms: ObservableMetric::Unobservable(UNOBSERVABLE_NO_GPU_TIMING),
468            gpu_wait_ms: ObservableMetric::Unobservable(UNOBSERVABLE_NO_GPU_TIMING),
469            input_to_present_latency_ms: ObservableMetric::Unobservable(
470                UNOBSERVABLE_NO_INPUT_CORRELATION,
471            ),
472            target_frame_interval_ms: TARGET_FRAME_INTERVAL_60HZ_MS,
473            os_refresh_throttled: ObservableMetric::Unobservable(
474                UNOBSERVABLE_NO_OS_THROTTLE_SIGNAL,
475            ),
476            adaptive_router: AdaptiveRouterSnapshot::default(),
477        }
478    }
479}
480
481/// Constructors, target-interval calculation, and JSON serialization helpers for `AdaptiveFrameMetrics`.
482impl AdaptiveFrameMetrics {
483    /// Computes the exact target frame interval in milliseconds for `display_hz` (falling back to 60 Hz when non-positive).
484    ///
485    /// # Arguments
486    ///
487    /// - `f64` - Display refresh rate in Hertz (e.g., `144.0` yields `~6.94 ms`).
488    ///
489    /// # Returns
490    ///
491    /// - `f64` - Target frame interval in milliseconds.
492    #[must_use]
493    pub fn target_frame_interval_ms_for_hz(display_hz: f64) -> f64 {
494        if !display_hz.is_finite() || display_hz <= 0.0 {
495            return TARGET_FRAME_INTERVAL_60HZ_MS;
496        }
497        1_000.0 / display_hz
498    }
499
500    /// Creates a truthful metrics snapshot seeded with `display_hz`, `timing_source`, and `router_snapshot`.
501    ///
502    /// # Arguments
503    ///
504    /// - `ObservableMetric<f64>` - Observed display refresh rate in Hertz.
505    /// - `PresentTimingSource` - Provenance of presentation timing.
506    /// - `AdaptiveRouterSnapshot` - Current adaptive router state snapshot.
507    ///
508    /// # Returns
509    ///
510    /// - `Self` - Initialized truthful metrics snapshot.
511    #[must_use]
512    pub fn with_context(
513        display_mode_hz: ObservableMetric<f64>,
514        present_timing_source: PresentTimingSource,
515        adaptive_router: AdaptiveRouterSnapshot,
516    ) -> Self {
517        let target_ms: f64 = display_mode_hz.value_ref().copied().map_or(
518            TARGET_FRAME_INTERVAL_60HZ_MS,
519            Self::target_frame_interval_ms_for_hz,
520        );
521        let mut metrics: Self = Self::default();
522        metrics.set_display_mode_hz(display_mode_hz);
523        metrics.set_present_timing_source(present_timing_source);
524        metrics.set_target_frame_interval_ms(target_ms);
525        metrics.set_adaptive_router(adaptive_router);
526        metrics
527    }
528
529    /// Serializes this snapshot into pretty-printed JSON preserving `null` + `"unobservable"` on unavailable metrics.
530    ///
531    /// # Arguments
532    ///
533    /// - `&Self` - Metrics snapshot reference.
534    ///
535    /// # Returns
536    ///
537    /// - `String` - Pretty-printed JSON string.
538    #[must_use]
539    pub fn to_json_pretty(&self) -> String {
540        to_string_pretty(self).unwrap_or_default()
541    }
542
543    /// Ingests shared mobile presentation telemetry (`AndroidPresentTelemetry::get_base` / `IosPresentTelemetry::get_base`) truthfully into this unified snapshot.
544    ///
545    /// # Arguments
546    ///
547    /// - `&Self` - Mutable unified metrics snapshot.
548    /// - `&MobilePresentTelemetry` - Mobile presentation telemetry record.
549    pub fn apply_mobile_telemetry(&mut self, telemetry: &MobilePresentTelemetry) {
550        let hz: f64 = f64::from(telemetry.get_display_mode_hz());
551        if hz.is_finite() && hz > 0.0 {
552            self.set_display_mode_hz(ObservableMetric::Measured(hz));
553            self.set_target_frame_interval_ms(Self::target_frame_interval_ms_for_hz(hz));
554        }
555        self.set_frame_callback_count(telemetry.get_frame_callback_count());
556        if let Some(cb_ms) = telemetry.get_last_callback_interval_ms() {
557            self.set_frame_callback_interval_ms(ObservableMetric::Measured(cb_ms));
558        }
559        let timing_src: PresentTimingSource =
560            PresentTimingSource::from_mobile_timing_source(telemetry.get_timing_source());
561        self.set_present_timing_source(timing_src);
562        let presented: u64 = telemetry.get_actual_presented_frames();
563        if telemetry.get_is_simulator() {
564            let reason: &'static str = telemetry
565                .get_unobservable_reason()
566                .unwrap_or(UNOBSERVABLE_SIMULATOR_NO_COMPOSITOR);
567            self.set_actual_presented_new_frames(ObservableMetric::Proxy(presented));
568            self.set_actual_present_interval_p50_ms(ObservableMetric::Unobservable(reason));
569            self.set_actual_present_interval_p95_ms(ObservableMetric::Unobservable(reason));
570            self.set_actual_present_interval_p99_ms(ObservableMetric::Unobservable(reason));
571        } else if timing_src == PresentTimingSource::CompositorMeasured {
572            self.set_actual_presented_new_frames(ObservableMetric::Measured(presented));
573        } else if timing_src == PresentTimingSource::SubmissionProxy {
574            self.set_actual_presented_new_frames(ObservableMetric::Proxy(presented));
575        } else {
576            let reason: &'static str = telemetry
577                .get_unobservable_reason()
578                .unwrap_or(UNOBSERVABLE_NO_COMPOSITOR_TIMING);
579            self.set_actual_presented_new_frames(ObservableMetric::Unobservable(reason));
580        }
581        self.set_present_submit_failures(telemetry.get_submit_failures());
582        self.set_present_failures(telemetry.get_present_failures());
583        self.set_cpu_mirror_active(telemetry.get_cpu_mirror_active());
584        self.set_texture_upload_bytes(telemetry.get_upload_bytes_last_frame());
585        self.set_upload_strategy(UploadStrategy::from_mobile_upload_strategy(
586            telemetry.get_upload_strategy(),
587        ));
588        let outcome: SurfacePresentOutcome =
589            if telemetry.get_submit_failures() > 0 || telemetry.get_present_failures() > 0 {
590                SurfacePresentOutcome::Failed
591            } else if presented > 0 {
592                SurfacePresentOutcome::Submitted
593            } else {
594                SurfacePresentOutcome::SkippedUnchanged
595            };
596        self.set_present_outcome(outcome);
597    }
598
599    /// Ingests Android Choreographer & EGL presentation telemetry truthfully into this unified snapshot.
600    ///
601    /// # Arguments
602    ///
603    /// - `&Self` - Mutable unified metrics snapshot.
604    /// - `&AndroidPresentTelemetry` - Android presentation telemetry record.
605    #[cfg(target_os = "android")]
606    pub fn apply_android_telemetry(&mut self, telemetry: &AndroidPresentTelemetry) {
607        let base: MobilePresentTelemetry = telemetry.get_base();
608        self.apply_mobile_telemetry(&base);
609        let swap_us: u64 = telemetry.get_egl_swap_duration_us();
610        if swap_us > 0 {
611            self.set_gpu_exec_ms(ObservableMetric::Proxy((swap_us as f64) / 1_000.0));
612        }
613    }
614
615    /// Ingests iOS/iPadOS `CADisplayLink` & `MTLDrawable.presentedTime` telemetry truthfully into this unified snapshot.
616    ///
617    /// # Arguments
618    ///
619    /// - `&Self` - Mutable unified metrics snapshot.
620    /// - `&IosPresentTelemetry` - iOS presentation telemetry record.
621    #[cfg(target_os = "ios")]
622    pub fn apply_ios_telemetry(&mut self, telemetry: &IosPresentTelemetry) {
623        let base: MobilePresentTelemetry = telemetry.get_base();
624        self.apply_mobile_telemetry(&base);
625        let gpu_us: u64 = telemetry.get_metal_gpu_exec_us();
626        if !telemetry.get_is_simulator() && gpu_us > 0 {
627            self.set_gpu_exec_ms(ObservableMetric::Measured((gpu_us as f64) / 1_000.0));
628        } else if telemetry.get_is_simulator() {
629            self.set_gpu_exec_ms(ObservableMetric::Unobservable(
630                UNOBSERVABLE_SIMULATOR_NO_COMPOSITOR,
631            ));
632        }
633    }
634
635    /// Ingests Linux Wayland `wl_shm`, X11 multi-rect, or Vulkan direct-GPU telemetry truthfully into this unified snapshot.
636    ///
637    /// # Arguments
638    ///
639    /// - `&Self` - Mutable unified metrics snapshot.
640    /// - `&LinuxPresentTelemetry` - Linux presentation telemetry record.
641    #[cfg(target_os = "linux")]
642    pub fn apply_linux_telemetry(&mut self, telemetry: &LinuxPresentTelemetry) {
643        let outcome: SurfacePresentOutcome = match telemetry.get_outcome() {
644            LinuxPresentOutcome::Submitted => SurfacePresentOutcome::Submitted,
645            LinuxPresentOutcome::SkippedUnchanged => SurfacePresentOutcome::SkippedUnchanged,
646            LinuxPresentOutcome::Failed => SurfacePresentOutcome::Failed,
647        };
648        let strategy: UploadStrategy = match telemetry.get_mode() {
649            LinuxPresentationMode::GpuDirect => UploadStrategy::DirectGpu,
650            LinuxPresentationMode::WaylandShmSoftware | LinuxPresentationMode::X11Software => {
651                if telemetry.get_dirty_rect_count() > 1 {
652                    UploadStrategy::MultiRect
653                } else if telemetry.get_upload_bytes() > 0 {
654                    UploadStrategy::FullFrame
655                } else {
656                    UploadStrategy::None
657                }
658            }
659        };
660        self.set_present_outcome(outcome);
661        self.set_cpu_mirror_active(telemetry.get_cpu_mirror_active());
662        self.set_texture_upload_bytes(telemetry.get_upload_bytes());
663        self.set_upload_strategy(strategy);
664        self.set_present_failures(telemetry.get_failed_frames());
665        self.set_present_timing_source(PresentTimingSource::SubmissionProxy);
666        self.set_actual_presented_new_frames(ObservableMetric::Proxy(
667            telemetry.get_submitted_frames(),
668        ));
669    }
670
671    /// Ingests macOS direct Metal drawable or `CGImage` software fallback telemetry truthfully into this unified snapshot.
672    ///
673    /// # Arguments
674    ///
675    /// - `&Self` - Mutable unified metrics snapshot.
676    /// - `&MacOsPresentTelemetry` - macOS presentation telemetry record.
677    #[cfg(target_os = "macos")]
678    pub fn apply_macos_telemetry(&mut self, telemetry: &MacOsPresentTelemetry) {
679        let timing_src: PresentTimingSource = match telemetry.get_timing_source() {
680            MacOsPresentTimingSource::CompositorMeasured => PresentTimingSource::CompositorMeasured,
681            MacOsPresentTimingSource::SubmissionProxy => PresentTimingSource::SubmissionProxy,
682            MacOsPresentTimingSource::Unobservable => PresentTimingSource::Unobservable,
683        };
684        let strategy: UploadStrategy = match telemetry.get_path() {
685            MacOsPresentationPath::GpuDirect => UploadStrategy::DirectGpu,
686            MacOsPresentationPath::SoftwareCgImage => {
687                if telemetry.get_upload_bytes() > 0 {
688                    UploadStrategy::FullFrame
689                } else {
690                    UploadStrategy::None
691                }
692            }
693        };
694        let total_frames: u64 = telemetry
695            .get_direct_gpu_frames()
696            .saturating_add(telemetry.get_software_fallback_frames());
697        self.set_cpu_mirror_active(telemetry.get_cpu_mirror_active());
698        self.set_upload_strategy(strategy);
699        self.set_texture_upload_bytes(telemetry.get_upload_bytes());
700        self.set_present_timing_source(timing_src);
701        self.set_present_failures(telemetry.get_failed_frames());
702        if timing_src == PresentTimingSource::CompositorMeasured {
703            self.set_actual_presented_new_frames(ObservableMetric::Measured(total_frames));
704        } else if timing_src == PresentTimingSource::SubmissionProxy {
705            self.set_actual_presented_new_frames(ObservableMetric::Proxy(total_frames));
706        }
707        let gpu_ns: u64 = telemetry.get_gpu_exec_ns();
708        if gpu_ns > 0 {
709            self.set_gpu_exec_ms(ObservableMetric::Measured((gpu_ns as f64) / 1_000_000.0));
710        }
711        if telemetry.get_failed_frames() > 0 {
712            self.set_present_outcome(SurfacePresentOutcome::Failed);
713        } else if total_frames > 0 {
714            self.set_present_outcome(SurfacePresentOutcome::Submitted);
715        }
716    }
717
718    /// Ingests Windows DXGI direct swapchain or GDI software fallback telemetry truthfully into this unified snapshot.
719    ///
720    /// # Arguments
721    ///
722    /// - `&Self` - Mutable unified metrics snapshot.
723    /// - `&WindowsPresentTelemetry` - Windows presentation telemetry record.
724    #[cfg(target_os = "windows")]
725    pub fn apply_windows_telemetry(&mut self, telemetry: &WindowsPresentTelemetry) {
726        let timing_src: PresentTimingSource = match telemetry.get_timing_source() {
727            WindowsPresentTimingSource::DxgiFrameStatistics => {
728                PresentTimingSource::CompositorMeasured
729            }
730            WindowsPresentTimingSource::SubmissionProxy => PresentTimingSource::SubmissionProxy,
731            WindowsPresentTimingSource::Unobservable => PresentTimingSource::Unobservable,
732        };
733        let strategy: UploadStrategy = match telemetry.get_path() {
734            WindowsPresentationPath::GpuDirect => UploadStrategy::DirectGpu,
735            WindowsPresentationPath::SoftwareGdi => {
736                if telemetry.get_dirty_rect_count() > 1 {
737                    UploadStrategy::MultiRect
738                } else if telemetry.get_upload_bytes() > 0 {
739                    UploadStrategy::FullFrame
740                } else {
741                    UploadStrategy::None
742                }
743            }
744        };
745        let total_frames: u64 = telemetry
746            .get_direct_gpu_frames()
747            .saturating_add(telemetry.get_software_fallback_frames());
748        self.set_cpu_mirror_active(telemetry.get_cpu_mirror_active());
749        self.set_upload_strategy(strategy);
750        self.set_texture_upload_bytes(telemetry.get_upload_bytes());
751        self.set_present_timing_source(timing_src);
752        self.set_present_failures(telemetry.get_failed_frames());
753        if timing_src == PresentTimingSource::CompositorMeasured {
754            self.set_actual_presented_new_frames(ObservableMetric::Measured(total_frames));
755        } else if timing_src == PresentTimingSource::SubmissionProxy {
756            self.set_actual_presented_new_frames(ObservableMetric::Proxy(total_frames));
757        }
758        if telemetry.get_failed_frames() > 0 {
759            self.set_present_outcome(SurfacePresentOutcome::Failed);
760        } else if total_frames > 0 {
761            self.set_present_outcome(SurfacePresentOutcome::Submitted);
762        }
763    }
764
765    /// Ingests browser WebGL2/WebGPU/Canvas2D telemetry truthfully into this unified snapshot (rAF always remains `SubmissionProxy`).
766    ///
767    /// # Arguments
768    ///
769    /// - `&Self` - Mutable unified metrics snapshot.
770    /// - `&WebPresentTelemetry` - Browser presentation telemetry record.
771    #[cfg(target_arch = "wasm32")]
772    pub fn apply_web_telemetry(&mut self, telemetry: &WebPresentTelemetry) {
773        let timing_src: PresentTimingSource = match telemetry.get_present_timing_source() {
774            WebPresentTimingSource::SubmissionProxy => PresentTimingSource::SubmissionProxy,
775            WebPresentTimingSource::Unobservable => PresentTimingSource::Unobservable,
776        };
777        let strategy: UploadStrategy = match telemetry.get_mode() {
778            WebPresentationMode::GpuDirect => UploadStrategy::DirectGpu,
779            WebPresentationMode::GpuUpload => UploadStrategy::MultiRect,
780            WebPresentationMode::Software => UploadStrategy::FullFrame,
781        };
782        self.set_cpu_mirror_active(telemetry.get_cpu_mirror_active());
783        self.set_upload_strategy(strategy);
784        self.set_texture_upload_bytes(telemetry.get_upload_bytes());
785        self.set_present_timing_source(timing_src);
786        self.set_frame_callback_count(telemetry.get_raf_callback_count());
787        self.set_actual_presented_new_frames(ObservableMetric::Proxy(
788            telemetry.get_raf_callback_count(),
789        ));
790        self.set_present_outcome(SurfacePresentOutcome::Submitted);
791    }
792
793    /// Ingests non-GPU, non-Hz TUI/CLI telemetry truthfully into this unified snapshot without applying screen refresh Hz.
794    ///
795    /// # Arguments
796    ///
797    /// - `&Self` - Mutable unified metrics snapshot.
798    /// - `&TerminalNonGpuTelemetry` - Terminal cell-diff and batched-write telemetry record.
799    pub fn apply_terminal_telemetry(&mut self, telemetry: &TerminalNonGpuTelemetry) {
800        self.set_display_mode_hz(ObservableMetric::Unobservable(UNOBSERVABLE_TERMINAL_NON_HZ));
801        self.set_present_timing_source(PresentTimingSource::Unobservable);
802        self.set_cpu_mirror_active(false);
803        self.set_upload_strategy(UploadStrategy::None);
804        self.set_texture_upload_bytes(0);
805        self.set_gpu_exec_ms(ObservableMetric::Unobservable(UNOBSERVABLE_TERMINAL_NON_HZ));
806        self.set_gpu_wait_ms(ObservableMetric::Unobservable(UNOBSERVABLE_TERMINAL_NON_HZ));
807        if let Some(i2o_ms) = telemetry.input_to_output_ms() {
808            self.set_input_to_present_latency_ms(ObservableMetric::Measured(i2o_ms));
809        }
810        let outcome: SurfacePresentOutcome = if telemetry.get_unchanged_frame_skipped() {
811            SurfacePresentOutcome::SkippedUnchanged
812        } else {
813            SurfacePresentOutcome::Submitted
814        };
815        self.set_present_outcome(outcome);
816    }
817}