Skip to main content

rlx_core/render/
capture_api.rs

1//! The capture API — `Renderer`'s headless, off-hot-path entry points
2//! (Plan 0013), carved out of `render/mod.rs` by Plan 0061 Phase 3.
3//!
4//! **Dev-tooling API, with one exception at the bottom of the file.** Every
5//! `capture_*` entry point here is driven by the `shot` example and
6//! `core/tests/`, never by the standalone's frame loop and never from behind the
7//! C ABI: each blocks on a GPU readback, so calling one from a *display* loop is
8//! a stutter by construction. The frame tap (Plan 0115) blocks on the same
9//! readback and is nonetheless a live path — a headless source has no present
10//! deadline to miss, only throughput to hold, and its readback is what bounds
11//! the run's memory. It lives here because it shares the offscreen machinery,
12//! not because it shares the caller.
13//!
14//! It is a second `impl Renderer` block rather than a separate type, because the
15//! methods are public API whose paths must not move — `Renderer::capture_preset`
16//! is spelled the same before and after this split.
17
18// Hot-path panic-denial pragma (Plan 0002 Phase 2; render/ is scanned by the
19// hygiene guard). These paths are off the frame loop, but they share
20// `Renderer`'s state and the pragma travels with the code, not with the file.
21#![deny(
22    clippy::unwrap_used,
23    clippy::expect_used,
24    clippy::indexing_slicing,
25    clippy::panic,
26    clippy::unreachable
27)]
28
29// A continuation of one `impl` block that was split across two files, so it
30// needs the same names `render/mod.rs` has in scope. Enumerating them would be a
31// list to keep in sync with a file whose whole purpose is to be the other half
32// of this one.
33use super::*;
34
35/// What one [`Renderer::capture_audio_after_warmup`] run produced.
36///
37/// The two fields beside the images exist so a caller can check *what the run
38/// did* rather than infer it from a stopwatch (Plan 0084 Phase 3): `analysis`
39/// is the analyzer state the run walked through, and `rendered` is how much of
40/// it reached a rasterizer.
41pub struct AudioCapture {
42    /// The requested frames, in `at_frames` order.
43    pub images: Vec<CaptureImage>,
44    /// One published [`AnalysisFrame`] per hop, in hop order. Independent of
45    /// whether the hop was rendered — which is the property that makes feeding
46    /// warm-up hops without pixels safe, and is asserted rather than argued
47    /// (`core/tests/capture_advance.rs`).
48    pub analysis: Vec<AnalysisFrame>,
49    /// How many frames were rasterized. Zero when every hop is a warm-up hop.
50    pub rendered: usize,
51}
52
53impl Renderer {
54    /// Advance the scene clock one step and capture that single frame into an
55    /// offscreen texture, returning tight RGBA (Plan 0013). Off the hot path —
56    /// blocks on GPU readback; never call it from a live loop.
57    pub fn capture_frame(&mut self, frame: &AnalysisFrame) -> Result<CaptureImage, RenderError> {
58        self.time += scenes::FALLBACK_DT;
59        self.capture_at_clock(frame)
60    }
61
62    /// Draw the active preset for `frame` at the **current** clock into a fresh
63    /// offscreen texture and read it back. Does not advance the clock, so
64    /// callers that already stepped it share this. The whole path (clear → draw
65    /// → copy → map) is deterministic for a given `(preset, frame, clock)`.
66    fn capture_at_clock(&mut self, frame: &AnalysisFrame) -> Result<CaptureImage, RenderError> {
67        let (width, height) = (self.ctx.config.width, self.ctx.config.height);
68        let format = self.ctx.surface_format();
69        let (texture, view) = capture::create_target(&self.ctx.device, format, width, height);
70        let (buffer, padded_bpr) = capture::create_readback(&self.ctx.device, width, height);
71        let mut encoder = self
72            .ctx
73            .device
74            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
75                label: Some("rlx-capture-frame"),
76            });
77        // The preview intermediate, when one is open, sits between the draw and
78        // the destination here exactly as it does on the present path — same
79        // clear, same draw, same `copy_texture_to_texture`. That is what lets
80        // the intermediate's one real claim — that a frame routed through it is
81        // byte-identical to one drawn straight at the target — be asserted with
82        // no window, in `core/tests/console_preview.rs`.
83        let preview = self.preview.take();
84        capture::record_clear(&mut encoder, preview.as_ref().map_or(&view, |p| &p.view));
85        let _ = self.draw_frame(
86            frame,
87            &mut encoder,
88            preview.as_ref().map_or(&view, |p| &p.view),
89            (width, height),
90            scenes::FALLBACK_DT,
91            SaltMode::Pinned,
92        );
93        if let Some(p) = preview.as_ref() {
94            p.record_copy_to(&mut encoder, &texture);
95        }
96        self.preview = preview;
97        // The preview readback advances on **every** frame drawn through the
98        // intermediate, which is this path as much as the present path: the two
99        // record the same clear, draw and copy, and stating the rule once is
100        // what lets the readback's own claims be asserted with no window
101        // (`core/tests/console_preview.rs`). It changes nothing about the image
102        // returned below — it is an extra copy out of the intermediate, not a
103        // change to what was drawn into it.
104        let recorded = self.step_preview_readback(&mut encoder);
105        capture::record_copy(&mut encoder, &texture, &buffer, padded_bpr, width, height);
106        self.ctx.queue.submit(std::iter::once(encoder.finish()));
107        if recorded {
108            self.arm_preview_readback();
109        }
110
111        #[cfg(feature = "text")]
112        self.text_layer.end_frame();
113
114        capture::read_back(&self.ctx.device, &buffer, width, height, padded_bpr)
115    }
116
117    /// Capture preset `name` after advancing it `frames` steps from a fixed
118    /// initial state, driven by a single constant `frame` (Plan 0013). A **pure
119    /// function** of `(name, frame, frames)`: the scenes are rebuilt so any
120    /// stateful system (e.g. the seeded swarm particles) starts from its
121    /// deterministic seed, and the scene clock resets to `0.0`, so the result is
122    /// independent of any earlier capture. Errors if `name` is not in the
123    /// roster. `frames` is treated as at least 1.
124    pub fn capture_preset(
125        &mut self,
126        name: &str,
127        frame: &AnalysisFrame,
128        frames: u32,
129    ) -> Result<CaptureImage, RenderError> {
130        self.reset_for_capture(name)?;
131
132        let (width, height) = (self.ctx.config.width, self.ctx.config.height);
133        let format = self.ctx.surface_format();
134        let (texture, view) = capture::create_target(&self.ctx.device, format, width, height);
135
136        // Warm the scene through the first frames-1 steps (state advances, pixels
137        // discarded); then capture the final frame.
138        let n = frames.max(1);
139        for _ in 1..n {
140            self.time += scenes::FALLBACK_DT;
141            self.step_offscreen(frame, &view, width, height, scenes::FALLBACK_DT);
142        }
143        self.time += scenes::FALLBACK_DT;
144
145        let (buffer, padded_bpr) = capture::create_readback(&self.ctx.device, width, height);
146        let mut encoder = self
147            .ctx
148            .device
149            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
150                label: Some("rlx-capture-preset"),
151            });
152        capture::record_clear(&mut encoder, &view);
153        let _ = self.draw_frame(
154            frame,
155            &mut encoder,
156            &view,
157            (width, height),
158            scenes::FALLBACK_DT,
159            SaltMode::Pinned,
160        );
161        capture::record_copy(&mut encoder, &texture, &buffer, padded_bpr, width, height);
162        self.ctx.queue.submit(std::iter::once(encoder.finish()));
163
164        #[cfg(feature = "text")]
165        self.text_layer.end_frame();
166
167        capture::read_back(&self.ctx.device, &buffer, width, height, padded_bpr)
168    }
169
170    /// Capture preset `name` across a **time-varying** stimulus (Plan 0037):
171    /// one rendered frame per entry of `stimulus`, read back in order, so the
172    /// returned images are the response *while it changes* rather than after it
173    /// settles.
174    ///
175    /// This is the primitive [`capture_preset`](Self::capture_preset) cannot be:
176    /// holding one frame for every step converges every smoother before the
177    /// pixels are read, which makes the result identical for any `[smoothing]`
178    /// constant (ADR-0039). `capture_preset` is left exactly as it was — four
179    /// suites and `--report` consume it — and this is its sibling, sharing the
180    /// same `reset_for_capture` seed so both are pure
181    /// functions of their arguments.
182    ///
183    /// The clock advances one `FALLBACK_DT` per entry, so
184    /// index `i` is second `i * dt` of the response. An empty `stimulus` yields
185    /// no images. Errors if `name` is not in the roster.
186    ///
187    /// **Off the hot path, and more so than its sibling** — it blocks on a GPU
188    /// readback *per frame*, not once per call. The target and readback buffer
189    /// are allocated up front rather than per frame, because building GPU
190    /// resources mid-sequence perturbs what the feedback stages resolve to on the
191    /// DX12 software adapter.
192    pub fn capture_preset_over(
193        &mut self,
194        name: &str,
195        stimulus: &[AnalysisFrame],
196    ) -> Result<Vec<CaptureImage>, RenderError> {
197        self.reset_for_capture(name)?;
198
199        let (width, height) = (self.ctx.config.width, self.ctx.config.height);
200        let format = self.ctx.surface_format();
201        let (texture, view) = capture::create_target(&self.ctx.device, format, width, height);
202        let (buffer, padded_bpr) = capture::create_readback(&self.ctx.device, width, height);
203
204        let mut images = Vec::with_capacity(stimulus.len());
205        for frame in stimulus {
206            self.time += scenes::FALLBACK_DT;
207            let mut encoder =
208                self.ctx
209                    .device
210                    .create_command_encoder(&wgpu::CommandEncoderDescriptor {
211                        label: Some("rlx-capture-over"),
212                    });
213            capture::record_clear(&mut encoder, &view);
214            let _ = self.draw_frame(
215                frame,
216                &mut encoder,
217                &view,
218                (width, height),
219                scenes::FALLBACK_DT,
220                SaltMode::Pinned,
221            );
222            capture::record_copy(&mut encoder, &texture, &buffer, padded_bpr, width, height);
223            self.ctx.queue.submit(std::iter::once(encoder.finish()));
224
225            #[cfg(feature = "text")]
226            self.text_layer.end_frame();
227
228            images.push(capture::read_back(
229                &self.ctx.device,
230                &buffer,
231                width,
232                height,
233                padded_bpr,
234            )?);
235        }
236        Ok(images)
237    }
238
239    /// Advance preset `name` under a single constant `frame` and read back only
240    /// the frames named in `at_frames` (Plan 0085 Phase 1) — the **long-run**
241    /// primitive, and the one a horizon needs.
242    ///
243    /// Its two siblings cannot serve a run of tens of thousands of frames:
244    /// [`capture_preset`](Self::capture_preset) reseeds from scratch on every
245    /// call, so sampling *k* points costs `O(k·N)` renders, and
246    /// [`capture_preset_over`](Self::capture_preset_over) reads back *every*
247    /// frame, so a ten-minute run at 720p would materialize ~36,000 images. This
248    /// renders `N` frames once and holds `at_frames.len()` of them.
249    ///
250    /// Frame numbering matches [`capture_audio`](Self::capture_audio): frame 0
251    /// is the first advanced frame, so `at_frames = [n - 1]` returns exactly what
252    /// `capture_preset(name, frame, n)` returns — asserted in
253    /// `core/tests/capture_advance.rs` rather than argued, because it is the
254    /// property that lets a horizon's rows be compared with every other capture
255    /// this repo takes.
256    ///
257    /// Deterministic on the same terms as its siblings: scenes are rebuilt to
258    /// their seed, the clock resets to `0.0`, and the step is a fixed
259    /// `FALLBACK_DT` — so a row at index *k* does not
260    /// depend on how far the run was asked to go. Images come back in
261    /// `at_frames` order; a repeated index yields the same frame twice rather
262    /// than rendering it twice. An empty `at_frames` renders nothing.
263    ///
264    /// **Off the hot path** — it blocks on a GPU readback per requested frame.
265    /// The readback buffer is built **once, at the first requested frame**, and
266    /// reused for every later one. Both halves of that matter on the DX12
267    /// software adapter, where building GPU resources mid-sequence perturbs what
268    /// the feedback stages resolve to (the hazard
269    /// [`capture_preset_over`](Self::capture_preset_over) documents, and a
270    /// horizon is precisely a long feedback sequence): reusing it means the
271    /// perturbation happens once rather than per sample, and doing it at the
272    /// first sample rather than up front is what puts the allocation at the same
273    /// point in the sequence [`capture_preset`](Self::capture_preset) puts it —
274    /// which is what makes the two agree pixel-for-pixel on WARP as well as on
275    /// hardware. It also stays independent of the horizon requested, since the
276    /// first sample sits at the same frame index however long the run is.
277    pub fn capture_preset_at(
278        &mut self,
279        name: &str,
280        frame: &AnalysisFrame,
281        at_frames: &[u32],
282    ) -> Result<Vec<CaptureImage>, RenderError> {
283        self.reset_for_capture(name)?;
284        let Some(&last) = at_frames.iter().max() else {
285            return Ok(Vec::new());
286        };
287
288        let (width, height) = (self.ctx.config.width, self.ctx.config.height);
289        let format = self.ctx.surface_format();
290        let (texture, view) = capture::create_target(&self.ctx.device, format, width, height);
291        let mut readback: Option<(wgpu::Buffer, u32)> = None;
292
293        let mut captured: Vec<(u32, CaptureImage)> = Vec::with_capacity(at_frames.len());
294        for index in 0..=last {
295            self.time += scenes::FALLBACK_DT;
296            if !at_frames.contains(&index) {
297                self.step_offscreen(frame, &view, width, height, scenes::FALLBACK_DT);
298                continue;
299            }
300            let slot = readback
301                .get_or_insert_with(|| capture::create_readback(&self.ctx.device, width, height));
302            let (buffer, padded_bpr) = (&slot.0, slot.1);
303            let mut encoder =
304                self.ctx
305                    .device
306                    .create_command_encoder(&wgpu::CommandEncoderDescriptor {
307                        label: Some("rlx-capture-at"),
308                    });
309            capture::record_clear(&mut encoder, &view);
310            let _ = self.draw_frame(
311                frame,
312                &mut encoder,
313                &view,
314                (width, height),
315                scenes::FALLBACK_DT,
316                SaltMode::Pinned,
317            );
318            capture::record_copy(&mut encoder, &texture, buffer, padded_bpr, width, height);
319            self.ctx.queue.submit(std::iter::once(encoder.finish()));
320
321            #[cfg(feature = "text")]
322            self.text_layer.end_frame();
323
324            let img = capture::read_back(&self.ctx.device, buffer, width, height, padded_bpr)?;
325            captured.push((index, img));
326        }
327
328        at_frames
329            .iter()
330            .map(|idx| {
331                captured
332                    .iter()
333                    .find(|(i, _)| i == idx)
334                    .map(|(_, img)| img.clone())
335                    .ok_or(RenderError::CaptureReadback)
336            })
337            .collect()
338    }
339
340    /// Render preset `name` for `frames` frames at an **injected** `dt`, handing
341    /// each frame to `sink` the moment it is read back (Plan 0101 / ADR-0114) —
342    /// the **streaming** primitive, and the one an offline video render needs.
343    ///
344    /// Its three siblings all return a `Vec<CaptureImage>`, which is exactly what
345    /// a video render cannot afford: a 1080p frame is 8.29 MB, so a four-minute
346    /// track at 60 fps is 119 GB of retained images. Nothing is retained here —
347    /// the frame is handed to `sink` and dropped, so the resident set of a
348    /// 14,400-frame render is the same as a 100-frame one.
349    ///
350    /// It is also the only capture entry point whose step is **not** the fixed
351    /// `FALLBACK_DT`. A render at `--fps 30` advances the
352    /// scene by 1/30 s a frame, or the visuals would run at half speed against
353    /// their own soundtrack; that `dt` is the caller's, exactly as it is for the
354    /// live frontend (ADR-0013). At 60 fps `dt` *is* `FALLBACK_DT`, which is what
355    /// makes a rendered frame comparable with every other capture this repo takes.
356    ///
357    /// `analysis` supplies the [`AnalysisFrame`] for each frame index. The audio
358    /// hop clock and the frame clock are different clocks and only the caller
359    /// knows the mapping between them, so this deliberately does not walk PCM —
360    /// unlike [`capture_audio`](Self::capture_audio), which welds one rendered
361    /// frame to one analysis hop.
362    ///
363    /// Deterministic on the same terms as its siblings: scenes rebuilt to their
364    /// seed, the clock reset to `0.0`, the salt pinned. Given a deterministic
365    /// `analysis` the whole run is a pure function of `(name, frames, dt)`.
366    ///
367    /// **Off the hot path** — it blocks on a GPU readback every frame, which is
368    /// also what bounds its memory: `read_back` polls, so each frame's submission
369    /// is retired before the next is encoded (the retention Plan 0099 measured).
370    /// The target and the readback buffer are built **once** and reused, so a
371    /// long run allocates no GPU resources mid-sequence.
372    ///
373    /// A `sink` error stops the run and comes back as
374    /// [`RenderError::Sink`] carrying the consumer's own
375    /// message.
376    pub fn capture_stream(
377        &mut self,
378        name: &str,
379        frames: u32,
380        dt: f32,
381        analysis: &mut dyn FnMut(u32) -> AnalysisFrame,
382        sink: &mut dyn FnMut(u32, &CaptureImage) -> Result<(), String>,
383    ) -> Result<(), RenderError> {
384        self.reset_for_capture(name)?;
385
386        let (width, height) = (self.ctx.config.width, self.ctx.config.height);
387        let format = self.ctx.surface_format();
388        let (texture, view) = capture::create_target(&self.ctx.device, format, width, height);
389        let (buffer, padded_bpr) = capture::create_readback(&self.ctx.device, width, height);
390
391        for index in 0..frames {
392            let frame = analysis(index);
393            self.time += dt;
394            let mut encoder =
395                self.ctx
396                    .device
397                    .create_command_encoder(&wgpu::CommandEncoderDescriptor {
398                        label: Some("rlx-capture-stream"),
399                    });
400            capture::record_clear(&mut encoder, &view);
401            let _ = self.draw_frame(
402                &frame,
403                &mut encoder,
404                &view,
405                (width, height),
406                dt,
407                SaltMode::Pinned,
408            );
409            capture::record_copy(&mut encoder, &texture, &buffer, padded_bpr, width, height);
410            self.ctx.queue.submit(std::iter::once(encoder.finish()));
411
412            #[cfg(feature = "text")]
413            self.text_layer.end_frame();
414
415            let img = capture::read_back(&self.ctx.device, &buffer, width, height, padded_bpr)?;
416            sink(index, &img).map_err(RenderError::Sink)?;
417        }
418        Ok(())
419    }
420
421    /// Select `name` and reset every stateful system to its deterministic seed —
422    /// the shared preamble of [`capture_preset`](Self::capture_preset) and
423    /// [`capture_preset_over`](Self::capture_preset_over), so both are pure
424    /// functions of their arguments and neither inherits an earlier capture's
425    /// history.
426    fn reset_for_capture(&mut self, name: &str) -> Result<(), RenderError> {
427        if !self.select_preset_by_name_now(name) {
428            return Err(RenderError::UnknownPreset(name.to_string()));
429        }
430        self.scenes =
431            scenes::create_all(&self.ctx.device, COMPOSITE_FORMAT, &self.tier, self.budget);
432        self.cancel_transition();
433        self.side.reset_resources();
434        self.tonemap.reset_resources();
435        self.ink.reset_resources();
436        self.blend.reset_resources();
437        self.time = 0.0;
438        // The rebuilt scenes are fresh — re-apply the active preset's structural
439        // config (ADR-0007) so a line scene captures with its geometry built.
440        self.configure_active_scene();
441        Ok(())
442    }
443
444    /// Drive preset `name` with **real audio through the real analyzer** and
445    /// capture the frames at `at_frames` (Plan 0013). The PCM is fed hop-by-hop
446    /// into a fresh [`Analyzer`](crate::dsp::Analyzer) (format validated at the
447    /// intake boundary — the source-agnostic rule); each produced
448    /// [`AnalysisFrame`] drives one rendered frame, so `at_frames` indexes the
449    /// hop sequence (frame 0 is the first hop). Deterministic: scenes are rebuilt
450    /// to their seed and the clock resets to 0, exactly like
451    /// [`capture_preset`](Self::capture_preset).
452    ///
453    /// This is in-memory PCM only — no file, decoder, or OS audio-source code,
454    /// just like a frontend pushing samples. Returned images are in `at_frames`
455    /// order; an index past the audio length is an error.
456    pub fn capture_audio(
457        &mut self,
458        name: &str,
459        pcm: &[f32],
460        format: AudioFormat,
461        at_frames: &[u32],
462    ) -> Result<Vec<CaptureImage>, RenderError> {
463        Ok(self
464            .capture_audio_after_warmup(name, pcm, format, at_frames, 0)?
465            .images)
466    }
467
468    /// [`capture_audio`](Self::capture_audio), with the first `warmup_hops` hops
469    /// **advanced but not rasterized** (Plan 0084 Phase 3).
470    ///
471    /// A warm-up hop still pushes its samples, still publishes its
472    /// [`AnalysisFrame`], and still advances the scene clock by one
473    /// `FALLBACK_DT` — the hop happened, it just did not
474    /// draw. What it skips is the render pass, which is why a caller that only
475    /// needs the analyzer warm (`core/tests/reactivity.rs` drives
476    /// `WARMUP_HOPS` of them per capture, at silence, and reads none of them
477    /// back) stops paying a full rasterization per hop to reach a DSP state that
478    /// needs no pixels.
479    ///
480    /// **This does not warm GPU-side scene state.** Analysis is a pure function
481    /// of its window and the render pass never touches the analyzer, so the
482    /// published frames are bit-for-bit what they would have been — but a scene
483    /// that *integrates* on the GPU (particles, trails, reaction-diffusion) has
484    /// that many fewer steps behind it at the first rendered hop. Time-driven
485    /// scenes are unaffected, since the clock advances either way.
486    ///
487    /// An `at_frames` entry inside the warm-up span was never rendered and is an
488    /// error, the same one an index past the audio length gives.
489    pub fn capture_audio_after_warmup(
490        &mut self,
491        name: &str,
492        pcm: &[f32],
493        format: AudioFormat,
494        at_frames: &[u32],
495        warmup_hops: usize,
496    ) -> Result<AudioCapture, RenderError> {
497        if !self.select_preset_by_name_now(name) {
498            return Err(RenderError::UnknownPreset(name.to_string()));
499        }
500        let mut analyzer = crate::dsp::Analyzer::new(format).map_err(RenderError::AudioFormat)?;
501
502        self.scenes =
503            scenes::create_all(&self.ctx.device, COMPOSITE_FORMAT, &self.tier, self.budget);
504        self.cancel_transition();
505        self.side.reset_resources();
506        self.tonemap.reset_resources();
507        self.ink.reset_resources();
508        self.blend.reset_resources();
509        self.time = 0.0;
510        self.configure_active_scene();
511
512        let (width, height) = (self.ctx.config.width, self.ctx.config.height);
513        let target_format = self.ctx.surface_format();
514        let (texture, view) =
515            capture::create_target(&self.ctx.device, target_format, width, height);
516
517        let hop_samples = crate::dsp::HOP_SIZE * format.channels as usize;
518        let mut captured: Vec<(u32, CaptureImage)> = Vec::with_capacity(at_frames.len());
519        let mut published: Vec<AnalysisFrame> = Vec::new();
520        let mut rendered = 0usize;
521
522        for (index, hop) in pcm.chunks(hop_samples).enumerate() {
523            let frame_index = index as u32;
524            analyzer.push_interleaved(hop);
525            let analysis = analyzer.take_frame();
526            self.time += scenes::FALLBACK_DT;
527            published.push(analysis);
528
529            if index < warmup_hops {
530                continue;
531            }
532            rendered += 1;
533
534            let wanted = at_frames.contains(&frame_index)
535                && !captured.iter().any(|(i, _)| *i == frame_index);
536            if wanted {
537                let (buffer, padded_bpr) =
538                    capture::create_readback(&self.ctx.device, width, height);
539                let mut encoder =
540                    self.ctx
541                        .device
542                        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
543                            label: Some("rlx-capture-audio"),
544                        });
545                capture::record_clear(&mut encoder, &view);
546                let _ = self.draw_frame(
547                    &analysis,
548                    &mut encoder,
549                    &view,
550                    (width, height),
551                    scenes::FALLBACK_DT,
552                    SaltMode::Pinned,
553                );
554                capture::record_copy(&mut encoder, &texture, &buffer, padded_bpr, width, height);
555                self.ctx.queue.submit(std::iter::once(encoder.finish()));
556                #[cfg(feature = "text")]
557                self.text_layer.end_frame();
558                let img = capture::read_back(&self.ctx.device, &buffer, width, height, padded_bpr)?;
559                captured.push((frame_index, img));
560            } else {
561                self.step_offscreen(&analysis, &view, width, height, scenes::FALLBACK_DT);
562            }
563        }
564
565        let images = at_frames
566            .iter()
567            .map(|idx| {
568                captured
569                    .iter()
570                    .find(|(i, _)| i == idx)
571                    .map(|(_, img)| img.clone())
572                    .ok_or(RenderError::CaptureReadback)
573            })
574            .collect::<Result<Vec<_>, _>>()?;
575
576        Ok(AudioCapture {
577            images,
578            analysis: published,
579            rendered,
580        })
581    }
582
583    /// Draw one frame into `view` and submit it — advancing scene state without
584    /// reading anything back. The warm-up step [`capture_preset`] uses to reach
585    /// frame `N`.
586    ///
587    /// **It polls, and that is what bounds the memory of a long run** (Plan
588    /// 0099). Nothing else here reads anything back, so before this line the
589    /// only `device.poll` in the whole capture path was
590    /// [`capture::read_back`]'s — meaning wgpu got no opportunity to retire a
591    /// completed submission between two *sampled* frames. A horizon at the
592    /// default 30 s interval is 1,800 consecutive unpolled submits, and the
593    /// retention is per **pass**, not per pixel: measured over one such stretch
594    /// on the Windows dev box (hardware adapter, debug, 96x96), a
595    /// reaction-diffusion world — 12 simulation sub-steps plus a present, 13
596    /// passes a frame — retained **950 KB per frame** against a captured frame
597    /// of 36 KB, while single-pass worlds retained ~30 KB. That is what made
598    /// the ceiling look like a property of the RD family: every world grew, RD
599    /// grew ~32x faster and hit the allocator first, at ~4.4 GB.
600    fn step_offscreen(
601        &mut self,
602        frame: &AnalysisFrame,
603        view: &wgpu::TextureView,
604        width: u32,
605        height: u32,
606        dt: f32,
607    ) {
608        let mut encoder = self
609            .ctx
610            .device
611            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
612                label: Some("rlx-capture-step"),
613            });
614        capture::record_clear(&mut encoder, view);
615        let _ = self.draw_frame(
616            frame,
617            &mut encoder,
618            view,
619            (width, height),
620            dt,
621            SaltMode::Pinned,
622        );
623        self.ctx.queue.submit(std::iter::once(encoder.finish()));
624
625        // Retire this submission's resources. `wait_indefinitely` rather than a
626        // non-blocking `Poll`, and that was **measured, not assumed**: a
627        // `PollType::Poll` here took the same 3,600-frame stretch from
628        // 3,668 MB to 3,188 MB and no further, because a headless loop submits
629        // far faster than the GPU drains and a non-blocking poll finds almost
630        // nothing complete to retire. Waiting is what makes the retention
631        // per-frame instead of per-run.
632        //
633        // It is the same `poll(Wait)` `capture::read_back` already performs at
634        // every sampled frame, so this path pays what the sampled path always
635        // paid — and this whole file is off the hot path by construction (see
636        // the module docs); nothing in the frame loop or behind the C ABI
637        // reaches it.
638        //
639        // The result is discarded for the same reason `draw_frame`'s is above —
640        // this returns nothing, and a poll that fails means the device is gone,
641        // which the next `read_back` reports as `CaptureReadback` rather than
642        // letting the run pass silently.
643        let _ = self.ctx.device.poll(wgpu::PollType::wait_indefinitely());
644
645        #[cfg(feature = "text")]
646        self.text_layer.end_frame();
647    }
648}
649
650// ---------------------------------------------------------------------------
651// The sustained frame tap (Plan 0115 Phase 2)
652// ---------------------------------------------------------------------------
653
654impl Renderer {
655    /// Open a [`FrameTap`] sized to this renderer's configured target — the one
656    /// GPU allocation a tapped run makes, so the per-frame path makes none.
657    ///
658    /// The tap is fixed at the size it is built with. A [`resize`](Renderer::resize)
659    /// underneath a live tap leaves the two disagreeing, and the tap wins: it is
660    /// what [`render_tapped`](Self::render_tapped) draws and copies against.
661    /// Reopen after a resize to follow it.
662    ///
663    /// Infallible: `RenderContext` floors both dimensions at 1 where the size
664    /// enters, so there is nothing left to reject here.
665    pub fn open_tap(&self) -> FrameTap {
666        FrameTap::new(
667            &self.ctx.device,
668            self.ctx.surface_format(),
669            self.ctx.config.width,
670            self.ctx.config.height,
671        )
672    }
673
674    /// Advance the scene clock by `dt` real seconds, draw the active preset for
675    /// `frame` through the same `draw_frame` the window presents through, and
676    /// read the result back out of `tap`.
677    ///
678    /// `dt` is **per call**, which is the difference between this and
679    /// [`capture_stream`](Self::capture_stream)'s one fixed step: a caller that
680    /// falls behind the wall clock yields fewer, correctly-timed frames rather
681    /// than a picture running slow against the music.
682    ///
683    /// Draws under `SaltMode::Live`, because a tap is a live render path and
684    /// not a capture: a preset declaring `seed = "random"` (ADR-0051) must vary
685    /// per launch here exactly as it does in the window. Both salts are equal for
686    /// every preset that declares anything else, which is why a tapped frame and
687    /// a [`capture_frame`](Self::capture_frame) of the same preset at the same
688    /// clock are still byte-identical (`core/tests/frame_tap.rs`).
689    ///
690    /// **Blocks on the readback**, as every path through
691    /// `capture::read_back` does. That is what bounds a
692    /// long run's memory — the poll retires each frame's submission before the
693    /// next is encoded (the retention Plan 0099 measured) — and it is why this is
694    /// a *source* entry point and not a display one: there is no present deadline
695    /// here, only throughput.
696    pub fn render_tapped(
697        &mut self,
698        tap: &mut FrameTap,
699        frame: &AnalysisFrame,
700        dt: f32,
701    ) -> Result<CaptureImage, RenderError> {
702        let (width, height) = (tap.width, tap.height);
703        self.time += dt;
704        let mut encoder = self
705            .ctx
706            .device
707            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
708                label: Some("rlx-frame-tap"),
709            });
710        capture::record_clear(&mut encoder, &tap.view);
711        let _ = self.draw_frame(
712            frame,
713            &mut encoder,
714            &tap.view,
715            (width, height),
716            dt,
717            SaltMode::Live,
718        );
719        capture::record_copy(
720            &mut encoder,
721            &tap.texture,
722            &tap.buffer,
723            tap.padded_bpr,
724            width,
725            height,
726        );
727        self.ctx.queue.submit(std::iter::once(encoder.finish()));
728
729        #[cfg(feature = "text")]
730        self.text_layer.end_frame();
731
732        capture::read_back(&self.ctx.device, &tap.buffer, width, height, tap.padded_bpr)
733    }
734}