alpha2-render 0.10.0

Render graph and effect registry for alpha2.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use std::time::Duration;
use web_time::Instant;

use crate::prepared_frame::FramePack;
use crate::yuv::SourceWorkTicket;
use crate::{
    GraphError, PendingSourceWork, RenderError, RenderGraph, RenderedTexture, Renderer,
    Yuv420pReadback,
};
use alpha2_media::{PixelLayout, YuvEncoding};

/// Where one frame's graph construction and submission spent its time.
///
/// Fields are consecutive spans on one thread, separating a slow graph from a contended queue.
/// `graph_build` belongs to whoever built the [`RenderGraph`]; timed submissions write only the
/// later spans.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct FrameSubmitTimings {
    /// Effect validation, source availability, and render-graph construction.
    pub graph_build: Duration,
    /// Encoding source conversion, graph, and readback commands.
    pub command_encode: Duration,
    /// Native acquire and layout transition for imported decoder surfaces.
    pub source_acquire: Duration,
    /// Blocked on the queue lock shared with the native decoder.
    pub queue_lock_wait: Duration,
    /// Inside `wgpu`'s queue submit.
    pub queue_submit: Duration,
    /// Releasing decoder surfaces whose submission has completed.
    pub lease_retire: Duration,
    /// Building the readback handle and returning pooled textures.
    pub complete: Duration,
}

impl FrameSubmitTimings {
    /// Adds another call's spans to these, saturating on overflow.
    #[must_use]
    pub fn merged(self, other: Self) -> Self {
        Self {
            graph_build: self.graph_build.saturating_add(other.graph_build),
            command_encode: self.command_encode.saturating_add(other.command_encode),
            source_acquire: self.source_acquire.saturating_add(other.source_acquire),
            queue_lock_wait: self.queue_lock_wait.saturating_add(other.queue_lock_wait),
            queue_submit: self.queue_submit.saturating_add(other.queue_submit),
            lease_retire: self.lease_retire.saturating_add(other.lease_retire),
            complete: self.complete.saturating_add(other.complete),
        }
    }

    /// Replaces every span after graph construction with `later`'s.
    const fn with_submission(self, later: Self) -> Self {
        Self {
            graph_build: self.graph_build,
            ..later
        }
    }
}

/// A lap timer that reads no clock unless a caller asked for timings.
#[derive(Copy, Clone)]
struct StageClock(Option<Instant>);

impl StageClock {
    fn start(enabled: bool) -> Self {
        Self(enabled.then(Instant::now))
    }

    /// Returns the span since the previous lap and starts a new one.
    fn lap(&mut self) -> Duration {
        let Some(mark) = self.0 else {
            return Duration::ZERO;
        };
        let now = Instant::now();
        self.0 = Some(now);
        now.duration_since(mark)
    }
}

impl Renderer {
    /// Renders a graph, folding its sources' pending presentation work into the same submission.
    ///
    /// `sources` are in encode order; work another consumer already submitted is skipped.
    ///
    /// # Errors
    /// Returns [`RenderError`] when the graph or a render target is invalid.
    pub fn render_graph(
        &self,
        graph: &RenderGraph<'_>,
        sources: &[&PendingSourceWork],
    ) -> Result<RenderedTexture, RenderError> {
        // Held past the tickets, which revert to pending if the frame fails.
        let frame = self.frame_lock.hold();
        let source_work = begin_source_work(&frame, sources);
        let start = self
            .prepare_graph(graph, &source_work, FramePack::Nothing)
            .map_err(GraphError::into_render_error)?;
        let mut command_encoder = self.command_encoder("alpha2 frame encoder");
        let graph_work = self
            .encode_graph(start, graph, &mut command_encoder, &source_work, None)
            .map_err(GraphError::into_render_error)?;
        stage_source_submissions(&source_work)?;
        graph_work.flush_uniforms(self.gpu.queue());
        // A rejected submission returns before anything of the frame is kept.
        self.submit([command_encoder.finish()])?;
        let combined_submission = !source_work.is_empty();
        for work in source_work {
            work.complete(self, false);
        }
        let texture = self.complete_graph_work(graph_work, !combined_submission);
        if combined_submission {
            crate::diagnostics::record_frame_submission(&self.diagnostics);
        }
        Ok(texture)
    }

    /// Renders a graph, converts it to YUV420, and submits it with its sources' pending work in one
    /// command buffer. The output size must be even.
    ///
    /// # Errors
    /// Returns [`RenderError`] for invalid graph, target, or YUV layout data.
    pub fn render_graph_yuv420p(
        &self,
        graph: &RenderGraph<'_>,
        sources: &[&PendingSourceWork],
        encoding: YuvEncoding,
    ) -> Result<Yuv420pReadback, RenderError> {
        self.render_graph_readback_measured(
            graph,
            sources,
            encoding,
            ReadbackKind::PackedYuv420p,
            None,
        )
    }

