Skip to main content

alpha2_render/
diagnostics.rs

1//! Stable, host-readable renderer diagnostics.
2
3use std::collections::VecDeque;
4use std::sync::{Arc, Mutex};
5use std::time::Duration;
6
7use alpha2_gpu::{Capabilities, CapabilityTier};
8
9use crate::{
10    PipelineCacheStats, ReadbackBufferPoolStats, TexturePoolStats, UniformBufferPoolStats,
11    UploadTexturePoolStats,
12};
13
14/// Source of one pass duration.
15#[derive(Copy, Clone, Debug, Eq, PartialEq)]
16pub enum TimingSource {
17    /// Hardware timestamp query resolved by wgpu.
18    GpuTimestamp,
19    /// Wall-clock time spent encoding one pass on the CPU.
20    CpuEncoding,
21}
22
23/// Most recent timing for one named render pass.
24///
25/// Pass timing is opt-in; see [`crate::Renderer::set_pass_timing_enabled`].
26#[derive(Copy, Clone, Debug, Eq, PartialEq)]
27pub struct PassTiming {
28    /// Stable pass label.
29    pub label: &'static str,
30    /// Duration in nanoseconds.
31    pub nanoseconds: u64,
32    /// Measurement source.
33    pub source: TimingSource,
34}
35
36/// Adapter metadata recorded beside reproducible benchmark samples.
37#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct AdapterDiagnostics {
39    /// Platform adapter name.
40    pub name: String,
41    /// Selected graphics backend.
42    pub backend: String,
43    /// Driver name.
44    pub driver: String,
45    /// Driver version/details.
46    pub driver_info: String,
47    /// Capability tier driving deterministic degradation.
48    pub tier: CapabilityTier,
49    /// Whether hardware timestamps are active.
50    pub timestamp_queries: bool,
51    /// The DX12 shader compiler; empty on other backends and in browsers.
52    pub shader_compiler: String,
53}
54
55/// Snapshot of render performance, cache, memory, and scheduling behavior.
56#[derive(Clone, Debug, PartialEq)]
57pub struct RenderDiagnostics {
58    /// Reproducibility metadata.
59    pub adapter: AdapterDiagnostics,
60    /// Latest bounded pass timing history. Empty unless pass timing is enabled.
61    pub passes: Vec<PassTiming>,
62    /// Intermediate texture allocation/reuse counters.
63    pub textures: TexturePoolStats,
64    /// Source-upload texture allocation/reuse and live-byte counters.
65    pub upload_textures: UploadTexturePoolStats,
66    /// Mapped readback-buffer allocation/reuse and live-byte counters.
67    pub readback_buffers: ReadbackBufferPoolStats,
68    /// Submission uniform-arena allocation/reuse and live-byte counters.
69    pub uniform_buffers: UniformBufferPoolStats,
70    /// Runtime and built-in pipeline cache counts.
71    pub pipelines: PipelineCacheStats,
72    /// Bind groups created and reused.
73    pub bind_groups: crate::BindGroupStats,
74    /// Pipeline creations and their CPU time; a first draw that compiles shaders stalls its frame.
75    pub pipeline_creation: PipelineCreationStats,
76    /// Kept graph results: budget, occupancy, hits, misses, invalidations.
77    pub result_cache: crate::ResultCacheStats,
78    /// Frames presented by the caller.
79    pub presented_frames: u64,
80    /// Requests that could not render a new frame.
81    pub dropped_frames: u64,
82    /// Presentations that held a previous frame.
83    pub repeated_frames: u64,
84    /// Accumulated host decoder wait time.
85    pub decoder_wait: Duration,
86    /// Active filter sample budget, possibly below the request (see [`Self::degradations`]).
87    pub max_filter_samples: u32,
88    /// Fallbacks applied to the caller's request, such as a reduced filter sample budget.
89    pub degradations: Vec<crate::CapabilityDiagnostic>,
90    /// Non-source nodes encoded by completed graph executions.
91    pub graph_nodes: u64,
92    /// Actual render passes encoded by completed graph executions.
93    pub graph_passes: u64,
94    /// Queue submissions issued by completed graph executions.
95    pub graph_submissions: u64,
96    /// Queue submissions issued by source presentation/conversion.
97    pub source_submissions: u64,
98    /// Source passes converting a decoded picture into the working space.
99    pub source_conversions: u64,
100    /// Decoded 4:2:0 pictures copied plane for plane into NV12 targets.
101    pub yuv_repacks: u64,
102    /// Queue submissions issued by output packing and readback.
103    pub readback_submissions: u64,
104    /// Queue submissions combining graph execution with output readback.
105    pub frame_submissions: u64,
106    /// Actual render passes across graph, source, and readback work.
107    pub render_passes: u64,
108    /// GPU copy commands encoded for output readback.
109    pub copy_operations: u64,
110    /// Logical texel bytes copied by output readback commands.
111    pub copy_bytes: u64,
112}
113
114/// Pipelines this renderer created and the time it took.
115#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
116pub struct PipelineCreationStats {
117    /// Pipelines created.
118    pub created: u64,
119    /// Microseconds their creation took in all.
120    pub create_micros_total: u64,
121    /// Microseconds the slowest one took.
122    pub create_micros_max: u64,
123}
124
125/// How frames since the last [`crate::Renderer::take_gpu_submission_stats`] were split into
126/// submissions.
127#[derive(Copy, Clone, Debug, Default, PartialEq)]
128pub struct GpuSubmissionStats {
129    /// Frames rendered.
130    pub frames: u64,
131    /// Frames submitted in more than one submission.
132    pub split_frames: u64,
133    /// The most submissions one frame took.
134    pub max_per_frame: u32,
135    /// Longest predicted GPU time of one submission, in milliseconds, among planned frames.
136    pub max_predicted_ms: Option<f64>,
137    /// Submissions predicted over the submission budget: passes that could not be cut finer, and
138    /// frames spread past the per-frame submission cap.
139    pub over_budget: u64,
140    /// The submission budget the frames were planned under, in milliseconds.
141    pub budget_ms: Option<f64>,
142}
143
144/// One pipeline creation for tracing.
145#[derive(Clone, Debug, PartialEq)]
146pub struct PipelineCreation {
147    /// An effect's ID or the composite program's label.
148    pub label: String,
149    /// When its creation began.
150    pub started: web_time::Instant,
151    /// When it ended.
152    pub finished: web_time::Instant,
153}
154
155/// Reproducible metadata envelope written beside benchmark measurements.
156#[derive(Clone, Debug, PartialEq)]
157pub struct BenchmarkMetadata {
158    /// Caller-defined project or fixture identity.
159    pub project: String,
160    /// Version of the alpha2 render crate.
161    pub alpha2_version: &'static str,
162    /// Adapter and driver identity.
163    pub adapter: AdapterDiagnostics,
164    /// Output width and height.
165    pub dimensions: (u32, u32),
166    /// Output scale used by the caller.
167    pub resolution_scale: f32,
168    /// Filter sample budget.
169    pub max_filter_samples: u32,
170    /// Texture byte budget.
171    pub texture_budget_bytes: u64,
172}
173
174/// Entries retained while pass timing is enabled.
175const PASS_HISTORY: usize = 256;
176
177/// Pipeline creations kept until taken; oldest are dropped first.
178const PIPELINE_HISTORY: usize = 256;
179
180#[derive(Debug, Default)]
181pub(crate) struct DiagnosticsState {
182    passes: VecDeque<PassTiming>,
183    /// Incremented when timing turns off, so late GPU timestamp reads are dropped.
184    timing_epoch: u64,
185    presented_frames: u64,
186    dropped_frames: u64,
187    repeated_frames: u64,
188    decoder_wait: Duration,
189    graph_nodes: u64,
190    graph_passes: u64,
191    graph_submissions: u64,
192    source_submissions: u64,
193    source_conversions: u64,
194    yuv_repacks: u64,
195    readback_submissions: u64,
196    frame_submissions: u64,
197    render_passes: u64,
198    copy_operations: u64,
199    copy_bytes: u64,
200    pipeline_creation: PipelineCreationStats,
201    pipeline_creations: VecDeque<PipelineCreation>,
202    gpu_submissions: GpuSubmissionStats,
203}
204
205pub(crate) type SharedDiagnostics = Arc<Mutex<DiagnosticsState>>;
206
207#[derive(Copy, Clone)]
208pub(crate) struct ResourceDiagnostics {
209    pub(crate) textures: TexturePoolStats,
210    pub(crate) upload_textures: UploadTexturePoolStats,
211    pub(crate) readback_buffers: ReadbackBufferPoolStats,
212    pub(crate) uniform_buffers: UniformBufferPoolStats,
213    pub(crate) pipelines: PipelineCacheStats,
214    pub(crate) bind_groups: crate::BindGroupStats,
215    pub(crate) result_cache: crate::ResultCacheStats,
216}
217
218/// See [`crate::Renderer::pass_timing_epoch`].
219pub(crate) fn timing_epoch(state: &SharedDiagnostics) -> u64 {
220    state
221        .lock()
222        .unwrap_or_else(std::sync::PoisonError::into_inner)
223        .timing_epoch
224}
225
226/// Records one pass duration unless timing was turned off since `epoch`.
227pub(crate) fn record_pass(
228    state: &SharedDiagnostics,
229    epoch: u64,
230    label: &'static str,
231    duration: Duration,
232    source: TimingSource,
233) {
234    let mut state = state
235        .lock()
236        .unwrap_or_else(std::sync::PoisonError::into_inner);
237    if state.timing_epoch != epoch {
238        return;
239    }
240    if state.passes.len() == PASS_HISTORY {
241        state.passes.pop_front();
242    }
243    state.passes.push_back(PassTiming {
244        label,
245        nanoseconds: u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX),
246        source,
247    });
248}
249
250pub(crate) fn record_graph_work(
251    state: &SharedDiagnostics,
252    nodes: u64,
253    render_passes: u64,
254    standalone_submission: bool,
255) {
256    let mut state = state
257        .lock()
258        .unwrap_or_else(std::sync::PoisonError::into_inner);
259    state.graph_nodes = state.graph_nodes.saturating_add(nodes);
260    state.graph_passes = state.graph_passes.saturating_add(render_passes);
261    if standalone_submission {
262        state.graph_submissions = state.graph_submissions.saturating_add(1);
263    }
264    state.render_passes = state.render_passes.saturating_add(render_passes);
265}
266
267pub(crate) fn record_source_work(
268    state: &SharedDiagnostics,
269    render_passes: u64,
270    standalone_submission: bool,
271    conversion: bool,
272) {
273    let mut state = state
274        .lock()
275        .unwrap_or_else(std::sync::PoisonError::into_inner);
276    state.source_conversions = state
277        .source_conversions
278        .saturating_add(u64::from(conversion));
279    if standalone_submission {
280        state.source_submissions = state.source_submissions.saturating_add(1);
281    }
282    state.render_passes = state.render_passes.saturating_add(render_passes);
283}
284
285pub(crate) fn record_readback_work(
286    state: &SharedDiagnostics,
287    render_passes: u64,
288    copy_operations: u64,
289    copy_bytes: u64,
290    standalone_submission: bool,
291) {
292    let mut state = state
293        .lock()
294        .unwrap_or_else(std::sync::PoisonError::into_inner);
295    if standalone_submission {
296        state.readback_submissions = state.readback_submissions.saturating_add(1);
297    }
298    state.render_passes = state.render_passes.saturating_add(render_passes);
299    state.copy_operations = state.copy_operations.saturating_add(copy_operations);
300    state.copy_bytes = state.copy_bytes.saturating_add(copy_bytes);
301}
302
303pub(crate) fn record_frame_submission(state: &SharedDiagnostics) {
304    let mut state = state
305        .lock()
306        .unwrap_or_else(std::sync::PoisonError::into_inner);
307    state.frame_submissions = state.frame_submissions.saturating_add(1);
308}
309
310/// Drops pass history and ends the timing run.
311pub(crate) fn end_timing_run(state: &SharedDiagnostics) {
312    let mut state = state
313        .lock()
314        .unwrap_or_else(std::sync::PoisonError::into_inner);
315    state.passes.clear();
316    state.timing_epoch = state.timing_epoch.wrapping_add(1);
317}
318
319pub(crate) fn snapshot(
320    state: &SharedDiagnostics,
321    capabilities: &Capabilities,
322    resources: &ResourceDiagnostics,
323    max_filter_samples: u32,
324    degradations: Vec<crate::CapabilityDiagnostic>,
325) -> RenderDiagnostics {
326    let state = state
327        .lock()
328        .unwrap_or_else(std::sync::PoisonError::into_inner);
329    RenderDiagnostics {
330        adapter: AdapterDiagnostics {
331            name: capabilities.adapter_name.clone(),
332            backend: capabilities.backend.clone(),
333            driver: capabilities.driver.clone(),
334            driver_info: capabilities.driver_info.clone(),
335            tier: capabilities.tier,
336            timestamp_queries: capabilities.timestamp_queries,
337            shader_compiler: capabilities.shader_compiler.clone(),
338        },
339        passes: state.passes.iter().copied().collect(),
340        textures: resources.textures,
341        upload_textures: resources.upload_textures,
342        readback_buffers: resources.readback_buffers,
343        uniform_buffers: resources.uniform_buffers,
344        pipelines: resources.pipelines,
345        bind_groups: resources.bind_groups,
346        pipeline_creation: state.pipeline_creation,
347        result_cache: resources.result_cache,
348        presented_frames: state.presented_frames,
349        dropped_frames: state.dropped_frames,
350        repeated_frames: state.repeated_frames,
351        decoder_wait: state.decoder_wait,
352        max_filter_samples,
353        degradations,
354        graph_nodes: state.graph_nodes,
355        graph_passes: state.graph_passes,
356        graph_submissions: state.graph_submissions,
357        source_submissions: state.source_submissions,
358        source_conversions: state.source_conversions,
359        yuv_repacks: state.yuv_repacks,
360        readback_submissions: state.readback_submissions,
361        frame_submissions: state.frame_submissions,
362        render_passes: state.render_passes,
363        copy_operations: state.copy_operations,
364        copy_bytes: state.copy_bytes,
365    }
366}
367
368/// Runs `create`, recording its duration under `label`.
369pub(crate) fn timed_pipeline_creation<T>(
370    state: &SharedDiagnostics,
371    label: impl FnOnce() -> String,
372    create: impl FnOnce() -> T,
373) -> T {
374    let started = web_time::Instant::now();
375    let created = create();
376    let finished = web_time::Instant::now();
377    let micros = u64::try_from(finished.duration_since(started).as_micros()).unwrap_or(u64::MAX);
378    let mut state = state
379        .lock()
380        .unwrap_or_else(std::sync::PoisonError::into_inner);
381    let totals = &mut state.pipeline_creation;
382    totals.created = totals.created.saturating_add(1);
383    totals.create_micros_total = totals.create_micros_total.saturating_add(micros);
384    totals.create_micros_max = totals.create_micros_max.max(micros);
385    if state.pipeline_creations.len() == PIPELINE_HISTORY {
386        state.pipeline_creations.pop_front();
387    }
388    state.pipeline_creations.push_back(PipelineCreation {
389        label: label(),
390        started,
391        finished,
392    });
393    created
394}
395
396pub(crate) fn take_pipeline_creations(state: &SharedDiagnostics) -> Vec<PipelineCreation> {
397    state
398        .lock()
399        .unwrap_or_else(std::sync::PoisonError::into_inner)
400        .pipeline_creations
401        .drain(..)
402        .collect()
403}
404
405/// Records how one frame was submitted and its submissions' predicted times.
406pub(crate) fn record_frame_plan(
407    state: &SharedDiagnostics,
408    frame: &crate::FrameSubmissions,
409    buffer_ms: &[f64],
410    budget_ms: Option<f64>,
411) {
412    let max_predicted_ms = buffer_ms
413        .iter()
414        .copied()
415        .fold(None, |most: Option<f64>, ms| {
416            Some(most.map_or(ms, |most| most.max(ms)))
417        });
418    let over_budget = budget_ms.map_or(0, |budget| {
419        buffer_ms
420            .iter()
421            .filter(|ms| **ms > budget * OVER_BUDGET_ROUNDING)
422            .count()
423    });
424    let mut state = state
425        .lock()
426        .unwrap_or_else(std::sync::PoisonError::into_inner);
427    let totals = &mut state.gpu_submissions;
428    totals.frames = totals.frames.saturating_add(1);
429    totals.split_frames = totals
430        .split_frames
431        .saturating_add(u64::from(frame.submissions > 1));
432    totals.max_per_frame = totals.max_per_frame.max(frame.submissions);
433    if let Some(ms) = max_predicted_ms {
434        totals.max_predicted_ms = Some(totals.max_predicted_ms.map_or(ms, |most| most.max(ms)));
435    }
436    totals.over_budget = totals
437        .over_budget
438        .saturating_add(u64::try_from(over_budget).unwrap_or(u64::MAX));
439    totals.budget_ms = budget_ms.or(totals.budget_ms);
440}
441
442const OVER_BUDGET_ROUNDING: f64 = 1.0 + 1e-9;
443
444/// Submission counts since the last call, then resets them.
445pub(crate) fn take_gpu_submission_stats(state: &SharedDiagnostics) -> GpuSubmissionStats {
446    std::mem::take(
447        &mut state
448            .lock()
449            .unwrap_or_else(std::sync::PoisonError::into_inner)
450            .gpu_submissions,
451    )
452}
453
454pub(crate) fn record_yuv_repack(state: &SharedDiagnostics) {
455    let mut state = state
456        .lock()
457        .unwrap_or_else(std::sync::PoisonError::into_inner);
458    state.yuv_repacks = state.yuv_repacks.saturating_add(1);
459}
460
461pub(crate) fn record_frame(state: &SharedDiagnostics, presented: bool, repeated: bool) {
462    let mut state = state
463        .lock()
464        .unwrap_or_else(std::sync::PoisonError::into_inner);
465    state.presented_frames += u64::from(presented);
466    state.dropped_frames += u64::from(!presented);
467    state.repeated_frames += u64::from(repeated);
468}
469
470pub(crate) fn record_decoder_wait(state: &SharedDiagnostics, duration: Duration) {
471    let mut state = state
472        .lock()
473        .unwrap_or_else(std::sync::PoisonError::into_inner);
474    state.decoder_wait = state.decoder_wait.saturating_add(duration);
475}