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