Skip to main content

alpha2_render/
graph_submit.rs

1use std::time::Duration;
2use web_time::Instant;
3
4use crate::prepared_frame::FramePack;
5use crate::yuv::SourceWorkTicket;
6use crate::{
7    GraphError, PendingSourceWork, RenderError, RenderGraph, RenderedTexture, Renderer,
8    Yuv420pReadback,
9};
10use alpha2_media::{PixelLayout, YuvEncoding};
11
12/// Where one frame's graph construction and submission spent its time.
13///
14/// Fields are consecutive spans on one thread, separating a slow graph from a contended queue.
15/// `graph_build` belongs to whoever built the [`RenderGraph`]; timed submissions write only the
16/// later spans.
17#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
18pub struct FrameSubmitTimings {
19    /// Effect validation, source availability, and render-graph construction.
20    pub graph_build: Duration,
21    /// Encoding source conversion, graph, and readback commands.
22    pub command_encode: Duration,
23    /// Native acquire and layout transition for imported decoder surfaces.
24    pub source_acquire: Duration,
25    /// Blocked on the queue lock shared with the native decoder.
26    pub queue_lock_wait: Duration,
27    /// Inside `wgpu`'s queue submit.
28    pub queue_submit: Duration,
29    /// Releasing decoder surfaces whose submission has completed.
30    pub lease_retire: Duration,
31    /// Building the readback handle and returning pooled textures.
32    pub complete: Duration,
33}
34
35impl FrameSubmitTimings {
36    /// Adds another call's spans to these, saturating on overflow.
37    #[must_use]
38    pub fn merged(self, other: Self) -> Self {
39        Self {
40            graph_build: self.graph_build.saturating_add(other.graph_build),
41            command_encode: self.command_encode.saturating_add(other.command_encode),
42            source_acquire: self.source_acquire.saturating_add(other.source_acquire),
43            queue_lock_wait: self.queue_lock_wait.saturating_add(other.queue_lock_wait),
44            queue_submit: self.queue_submit.saturating_add(other.queue_submit),
45            lease_retire: self.lease_retire.saturating_add(other.lease_retire),
46            complete: self.complete.saturating_add(other.complete),
47        }
48    }
49
50    /// Replaces every span after graph construction with `later`'s.
51    const fn with_submission(self, later: Self) -> Self {
52        Self {
53            graph_build: self.graph_build,
54            ..later
55        }
56    }
57}
58
59/// A lap timer that reads no clock unless a caller asked for timings.
60#[derive(Copy, Clone)]
61struct StageClock(Option<Instant>);
62
63impl StageClock {
64    fn start(enabled: bool) -> Self {
65        Self(enabled.then(Instant::now))
66    }
67
68    /// Returns the span since the previous lap and starts a new one.
69    fn lap(&mut self) -> Duration {
70        let Some(mark) = self.0 else {
71            return Duration::ZERO;
72        };
73        let now = Instant::now();
74        self.0 = Some(now);
75        now.duration_since(mark)
76    }
77}
78
79impl Renderer {
80    /// Renders a graph, folding its sources' pending presentation work into the same submission.
81    ///
82    /// `sources` are in encode order; work another consumer already submitted is skipped.
83    ///
84    /// # Errors
85    /// Returns [`RenderError`] when the graph or a render target is invalid.
86    pub fn render_graph(
87        &self,
88        graph: &RenderGraph<'_>,
89        sources: &[&PendingSourceWork],
90    ) -> Result<RenderedTexture, RenderError> {
91        // Held past the tickets, which revert to pending if the frame fails.
92        let frame = self.frame_lock.hold();
93        let source_work = begin_source_work(&frame, sources);
94        let start = self
95            .prepare_graph(graph, &source_work, FramePack::Nothing)
96            .map_err(GraphError::into_render_error)?;
97        let mut command_encoder = self.command_encoder("alpha2 frame encoder");
98        let graph_work = self
99            .encode_graph(start, graph, &mut command_encoder, &source_work, None)
100            .map_err(GraphError::into_render_error)?;
101        stage_source_submissions(&source_work)?;
102        graph_work.flush_uniforms(self.gpu.queue());
103        // A rejected submission returns before anything of the frame is kept.
104        self.submit([command_encoder.finish()])?;
105        let combined_submission = !source_work.is_empty();
106        for work in source_work {
107            work.complete(self, false);
108        }
109        let texture = self.complete_graph_work(graph_work, !combined_submission);
110        if combined_submission {
111            crate::diagnostics::record_frame_submission(&self.diagnostics);
112        }
113        Ok(texture)
114    }
115
116    /// Renders a graph, converts it to YUV420, and submits it with its sources' pending work in one
117    /// command buffer. The output size must be even.
118    ///
119    /// # Errors
120    /// Returns [`RenderError`] for invalid graph, target, or YUV layout data.
121    pub fn render_graph_yuv420p(
122        &self,
123        graph: &RenderGraph<'_>,
124        sources: &[&PendingSourceWork],
125        encoding: YuvEncoding,
126    ) -> Result<Yuv420pReadback, RenderError> {
127        self.render_graph_readback_measured(
128            graph,
129            sources,
130            encoding,
131            ReadbackKind::PackedYuv420p,
132            None,
133        )
134    }
135
136    /// [`Renderer::render_graph_yuv420p`] that also writes every span after `graph_build` to
137    /// `timings`.
138    ///
139    /// # Errors
140    /// Returns [`RenderError`] for invalid graph, target, or YUV layout data.
141    pub fn render_graph_yuv420p_timed(
142        &self,
143        graph: &RenderGraph<'_>,
144        sources: &[&PendingSourceWork],
145        encoding: YuvEncoding,
146        timings: &mut FrameSubmitTimings,
147    ) -> Result<Yuv420pReadback, RenderError> {
148        self.render_graph_readback_measured(
149            graph,
150            sources,
151            encoding,
152            ReadbackKind::PackedYuv420p,
153            Some(timings),
154        )
155    }
156
157    /// Renders a graph and packs the result into `layout`'s planes on the GPU for
158    /// [`Yuv420pReadback::finish_into_planes`], in one command buffer with its sources' pending
159    /// work.
160    ///
161    /// With `timings`, also writes every span after `graph_build` to them and samples the frame's
162    /// GPU time ([`Renderer::take_frame_gpu_times`]).
163    ///
164    /// # Errors
165    /// As [`Self::render_graph_yuv420p`] and [`Self::begin_layout_readback`].
166    pub fn render_graph_layout_readback(
167        &self,
168        graph: &RenderGraph<'_>,
169        sources: &[&PendingSourceWork],
170        encoding: YuvEncoding,
171        layout: PixelLayout,
172        timings: Option<&mut FrameSubmitTimings>,
173    ) -> Result<Yuv420pReadback, RenderError> {
174        self.render_graph_readback_measured(
175            graph,
176            sources,
177            encoding,
178            ReadbackKind::Layout(layout),
179            timings,
180        )
181    }
182
183    /// [`Renderer::render_graph_yuv420p_timed`] packing into caller-owned NV12 plane textures
184    /// instead of a staging buffer, for feeding a hardware encoder.
185    ///
186    /// # Errors
187    /// Returns [`RenderError`] for invalid graph or plane-target data.
188    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
189    pub fn render_graph_nv12_timed(
190        &self,
191        graph: &RenderGraph<'_>,
192        sources: &[&PendingSourceWork],
193        planes: crate::Nv12PlaneTargets<'_>,
194        encoding: YuvEncoding,
195        timings: &mut FrameSubmitTimings,
196    ) -> Result<(), RenderError> {
197        let mut clock = StageClock::start(true);
198        let mut collected = FrameSubmitTimings::default();
199        let frame = self.frame_lock.hold();
200        self.check_submitted_work()?;
201        let source_work = begin_source_work(&frame, sources);
202        let start = self
203            .prepare_graph(graph, &source_work, FramePack::Nv12)
204            .map_err(GraphError::into_render_error)?;
205        let mut command_encoder = self.command_encoder("alpha2 render and NV12 pack encoder");
206        let sample = self
207            .frame_gpu_timer()
208            .and_then(crate::frame_gpu_time::FrameGpuTimer::begin);
209        let mut graph_work = self
210            .encode_graph(
211                start,
212                graph,
213                &mut command_encoder,
214                &source_work,
215                sample.as_ref(),
216            )
217            .map_err(GraphError::into_render_error)?;
218        if let Some(sample) = &sample {
219            sample.graph_end(&mut command_encoder);
220        }
221        let (output, uniforms) = graph_work.output_and_uniforms();
222        self.encode_nv12_pack_into(output, planes, encoding, &mut command_encoder, uniforms)?;
223        if let Some(sample) = &sample {
224            sample.pack_end(&mut command_encoder);
225        }
226        // No readback, so the canary goes in a buffer of its own.
227        let (canary_buffer, canary) = self.canaries.encode_own(&self.gpu, &mut command_encoder)?;
228        collected.command_encode = clock.lap();
229        stage_source_submissions(&source_work)?;
230        collected.source_acquire = clock.lap();
231        graph_work.flush_uniforms(self.gpu.queue());
232        let command_buffer = command_encoder.finish();
233        collected.command_encode = collected.command_encode.saturating_add(clock.lap());
234        // A rejected submission wrote nothing, so the frame fails here untracked.
235        let submitted = self.submit_measured([command_buffer], true)?;
236        if let Some(sample) = sample {
237            sample.submitted(&self.gpu);
238        }
239        self.submission_canaries
240            .track(&self.gpu, canary_buffer, canary);
241        collected.queue_lock_wait = submitted.timings.queue_lock_wait;
242        collected.queue_submit = submitted.timings.queue_submit;
243        collected.lease_retire = submitted.lease_retire;
244        let _ = clock.lap();
245        for work in source_work {
246            work.complete(self, false);
247        }
248        drop(self.complete_graph_work(graph_work, false));
249        crate::diagnostics::record_frame_submission(&self.diagnostics);
250        collected.complete = clock.lap();
251        *timings = timings.with_submission(collected);
252        Ok(())
253    }
254
255    fn render_graph_readback_measured(
256        &self,
257        graph: &RenderGraph<'_>,
258        sources: &[&PendingSourceWork],
259        encoding: YuvEncoding,
260        readback: ReadbackKind,
261        timings: Option<&mut FrameSubmitTimings>,
262    ) -> Result<Yuv420pReadback, RenderError> {
263        let measure = timings.is_some();
264        let mut clock = StageClock::start(measure);
265        let mut collected = FrameSubmitTimings::default();
266        let frame = self.frame_lock.hold();
267        let source_work = begin_source_work(&frame, sources);
268        let start = self
269            .prepare_graph(
270                graph,
271                &source_work,
272                match readback {
273                    ReadbackKind::PackedYuv420p => FramePack::Yuv420p,
274                    ReadbackKind::Layout(layout) => FramePack::Layout(layout),
275                },
276            )
277            .map_err(GraphError::into_render_error)?;
278        let mut command_encoder = self.command_encoder(match readback {
279            ReadbackKind::PackedYuv420p => "alpha2 render and YUV420P readback encoder",
280            ReadbackKind::Layout(_) => "alpha2 render and layout readback encoder",
281        });
282        // Only an export's timed frames are sampled.
283        let sample = measure
284            .then(|| self.frame_gpu_timer())
285            .flatten()
286            .and_then(crate::frame_gpu_time::FrameGpuTimer::begin);
287        let mut graph_work = self
288            .encode_graph(
289                start,
290                graph,
291                &mut command_encoder,
292                &source_work,
293                sample.as_ref(),
294            )
295            .map_err(GraphError::into_render_error)?;
296        if let Some(sample) = &sample {
297            sample.graph_end(&mut command_encoder);
298        }
299        let (output, uniforms) = graph_work.output_and_uniforms();
300        let readback_work = match readback {
301            ReadbackKind::Layout(layout) => {
302                EncodedReadback::Layout(Box::new(self.encode_layout_readback(
303                    output,
304                    encoding,
305                    layout,
306                    &mut command_encoder,
307                    uniforms,
308                )?))
309            }
310            ReadbackKind::PackedYuv420p => EncodedReadback::Yuv420p(Box::new(
311                self.encode_yuv420p_readback(output, encoding, &mut command_encoder, uniforms)?,
312            )),
313        };
314        if let Some(sample) = &sample {
315            sample.pack_end(&mut command_encoder);
316        }
317        collected.command_encode = clock.lap();
318        stage_source_submissions(&source_work)?;
319        collected.source_acquire = clock.lap();
320        graph_work.flush_uniforms(self.gpu.queue());
321        let command_buffer = command_encoder.finish();
322        // Finishing the encoder and flushing uniforms count as command encoding.
323        collected.command_encode = collected.command_encode.saturating_add(clock.lap());
324        let submitted = self.submit_measured([command_buffer], measure)?;
325        if let Some(sample) = sample {
326            sample.submitted(&self.gpu);
327        }
328        collected.queue_lock_wait = submitted.timings.queue_lock_wait;
329        collected.queue_submit = submitted.timings.queue_submit;
330        collected.lease_retire = submitted.lease_retire;
331        // The submission timed itself; discard this lap.
332        let _ = clock.lap();
333        let readback = match readback_work {
334            EncodedReadback::Yuv420p(work) => self.complete_yuv420p_readback(
335                *work,
336                #[cfg(not(target_arch = "wasm32"))]
337                submitted.submission,
338                false,
339            ),
340            EncodedReadback::Layout(work) => self.complete_layout_readback(
341                *work,
342                #[cfg(not(target_arch = "wasm32"))]
343                submitted.submission,
344                false,
345            ),
346        };
347        for work in source_work {
348            work.complete(self, false);
349        }
350        drop(self.complete_graph_work(graph_work, false));
351        crate::diagnostics::record_frame_submission(&self.diagnostics);
352        collected.complete = clock.lap();
353        if let Some(timings) = timings {
354            *timings = timings.with_submission(collected);
355        }
356        Ok(readback)
357    }
358}
359
360#[derive(Copy, Clone)]
361enum ReadbackKind {
362    PackedYuv420p,
363    Layout(PixelLayout),
364}
365
366enum EncodedReadback {
367    Yuv420p(Box<crate::readback::EncodedYuv420pReadback>),
368    Layout(Box<crate::readback::EncodedLayoutReadback>),
369}
370
371/// Stages external textures' native waits and signals on the submission about to sample them.
372///
373/// Every graph submission must run this before `queue.submit`, or a decoder surface could be
374/// sampled before it is waited on and transitioned out of its decode layout.
375pub(crate) fn stage_source_submissions(
376    source_work: &[SourceWorkTicket<'_>],
377) -> Result<(), RenderError> {
378    debug_assert!(
379        source_work
380            .iter()
381            .all(SourceWorkTicket::has_no_staged_signals),
382        "a source lease carried a staged native signal into the next frame"
383    );
384    for work in source_work {
385        if !work.prepare_submission() {
386            return Err(RenderError::ExternalTextureSync(None));
387        }
388    }
389    // Staging is separate from flushing so one native submission carries every source.
390    for work in source_work {
391        work.flush_submission()?;
392    }
393    Ok(())
394}
395
396/// Takes the pending work of `sources` no other frame has taken.
397///
398/// Call only under the frame lock, held until the tickets complete or drop, so "taken" always
399/// means "submitted ahead of this frame", never "being encoded".
400pub(crate) fn begin_source_work<'a>(
401    frame: &crate::renderer::FrameGuard,
402    sources: &[&'a PendingSourceWork],
403) -> Vec<SourceWorkTicket<'a>> {
404    sources
405        .iter()
406        .filter_map(|pending| pending.begin(frame))
407        .collect()
408}