    /// [`Renderer::render_graph_yuv420p`] that also writes every span after `graph_build` to
    /// `timings`.
    ///
    /// # Errors
    /// Returns [`RenderError`] for invalid graph, target, or YUV layout data.
    pub fn render_graph_yuv420p_timed(
        &self,
        graph: &RenderGraph<'_>,
        sources: &[&PendingSourceWork],
        encoding: YuvEncoding,
        timings: &mut FrameSubmitTimings,
    ) -> Result<Yuv420pReadback, RenderError> {
        self.render_graph_readback_measured(
            graph,
            sources,
            encoding,
            ReadbackKind::PackedYuv420p,
            Some(timings),
        )
    }

    /// Renders a graph and packs the result into `layout`'s planes on the GPU for
    /// [`Yuv420pReadback::finish_into_planes`], in one command buffer with its sources' pending
    /// work.
    ///
    /// With `timings`, also writes every span after `graph_build` to them and samples the frame's
    /// GPU time ([`Renderer::take_frame_gpu_times`]).
    ///
    /// # Errors
    /// As [`Self::render_graph_yuv420p`] and [`Self::begin_layout_readback`].
    pub fn render_graph_layout_readback(
        &self,
        graph: &RenderGraph<'_>,
        sources: &[&PendingSourceWork],
        encoding: YuvEncoding,
        layout: PixelLayout,
        timings: Option<&mut FrameSubmitTimings>,
    ) -> Result<Yuv420pReadback, RenderError> {
        self.render_graph_readback_measured(
            graph,
            sources,
            encoding,
            ReadbackKind::Layout(layout),
            timings,
        )
    }

    /// [`Renderer::render_graph_yuv420p_timed`] packing into caller-owned NV12 plane textures
    /// instead of a staging buffer, for feeding a hardware encoder.
    ///
    /// # Errors
    /// Returns [`RenderError`] for invalid graph or plane-target data.
    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
    pub fn render_graph_nv12_timed(
        &self,
        graph: &RenderGraph<'_>,
        sources: &[&PendingSourceWork],
        planes: crate::Nv12PlaneTargets<'_>,
        encoding: YuvEncoding,
        timings: &mut FrameSubmitTimings,
    ) -> Result<(), RenderError> {
        let mut clock = StageClock::start(true);
        let mut collected = FrameSubmitTimings::default();
        let frame = self.frame_lock.hold();
        self.check_submitted_work()?;
        let source_work = begin_source_work(&frame, sources);
        let start = self
            .prepare_graph(graph, &source_work, FramePack::Nv12)
            .map_err(GraphError::into_render_error)?;
        let mut command_encoder = self.command_encoder("alpha2 render and NV12 pack encoder");
        let sample = self
            .frame_gpu_timer()
            .and_then(crate::frame_gpu_time::FrameGpuTimer::begin);
        let mut graph_work = self
            .encode_graph(
                start,
                graph,
                &mut command_encoder,
                &source_work,
                sample.as_ref(),
            )
            .map_err(GraphError::into_render_error)?;
        if let Some(sample) = &sample {
            sample.graph_end(&mut command_encoder);
        }
        let (output, uniforms) = graph_work.output_and_uniforms();
        self.encode_nv12_pack_into(output, planes, encoding, &mut command_encoder, uniforms)?;
        if let Some(sample) = &sample {
            sample.pack_end(&mut command_encoder);
        }
        // No readback, so the canary goes in a buffer of its own.
        let (canary_buffer, canary) = self.canaries.encode_own(&self.gpu, &mut command_encoder)?;
        collected.command_encode = clock.lap();
        stage_source_submissions(&source_work)?;
        collected.source_acquire = clock.lap();
        graph_work.flush_uniforms(self.gpu.queue());
        let command_buffer = command_encoder.finish();
        collected.command_encode = collected.command_encode.saturating_add(clock.lap());
        // A rejected submission wrote nothing, so the frame fails here untracked.
        let submitted = self.submit_measured([command_buffer], true)?;
        if let Some(sample) = sample {
            sample.submitted(&self.gpu);
        }
        self.submission_canaries
            .track(&self.gpu, canary_buffer, canary);
        collected.queue_lock_wait = submitted.timings.queue_lock_wait;
        collected.queue_submit = submitted.timings.queue_submit;
        collected.lease_retire = submitted.lease_retire;
        let _ = clock.lap();
        for work in source_work {
            work.complete(self, false);
        }
        drop(self.complete_graph_work(graph_work, false));
        crate::diagnostics::record_frame_submission(&self.diagnostics);
        collected.complete = clock.lap();
        *timings = timings.with_submission(collected);
        Ok(())
    }

