Skip to main content

alpha2_gpu/
context.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use web_time::Instant;
5
6use crate::diagnostic::DiagnosticHook;
7use crate::{
8    Capabilities, CapabilityTier, GpuDiagnostic, GpuDiagnosticHandler, GpuError, IntermediateFormat,
9};
10
11/// A GPU device and queue owned by one render host.
12///
13/// Clones are cheap and share the same device and diagnostic handler
14/// ([`GpuContext::set_diagnostic_handler`]).
15///
16/// # The queue (`wgpu` interop)
17///
18/// Every `wgpu` call that can reach the native queue is a method here and takes the shared-queue
19/// lock when there is one: `submit`, [`Self::on_submitted_work_done`] and `map_async` (both may
20/// flush pending writes), and `present`. Dropping the last clone also drops the queue under the
21/// lock, because `wgpu` waits for the native queue to idle there. `queue` hands out the handle
22/// for everything else, and each crate's clippy configuration forbids queue-reaching calls on it.
23#[derive(Clone, Debug)]
24pub struct GpuContext {
25    adapter: wgpu::Adapter,
26    device: wgpu::Device,
27    queue: Arc<LockedQueue>,
28    // Shared so clones (one per readback) copy no strings.
29    capabilities: Arc<Capabilities>,
30    diagnostics: Arc<DiagnosticHook>,
31    rate: Arc<crate::rate::GpuRate>,
32}
33
34/// The queue and its shared lock.
35#[derive(Debug)]
36struct LockedQueue {
37    // Declared before `lock` so it drops while `Drop` holds the lock.
38    queue: wgpu::Queue,
39    lock: QueueLockSlot,
40}
41
42/// The shared-queue lock, released on drop if [`LockedQueue`]'s `Drop` took it.
43#[derive(Debug)]
44struct QueueLockSlot {
45    lock: Option<Arc<dyn ExternalQueueLock>>,
46    held: bool,
47}
48
49impl LockedQueue {
50    // On wasm32 the handles are not Send or Sync, so this Arc acts as an Rc; one type keeps every
51    // target the same.
52    #[cfg_attr(target_arch = "wasm32", allow(clippy::arc_with_non_send_sync))]
53    fn shared(queue: wgpu::Queue, lock: Option<Arc<dyn ExternalQueueLock>>) -> Arc<Self> {
54        Arc::new(Self {
55            queue,
56            lock: QueueLockSlot { lock, held: false },
57        })
58    }
59
60    /// Runs `call` holding the shared-queue lock, when there is one.
61    fn locked<T>(&self, call: impl FnOnce(&wgpu::Queue) -> T) -> T {
62        let guard = self.lock.lock.as_ref().map(|lock| {
63            lock.lock();
64            QueueGuard(lock.as_ref())
65        });
66        let result = call(&self.queue);
67        drop(guard);
68        result
69    }
70}
71
72impl Drop for LockedQueue {
73    fn drop(&mut self) {
74        // Dropping the last handle waits for the native queue to idle, a queue access that needs
75        // the lock.
76        if let Some(lock) = &self.lock.lock {
77            lock.lock();
78            self.lock.held = true;
79        }
80    }
81}
82
83impl Drop for QueueLockSlot {
84    fn drop(&mut self) {
85        if self.held
86            && let Some(lock) = &self.lock
87        {
88            lock.unlock();
89        }
90    }
91}
92
93/// Serializes queue access with another API that shares the same queue.
94///
95/// A native decoder sharing the renderer's queue must take the same lock. [`GpuContext`] takes
96/// it around every call that can reach the native queue. Implementations must be re-entrant,
97/// because a queue-completion callback may submit while the lock is held.
98pub trait ExternalQueueLock: std::fmt::Debug + Send + Sync + 'static {
99    /// Acquires exclusive access to the shared queue.
100    fn lock(&self);
101    /// Releases access taken by [`ExternalQueueLock::lock`].
102    fn unlock(&self);
103}
104
105/// Where one [`GpuContext::submit_timed`] call spent its time.
106#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
107#[non_exhaustive]
108#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
109pub struct SubmitTimings {
110    /// Blocked acquiring the queue lock shared with another API.
111    pub queue_lock_wait: Duration,
112    /// Inside `wgpu`'s own submission, with the lock already held.
113    pub queue_submit: Duration,
114}
115
116struct QueueGuard<'a>(&'a dyn ExternalQueueLock);
117
118impl Drop for QueueGuard<'_> {
119    fn drop(&mut self) {
120        self.0.unlock();
121    }
122}
123
124impl GpuContext {
125    /// Adopts an already-created adapter, device, and queue.
126    ///
127    /// Used by native interop backends that create one device for both wgpu and a platform
128    /// decoder.
129    #[must_use]
130    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
131    pub fn from_parts(adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Self {
132        Self::from_parts_with_queue_lock(adapter, device, queue, None)
133    }
134
135    /// Adopts existing handles whose queue is shared with another API.
136    ///
137    /// Every call that can reach the native queue takes `queue_lock` first; see [`GpuContext`].
138    /// Such a context has no surface, since presenting would bypass the lock.
139    #[must_use]
140    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
141    pub fn from_parts_with_queue_lock(
142        adapter: wgpu::Adapter,
143        device: wgpu::Device,
144        queue: wgpu::Queue,
145        queue_lock: Option<Arc<dyn ExternalQueueLock>>,
146    ) -> Self {
147        let capabilities = Arc::new(Capabilities::from_device(&adapter, &device));
148        crate::validation_log::watch_device(&device, &capabilities.summary());
149        let diagnostics = Arc::new(DiagnosticHook::new());
150        install_device_callbacks(&device, &diagnostics);
151        Self {
152            adapter,
153            device,
154            queue: LockedQueue::shared(queue, queue_lock),
155            capabilities,
156            diagnostics,
157            rate: Arc::default(),
158        }
159    }
160
161    /// The logical device.
162    #[must_use]
163    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
164    pub const fn device(&self) -> &wgpu::Device {
165        &self.device
166    }
167
168    /// The queue, for calls that never reach the native queue (writes, timestamp periods,
169    /// backend interop). Submit, present, wait and map through this context instead.
170    #[must_use]
171    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
172    pub fn queue(&self) -> &wgpu::Queue {
173        &self.queue.queue
174    }
175
176    /// Calls `callback` once submitted work completes, holding the shared-queue lock.
177    ///
178    /// `wgpu` flushes pending writes here, which is a native submission.
179    pub fn on_submitted_work_done(&self, callback: impl FnOnce() + Send + 'static) {
180        #[expect(clippy::disallowed_methods, reason = "this is the locked wrapper")]
181        self.queue
182            .locked(|queue| queue.on_submitted_work_done(callback));
183    }
184
185    /// Maps `slice` for `mode`, holding the shared-queue lock, since `wgpu` may first submit
186    /// pending writes.
187    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
188    pub fn map_async(
189        &self,
190        slice: &wgpu::BufferSlice<'_>,
191        mode: wgpu::MapMode,
192        callback: impl FnOnce(Result<(), wgpu::BufferAsyncError>) + wgpu::WasmNotSend + 'static,
193    ) {
194        #[expect(clippy::disallowed_methods, reason = "this is the locked wrapper")]
195        self.queue.locked(|_| slice.map_async(mode, callback));
196    }
197
198    /// Presents `texture`, holding the shared-queue lock when one is set.
199    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
200    pub fn present(&self, texture: wgpu::SurfaceTexture) {
201        #[expect(clippy::disallowed_methods, reason = "this is the locked wrapper")]
202        self.queue.locked(|queue| queue.present(texture));
203    }
204
205    /// Submits command buffers, holding the shared-queue lock. Never submit through the queue
206    /// directly.
207    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
208    pub fn submit<I>(&self, command_buffers: I) -> wgpu::SubmissionIndex
209    where
210        I: IntoIterator<Item = wgpu::CommandBuffer>,
211    {
212        self.submit_measured(command_buffers, false).0
213    }
214
215    /// Submits command buffers and reports where the call spent its time.
216    ///
217    /// Lock wait reflects a native decoder using the queue; submit time is `wgpu`'s own
218    /// validation cost. Plain [`GpuContext::submit`] reads no clock.
219    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
220    pub fn submit_timed<I>(&self, command_buffers: I) -> (wgpu::SubmissionIndex, SubmitTimings)
221    where
222        I: IntoIterator<Item = wgpu::CommandBuffer>,
223    {
224        self.submit_measured(command_buffers, true)
225    }
226
227    fn submit_measured<I>(
228        &self,
229        command_buffers: I,
230        measure: bool,
231    ) -> (wgpu::SubmissionIndex, SubmitTimings)
232    where
233        I: IntoIterator<Item = wgpu::CommandBuffer>,
234    {
235        let mut timings = SubmitTimings::default();
236        let started = measure.then(Instant::now);
237        let index = self.queue.locked(|queue| {
238            let acquired = started.map(|started| {
239                let now = Instant::now();
240                timings.queue_lock_wait = now.duration_since(started);
241                now
242            });
243            #[expect(clippy::disallowed_methods, reason = "this is the locked wrapper")]
244            let index = queue.submit(command_buffers);
245            if let Some(acquired) = acquired {
246                timings.queue_submit = acquired.elapsed();
247            }
248            index
249        });
250        (index, timings)
251    }
252
253    /// Requests a surface-independent device.
254    ///
255    /// # Errors
256    /// Returns [`GpuError`] when adapter or device acquisition fails.
257    pub async fn request() -> Result<Self, GpuError> {
258        let _turn = crate::serialize_acquisition();
259        let instance = crate::new_instance(wgpu::Backends::all());
260        Self::request_compatible(&instance, None).await
261    }
262
263    /// Requests the product device with the default request ([`Self::request_product_with`]).
264    ///
265    /// # Errors
266    /// Returns [`GpuError`] when no adapter opens a device.
267    #[cfg(not(target_arch = "wasm32"))]
268    pub async fn request_product() -> Result<Self, GpuError> {
269        Self::request_product_with(&ProductRequest::default()).await
270    }
271
272    /// Requests the product device on [`product_backends`]: the adapter the request's policy
273    /// (else `ALPHA2_GPU_ADAPTER`) pins, else the first in high-performance order that opens a
274    /// device.
275    ///
276    /// A DX12 group that lists no adapter is a failed instance, since WARP is always listed.
277    /// GL adapters older than GL 4.3 or GLES 3.1 are refused. `WGPU_POWER_PREF` is ignored.
278    ///
279    /// # Errors
280    /// Returns [`GpuError`] for an unmatched pin, a failed DX12 instance, no hardware adapter
281    /// under [`SoftwareAdapters::Refuse`], or the first device error.
282    #[cfg(not(target_arch = "wasm32"))]
283    pub async fn request_product_with(request: &ProductRequest) -> Result<Self, GpuError> {
284        let _turn = crate::serialize_acquisition();
285        let (candidates, seen) = product_candidates(request).await?;
286        let mut tried = ProductAttempt::seeing(seen);
287        for adapter in candidates {
288            match Self::open_device(adapter.adapter, request.withheld).await {
289                Ok(context) => return Ok(context),
290                Err(error) => tried.refused(adapter.record, adapter.name, error),
291            }
292        }
293        Err(tried.into_error(request))
294    }
295
296    /// Requests the product device that `accept` takes, in [`Self::request_product_with`] order.
297    ///
298    /// A shared-device hardware decoder may open on only some adapters (D3D12VA needs a D3D12
299    /// video device). Each hardware adapter is tried until `accept` takes one; a CPU adapter
300    /// only when pinned. If none is taken, the result holds the first device.
301    ///
302    /// # Errors
303    /// Returns [`GpuError`] when no adapter opens a device.
304    #[cfg(not(target_arch = "wasm32"))]
305    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
306    pub async fn request_product_accepted<T, E>(
307        mut accept: impl FnMut(&Self) -> Result<T, E>,
308    ) -> Result<AcceptedDevice<T, E>, GpuError> {
309        let _turn = crate::serialize_acquisition();
310        let request = ProductRequest::default();
311        let (candidates, seen) = product_candidates(&request).await?;
312        let mut tried = ProductAttempt::seeing(seen);
313        let mut refusals = AdapterRefusals(Vec::new());
314        let mut first: Option<Self> = None;
315        for candidate in candidates {
316            if first.is_some() && candidate.cpu && !candidate.pinned {
317                continue;
318            }
319            let context = match Self::open_device(candidate.adapter, request.withheld).await {
320                Ok(context) => context,
321                Err(error) => {
322                    tried.refused(candidate.record, candidate.name, error);
323                    continue;
324                }
325            };
326            match accept(&context) {
327                Ok(value) => {
328                    return Ok(AcceptedDevice {
329                        context,
330                        accepted: Some(value),
331                        refusals,
332                    });
333                }
334                Err(error) => {
335                    refusals.0.push((candidate.name, error));
336                    first.get_or_insert(context);
337                }
338            }
339        }
340        match first {
341            Some(context) => Ok(AcceptedDevice {
342                context,
343                accepted: None,
344                refusals,
345            }),
346            None => Err(tried.into_error(&request)),
347        }
348    }
349
350    /// Every adapter on `backends` in product-request order, each with its enumeration index.
351    /// Open them with [`Self::open_adapter`].
352    #[cfg(not(target_arch = "wasm32"))]
353    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
354    pub async fn adapters_by_preference_on(
355        backends: wgpu::Backends,
356    ) -> Vec<(usize, wgpu::Adapter)> {
357        let _turn = crate::serialize_acquisition();
358        let instance = crate::new_instance(backends);
359        let mut adapters: Vec<Option<wgpu::Adapter>> = instance
360            .enumerate_adapters(wgpu::Backends::all())
361            .await
362            .into_iter()
363            .map(Some)
364            .collect();
365        let kinds: Vec<(usize, wgpu::DeviceType)> = adapters
366            .iter()
367            .enumerate()
368            .map(|(index, adapter)| {
369                let kind = adapter.as_ref().map_or(wgpu::DeviceType::Other, |adapter| {
370                    adapter.get_info().device_type
371                });
372                (index, kind)
373            })
374            .collect();
375        crate::adapter_pin::product_order(&kinds)
376            .into_iter()
377            .filter_map(|index| adapters[index].take().map(|adapter| (index, adapter)))
378            .collect()
379    }
380
381    /// Opens a device on `adapter` with the standard features and limits.
382    ///
383    /// # Errors
384    /// Returns [`GpuError`] when the adapter cannot create a device.
385    #[cfg(not(target_arch = "wasm32"))]
386    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
387    pub async fn open_adapter(adapter: wgpu::Adapter) -> Result<Self, GpuError> {
388        Self::open_adapter_without(adapter, wgpu::Features::empty()).await
389    }
390
391    /// Like [`Self::open_adapter`] but without the optional features in `withheld`, for tests.
392    ///
393    /// # Errors
394    /// Returns [`GpuError`] when the adapter cannot create the device.
395    #[cfg(not(target_arch = "wasm32"))]
396    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
397    pub async fn open_adapter_without(
398        adapter: wgpu::Adapter,
399        withheld: wgpu::Features,
400    ) -> Result<Self, GpuError> {
401        let _turn = crate::serialize_acquisition();
402        Self::open_device(adapter, withheld).await
403    }
404
405    /// The adapter this device was opened on.
406    #[must_use]
407    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
408    pub const fn adapter(&self) -> &wgpu::Adapter {
409        &self.adapter
410    }
411
412    /// Requests a device compatible with an optional presentation surface.
413    ///
414    /// WebGL2 requires a compatible surface during adapter selection, while
415    /// browser WebGPU and native headless callers may pass `None`.
416    ///
417    /// # Errors
418    /// Returns [`GpuError`] when adapter or device acquisition fails.
419    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
420    pub async fn request_compatible(
421        instance: &wgpu::Instance,
422        compatible_surface: Option<&wgpu::Surface<'_>>,
423    ) -> Result<Self, GpuError> {
424        let preference = wgpu::PowerPreference::from_env().unwrap_or_default();
425        Self::request_compatible_with_preference(
426            instance,
427            compatible_surface,
428            preference,
429            wgpu::Features::empty(),
430        )
431        .await
432    }
433
434    /// Opens a device on the adapter `wgpu` prefers, falling back to the next adapter that can.
435    ///
436    /// A listed adapter can still fail every device request (such as a GL driver beside a
437    /// lavapipe-only Vulkan loader). On failure of all, the preferred adapter's error is returned.
438    async fn request_compatible_with_preference(
439        instance: &wgpu::Instance,
440        compatible_surface: Option<&wgpu::Surface<'_>>,
441        power_preference: wgpu::PowerPreference,
442        withheld: wgpu::Features,
443    ) -> Result<Self, GpuError> {
444        let _turn = crate::serialize_acquisition();
445        let adapter = instance
446            .request_adapter(&wgpu::RequestAdapterOptions {
447                compatible_surface,
448                power_preference,
449                ..Default::default()
450            })
451            .await
452            .map_err(GpuError::adapter)?;
453        #[cfg(not(target_arch = "wasm32"))]
454        let preferred = adapter.get_info();
455        let error = match Self::open_device(adapter, withheld).await {
456            Ok(context) => return Ok(context),
457            Err(error) => error,
458        };
459        #[cfg(not(target_arch = "wasm32"))]
460        {
461            let mut others: Vec<wgpu::Adapter> = instance
462                .enumerate_adapters(wgpu::Backends::all())
463                .await
464                .into_iter()
465                .filter(|other| other.get_info() != preferred)
466                .filter(|other| {
467                    compatible_surface.is_none_or(|surface| other.is_surface_supported(surface))
468                })
469                .collect();
470            others
471                .sort_by_key(|other| fallback_rank(other.get_info().device_type, power_preference));
472            for other in others {
473                if let Ok(context) = Self::open_device(other, withheld).await {
474                    return Ok(context);
475                }
476            }
477        }
478        Err(error)
479    }
480
481    async fn open_device(
482        adapter: wgpu::Adapter,
483        withheld: wgpu::Features,
484    ) -> Result<Self, GpuError> {
485        // 16-bit norm formats hold CoreVideo's 10-bit planes as R16/RG16 textures; NV12/P010 are
486        // only needed for bi-planar decoder resources.
487        let optional_features = wgpu::Features::TIMESTAMP_QUERY
488            | wgpu::Features::TEXTURE_FORMAT_16BIT_NORM
489            | if cfg!(target_os = "windows") {
490                wgpu::Features::TEXTURE_FORMAT_NV12 | wgpu::Features::TEXTURE_FORMAT_P010
491            } else {
492                wgpu::Features::empty()
493            };
494        let required_features = adapter.features() & optional_features & !withheld;
495        let required_limits =
496            wgpu::Limits::downlevel_webgl2_defaults().using_resolution(adapter.limits());
497        let (device, queue) = adapter
498            .request_device(&wgpu::DeviceDescriptor {
499                required_features,
500                required_limits,
501                ..wgpu::DeviceDescriptor::default()
502            })
503            .await
504            .map_err(GpuError::device)?;
505        let capabilities = Arc::new(Capabilities::from_device(&adapter, &device));
506        crate::validation_log::watch_device(&device, &capabilities.summary());
507        let diagnostics = Arc::new(DiagnosticHook::new());
508        install_device_callbacks(&device, &diagnostics);
509        Ok(Self {
510            adapter,
511            device,
512            queue: LockedQueue::shared(queue, None),
513            capabilities,
514            diagnostics,
515            rate: Arc::default(),
516        })
517    }
518
519    /// Routes uncaptured errors and device-loss notifications to `handler`.
520    ///
521    /// Without a handler, uncaptured errors are dropped in release and panic in debug or under
522    /// `ALPHA2_GPU_STRICT=1`; device loss is dropped. The handler may run on any thread and must
523    /// not block. It replaces any previous handler and is never invoked on `wasm32`.
524    pub fn set_diagnostic_handler(&self, handler: impl Fn(GpuDiagnostic) + Send + Sync + 'static) {
525        let handler: GpuDiagnosticHandler = Arc::new(handler);
526        self.diagnostics.set(Some(handler));
527    }
528
529    /// Drops the installed diagnostic handler, if any.
530    pub fn clear_diagnostic_handler(&self) {
531        self.diagnostics.set(None);
532    }
533
534    /// Returns immutable capability decisions.
535    #[must_use]
536    pub fn capabilities(&self) -> &Capabilities {
537        &self.capabilities
538    }
539
540    /// This device's throughput rate.
541    #[must_use]
542    pub fn rate(&self) -> &Arc<crate::rate::GpuRate> {
543        &self.rate
544    }
545
546    /// This device with an `Rgba8Unorm` intermediate format, so the 8-bit fallback can be tested
547    /// on any device. Shares the device, queue and handler with `self`.
548    #[must_use]
549    pub fn with_rgba8_intermediate(&self) -> Self {
550        let mut capabilities = Capabilities::clone(&self.capabilities);
551        capabilities.intermediate_format = IntermediateFormat::Rgba8Unorm;
552        Self {
553            capabilities: Arc::new(capabilities),
554            ..self.clone()
555        }
556    }
557
558    /// This device reported as `tier`, so downlevel policy can be tested on any device. Shares
559    /// the device, queue and handler with `self`.
560    #[must_use]
561    pub fn with_tier(&self, tier: CapabilityTier) -> Self {
562        let mut capabilities = Capabilities::clone(&self.capabilities);
563        capabilities.tier = tier;
564        Self {
565            capabilities: Arc::new(capabilities),
566            ..self.clone()
567        }
568    }
569
570    /// Chooses a surface configuration with a non-sRGB format where available.
571    ///
572    /// Presented frames are already sRGB-encoded, so an sRGB format would encode them twice
573    /// (wgpu defaults WebGL2 canvases to `Rgba8UnormSrgb`).
574    #[must_use]
575    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
576    pub fn surface_config(
577        &self,
578        surface: &wgpu::Surface<'_>,
579        width: u32,
580        height: u32,
581    ) -> Option<wgpu::SurfaceConfiguration> {
582        let mut config = surface.get_default_config(&self.adapter, width, height)?;
583        if let Some(format) = surface
584            .get_capabilities(&self.adapter)
585            .formats
586            .into_iter()
587            .find(|format| !format.is_srgb())
588        {
589            config.format = format;
590        }
591        Some(config)
592    }
593}
594
595/// The result of [`GpuContext::request_product_accepted`].
596#[derive(Debug)]
597#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
598pub struct AcceptedDevice<T, E> {
599    /// The device `accept` took, or the preferred adapter's when none was.
600    pub context: GpuContext,
601    /// What `accept` made of `context`; `None` when it took no device.
602    pub accepted: Option<T>,
603    /// Each adapter `accept` refused before, in the order they were tried.
604    pub refusals: AdapterRefusals<E>,
605}
606
607/// Refused adapters by name with reasons, in the order tried.
608#[derive(Debug)]
609#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
610pub struct AdapterRefusals<E>(pub Vec<(String, E)>);
611
612impl<E: std::fmt::Display> std::fmt::Display for AdapterRefusals<E> {
613    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
614        for (index, (adapter, error)) in self.0.iter().enumerate() {
615            if index > 0 {
616                formatter.write_str("; ")?;
617            }
618            write!(formatter, "{adapter}: {error}")?;
619        }
620        Ok(())
621    }
622}
623
624impl<E: std::fmt::Display + std::fmt::Debug> std::error::Error for AdapterRefusals<E> {}
625
626/// Whether a product request may open a device on a software adapter
627/// (lavapipe, llvmpipe, WARP, `SwiftShader`).
628#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
629pub enum SoftwareAdapters {
630    /// A software adapter is tried after every hardware one.
631    #[default]
632    Allow,
633    /// Software adapters open only when `ALPHA2_GPU_ADAPTER` pins them.
634    Refuse,
635}
636
637/// What a product request may open.
638#[derive(Clone, Debug, Default)]
639pub struct ProductRequest {
640    /// Whether software adapters are acceptable.
641    pub software: SoftwareAdapters,
642    /// How the adapter is chosen; `None` reads `ALPHA2_GPU_ADAPTER`.
643    pub adapter: Option<crate::AdapterPolicy>,
644    /// Optional features to withhold, for tests.
645    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
646    pub withheld: wgpu::Features,
647}
648
649/// Product backend groups in order: DX12 on Windows, Metal on macOS, Vulkan then GL elsewhere,
650/// any in the browser. `WGPU_BACKEND` replaces them when set.
651#[must_use]
652pub fn product_backends() -> Vec<wgpu::Backends> {
653    if let Some(backends) = wgpu::Backends::from_env() {
654        return vec![backends];
655    }
656    if cfg!(target_arch = "wasm32") {
657        vec![wgpu::Backends::all()]
658    } else if cfg!(target_os = "windows") {
659        vec![wgpu::Backends::DX12]
660    } else if cfg!(any(target_os = "macos", target_os = "ios")) {
661        vec![wgpu::Backends::METAL]
662    } else {
663        vec![wgpu::Backends::VULKAN, wgpu::Backends::GL]
664    }
665}
666
667/// An adapter a product request will try.
668#[cfg(not(target_arch = "wasm32"))]
669struct Candidate<A = wgpu::Adapter> {
670    adapter: A,
671    name: String,
672    cpu: bool,
673    pinned: bool,
674    record: usize,
675}
676
677/// What a product request tried and why each failed.
678#[cfg(not(target_arch = "wasm32"))]
679#[derive(Default)]
680struct ProductAttempt {
681    refusals: Vec<(String, String)>,
682    first: Option<GpuError>,
683    seen: Vec<crate::AdapterRecord>,
684}
685
686#[cfg(not(target_arch = "wasm32"))]
687impl ProductAttempt {
688    fn seeing(seen: Vec<crate::AdapterRecord>) -> Self {
689        Self {
690            seen,
691            ..Self::default()
692        }
693    }
694
695    fn refused(&mut self, record: usize, adapter: String, error: GpuError) {
696        let reason = error.to_string();
697        if let Some(record) = self.seen.get_mut(record) {
698            record.renders = Err(reason.clone());
699        }
700        self.refusals.push((adapter, reason));
701        self.first.get_or_insert(error);
702    }
703
704    fn into_error(self, request: &ProductRequest) -> GpuError {
705        match (request.software, self.first) {
706            (SoftwareAdapters::Allow, Some(first)) => first.tried(self.refusals),
707            _ => GpuError::no_hardware(Vec::new(), self.refusals, self.seen),
708        }
709    }
710}
711
712/// The adapters a product request tries, in order ([`order_product_candidates`]), and a record of
713/// every adapter it listed.
714#[cfg(not(target_arch = "wasm32"))]
715async fn product_candidates(
716    request: &ProductRequest,
717) -> Result<(Vec<Candidate>, Vec<crate::AdapterRecord>), GpuError> {
718    let mut groups = Vec::new();
719    for group in product_backends() {
720        let instance = crate::new_instance(group);
721        let adapters = instance.enumerate_adapters(group).await;
722        if group == wgpu::Backends::DX12 && adapters.is_empty() {
723            return Err(GpuError::no_dx12_adapter());
724        }
725        groups.push(
726            adapters
727                .into_iter()
728                .map(|adapter| {
729                    let info = adapter.get_info();
730                    (adapter, info)
731                })
732                .collect(),
733        );
734    }
735    let pin = request
736        .adapter
737        .clone()
738        .unwrap_or_else(crate::AdapterPolicy::from_env);
739    order_product_candidates(groups, request, &pin)
740}
741
742/// Orders the adapters of each backend group (in group order, each group in enumeration order):
743/// the hardware adapters of every group, then the software adapters of every group. The records
744/// are of every adapter listed, whether tried or not.
745///
746/// Under a pin the first group with a pinned adapter is the only one tried, since an index pin
747/// names a position in one group's enumeration.
748#[cfg(not(target_arch = "wasm32"))]
749fn order_product_candidates<A>(
750    groups: Vec<Vec<(A, wgpu::AdapterInfo)>>,
751    request: &ProductRequest,
752    pin: &crate::AdapterPolicy,
753) -> Result<(Vec<Candidate<A>>, Vec<crate::AdapterRecord>), GpuError> {
754    let mut listed = Vec::new();
755    let mut seen = Vec::new();
756    let mut software = Vec::new();
757    let mut refusals = Vec::new();
758    let (mut hardware_candidates, mut software_candidates) = (Vec::new(), Vec::new());
759    for group in groups {
760        let kinds: Vec<(usize, wgpu::DeviceType)> = group
761            .iter()
762            .enumerate()
763            .map(|(index, (_, info))| (index, info.device_type))
764            .collect();
765        let mut adapters: Vec<Option<(A, wgpu::AdapterInfo)>> =
766            group.into_iter().map(Some).collect();
767        let mut candidates = Vec::new();
768        for index in crate::adapter_pin::product_order(&kinds) {
769            let Some((adapter, info)) = adapters[index].take() else {
770                continue;
771            };
772            listed.push(format!("[{index}] {} ({:?})", info.name, info.backend));
773            let pinned = pin.names(index, &info.name);
774            if pin.is_pin() && !pinned {
775                continue;
776            }
777            let cpu = crate::software_adapter(&info);
778            let mut record =
779                crate::AdapterRecord::unasked(index, info.name.clone(), info.backend.to_str(), cpu);
780            if cpu && request.software == SoftwareAdapters::Refuse && !pinned {
781                record.renders = Err(SOFTWARE_ADAPTER_UNPINNED.to_owned());
782                seen.push(record);
783                software.push(info.name);
784                continue;
785            }
786            if info.backend == wgpu::Backend::Gl
787                && let Err(reason) = crate::adapter_pin::gl_version_supported(&info.driver_info)
788            {
789                record.renders = Err(reason.clone());
790                seen.push(record);
791                refusals.push((info.name.clone(), reason));
792                continue;
793            }
794            seen.push(record);
795            candidates.push(Candidate {
796                adapter,
797                name: info.name,
798                cpu,
799                pinned,
800                record: seen.len() - 1,
801            });
802        }
803        if pin.is_pin() && !candidates.is_empty() {
804            return Ok((candidates, seen));
805        }
806        let (cpu, gpu): (Vec<_>, Vec<_>) = candidates.into_iter().partition(|each| each.cpu);
807        hardware_candidates.extend(gpu);
808        software_candidates.extend(cpu);
809    }
810    hardware_candidates.extend(software_candidates);
811    if !hardware_candidates.is_empty() {
812        return Ok((hardware_candidates, seen));
813    }
814    if pin.is_pin() {
815        return Err(GpuError::pin(format!(
816            "{} names no adapter; the adapters are {}",
817            pin.setting(),
818            if listed.is_empty() {
819                "none".to_owned()
820            } else {
821                listed.join(", ")
822            }
823        )));
824    }
825    Err(GpuError::no_hardware(software, refusals, seen))
826}
827
828#[cfg(not(target_arch = "wasm32"))]
829const SOFTWARE_ADAPTER_UNPINNED: &str =
830    "a software adapter, opened only when ALPHA2_GPU_ADAPTER pins it";
831
832/// Fallback rank for `preference`: requested GPU kinds first, CPU last.
833#[cfg(not(target_arch = "wasm32"))]
834fn fallback_rank(device_type: wgpu::DeviceType, preference: wgpu::PowerPreference) -> u8 {
835    use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, Other, VirtualGpu};
836    let order: &[wgpu::DeviceType] = match preference {
837        wgpu::PowerPreference::HighPerformance => {
838            &[DiscreteGpu, IntegratedGpu, VirtualGpu, Other, Cpu]
839        }
840        wgpu::PowerPreference::LowPower => &[IntegratedGpu, DiscreteGpu, VirtualGpu, Other, Cpu],
841        wgpu::PowerPreference::None => return 0,
842    };
843    order
844        .iter()
845        .position(|kind| *kind == device_type)
846        .and_then(|rank| u8::try_from(rank).ok())
847        .unwrap_or(u8::MAX)
848}
849
850// A library must not write to stderr, so device events go through the opt-in hook.
851#[cfg(not(target_arch = "wasm32"))]
852fn install_device_callbacks(device: &wgpu::Device, diagnostics: &Arc<DiagnosticHook>) {
853    let uncaptured = Arc::clone(diagnostics);
854    device.on_uncaptured_error(Arc::new(move |error| {
855        uncaptured.emit(GpuDiagnostic::uncaptured(&error));
856    }));
857    let lost = Arc::clone(diagnostics);
858    device.set_device_lost_callback(move |reason, message| {
859        lost.emit(GpuDiagnostic::DeviceLost {
860            reason: format!("{reason:?}"),
861            message,
862        });
863    });
864}
865
866#[cfg(target_arch = "wasm32")]
867fn install_device_callbacks(_device: &wgpu::Device, _diagnostics: &Arc<DiagnosticHook>) {}
868
869#[cfg(all(test, not(target_arch = "wasm32")))]
870mod tests {
871    use super::fallback_rank;
872    use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, Other, VirtualGpu};
873    use wgpu::PowerPreference;
874
875    #[test]
876    fn fallback_adapters_follow_the_preference_and_a_cpu_comes_last() {
877        let ordered = |preference| {
878            let mut kinds = vec![Cpu, Other, VirtualGpu, IntegratedGpu, DiscreteGpu];
879            kinds.sort_by_key(|kind| fallback_rank(*kind, preference));
880            kinds
881        };
882        assert_eq!(
883            ordered(PowerPreference::HighPerformance),
884            [DiscreteGpu, IntegratedGpu, VirtualGpu, Other, Cpu]
885        );
886        assert_eq!(
887            ordered(PowerPreference::LowPower),
888            [IntegratedGpu, DiscreteGpu, VirtualGpu, Other, Cpu]
889        );
890        assert_eq!(
891            ordered(PowerPreference::None),
892            [Cpu, Other, VirtualGpu, IntegratedGpu, DiscreteGpu]
893        );
894    }
895
896    fn info(
897        name: &str,
898        device_type: wgpu::DeviceType,
899        backend: wgpu::Backend,
900    ) -> wgpu::AdapterInfo {
901        wgpu::AdapterInfo {
902            name: name.to_owned(),
903            vendor: 0,
904            device: 0,
905            device_type,
906            device_pci_bus_id: String::new(),
907            driver: String::new(),
908            driver_info: if backend == wgpu::Backend::Gl {
909                "4.6 (Core Profile) Mesa 24.0".to_owned()
910            } else {
911                String::new()
912            },
913            backend,
914            subgroup_min_size: 0,
915            subgroup_max_size: 0,
916            transient_saves_memory: None,
917            limit_bucket: None,
918        }
919    }
920
921    fn order(
922        groups: &[&[(&'static str, wgpu::DeviceType)]],
923        software: super::SoftwareAdapters,
924        pin: &crate::AdapterPolicy,
925    ) -> Result<Vec<&'static str>, String> {
926        let backends = [wgpu::Backend::Vulkan, wgpu::Backend::Gl];
927        let groups = groups
928            .iter()
929            .zip(backends)
930            .map(|(group, backend)| {
931                group
932                    .iter()
933                    .map(|(name, kind)| (*name, info(name, *kind, backend)))
934                    .collect()
935            })
936            .collect();
937        let request = super::ProductRequest {
938            software,
939            ..super::ProductRequest::default()
940        };
941        super::order_product_candidates(groups, &request, pin)
942            .map(|(candidates, _)| candidates.into_iter().map(|each| each.adapter).collect())
943            .map_err(|error| error.to_string())
944    }
945
946    #[test]
947    fn hardware_adapters_of_every_backend_group_come_before_any_software_one() {
948        use super::SoftwareAdapters::{Allow, Refuse};
949        let auto = crate::AdapterPolicy::Auto;
950        let lavapipe = ("llvmpipe (LLVM 15.0.7, 256 bits)", Cpu);
951        assert_eq!(
952            order(
953                &[&[lavapipe], &[("AMD Radeon", IntegratedGpu)]],
954                Allow,
955                &auto
956            ),
957            Ok(vec!["AMD Radeon", lavapipe.0])
958        );
959        assert_eq!(
960            order(
961                &[&[("GPU", DiscreteGpu)], &[("AMD Radeon", IntegratedGpu)]],
962                Allow,
963                &auto
964            ),
965            Ok(vec!["GPU", "AMD Radeon"]),
966            "a Vulkan adapter that fails to open is followed by the GL one"
967        );
968        assert_eq!(
969            order(
970                &[&[lavapipe], &[("AMD Radeon", IntegratedGpu), lavapipe]],
971                Refuse,
972                &auto
973            ),
974            Ok(vec!["AMD Radeon"])
975        );
976        let refused =
977            order(&[&[lavapipe], &[lavapipe]], Refuse, &auto).expect_err("only software adapters");
978        assert!(refused.contains("no hardware GPU"), "{refused}");
979        assert_eq!(
980            order(
981                &[&[("GPU", DiscreteGpu)], &[("AMD Radeon", IntegratedGpu)]],
982                Allow,
983                &crate::AdapterPolicy::Index(0)
984            ),
985            Ok(vec!["GPU"]),
986            "a pin stays in the first group that has the pinned adapter"
987        );
988    }
989
990    #[test]
991    fn refuse_takes_a_software_adapter_only_when_a_pin_names_it() {
992        use super::SoftwareAdapters::Refuse;
993        let lavapipe = ("llvmpipe (LLVM 15.0.7, 256 bits)", Cpu);
994        let warp = ("Microsoft Basic Render Driver", Other);
995        let refused = order(
996            &[&[lavapipe], &[lavapipe]],
997            Refuse,
998            &crate::AdapterPolicy::Auto,
999        )
1000        .expect_err("no pin, only software adapters");
1001        assert!(refused.contains("only software adapters"), "{refused}");
1002        assert_eq!(
1003            order(
1004                &[&[lavapipe], &[("AMD Radeon", IntegratedGpu)]],
1005                Refuse,
1006                &crate::AdapterPolicy::Name("llvmpipe".to_owned())
1007            ),
1008            Ok(vec![lavapipe.0]),
1009            "a name pin opens the software adapter it names"
1010        );
1011        assert_eq!(
1012            order(
1013                &[&[("AMD Radeon", IntegratedGpu), warp]],
1014                Refuse,
1015                &crate::AdapterPolicy::Index(1)
1016            ),
1017            Ok(vec![warp.0]),
1018            "an index pin opens the software adapter at that position"
1019        );
1020        assert_eq!(
1021            order(
1022                &[&[warp, ("AMD Radeon", IntegratedGpu)]],
1023                Refuse,
1024                &crate::AdapterPolicy::Performance
1025            ),
1026            Ok(vec!["AMD Radeon"]),
1027            "a policy that is not a pin passes over the software adapter"
1028        );
1029    }
1030
1031    #[test]
1032    fn a_refused_request_records_every_adapter_it_listed() {
1033        let request = super::ProductRequest {
1034            software: super::SoftwareAdapters::Refuse,
1035            ..super::ProductRequest::default()
1036        };
1037        let groups = vec![
1038            vec![(
1039                (),
1040                info(
1041                    "llvmpipe (LLVM 15.0.7, 256 bits)",
1042                    Cpu,
1043                    wgpu::Backend::Vulkan,
1044                ),
1045            )],
1046            vec![(
1047                (),
1048                info("llvmpipe (LLVM 15.0.7, 256 bits)", Cpu, wgpu::Backend::Gl),
1049            )],
1050        ];
1051        let error = super::order_product_candidates(groups, &request, &crate::AdapterPolicy::Auto)
1052            .err()
1053            .expect("only software adapters");
1054        assert_eq!(error.step(), crate::GpuAcquisitionStep::NoHardwareAdapter);
1055        let seen = error.adapters_seen();
1056        assert_eq!(
1057            seen.iter()
1058                .map(|record| (record.backend, record.software, record.renders.is_ok()))
1059                .collect::<Vec<_>>(),
1060            [("vulkan", true, false), ("gl", true, false)]
1061        );
1062        assert!(
1063            seen.iter()
1064                .all(|record| record.name.starts_with("llvmpipe"))
1065        );
1066
1067        let mut attempt = super::ProductAttempt::seeing(vec![crate::AdapterRecord::unasked(
1068            0,
1069            "GPU".to_owned(),
1070            "vulkan",
1071            false,
1072        )]);
1073        attempt.refused(
1074            0,
1075            "GPU".to_owned(),
1076            crate::GpuError::pin("device lost".to_owned()),
1077        );
1078        let error = attempt.into_error(&request);
1079        assert_eq!(
1080            error.adapters_seen()[0].renders,
1081            Err("device lost".to_owned())
1082        );
1083    }
1084
1085    #[test]
1086    fn a_request_that_fails_on_every_adapter_names_each_attempt() {
1087        let mut attempt = super::ProductAttempt::default();
1088        attempt.refused(
1089            0,
1090            "GPU".to_owned(),
1091            crate::GpuError::pin("device lost".to_owned()),
1092        );
1093        attempt.refused(
1094            1,
1095            "AMD Radeon".to_owned(),
1096            crate::GpuError::pin("out of memory".to_owned()),
1097        );
1098        let error = attempt
1099            .into_error(&super::ProductRequest::default())
1100            .to_string();
1101        assert!(
1102            error.starts_with("device lost")
1103                && error.contains("tried GPU: device lost")
1104                && error.contains("tried AMD Radeon: out of memory"),
1105            "{error}"
1106        );
1107    }
1108}