Skip to main content

alpha2_render/
renderer.rs

1use crate::{BlendSpace, Color, RenderError, RenderSize, RenderedTexture};
2use alpha2_gpu::GpuContext;
3use alpha2_gpu::IntermediateFormat;
4use alpha2_gpu::SubmitTimings;
5use std::sync::{Arc, Mutex};
6use std::time::Duration;
7
8/// Renders graphs of sources, effects, transitions and composites on one GPU
9/// device, and owns the pipelines, pools and caches they use.
10#[derive(Debug)]
11pub struct Renderer {
12    pub(crate) gpu: GpuContext,
13    pub(crate) blend_space: BlendSpace,
14    pub(crate) effects: std::sync::RwLock<crate::registry::EffectRegistry>,
15    pub(crate) effect_resources: std::sync::RwLock<crate::effect_resource::EffectResourceRegistry>,
16    pub(crate) textures: crate::Shared<crate::pool::TexturePool>,
17    pub(crate) upload_textures: crate::Shared<crate::pool::UploadTexturePool>,
18    /// Device memory budget in bytes, 0 when unknown.
19    pub(crate) gpu_memory_budget: std::sync::atomic::AtomicU64,
20    pub(crate) readback_buffers: crate::Shared<crate::pool::ReadbackBufferPool>,
21    pub(crate) uniform_buffers: crate::Shared<crate::uniform::UniformBufferPool>,
22    pub(crate) retirement: crate::Shared<crate::retire::Retirement>,
23    pub(crate) pipelines: crate::pipeline::PipelineCache,
24    pub(crate) diagnostics: crate::diagnostics::SharedDiagnostics,
25    pub(crate) quality: Mutex<QualityState>,
26    pub(crate) result_cache: Mutex<crate::result_cache::ResultCache>,
27    pub(crate) vector_state: Mutex<crate::vector::VectorState>,
28    pub(crate) timestamp_probe: std::sync::OnceLock<Option<crate::runtime_effect::TimestampProbe>>,
29    /// Timestamp queries for sampled export frames, created on first use.
30    pub(crate) frame_gpu_timer: std::sync::OnceLock<Option<crate::frame_gpu_time::FrameGpuTimer>>,
31    pub(crate) pass_timing: std::sync::atomic::AtomicBool,
32    /// Test-only: composite every layer full-frame as the culling reference.
33    #[cfg(test)]
34    pub(crate) full_frame_layers: std::sync::atomic::AtomicBool,
35    /// Test-only: max layers per composite pass when nonzero (1 = batching reference).
36    #[cfg(test)]
37    pub(crate) composite_batch_limit: std::sync::atomic::AtomicUsize,
38    /// Test-only: tile rows per vector atlas page when nonzero.
39    #[cfg(test)]
40    pub(crate) vector_page_rows: std::sync::atomic::AtomicU32,
41    /// Test-only: composite pipeline log.
42    #[cfg(test)]
43    pub(crate) composite_pipelines: Mutex<crate::composite::CompositePipelineLog>,
44    /// Test-only: the next lazily created composite or effect pipeline fails to create.
45    #[cfg(test)]
46    pub(crate) fail_next_pipeline: std::sync::atomic::AtomicBool,
47    pub(crate) retired_leases: Arc<crate::yuv::RetiredLeases>,
48    pub(crate) gpu_wait_timeout: Duration,
49    /// Read once because every field read crosses into JavaScript on the browser backend.
50    pub(crate) limits: wgpu::Limits,
51    pub(crate) features: wgpu::Features,
52    /// Bound to a generator's unused image inputs.
53    pub(crate) empty_input: wgpu::TextureView,
54    pub(crate) canaries: crate::canary::Canaries,
55    pub(crate) submission_canaries: crate::canary::SubmissionCanaries,
56    /// GPU errors the embedding saw outside the renderer's own scopes.
57    pub(crate) gpu_errors: crate::GpuErrorReports,
58    pub(crate) frame_lock: crate::Shared<FrameLock>,
59    pub(crate) submission_clock: Arc<crate::submission_clock::SubmissionClock>,
60    pub(crate) last_frame_submissions: Mutex<Option<crate::FrameSubmissions>>,
61    pub(crate) calibration: std::sync::OnceLock<crate::registry::RegisteredEffect>,
62}
63
64/// A command encoder open until submitted.
65///
66/// Pooled resources released meanwhile are destroyed only after submission (see
67/// [`crate::retire`]). It also holds the frame's error scopes, so it must stay on the creating
68/// thread, and the [`FrameLock`]. A heavy frame may be split into several command buffers
69/// ([`crate::submission_planner`]); finished ones wait here for the submission.
70#[derive(Debug)]
71pub(crate) struct RenderEncoder {
72    encoder: wgpu::CommandEncoder,
73    finished: Vec<wgpu::CommandBuffer>,
74    planner: crate::submission_planner::SubmissionPlanner,
75    device: wgpu::Device,
76    label: &'static str,
77    errors: crate::gpu_errors::FrameErrorScope,
78    scope: crate::retire::EncodeScope,
79    frame: FrameGuard,
80}
81
82/// Lets one thread at a time record and submit renderer work.
83///
84/// A graph returns intermediates to the pool once their last reader is encoded, while the
85/// passes that wrote them are still unsubmitted. Holding this lock from encoder creation to
86/// submission stops another thread from reusing such a texture and submitting first.
87/// Re-entrant for the holding thread.
88#[derive(Debug, Default)]
89pub(crate) struct FrameLock {
90    owner: Mutex<Option<(std::thread::ThreadId, usize)>>,
91    released: std::sync::Condvar,
92}
93
94#[derive(Debug)]
95pub(crate) struct FrameGuard {
96    lock: crate::Shared<FrameLock>,
97}
98
99impl FrameLock {
100    pub(crate) fn hold(self: &crate::Shared<Self>) -> FrameGuard {
101        let me = std::thread::current().id();
102        let mut owner = self
103            .owner
104            .lock()
105            .unwrap_or_else(std::sync::PoisonError::into_inner);
106        loop {
107            match owner.as_mut() {
108                None => {
109                    *owner = Some((me, 1));
110                    break;
111                }
112                Some((thread, depth)) if *thread == me => {
113                    *depth += 1;
114                    break;
115                }
116                Some(_) => {
117                    owner = self
118                        .released
119                        .wait(owner)
120                        .unwrap_or_else(std::sync::PoisonError::into_inner);
121                }
122            }
123        }
124        drop(owner);
125        FrameGuard {
126            lock: crate::Shared::clone(self),
127        }
128    }
129}
130
131impl Drop for FrameGuard {
132    fn drop(&mut self) {
133        let mut owner = self
134            .lock
135            .owner
136            .lock()
137            .unwrap_or_else(std::sync::PoisonError::into_inner);
138        if let Some((_, depth)) = owner.as_mut() {
139            *depth -= 1;
140            if *depth == 0 {
141                *owner = None;
142                drop(owner);
143                self.lock.released.notify_all();
144            }
145        }
146    }
147}
148
149impl std::ops::Deref for RenderEncoder {
150    type Target = wgpu::CommandEncoder;
151
152    fn deref(&self) -> &Self::Target {
153        &self.encoder
154    }
155}
156
157impl std::ops::DerefMut for RenderEncoder {
158    fn deref_mut(&mut self) -> &mut Self::Target {
159        &mut self.encoder
160    }
161}
162
163impl RenderEncoder {
164    pub(crate) fn finish(self) -> RenderCommands {
165        let mut buffers = self.finished;
166        buffers.push(self.encoder.finish());
167        RenderCommands {
168            buffers,
169            planner: self.planner,
170            errors: self.errors,
171            scope: self.scope,
172            frame: self.frame,
173        }
174    }
175
176    pub(crate) const fn planner(&mut self) -> &mut crate::submission_planner::SubmissionPlanner {
177        &mut self.planner
178    }
179
180    /// Charges a pass to the plan and places it, finishing the command buffer first when the plan
181    /// says so.
182    pub(crate) fn place_pass(
183        &mut self,
184        cost: crate::effect_cost::EffectCost,
185        pixels: u64,
186        bandable: bool,
187        pass: Option<alpha2_gpu::PassKey>,
188    ) -> crate::submission_planner::PassPlacement {
189        let placement = self.planner.pass(cost, pixels, bandable, pass);
190        if placement.cut_before {
191            self.cut();
192        }
193        placement
194    }
195
196    pub(crate) fn next_band(&mut self) {
197        self.planner.next_band();
198        self.cut();
199    }
200
201    fn cut(&mut self) {
202        #[allow(clippy::disallowed_methods)]
203        let next = self
204            .device
205            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
206                label: Some(self.label),
207            });
208        let done = std::mem::replace(&mut self.encoder, next);
209        self.finished.push(done.finish());
210    }
211}
212
213#[derive(Debug)]
214pub(crate) struct RenderCommands {
215    buffers: Vec<wgpu::CommandBuffer>,
216    planner: crate::submission_planner::SubmissionPlanner,
217    errors: crate::gpu_errors::FrameErrorScope,
218    scope: crate::retire::EncodeScope,
219    frame: FrameGuard,
220}
221
222/// Classifies a loss by the submission times of its renderer.
223#[derive(Clone, Debug)]
224pub struct LossClassifier(Arc<crate::submission_clock::SubmissionClock>);
225
226impl LossClassifier {
227    /// Classifies `error` as [`Renderer::classify_loss`] does.
228    #[must_use]
229    pub fn classify(&self, error: RenderError) -> RenderError {
230        match error {
231            RenderError::GpuWorkDropped
232            | RenderError::GpuDeviceLost
233            | RenderError::GpuTimeout
234            | RenderError::ExternalTextureSync(Some(alpha2_media::GpuFault::DeviceLost)) => self
235                .0
236                .hung()
237                .map_or(error, |report| crate::canary::hung_error(&report)),
238            error => error,
239        }
240    }
241
242    /// The recent submission that kept the GPU busy longest.
243    #[must_use]
244    pub fn longest_submission(&self) -> Option<crate::SubmissionReport> {
245        self.0.longest()
246    }
247}
248
249struct SubmittedBuffers {
250    index: wgpu::SubmissionIndex,
251    timings: SubmitTimings,
252    sequences: std::ops::Range<u64>,
253    first: (web_time::Instant, crate::submission_clock::Recorded),
254}
255
256pub(crate) struct MeasuredSubmit {
257    pub(crate) submission: crate::submission_clock::ClockedSubmission,
258    pub(crate) sequences: std::ops::Range<u64>,
259    pub(crate) queue_idle: bool,
260    pub(crate) timings: SubmitTimings,
261    pub(crate) lease_retire: Duration,
262}
263
264/// Quality controls consumed by graph compilation and pass execution.
265#[derive(Copy, Clone, Debug, Eq, PartialEq)]
266#[non_exhaustive]
267pub struct RenderQualityControls {
268    /// Maximum samples for filter effects and layer minification. Analytic edge coverage stays
269    /// on even with a one-sample budget.
270    pub max_filter_samples: u32,
271    /// Temporal samples used by motion-aware runners.
272    pub motion_blur_subframes: u32,
273}
274
275impl RenderQualityControls {
276    /// Upper bound on filter samples; every pass caps there, so a larger budget changes nothing.
277    pub const MAX_FILTER_SAMPLES: u32 = 64;
278}
279
280impl Default for RenderQualityControls {
281    fn default() -> Self {
282        Self {
283            max_filter_samples: Self::MAX_FILTER_SAMPLES,
284            motion_blur_subframes: 1,
285        }
286    }
287}
288
289#[derive(Copy, Clone, Debug)]
290pub(crate) struct QualityState {
291    applied: RenderQualityControls,
292    requested_filter_samples: u32,
293}
294
295impl QualityState {
296    fn new(limit: u32) -> Self {
297        let requested = RenderQualityControls::default();
298        Self {
299            applied: RenderQualityControls {
300                max_filter_samples: requested.max_filter_samples.min(limit),
301                ..requested
302            },
303            requested_filter_samples: requested.max_filter_samples,
304        }
305    }
306}
307
308impl Renderer {
309    pub(crate) fn validate_size(&self, size: RenderSize) -> Result<(), RenderError> {
310        RenderSize::new(size.width, size.height)?;
311        let maximum = self.limits.max_texture_dimension_2d;
312        if size.width > maximum || size.height > maximum {
313            return Err(RenderError::DimensionTooLarge);
314        }
315        Ok(())
316    }
317
318    /// Creates a renderer that owns the supplied GPU context.
319    #[must_use]
320    pub fn new(gpu: GpuContext) -> Self {
321        #[allow(clippy::disallowed_methods)]
322        let limits = gpu.device().limits();
323        let uniform_alignment = u64::from(limits.min_uniform_buffer_offset_alignment.max(1));
324        let features = gpu.device().features();
325        let filter_sample_limit = crate::filter_sample_limit(gpu.capabilities().tier);
326        let retirement = crate::Shared::new(crate::retire::Retirement::default());
327        let gpu_errors = crate::GpuErrorReports::default();
328        let submission_clock = Arc::new(crate::submission_clock::SubmissionClock::default());
329        let canaries = crate::canary::Canaries::new(
330            gpu_errors.clone(),
331            &retirement,
332            Arc::clone(&submission_clock),
333        );
334        let empty_input =
335            crate::pool::default_view(&gpu.device().create_texture(&wgpu::TextureDescriptor {
336                label: Some("alpha2 generator empty input"),
337                size: wgpu::Extent3d {
338                    width: 1,
339                    height: 1,
340                    depth_or_array_layers: 1,
341                },
342                mip_level_count: 1,
343                sample_count: 1,
344                dimension: wgpu::TextureDimension::D2,
345                format: wgpu::TextureFormat::Rgba8Unorm,
346                usage: wgpu::TextureUsages::TEXTURE_BINDING,
347                view_formats: &[],
348            }));
349        Self {
350            gpu,
351            blend_space: BlendSpace::default(),
352            effects: std::sync::RwLock::default(),
353            effect_resources: std::sync::RwLock::default(),
354            textures: crate::Shared::new(crate::pool::TexturePool::new(crate::Shared::clone(
355                &retirement,
356            ))),
357            upload_textures: crate::Shared::new(crate::pool::UploadTexturePool::new(
358                crate::Shared::clone(&retirement),
359            )),
360            gpu_memory_budget: std::sync::atomic::AtomicU64::new(0),
361            readback_buffers: crate::Shared::new(crate::pool::ReadbackBufferPool::new(
362                crate::Shared::clone(&retirement),
363            )),
364            uniform_buffers: crate::Shared::new(crate::uniform::UniformBufferPool::new(
365                uniform_alignment,
366                crate::Shared::clone(&retirement),
367            )),
368            retirement,
369            pipelines: crate::pipeline::PipelineCache::default(),
370            diagnostics: Arc::new(Mutex::new(crate::diagnostics::DiagnosticsState::default())),
371            quality: Mutex::new(QualityState::new(filter_sample_limit)),
372            result_cache: Mutex::new(crate::result_cache::ResultCache::default()),
373            vector_state: Mutex::default(),
374            timestamp_probe: std::sync::OnceLock::new(),
375            frame_gpu_timer: std::sync::OnceLock::new(),
376            pass_timing: std::sync::atomic::AtomicBool::new(false),
377            #[cfg(test)]
378            full_frame_layers: std::sync::atomic::AtomicBool::new(false),
379            #[cfg(test)]
380            composite_batch_limit: std::sync::atomic::AtomicUsize::new(0),
381            #[cfg(test)]
382            vector_page_rows: std::sync::atomic::AtomicU32::new(0),
383            #[cfg(test)]
384            composite_pipelines: Mutex::new(crate::composite::CompositePipelineLog::default()),
385            #[cfg(test)]
386            fail_next_pipeline: std::sync::atomic::AtomicBool::new(false),
387            retired_leases: Arc::new(crate::yuv::RetiredLeases::default()),
388            gpu_wait_timeout: crate::error::DEFAULT_GPU_WAIT_TIMEOUT,
389            limits,
390            features,
391            empty_input,
392            canaries,
393            submission_canaries: crate::canary::SubmissionCanaries::default(),
394            gpu_errors,
395            frame_lock: crate::Shared::default(),
396            submission_clock,
397            last_frame_submissions: Mutex::new(None),
398            calibration: std::sync::OnceLock::new(),
399        }
400    }
401
402    /// `None` on a device without timestamp queries, and in a browser.
403    pub(crate) fn frame_gpu_timer(&self) -> Option<&crate::frame_gpu_time::FrameGpuTimer> {
404        self.frame_gpu_timer
405            .get_or_init(|| {
406                (cfg!(not(target_arch = "wasm32"))
407                    && self.features.contains(wgpu::Features::TIMESTAMP_QUERY))
408                .then(|| {
409                    crate::frame_gpu_time::FrameGpuTimer::new(self.gpu.device(), self.gpu.queue())
410                })
411            })
412            .as_ref()
413    }
414
415    /// GPU time of the export frames sampled since the last call, then resets the totals.
416    ///
417    /// Every eighth frame of [`Self::render_graph_nv12_timed`] or
418    /// [`Self::render_graph_yuv420p_timed`] is timed and read back later without waiting.
419    ///
420    /// # Errors
421    /// The device has no timestamp queries.
422    pub fn take_frame_gpu_times(&self) -> Result<crate::FrameGpuTimes, &'static str> {
423        let timer = self
424            .frame_gpu_timer()
425            .ok_or("the device has no timestamp queries")?;
426        let _ = self.gpu.device().poll(wgpu::PollType::Poll);
427        Ok(timer.take())
428    }
429
430    /// Where an embedding reports errors from its uncaptured-error handler.
431    ///
432    /// Needed only in a browser, where error scopes resolve after the frame returns. After a
433    /// report the renderer drops its cached results and pooled resources, and treats a missing
434    /// readback canary as that error rather than as dropped work.
435    #[must_use]
436    pub fn gpu_error_reports(&self) -> crate::GpuErrorReports {
437        self.gpu_errors.clone()
438    }
439
440    /// This renderer, using `reports` for GPU errors the embedding saw before it existed.
441    #[must_use]
442    pub fn with_gpu_error_reports(mut self, reports: crate::GpuErrorReports) -> Self {
443        self.canaries.clear();
444        self.canaries = crate::canary::Canaries::new(
445            reports.clone(),
446            &self.retirement,
447            Arc::clone(&self.submission_clock),
448        );
449        self.gpu_errors = reports;
450        self
451    }
452
453    /// Drops pooled resources after the GPU reported an error that may involve them.
454    fn forget_untrusted_resources(&self) {
455        self.retirement.doubt();
456        self.textures.clear();
457        self.upload_textures.clear();
458        self.readback_buffers.clear();
459        self.uniform_buffers.clear();
460        self.canaries.clear();
461    }
462
463    /// Tier, intermediate format, adapter and limits of the GPU.
464    #[must_use]
465    pub fn gpu_capabilities(&self) -> &alpha2_gpu::Capabilities {
466        self.gpu.capabilities()
467    }
468
469    /// The device's limits.
470    #[must_use]
471    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
472    pub const fn limits(&self) -> &wgpu::Limits {
473        &self.limits
474    }
475
476    /// Sets how long a native GPU wait may take before [`RenderError::GpuTimeout`].
477    pub fn set_gpu_wait_timeout(&mut self, timeout: Duration) {
478        self.gpu_wait_timeout = timeout;
479    }
480
481    /// Why the device can no longer run work, once known.
482    ///
483    /// Either a readback canary showed dropped work ([`RenderError::GpuWorkDropped`]) or resources
484    /// could no longer be created ([`RenderError::GpuDeviceLost`]). Later readbacks and NV12 packs
485    /// fail with this error; a host should report it and restart the process.
486    #[must_use]
487    pub fn gpu_lost(&self) -> Option<RenderError> {
488        self.canaries.lost()
489    }
490
491    /// Marks the frame later submissions render, for [`RenderError::GpuDeviceHung`] reports.
492    pub fn mark_frame(&self, frame: Option<crate::FrameMark>) {
493        self.submission_clock.mark_frame(frame);
494    }
495
496    /// The recent submission, possibly still running, that kept the GPU busy longest.
497    #[must_use]
498    pub fn longest_submission(&self) -> Option<crate::SubmissionReport> {
499        self.submission_clock.longest()
500    }
501
502    /// Classifies `error` using this renderer's submission times.
503    ///
504    /// A device loss or timeout becomes [`RenderError::GpuDeviceHung`] when a recent submission
505    /// ran for at least half the GPU watchdog ([`alpha2_gpu::hung_threshold_ms`]). Other errors
506    /// pass through.
507    #[must_use]
508    pub fn classify_loss(&self, error: RenderError) -> RenderError {
509        self.loss_classifier().classify(error)
510    }
511
512    /// [`Renderer::classify_loss`] as an owned handle, for readbacks finished on an event loop.
513    #[must_use]
514    pub fn loss_classifier(&self) -> LossClassifier {
515        LossClassifier(Arc::clone(&self.submission_clock))
516    }
517
518    pub(crate) fn ensure_gpu_runs_work(&self) -> Result<(), RenderError> {
519        self.canaries.lost().map_or(Ok(()), Err)
520    }
521
522    /// Checks canaries of earlier NV12 packs and repacks that have mapped, without waiting.
523    pub(crate) fn check_submitted_work(&self) -> Result<(), RenderError> {
524        // Map callbacks run only on poll; a hardware-encoder frame loop may not poll otherwise.
525        let _ = self.gpu.device().poll(wgpu::PollType::Poll);
526        self.submission_canaries.check_mapped()?;
527        self.ensure_gpu_runs_work()
528    }
529
530    /// Waits for every submitted NV12 pack and repack and checks that the GPU ran it.
531    ///
532    /// These submissions read nothing back, so a canary is the only proof the planes were written.
533    /// Exports call this after the last frame. Safe while another thread polls the device (the
534    /// macOS `VideoToolbox` worker does).
535    ///
536    /// # Errors
537    /// [`RenderError::GpuWorkDropped`] when a canary is missing, or [`RenderError::GpuTimeout`]
538    /// when work or a mapping report does not arrive in time.
539    #[cfg(not(target_arch = "wasm32"))]
540    pub fn confirm_gpu_work(&self) -> Result<(), RenderError> {
541        let deadline = web_time::Instant::now() + self.gpu_wait_timeout;
542        self.gpu
543            .device()
544            .poll(wgpu::PollType::Wait {
545                submission_index: None,
546                timeout: Some(self.gpu_wait_timeout),
547            })
548            .map_err(crate::error::poll_error)?;
549        let settled = self.settle(&self.submission_canaries.reports, deadline, || {
550            self.check_submitted_work()?;
551            Ok(self.submission_canaries.outstanding() == 0)
552        })?;
553        if settled {
554            Ok(())
555        } else {
556            Err(RenderError::GpuTimeout)
557        }
558    }
559
560    /// How long a native wait on GPU work may take.
561    #[must_use]
562    pub const fn gpu_wait_timeout(&self) -> Duration {
563        self.gpu_wait_timeout
564    }
565
566    /// Releases every native lease whose GPU work has finished, returning how many.
567    ///
568    /// A decoder surface returns only after the submission sampling it completes, so a caller out
569    /// of surface budget can call this and retry. Unsubmitted work is not waited on.
570    ///
571    /// # Errors
572    /// A readback error if the device cannot be polled.
573    #[cfg(not(target_arch = "wasm32"))]
574    pub fn reclaim_external_leases(&self) -> Result<usize, RenderError> {
575        let deadline = web_time::Instant::now() + self.gpu_wait_timeout;
576        self.gpu
577            .device()
578            .poll(wgpu::PollType::Wait {
579                submission_index: None,
580                timeout: Some(self.gpu_wait_timeout),
581            })
582            .map_err(crate::error::poll_error)?;
583        self.settle(&self.retired_leases.parks, deadline, || {
584            Ok(self.retired_leases.awaited() == 0)
585        })?;
586        Ok(self.retired_leases.drain())
587    }
588
589    /// Submits command buffers, then releases completed native leases.
590    ///
591    /// Leases must not be released inside `wgpu`'s submit: a shared-queue backend holds the decoder
592    /// queue lock there, and freeing a frame takes `FFmpeg`'s frame lock, which `FFmpeg` decode
593    /// threads take in the opposite order.
594    ///
595    /// # Errors
596    /// [`RenderError::Gpu`] when a scope caught an error; then nothing in the submission ran.
597    pub(crate) fn submit<I>(
598        &self,
599        commands: I,
600    ) -> Result<crate::submission_clock::ClockedSubmission, RenderError>
601    where
602        I: IntoIterator<Item = RenderCommands>,
603    {
604        self.submit_measured(commands, false)
605            .map(|submitted| submitted.submission)
606    }
607
608    /// Opens a command encoder and the error scopes its submission closes.
609    ///
610    /// Open it before acquiring the frame's targets so a failed allocation is the frame's error.
611    pub(crate) fn command_encoder(&self, label: &'static str) -> RenderEncoder {
612        if self.gpu_errors.take_unhandled() {
613            // The browser reported an error for earlier work; cached results may be bad.
614            self.clear_result_cache_for(crate::CacheInvalidation::GpuError);
615            self.forget_untrusted_resources();
616        }
617        // Wait for other frames before opening any scope of this one.
618        let frame = self.frame_lock.hold();
619        // Open first so nothing the encoder uses can be destroyed under it.
620        let scope = self.retirement.open();
621        let errors = crate::gpu_errors::FrameErrorScope::open(
622            self.gpu.device(),
623            crate::Shared::clone(&self.retirement),
624        );
625        #[allow(clippy::disallowed_methods)] // The one place a renderer encoder is created.
626        let encoder = self
627            .gpu
628            .device()
629            .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some(label) });
630        RenderEncoder {
631            encoder,
632            finished: Vec::new(),
633            planner: crate::submission_planner::SubmissionPlanner::default(),
634            device: self.gpu.device().clone(),
635            label,
636            errors,
637            scope,
638            frame,
639        }
640    }
641
642    /// Defers destruction of released pool resources until the returned scope is dropped.
643    pub(crate) fn open_encode(&self) -> crate::retire::EncodeScope {
644        self.retirement.open()
645    }
646
647    /// Submits and reports the queue wait, submit and lease drain times.
648    ///
649    /// With `measure` false every span is zero; the submission clock still records it.
650    ///
651    /// # Errors
652    /// [`RenderError::Gpu`] when a scope caught an error; pooled resources are no longer trusted.
653    pub(crate) fn submit_measured<I>(
654        &self,
655        commands: I,
656        measure: bool,
657    ) -> Result<MeasuredSubmit, RenderError>
658    where
659        I: IntoIterator<Item = RenderCommands>,
660    {
661        let mut command_buffers = Vec::new();
662        let mut errors = Vec::new();
663        let mut scopes = Vec::new();
664        let mut frames = Vec::new();
665        let mut planners = Vec::new();
666        for commands in commands {
667            command_buffers.extend(commands.buffers.into_iter().map(|buffer| (buffer, None)));
668            if let Some(buffer_ms) = commands.planner.buffer_ms() {
669                let first = command_buffers.len() - buffer_ms.len();
670                for (slot, ms) in command_buffers[first..].iter_mut().zip(buffer_ms) {
671                    slot.1 = Some(ms);
672                }
673            }
674            planners.push(commands.planner);
675            errors.push(commands.errors);
676            scopes.push(commands.scope);
677            frames.push(commands.frame);
678        }
679        let watch_previous = planners
680            .iter()
681            .any(|planner| planner.is_frame() && planner.is_planned());
682        let submitted = self.submit_buffers(command_buffers, measure, watch_previous);
683        self.note_frame_submissions(&planners, &submitted);
684        let SubmittedBuffers {
685            index,
686            timings,
687            sequences,
688            first: (_, first),
689        } = submitted;
690        let queue_idle = first.queue_idle;
691        // Scopes close after the submit, in reverse order.
692        let mut caught = None;
693        for scope in errors.into_iter().rev() {
694            caught = match (caught, scope.close()) {
695                (Some(alpha2_gpu::GpuErrorKind::OutOfMemory), _) | (_, None) => caught,
696                (_, kind) => kind,
697            };
698        }
699        drop(scopes);
700        drop(frames);
701        let drain_started = measure.then(web_time::Instant::now);
702        self.retired_leases.drain();
703        if let Some(kind) = caught {
704            self.forget_untrusted_resources();
705            return Err(RenderError::Gpu { kind });
706        }
707        Ok(MeasuredSubmit {
708            submission: crate::submission_clock::ClockedSubmission::new(
709                index,
710                Arc::clone(&self.submission_clock),
711                sequences.end - 1,
712            ),
713            sequences,
714            queue_idle,
715            timings,
716            lease_retire: drain_started.map_or(Duration::ZERO, |started| started.elapsed()),
717        })
718    }
719
720    /// Submits `buffers` in one submission, or one per buffer when the frame was split so the GPU
721    /// can be preempted between them. Every submission is timed for loss classification.
722    fn submit_buffers(
723        &self,
724        buffers: Vec<(wgpu::CommandBuffer, Option<f64>)>,
725        measure: bool,
726        watch_previous: bool,
727    ) -> SubmittedBuffers {
728        let submit =
729            |buffers: Vec<wgpu::CommandBuffer>, predicted_ms: Option<f64>, watch_previous: bool| {
730                let (index, timings) = if measure {
731                    self.gpu.submit_timed(buffers)
732                } else {
733                    (self.gpu.submit(buffers), SubmitTimings::default())
734                };
735                let at = web_time::Instant::now();
736                let recorded = self
737                    .submission_clock
738                    .record(at, predicted_ms, watch_previous);
739                let sequence = recorded.sequence;
740                let clock = Arc::clone(&self.submission_clock);
741                self.gpu.on_submitted_work_done(move || {
742                    let as_it_happens = clock.sees_as_it_happens(sequence);
743                    clock.complete(sequence, web_time::Instant::now(), as_it_happens);
744                });
745                (index, timings, sequence, (at, recorded))
746            };
747        if buffers.len() <= 1 || buffers.iter().all(|(_, ms)| ms.is_none()) {
748            let predicted_ms = buffers
749                .iter()
750                .filter_map(|(_, ms)| *ms)
751                .reduce(|a, b| a + b);
752            let (index, timings, sequence, first) = submit(
753                buffers.into_iter().map(|(buffer, _)| buffer).collect(),
754                predicted_ms,
755                watch_previous,
756            );
757            return SubmittedBuffers {
758                index,
759                timings,
760                sequences: sequence..sequence + 1,
761                first,
762            };
763        }
764        let mut total = SubmitTimings::default();
765        let mut last = None;
766        let mut first = None;
767        for (buffer, predicted_ms) in buffers {
768            let (index, timings, sequence, started) = submit(
769                vec![buffer],
770                predicted_ms,
771                watch_previous && first.is_none(),
772            );
773            total.queue_lock_wait = total
774                .queue_lock_wait
775                .saturating_add(timings.queue_lock_wait);
776            total.queue_submit = total.queue_submit.saturating_add(timings.queue_submit);
777            first.get_or_insert((sequence, started));
778            last = Some((index, sequence));
779        }
780        let (index, last_sequence) = last.expect("at least two buffers");
781        let (first_sequence, first) = first.expect("at least two buffers");
782        SubmittedBuffers {
783            index,
784            timings: total,
785            sequences: first_sequence..last_sequence + 1,
786            first,
787        }
788    }
789
790    /// Records frame submissions and folds measured GPU time into the device rate on completion.
791    fn note_frame_submissions(
792        &self,
793        planners: &[crate::submission_planner::SubmissionPlanner],
794        submitted: &SubmittedBuffers,
795    ) {
796        let Some(planner) = planners.iter().find(|planner| planner.is_frame()) else {
797            return;
798        };
799        let submissions =
800            u32::try_from(submitted.sequences.end - submitted.sequences.start).unwrap_or(u32::MAX);
801        let buffer_ms = planner.buffer_ms();
802        let report = crate::FrameSubmissions {
803            submissions,
804            predicted_ms: buffer_ms.as_ref().map(|buffers| buffers.iter().sum()),
805            cost: planner.cost(),
806        };
807        crate::diagnostics::record_frame_plan(
808            &self.diagnostics,
809            &report,
810            buffer_ms
811                .iter()
812                .flatten()
813                .copied()
814                .fold(None, |most: Option<f64>, ms| {
815                    Some(most.map_or(ms, |most| most.max(ms)))
816                }),
817        );
818        *self
819            .last_frame_submissions
820            .lock()
821            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(report);
822        if let (Some(predicted_ms), Some((planned_ms_per_unit_pixel, budget_ms))) =
823            (report.predicted_ms, planner.planned_at())
824        {
825            let clock = Arc::clone(&self.submission_clock);
826            let rate = Arc::clone(self.gpu.rate());
827            let last = submitted.sequences.end - 1;
828            let (submitted_at, first) = submitted.first.clone();
829            self.gpu.on_submitted_work_done(move || {
830                let Some(started) = first.started(submitted_at) else {
831                    return;
832                };
833                let trust = if clock.sees_as_it_happens(last) {
834                    alpha2_gpu::SpanTrust::Exact
835                } else {
836                    alpha2_gpu::SpanTrust::UpperBound
837                };
838                rate.observe(alpha2_gpu::FrameMeasurement {
839                    measured_ms: started.elapsed().as_secs_f64() * 1_000.0,
840                    predicted_ms,
841                    planned_ms_per_unit_pixel,
842                    budget_ms,
843                    trust,
844                });
845            });
846        }
847    }
848
849    /// How the last frame was submitted; each frame's is returned once.
850    pub fn take_frame_submissions(&self) -> Option<crate::FrameSubmissions> {
851        self.last_frame_submissions
852            .lock()
853            .unwrap_or_else(std::sync::PoisonError::into_inner)
854            .take()
855    }
856
857    /// Submission split counts since the last call, then resets them.
858    pub fn take_gpu_submission_stats(&self) -> crate::GpuSubmissionStats {
859        crate::diagnostics::take_gpu_submission_stats(&self.diagnostics)
860    }
861
862    /// Returns whether per-pass timing is being collected.
863    #[must_use]
864    pub fn pass_timing_enabled(&self) -> bool {
865        self.pass_timing.load(std::sync::atomic::Ordering::Relaxed)
866    }
867
868    /// Enables or disables per-pass timing collection. Disabled by default.
869    ///
870    /// While off, no clock is read and no timestamp resources are created. Turning it off drops
871    /// the retained timing history. Other diagnostics are always available.
872    pub fn set_pass_timing_enabled(&self, enabled: bool) {
873        self.pass_timing
874            .store(enabled, std::sync::atomic::Ordering::Relaxed);
875        if !enabled {
876            crate::diagnostics::end_timing_run(&self.diagnostics);
877        }
878    }
879
880    /// The timing run a pass encoded now records into, or `None` while timing is off. Read before
881    /// the flag: a run that ends after this read drops the pass's record.
882    pub(crate) fn pass_timing_epoch(&self) -> Option<u64> {
883        let epoch = crate::diagnostics::timing_epoch(&self.diagnostics);
884        self.pass_timing_enabled().then_some(epoch)
885    }
886
887    /// Capability-negotiated storage precision. Graph images hold premultiplied sRGB; layer blends
888    /// may use linear light.
889    #[must_use]
890    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
891    pub fn intermediate_format(&self) -> wgpu::TextureFormat {
892        match self.gpu.capabilities().intermediate_format {
893            IntermediateFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
894            _ => wgpu::TextureFormat::Rgba8Unorm,
895        }
896    }
897
898    /// Returns allocation and reuse counters for intermediate render targets.
899    #[must_use]
900    pub fn texture_pool_stats(&self) -> crate::TexturePoolStats {
901        self.textures.stats()
902    }
903
904    /// Acquires a pooled RGBA8 source-upload texture.
905    ///
906    /// Submissions using it must be issued before the handle is dropped so later uploads stay
907    /// queue-ordered.
908    ///
909    /// # Errors
910    /// The dimensions exceed device limits.
911    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
912    pub fn acquire_rgba8_upload_texture(
913        &self,
914        size: RenderSize,
915    ) -> Result<crate::UploadTexture, RenderError> {
916        self.validate_size(size)?;
917        Ok(self.upload_textures.acquire(
918            self.gpu.device(),
919            size,
920            wgpu::TextureFormat::Rgba8Unorm,
921            "alpha2 RGBA upload texture",
922        ))
923    }
924
925    /// Destroys all currently idle intermediate textures.
926    pub fn clear_texture_pool(&self) {
927        self.textures.clear();
928    }
929
930    /// Destroys GPU memory held only for reuse (idle pools and kept graph results) and returns the
931    /// bytes freed.
932    ///
933    /// Resources are destroyed rather than dropped so browser `WebGPU` frees them immediately.
934    /// Nothing still in use is released, and submitted work completes first, so this is safe
935    /// between calls.
936    pub fn release_idle_memory(&self) -> u64 {
937        let before = self.retirement.retired_bytes();
938        self.clear_result_cache();
939        self.textures.clear();
940        self.upload_textures.clear();
941        self.readback_buffers.clear();
942        self.uniform_buffers.clear();
943        self.canaries.clear();
944        self.vector_state
945            .lock()
946            .unwrap_or_else(std::sync::PoisonError::into_inner)
947            .cache
948            .clear();
949        self.retirement.retired_bytes().saturating_sub(before)
950    }
951
952    /// Sets the soft byte budget for idle intermediate textures, evicting down to it now.
953    pub fn set_texture_budget_bytes(&self, budget_bytes: u64) {
954        self.textures
955            .set_budget(budget_bytes.min(self.pool_budget_cap()));
956    }
957
958    /// Records the adapter's memory budget (`None` if unreported) and caps idle pools at a quarter
959    /// of it. Returns whether a pool budget was lowered.
960    pub fn set_gpu_memory_budget(&self, budget_bytes: Option<u64>) -> bool {
961        self.gpu_memory_budget.store(
962            budget_bytes.unwrap_or(0),
963            std::sync::atomic::Ordering::Relaxed,
964        );
965        let cap = self.pool_budget_cap();
966        let textures = self.textures.stats().budget_bytes;
967        let uploads = self.upload_textures.stats().budget_bytes;
968        if textures > cap {
969            self.textures.set_budget(cap);
970        }
971        if uploads > cap {
972            self.upload_textures.set_budget(cap);
973        }
974        textures > cap || uploads > cap
975    }
976
977    /// The adapter's device memory budget, when reported.
978    #[must_use]
979    pub fn gpu_memory_budget(&self) -> Option<u64> {
980        match self
981            .gpu_memory_budget
982            .load(std::sync::atomic::Ordering::Relaxed)
983        {
984            0 => None,
985            bytes => Some(bytes),
986        }
987    }
988
989    /// A quarter of the device memory budget, or unlimited when unknown.
990    fn pool_budget_cap(&self) -> u64 {
991        self.gpu_memory_budget().map_or(u64::MAX, |bytes| bytes / 4)
992    }
993
994    /// Applies filter and temporal sampling controls.
995    ///
996    /// The filter budget is capped at [`Self::filter_sample_limit`]; a reduction is reported as
997    /// [`crate::CapabilityDiagnostic::FilterSamplesReduced`]. Kept results are dropped only when
998    /// the applied values change.
999    pub fn set_quality_controls(&self, max_filter_samples: u32, motion_blur_subframes: u32) {
1000        let requested = max_filter_samples.max(1);
1001        let next = RenderQualityControls {
1002            max_filter_samples: requested.min(self.filter_sample_limit()),
1003            motion_blur_subframes: motion_blur_subframes.max(1),
1004        };
1005        let mut quality = self
1006            .quality
1007            .lock()
1008            .unwrap_or_else(std::sync::PoisonError::into_inner);
1009        quality.requested_filter_samples = requested;
1010        if quality.applied != next {
1011            quality.applied = next;
1012            self.clear_result_cache_for(crate::CacheInvalidation::Quality);
1013        }
1014    }
1015
1016    /// [`RenderQualityControls::MAX_FILTER_SAMPLES`], or 16 on a Tier-B device.
1017    #[must_use]
1018    pub fn filter_sample_limit(&self) -> u32 {
1019        crate::filter_sample_limit(self.gpu.capabilities().tier)
1020    }
1021
1022    /// Lets kept graph results use up to `budget_bytes` (see
1023    /// [`crate::RenderGraph::set_cache_intent`]); zero, the default, disables the cache. The
1024    /// texture pool budget does not count these results.
1025    pub fn set_result_cache_budget(&self, budget_bytes: u64) {
1026        self.lock_result_cache().set_budget(budget_bytes);
1027    }
1028
1029    /// Drops every kept graph result.
1030    pub fn clear_result_cache(&self) {
1031        self.clear_result_cache_for(crate::CacheInvalidation::Explicit);
1032    }
1033
1034    /// The result cache's counters.
1035    #[must_use]
1036    pub fn result_cache_stats(&self) -> crate::ResultCacheStats {
1037        self.lock_result_cache().stats()
1038    }
1039
1040    /// Changes whenever a graph with an unchanged [`Self::graph_cache_key`] may render differently
1041    /// (any result-cache clear or reported GPU error). Equal keys under an equal epoch mean equal
1042    /// pixels.
1043    #[must_use]
1044    pub fn content_epoch(&self) -> u64 {
1045        self.lock_result_cache()
1046            .clears()
1047            .wrapping_add(self.gpu_errors.count())
1048    }
1049
1050    pub(crate) fn clear_result_cache_for(&self, reason: crate::CacheInvalidation) {
1051        self.lock_result_cache().clear(reason);
1052    }
1053
1054    pub(crate) fn lock_result_cache(
1055        &self,
1056    ) -> std::sync::MutexGuard<'_, crate::result_cache::ResultCache> {
1057        self.result_cache
1058            .lock()
1059            .unwrap_or_else(std::sync::PoisonError::into_inner)
1060    }
1061
1062    /// Returns the active render quality controls.
1063    #[must_use]
1064    pub fn quality_controls(&self) -> RenderQualityControls {
1065        self.quality_state().applied
1066    }
1067
1068    fn quality_state(&self) -> QualityState {
1069        *self
1070            .quality
1071            .lock()
1072            .unwrap_or_else(std::sync::PoisonError::into_inner)
1073    }
1074
1075    fn degradations(&self) -> Vec<crate::CapabilityDiagnostic> {
1076        let quality = self.quality_state();
1077        let (requested, applied) = (
1078            quality.requested_filter_samples,
1079            quality.applied.max_filter_samples,
1080        );
1081        if requested > applied {
1082            vec![crate::CapabilityDiagnostic::FilterSamplesReduced { requested, applied }]
1083        } else {
1084            Vec::new()
1085        }
1086    }
1087
1088    /// Returns a stable snapshot for telemetry or benchmark output.
1089    #[must_use]
1090    pub fn diagnostics(&self) -> crate::RenderDiagnostics {
1091        let quality = self.quality_controls();
1092        crate::diagnostics::snapshot(
1093            &self.diagnostics,
1094            self.gpu.capabilities(),
1095            &crate::diagnostics::ResourceDiagnostics {
1096                textures: self.texture_pool_stats(),
1097                upload_textures: self.upload_textures.stats(),
1098                readback_buffers: self.readback_buffers.stats(),
1099                uniform_buffers: self.uniform_buffers.stats(),
1100                pipelines: self.pipeline_cache_stats(),
1101                result_cache: self.result_cache_stats(),
1102            },
1103            quality.max_filter_samples,
1104            quality.motion_blur_subframes,
1105            self.degradations(),
1106        )
1107    }
1108
1109    /// Pipeline creations since the last call, oldest first (at most 256), with start and end
1110    /// times.
1111    pub fn take_pipeline_creations(&self) -> Vec<crate::PipelineCreation> {
1112        crate::diagnostics::take_pipeline_creations(&self.diagnostics)
1113    }
1114
1115    /// Records a host presentation outcome without imposing a product clock.
1116    pub fn record_frame_outcome(&self, presented: bool, repeated: bool) {
1117        crate::diagnostics::record_frame(&self.diagnostics, presented, repeated);
1118    }
1119
1120    /// Adds time spent waiting for a host decoder or refill operation.
1121    pub fn record_decoder_wait(&self, duration: Duration) {
1122        crate::diagnostics::record_decoder_wait(&self.diagnostics, duration);
1123    }
1124
1125    /// Returns the number of cached runtime and built-in pipelines.
1126    #[must_use]
1127    pub fn pipeline_cache_stats(&self) -> crate::PipelineCacheStats {
1128        crate::PipelineCacheStats {
1129            runtime_effects: self.effects().len(),
1130            builtins: self.pipelines.builtin_count(),
1131        }
1132    }
1133
1134    /// Selects the single color space used by all layer blending.
1135    #[must_use]
1136    pub const fn with_blend_space(mut self, blend_space: BlendSpace) -> Self {
1137        self.blend_space = blend_space;
1138        self
1139    }
1140
1141    /// Returns the configured layer-compositing color space.
1142    #[must_use]
1143    pub const fn blend_space(&self) -> BlendSpace {
1144        self.blend_space
1145    }
1146
1147    /// Clears an offscreen RGBA texture and submits it to the GPU queue.
1148    ///
1149    /// # Errors
1150    ///
1151    /// Returns [`RenderError`] for an invalid size or color.
1152    pub fn render_solid(
1153        &self,
1154        size: RenderSize,
1155        color: Color,
1156    ) -> Result<RenderedTexture, RenderError> {
1157        self.validate_size(size)?;
1158        if !color.is_valid() {
1159            return Err(RenderError::InvalidColor);
1160        }
1161        let format = self.intermediate_format();
1162        let mut encoder = self.command_encoder("alpha2 solid encoder");
1163        let texture = self.textures.acquire(
1164            self.gpu.device(),
1165            size,
1166            format,
1167            "alpha2 solid render target",
1168        );
1169        {
1170            let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1171                label: Some("alpha2 solid clear pass"),
1172                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1173                    view: texture.view(),
1174                    depth_slice: None,
1175                    resolve_target: None,
1176                    ops: wgpu::Operations {
1177                        load: wgpu::LoadOp::Clear(wgpu::Color {
1178                            r: color.red,
1179                            g: color.green,
1180                            b: color.blue,
1181                            a: color.alpha,
1182                        }),
1183                        store: wgpu::StoreOp::Store,
1184                    },
1185                })],
1186                depth_stencil_attachment: None,
1187                timestamp_writes: None,
1188                occlusion_query_set: None,
1189                multiview_mask: None,
1190            });
1191        }
1192        self.submit([encoder.finish()])?;
1193        Ok(RenderedTexture::pooled(size, format, texture))
1194    }
1195}