    fn render_graph_readback_measured(
        &self,
        graph: &RenderGraph<'_>,
        sources: &[&PendingSourceWork],
        encoding: YuvEncoding,
        readback: ReadbackKind,
        timings: Option<&mut FrameSubmitTimings>,
    ) -> Result<Yuv420pReadback, RenderError> {
        let measure = timings.is_some();
        let mut clock = StageClock::start(measure);
        let mut collected = FrameSubmitTimings::default();
        let frame = self.frame_lock.hold();
        let source_work = begin_source_work(&frame, sources);
        let start = self
            .prepare_graph(
                graph,
                &source_work,
                match readback {
                    ReadbackKind::PackedYuv420p => FramePack::Yuv420p,
                    ReadbackKind::Layout(layout) => FramePack::Layout(layout),
                },
            )
            .map_err(GraphError::into_render_error)?;
        let mut command_encoder = self.command_encoder(match readback {
            ReadbackKind::PackedYuv420p => "alpha2 render and YUV420P readback encoder",
            ReadbackKind::Layout(_) => "alpha2 render and layout readback encoder",
        });
        // Only an export's timed frames are sampled.
        let sample = measure
            .then(|| self.frame_gpu_timer())
            .flatten()
            .and_then(crate::frame_gpu_time::FrameGpuTimer::begin);
        let mut graph_work = self
            .encode_graph(
                start,
                graph,
                &mut command_encoder,
                &source_work,
                sample.as_ref(),
            )
            .map_err(GraphError::into_render_error)?;
        if let Some(sample) = &sample {
            sample.graph_end(&mut command_encoder);
        }
        let (output, uniforms) = graph_work.output_and_uniforms();
        let readback_work = match readback {
            ReadbackKind::Layout(layout) => {
                EncodedReadback::Layout(Box::new(self.encode_layout_readback(
                    output,
                    encoding,
                    layout,
                    &mut command_encoder,
                    uniforms,
                )?))
            }
            ReadbackKind::PackedYuv420p => EncodedReadback::Yuv420p(Box::new(
                self.encode_yuv420p_readback(output, encoding, &mut command_encoder, uniforms)?,
            )),
        };
        if let Some(sample) = &sample {
            sample.pack_end(&mut command_encoder);
        }
        collected.command_encode = clock.lap();
        stage_source_submissions(&source_work)?;
        collected.source_acquire = clock.lap();
        graph_work.flush_uniforms(self.gpu.queue());
        let command_buffer = command_encoder.finish();
        // Finishing the encoder and flushing uniforms count as command encoding.
        collected.command_encode = collected.command_encode.saturating_add(clock.lap());
        let submitted = self.submit_measured([command_buffer], measure)?;
        if let Some(sample) = sample {
            sample.submitted(&self.gpu);
        }
        collected.queue_lock_wait = submitted.timings.queue_lock_wait;
        collected.queue_submit = submitted.timings.queue_submit;
        collected.lease_retire = submitted.lease_retire;
        // The submission timed itself; discard this lap.
        let _ = clock.lap();
        let readback = match readback_work {
            EncodedReadback::Yuv420p(work) => self.complete_yuv420p_readback(
                *work,
                #[cfg(not(target_arch = "wasm32"))]
                submitted.submission,
                false,
            ),
            EncodedReadback::Layout(work) => self.complete_layout_readback(
                *work,
                #[cfg(not(target_arch = "wasm32"))]
                submitted.submission,
                false,
            ),
        };
        for work in source_work {
            work.complete(self, false);
        }
        drop(self.complete_graph_work(graph_work, false));
        crate::diagnostics::record_frame_submission(&self.diagnostics);
        collected.complete = clock.lap();
        if let Some(timings) = timings {
            *timings = timings.with_submission(collected);
        }
        Ok(readback)
    }
}

#[derive(Copy, Clone)]
enum ReadbackKind {
    PackedYuv420p,
    Layout(PixelLayout),
}

enum EncodedReadback {
    Yuv420p(Box<crate::readback::EncodedYuv420pReadback>),
    Layout(Box<crate::readback::EncodedLayoutReadback>),
}

/// Stages external textures' native waits and signals on the submission about to sample them.
///
/// Every graph submission must run this before `queue.submit`, or a decoder surface could be
/// sampled before it is waited on and transitioned out of its decode layout.
pub(crate) fn stage_source_submissions(
    source_work: &[SourceWorkTicket<'_>],
) -> Result<(), RenderError> {
    debug_assert!(
        source_work
            .iter()
            .all(SourceWorkTicket::has_no_staged_signals),
        "a source lease carried a staged native signal into the next frame"
    );
    for work in source_work {
        if !work.prepare_submission() {
            return Err(RenderError::ExternalTextureSync(None));
        }
    }
    // Staging is separate from flushing so one native submission carries every source.
    for work in source_work {
        work.flush_submission()?;
    }
    Ok(())
}

/// Takes the pending work of `sources` no other frame has taken.
///
/// Call only under the frame lock, held until the tickets complete or drop, so "taken" always
/// means "submitted ahead of this frame", never "being encoded".
pub(crate) fn begin_source_work<'a>(
    frame: &crate::renderer::FrameGuard,
    sources: &[&'a PendingSourceWork],
) -> Vec<SourceWorkTicket<'a>> {
    sources
        .iter()
        .filter_map(|pending| pending.begin(frame))
        .collect()
}