Skip to main content

sk_tree/
surface.rs

1//! `<sk-surface name="…">`: a picture native code produces and a Skathi element shows, composited
2//! like any other content (object-fit, clipping, radii, transforms, z-order).
3//!
4//! A producer gets a [`SurfaceHandle`] by name ([`surface`]) and presents frames from any thread.
5//! The latest frame wins; an element picks it up on its next paint, and only while it is visible.
6//! On Windows a frame can be a D3D11 or D3D12 texture on the renderer's own device (GPU copy, no
7//! readback) or a shared texture from another device, API or process, synchronised by a keyed
8//! mutex or a fence. On macOS it can be a Metal texture on the renderer's device, an IOSurface
9//! (synchronised by an `MTLSharedEvent`) or a CVPixelBuffer. Everywhere it can be CPU BGRA.
10//!
11//! A surface set to [`SurfaceFormat::Rgba16Float`] takes half-float frames instead; they stay
12//! half-float until an element composites them: an HDR window (Windows, macOS, on an HDR display)
13//! shows them up to the element's `dynamic-range-limit`, a standard one maps them to 8-bit sRGB.
14
15mod color;
16#[cfg(windows)]
17mod d3d11;
18#[cfg(windows)]
19mod d3d12;
20mod display;
21pub(crate) mod feedback;
22#[cfg(target_os = "macos")]
23mod metal;
24pub(crate) mod node;
25#[cfg(windows)]
26mod shared;
27
28#[cfg(windows)]
29pub use d3d12::{D3D12Lease, D3D12Provider};
30pub use feedback::monotonic_ns;
31
32/// Under the D3D12 renderer, how surfaces reach its device and queue. Set once by the host.
33#[cfg(windows)]
34pub fn install_d3d12_provider(provider: D3D12Provider) {
35    d3d12::install(provider);
36}
37
38#[cfg(target_os = "macos")]
39const NO_D3D: &str = "Direct3D is Windows-only; on macOS present a Metal texture \
40                      (present_metal_texture), an IOSurface (SharedTexture::from_iosurface) or a \
41                      CVPixelBuffer (present_cv_pixel_buffer)";
42#[cfg(windows)]
43const NO_METAL: &str = "Metal is macOS-only; on Windows present a D3D11 or D3D12 texture, or a \
44                        SharedTexture opened from an NT handle";
45#[cfg(not(any(windows, target_os = "macos")))]
46const NO_D3D: &str =
47    "GPU surfaces are Windows and macOS only for now; present CPU frames with present_bgra";
48#[cfg(not(any(windows, target_os = "macos")))]
49const NO_METAL: &str = NO_D3D;
50
51use std::collections::HashMap;
52use std::ffi::c_void;
53use std::fmt;
54use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
55use std::sync::{Arc, Mutex, MutexGuard, Weak};
56use std::time::Duration;
57
58/// The largest frame side accepted, the renderer's texture limit.
59const MAX_SIDE: u32 = 16384;
60
61// Producers present from their own threads.
62const _: () = {
63    const fn send_sync<T: Send + Sync>() {}
64    const fn send<T: Send>() {}
65    send_sync::<SurfaceHandle>();
66    send_sync::<D3D11Device>();
67    send_sync::<D3D12Device>();
68    send_sync::<D3D12Fence>();
69    send_sync::<MetalDevice>();
70    send_sync::<MetalEvent>();
71    send::<SharedTexture>();
72};
73
74/// The surface named `name`, created on first use. Every handle and element with that name shares it.
75pub fn surface(name: &str) -> SurfaceHandle {
76    let mut map = lock(registry());
77    let shared = map
78        .entry(name.to_string())
79        .or_insert_with(|| {
80            ANY.store(true, Ordering::Relaxed);
81            let shared = Arc::new(Shared {
82                name: name.into(),
83                state: Mutex::new(State::default()),
84                watchers: Mutex::new(Vec::new()),
85                frames: Mutex::new(Vec::new()),
86            });
87            lock(&shared.state).key = feedback::key(&shared);
88            shared
89        })
90        .clone();
91    SurfaceHandle { shared }
92}
93
94/// Why a surface call failed.
95#[derive(Debug, Clone, PartialEq, Eq)]
96#[non_exhaustive]
97pub enum SurfaceError {
98    /// This platform or renderer has no such path; the message says which one to use.
99    /// [`SurfaceHandle::present_bgra`] works everywhere.
100    NotSupported(&'static str),
101    /// The renderer has no device yet (no window has drawn) or could not make one.
102    NoDevice(String),
103    /// The renderer recreated its device: ask for the device again and recreate textures (or
104    /// reopen shared ones) on it.
105    DeviceChanged,
106    /// The texture was made on another device; open it as a [`SharedTexture`] instead.
107    WrongDevice,
108    /// A pixel format the renderer cannot take; the message names it.
109    Format(String),
110    /// A zero or oversized frame, or a buffer too short for it.
111    Size(String),
112    /// The keyed mutex was not released to the acquire key, or the fence not signalled, in time;
113    /// nothing was presented.
114    Timeout,
115    /// Every texture of this surface is still being copied or shown; nothing was presented.
116    Busy,
117    /// The platform call failed; the message carries its error.
118    Platform(String),
119    /// The frame's format is not the one the surface is set to ([`SurfaceHandle::set_format`]).
120    FormatMismatch {
121        surface: SurfaceFormat,
122        frame: SurfaceFormat,
123    },
124}
125
126/// The pixels a surface takes, set with [`SurfaceHandle::set_format`].
127#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
128#[non_exhaustive]
129pub enum SurfaceFormat {
130    /// 8-bit BGRA, sRGB-encoded, straight alpha: `B8G8R8A8_UNORM`, `BGRA8Unorm`, `'BGRA'`, and
131    /// the 4:2:0 CVPixelBuffers.
132    #[default]
133    Bgra8,
134    /// Half-float RGBA in linear extended sRGB (scRGB primaries, 1.0 = SDR white), straight alpha:
135    /// `R16G16B16A16_FLOAT`, `RGBA16Float`, `'RGhA'`. Shown with values above 1.0 clamped.
136    Rgba16Float,
137}
138
139impl fmt::Display for SurfaceFormat {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        f.write_str(match self {
142            Self::Bgra8 => "Bgra8",
143            Self::Rgba16Float => "Rgba16Float",
144        })
145    }
146}
147
148fn check_format(surface: SurfaceFormat, frame: SurfaceFormat) -> Result<(), SurfaceError> {
149    if surface == frame {
150        Ok(())
151    } else {
152        Err(SurfaceError::FormatMismatch { surface, frame })
153    }
154}
155
156impl fmt::Display for SurfaceError {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        match self {
159            Self::NotSupported(why) => f.write_str(why),
160            Self::NoDevice(why) => write!(f, "the renderer has no GPU device: {why}"),
161            Self::DeviceChanged => f.write_str(
162                "the renderer recreated its device; get it again (d3d11_device, d3d12_device, \
163                 metal_device) and recreate the textures",
164            ),
165            Self::WrongDevice => f.write_str(
166                "the texture is not on the renderer's device (d3d11_device, d3d12_device, \
167                 metal_device); share it (CreateSharedHandle, or an IOSurface on macOS) and \
168                 present it as a SharedTexture",
169            ),
170            Self::Format(why) | Self::Size(why) => f.write_str(why),
171            Self::Timeout => f.write_str(
172                "the producer did not release the keyed mutex to the acquire key, or signal the \
173                 fence, in time",
174            ),
175            Self::Busy => f.write_str(
176                "every texture of this surface is still in use: the producer presents faster than \
177                 the window draws, or a fence it waits on is never signalled; drop this frame",
178            ),
179            Self::Platform(why) => f.write_str(why),
180            Self::FormatMismatch { surface, frame } => write!(
181                f,
182                "a {frame} frame on a surface set to {surface}: present {surface} frames, or call \
183                 set_format(SurfaceFormat::{frame}) first"
184            ),
185        }
186    }
187}
188
189impl std::error::Error for SurfaceError {}
190
191/// Where the elements showing a surface are, for a producer that renders at the painted size.
192#[derive(Clone, Copy, Debug, Default, PartialEq)]
193pub struct SurfaceInfo {
194    /// The largest element's content box in physical pixels; 0 while no element shows the surface.
195    pub width: u32,
196    pub height: u32,
197    /// That element's window scale factor.
198    pub scale: f32,
199    /// Whether any element showing it can be on screen. A hidden one takes no frames.
200    pub visible: bool,
201    /// The display that element is on; the last one known while no element shows the surface.
202    pub display: SurfaceDisplay,
203    /// That element's computed `dynamic-range-limit`.
204    pub dynamic_range_limit: sk_css::DynamicRangeLimit,
205}
206
207impl SurfaceInfo {
208    /// The brightest value a frame should reach, in [`SurfaceDisplay`]'s unit (1.0 is SDR white):
209    /// [`SurfaceDisplay::output_headroom`] as `dynamic-range-limit` allows it, for a producer that
210    /// tone-maps itself, such as a video player's target peak.
211    pub fn content_headroom(&self) -> f32 {
212        self.dynamic_range_limit
213            .headroom(self.display.output_headroom)
214    }
215}
216
217/// A display, in a surface's unit: 1.0 is SDR (paper) white, as in macOS EDR and as Windows
218/// composes SDR content, so scRGB is this scaled by [`Self::sdr_white_nits`] / 80.
219#[derive(Clone, Copy, Debug, PartialEq)]
220pub struct SurfaceDisplay {
221    /// Whether the platform reported it: not on Linux, and not before the window first drew.
222    pub known: bool,
223    /// The display is in HDR: Windows' HDR (PQ) mode, or a macOS screen with EDR headroom.
224    pub hdr: bool,
225    /// The brightest value it shows now; 1.0 on an SDR display. On macOS it follows the brightness,
226    /// and is 1.0 until a window on the screen asks for EDR.
227    pub headroom: f32,
228    /// The brightest it can show (macOS at full brightness); `headroom` on Windows.
229    pub potential_headroom: f32,
230    /// The brightest value a surface's frame reaches the display with: `headroom` where the
231    /// window can draw HDR (Windows, macOS), else 1.0, where frames are clamped.
232    pub output_headroom: f32,
233    /// Whether that element's window draws HDR now (a half-float swap chain or layer): while it
234    /// shows a half-float surface that may be brighter than SDR white, and two seconds after.
235    pub output_hdr: bool,
236    /// SDR white in nits: Windows in HDR mode (its SDR content brightness setting).
237    pub sdr_white_nits: Option<f32>,
238    /// The display's peak and full-frame luminance in nits, where Windows knows them.
239    pub peak_nits: Option<f32>,
240    pub full_frame_nits: Option<f32>,
241    /// The refresh rate in Hz: Windows' current mode, the screen's maximum on macOS.
242    pub refresh_hz: Option<f32>,
243    /// Whether the screen refreshes at a variable rate (macOS: ProMotion, Adaptive-Sync).
244    pub variable_refresh: Option<bool>,
245    /// The refresh period: on Windows measured from the vsync thread's vblank waits (since 0.5),
246    /// else from `refresh_hz`.
247    pub refresh_period: Option<Duration>,
248    /// When its latest vblank was, in [`monotonic_ns`]'s clock, as `info()` was called: never after
249    /// that, and at most `refresh_period` before. Off Windows it is extrapolated from the last
250    /// frame shown, so it is known once one was.
251    pub last_vblank: Option<u64>,
252}
253
254impl Default for SurfaceDisplay {
255    fn default() -> Self {
256        Self {
257            known: false,
258            hdr: false,
259            headroom: 1.0,
260            potential_headroom: 1.0,
261            output_headroom: 1.0,
262            output_hdr: false,
263            sdr_white_nits: None,
264            peak_nits: None,
265            full_frame_nits: None,
266            refresh_hz: None,
267            variable_refresh: None,
268            refresh_period: None,
269            last_vblank: None,
270        }
271    }
272}
273
274impl SurfaceDisplay {
275    /// A surface value in nits, where the SDR white level is known.
276    pub fn nits(&self, value: f32) -> Option<f32> {
277        self.sdr_white_nits.map(|white| value * white)
278    }
279
280    /// Whether `other` differs enough to report: a flag, or a level by more than 1 %.
281    fn differs(&self, other: &SurfaceDisplay) -> bool {
282        let level = |a: f32, b: f32| (a - b).abs() > 0.01 * a.abs().max(b.abs()).max(1.0);
283        let maybe = |a: Option<f32>, b: Option<f32>| match (a, b) {
284            (Some(a), Some(b)) => level(a, b),
285            (a, b) => a.is_some() != b.is_some(),
286        };
287        self.known != other.known
288            || self.hdr != other.hdr
289            || self.output_hdr != other.output_hdr
290            || self.variable_refresh != other.variable_refresh
291            || level(self.headroom, other.headroom)
292            || level(self.potential_headroom, other.potential_headroom)
293            || level(self.output_headroom, other.output_headroom)
294            || maybe(self.sdr_white_nits, other.sdr_white_nits)
295            || maybe(self.peak_nits, other.peak_nits)
296            || maybe(self.full_frame_nits, other.full_frame_nits)
297            || maybe(self.refresh_hz, other.refresh_hz)
298    }
299}
300
301/// What [`SurfaceHandle::on_change`] reports.
302#[derive(Clone, Copy, Debug, PartialEq)]
303pub enum SurfaceEvent {
304    /// The size, scale or visibility changed.
305    Changed(SurfaceInfo),
306    /// The renderer's device was removed or recreated; the frame is gone and GPU resources must be
307    /// dropped, and made again once there is a device.
308    DeviceLost,
309    /// The display became known, changed (headroom, SDR white, refresh rate), the window switched
310    /// to or from HDR output, or the largest element moved to another one.
311    DisplayChanged(SurfaceDisplay),
312}
313
314/// Frame counters, for a producer that wants to know whether its frames are seen.
315#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
316pub struct SurfaceStats {
317    pub presented: u64,
318    /// Frames that reached at least one element. A frame replaced before a visible element painted
319    /// it is not counted.
320    pub shown: u64,
321}
322
323/// What became of a presented frame, reported once per frame in frame order
324/// ([`SurfaceHandle::on_frame`]).
325#[derive(Clone, Copy, Debug, PartialEq, Eq)]
326pub enum FrameEvent {
327    /// The frame reached the screen, on the refresh that began at `shown_at` ([`monotonic_ns`]'s
328    /// clock). `refresh_interval` is that refresh's distance from the one before.
329    Presented {
330        frame: u64,
331        shown_at: u64,
332        refresh_interval: Duration,
333        precision: FramePrecision,
334    },
335    /// The frame never reached the screen.
336    Dropped { frame: u64, reason: FrameDropReason },
337}
338
339impl FrameEvent {
340    /// The frame id its present returned.
341    pub fn frame(&self) -> u64 {
342        match *self {
343            Self::Presented { frame, .. } | Self::Dropped { frame, .. } => frame,
344        }
345    }
346
347    fn dropped(frame: u64, reason: FrameDropReason) -> Self {
348        Self::Dropped { frame, reason }
349    }
350}
351
352/// How [`FrameEvent::Presented`]'s `shown_at` was known.
353#[derive(Clone, Copy, Debug, PartialEq, Eq)]
354pub enum FramePrecision {
355    /// Read from the display's own timing.
356    Exact,
357    /// Inferred, within a refresh either way.
358    Estimated,
359}
360
361/// Why a frame never reached the screen.
362#[derive(Clone, Copy, Debug, PartialEq, Eq)]
363pub enum FrameDropReason {
364    /// A newer frame replaced it first.
365    Superseded,
366    /// No element showing the surface could be on screen (`info().visible` false, or the window
367    /// minimised, covered or hidden).
368    Hidden,
369    /// The renderer lost its device.
370    DeviceLost,
371    /// The window showing it closed, or the app quit.
372    Closed,
373}
374
375/// What [`SurfaceHandle::present_d3d12`] and [`SurfaceHandle::present_metal_texture`] return.
376#[derive(Clone, Copy, Debug, PartialEq, Eq)]
377pub struct FramePresent {
378    /// The frame's id, as [`FrameEvent`] names it.
379    pub frame: u64,
380    /// The value the release fence or event reaches once the producer's texture is free.
381    pub release: u64,
382}
383
384type FrameCallback = Arc<Mutex<Box<dyn FnMut(FrameEvent) + Send>>>;
385
386/// A named surface. Cheap to clone, `Send + Sync`; present from any thread.
387#[derive(Clone)]
388pub struct SurfaceHandle {
389    shared: Arc<Shared>,
390}
391
392impl fmt::Debug for SurfaceHandle {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        f.debug_struct("SurfaceHandle")
395            .field("name", &self.shared.name)
396            .finish()
397    }
398}
399
400type Watcher = Arc<dyn Fn(&SurfaceHandle, SurfaceEvent) + Send + Sync>;
401
402pub(crate) struct Shared {
403    name: Arc<str>,
404    state: Mutex<State>,
405    watchers: Mutex<Vec<(u64, Watcher)>>,
406    frames: Mutex<Vec<(u64, FrameCallback)>>,
407}
408
409impl Shared {
410    fn frame_event(&self, event: FrameEvent) {
411        let callbacks: Vec<FrameCallback> =
412            lock(&self.frames).iter().map(|(_, f)| f.clone()).collect();
413        for callback in callbacks {
414            (lock(&callback))(event);
415        }
416    }
417}
418
419#[derive(Default)]
420pub(crate) struct State {
421    pub(crate) seq: u64,
422    pub(crate) frame: Option<Frame>,
423    /// The id of `frame`, and of the last frame presented.
424    pub(crate) frame_id: u64,
425    key: feedback::Key,
426    /// Whether anything listens to [`SurfaceHandle::on_frame`].
427    watched: bool,
428    /// Why the frame went, when it did: the element's `surfacelost` reason.
429    pub(crate) lost: &'static str,
430    presented: u64,
431    shown: u64,
432    shown_seq: u64,
433    /// The newest frame present feedback was told is ready to be shown.
434    settled: u64,
435    info: SurfaceInfo,
436    pub(crate) format: SurfaceFormat,
437    #[cfg(windows)]
438    gpu: d3d11::SurfaceGpu,
439    #[cfg(windows)]
440    gpu12: d3d12::SurfaceGpu,
441    #[cfg(target_os = "macos")]
442    metal: metal::SurfaceGpu,
443}
444
445#[derive(Clone)]
446pub(crate) enum Frame {
447    /// BGRA, straight alpha, rows packed; a half-float frame's own values too while a window can
448    /// draw HDR.
449    Cpu {
450        width: u32,
451        height: u32,
452        bgra: Arc<[u8]>,
453        halves: Option<Arc<[u16]>>,
454    },
455    /// In the surface's own texture on the renderer's device.
456    #[cfg(windows)]
457    Gpu { width: u32, height: u32 },
458    /// In one of the surface's D3D12 textures, once the copy into it has run.
459    #[cfg(windows)]
460    D3D12 { width: u32, height: u32 },
461    /// In one of the surface's Metal textures, once the copy into it has run.
462    #[cfg(target_os = "macos")]
463    Metal { width: u32, height: u32 },
464}
465
466impl Frame {
467    pub(crate) fn size(&self) -> (u32, u32) {
468        match self {
469            Frame::Cpu { width, height, .. } => (*width, *height),
470            #[cfg(windows)]
471            Frame::Gpu { width, height } | Frame::D3D12 { width, height } => (*width, *height),
472            #[cfg(target_os = "macos")]
473            Frame::Metal { width, height } => (*width, *height),
474        }
475    }
476}
477
478impl State {
479    fn put(&mut self, frame: Frame) -> u64 {
480        self.seq += 1;
481        self.presented += 1;
482        self.frame = Some(frame);
483        self.lost = "";
484        self.frame_id += 1;
485        if self.watched {
486            let (key, id, visible) = (self.key, self.frame_id, self.info.visible);
487            feedback::with(|t| t.put(key, id, visible));
488        }
489        let id = self.frame_id;
490        let copied_later = match &self.frame {
491            #[cfg(windows)]
492            Some(Frame::D3D12 { .. }) => true,
493            #[cfg(target_os = "macos")]
494            Some(Frame::Metal { .. }) => true,
495            _ => false,
496        };
497        if !copied_later {
498            self.settle(id);
499        }
500        id
501    }
502
503    pub(crate) fn note_shown(&mut self, seq: u64) {
504        if seq > self.shown_seq {
505            self.shown_seq = seq;
506            self.shown += 1;
507        }
508    }
509
510    /// Frame `frame` is ready to be shown, so no older one will be.
511    pub(crate) fn settle(&mut self, frame: u64) {
512        if frame > self.settled {
513            self.settled = frame;
514            if self.watched {
515                let key = self.key;
516                feedback::with(|t| t.settle(key, frame));
517            }
518        }
519    }
520
521    /// The tick is writing `frame`; called under the lock it read the frame with.
522    pub(crate) fn pin(&mut self, frame: u64) {
523        if self.watched {
524            let key = self.key;
525            feedback::with(|t| t.pin(key, frame));
526        }
527    }
528
529    /// The texture the atlas copies for a [`Frame::Gpu`], referenced for the caller; with `hdr`, a
530    /// half-float frame's own texture instead of its 8-bit mapping.
531    #[cfg(windows)]
532    pub(crate) fn gpu_texture(
533        &mut self,
534        hdr: bool,
535    ) -> Result<Option<d3d11::Texture>, SurfaceError> {
536        self.gpu.texture(hdr)
537    }
538}
539
540fn registry() -> &'static Mutex<HashMap<String, Arc<Shared>>> {
541    static REGISTRY: std::sync::OnceLock<Mutex<HashMap<String, Arc<Shared>>>> =
542        std::sync::OnceLock::new();
543    REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
544}
545
546static ANY: AtomicBool = AtomicBool::new(false);
547
548/// Whether `key`'s window can draw HDR on its display now: `dynamic-range: high`.
549pub(crate) fn dynamic_range_high(key: crate::windows::WinKey) -> bool {
550    display::dynamic_range_high(key)
551}
552
553pub(crate) fn any() -> bool {
554    ANY.load(Ordering::Relaxed)
555}
556
557/// The page was hidden: no element shows a frame now, whether or not a tick runs to say so.
558pub(crate) fn page_hidden() {
559    for surface in all() {
560        let info = surface.state().info;
561        if info.visible {
562            surface.set_info(SurfaceInfo {
563                visible: false,
564                ..info
565            });
566        }
567    }
568}
569
570pub(crate) fn all() -> Vec<SurfaceHandle> {
571    lock(registry())
572        .values()
573        .map(|shared| SurfaceHandle {
574            shared: shared.clone(),
575        })
576        .collect()
577}
578
579fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
580    m.lock().unwrap_or_else(|p| p.into_inner())
581}
582
583impl SurfaceHandle {
584    pub fn name(&self) -> &str {
585        &self.shared.name
586    }
587
588    pub fn info(&self) -> SurfaceInfo {
589        let mut info = self.state().info;
590        info.display = self.with_clock(info.display);
591        info
592    }
593
594    fn with_clock(&self, mut display: SurfaceDisplay) -> SurfaceDisplay {
595        if display.known {
596            (display.last_vblank, display.refresh_period) =
597                feedback::display_clock(feedback::key(&self.shared), display.refresh_hz);
598        }
599        display
600    }
601
602    /// Calls `f` with what became of each frame presented from now on: exactly one
603    /// [`FrameEvent`] per frame id, in frame order, until the returned guard drops. `f` runs on
604    /// Skathi's vsync thread (on macOS a thread of its own), not the UI thread; keep it short.
605    pub fn on_frame(&self, f: impl FnMut(FrameEvent) + Send + 'static) -> FrameWatch {
606        static NEXT: AtomicU64 = AtomicU64::new(1);
607        let id = NEXT.fetch_add(1, Ordering::Relaxed);
608        lock(&self.shared.frames).push((id, Arc::new(Mutex::new(Box::new(f)))));
609        let mut st = self.state();
610        if !st.watched {
611            st.watched = true;
612            feedback::watch(&self.shared);
613        }
614        FrameWatch {
615            shared: Arc::downgrade(&self.shared),
616            id,
617        }
618    }
619
620    pub fn stats(&self) -> SurfaceStats {
621        let st = self.state();
622        SurfaceStats {
623            presented: st.presented,
624            shown: st.shown,
625        }
626    }
627
628    /// Calls `f` on the UI thread when [`SurfaceInfo`] changes or the device is lost, until the
629    /// returned guard drops. Keep it short; it may present.
630    pub fn on_change(
631        &self,
632        f: impl Fn(&SurfaceHandle, SurfaceEvent) + Send + Sync + 'static,
633    ) -> SurfaceWatch {
634        static NEXT: AtomicU64 = AtomicU64::new(1);
635        let id = NEXT.fetch_add(1, Ordering::Relaxed);
636        lock(&self.shared.watchers).push((id, Arc::new(f)));
637        SurfaceWatch {
638            shared: Arc::downgrade(&self.shared),
639            id,
640        }
641    }
642
643    /// Sets the pixel format presents must have; [`SurfaceFormat::Bgra8`] until set. The frame
644    /// already shown stays until the next present.
645    pub fn set_format(&self, format: SurfaceFormat) {
646        self.state().format = format;
647    }
648
649    pub fn format(&self) -> SurfaceFormat {
650        self.state().format
651    }
652
653    /// Presents a CPU frame: BGRA with straight alpha, `stride` bytes per row. Works on every
654    /// platform. Every present returns the frame's id ([`Self::on_frame`]).
655    pub fn present_bgra(
656        &self,
657        pixels: &[u8],
658        width: u32,
659        height: u32,
660        stride: usize,
661    ) -> Result<u64, SurfaceError> {
662        self.present_cpu(pixels, width, height, stride, false)
663    }
664
665    /// Presents a CPU frame to a [`SurfaceFormat::Rgba16Float`] surface: RGBA half floats (IEEE
666    /// binary16 bits), straight alpha, `stride` values per row. It is mapped to 8-bit sRGB here,
667    /// and kept as it is too while a window can draw HDR.
668    pub fn present_rgba16f(
669        &self,
670        pixels: &[u16],
671        width: u32,
672        height: u32,
673        stride: usize,
674    ) -> Result<u64, SurfaceError> {
675        check_format(self.format(), SurfaceFormat::Rgba16Float)?;
676        check_size(width, height)?;
677        let row = width as usize * 4;
678        let need = stride * (height as usize - 1) + row;
679        if stride < row || pixels.len() < need {
680            return Err(SurfaceError::Size(format!(
681                "a {width}x{height} half-float frame with stride {stride} needs {need} values and \
682                 a stride of at least {row}; got {}",
683                pixels.len()
684            )));
685        }
686        let bgra = color::rgba16f_to_bgra8(pixels, width, height, stride);
687        let halves = display::any_capable().then(|| {
688            (0..height as usize)
689                .flat_map(|y| &pixels[y * stride..y * stride + row])
690                .copied()
691                .collect()
692        });
693        let frame = self.state().put(Frame::Cpu {
694            width,
695            height,
696            bgra: bgra.into(),
697            halves,
698        });
699        sk_runtime::frames::wake();
700        Ok(frame)
701    }
702
703    /// [`Self::present_bgra`] for BGRX: the fourth byte is ignored and the frame is opaque.
704    pub fn present_bgrx(
705        &self,
706        pixels: &[u8],
707        width: u32,
708        height: u32,
709        stride: usize,
710    ) -> Result<u64, SurfaceError> {
711        self.present_cpu(pixels, width, height, stride, true)
712    }
713
714    fn present_cpu(
715        &self,
716        pixels: &[u8],
717        width: u32,
718        height: u32,
719        stride: usize,
720        opaque: bool,
721    ) -> Result<u64, SurfaceError> {
722        check_format(self.format(), SurfaceFormat::Bgra8)?;
723        check_size(width, height)?;
724        let row = width as usize * 4;
725        let need = stride * (height as usize - 1) + row;
726        if stride < row || pixels.len() < need {
727            return Err(SurfaceError::Size(format!(
728                "a {width}x{height} BGRA frame with stride {stride} needs {need} bytes and a stride \
729                 of at least {row}; got {} bytes",
730                pixels.len()
731            )));
732        }
733        let mut packed = Vec::with_capacity(row * height as usize);
734        for y in 0..height as usize {
735            packed.extend_from_slice(&pixels[y * stride..y * stride + row]);
736        }
737        if opaque {
738            for alpha in packed.iter_mut().skip(3).step_by(4) {
739                *alpha = 255;
740            }
741        }
742        let frame = self.state().put(Frame::Cpu {
743            width,
744            height,
745            bgra: packed.into(),
746            halves: None,
747        });
748        sk_runtime::frames::wake();
749        Ok(frame)
750    }
751
752    /// Withdraws the frame: elements paint nothing and fire `surfacelost` with reason `"cleared"`.
753    pub fn clear(&self) {
754        let mut st = self.state();
755        if st.frame.take().is_some() {
756            st.seq += 1;
757            st.lost = "cleared";
758            #[cfg(windows)]
759            st.gpu12.withdraw();
760            #[cfg(target_os = "macos")]
761            st.metal.withdraw();
762            if st.watched {
763                let key = st.key;
764                feedback::with(|t| t.cleared(key));
765            }
766        }
767        drop(st);
768        sk_runtime::frames::wake();
769    }
770
771    /// The renderer's D3D11 device. Textures for [`Self::present_d3d11_texture`] are made on it.
772    pub fn d3d11_device(&self) -> Result<D3D11Device, SurfaceError> {
773        #[cfg(windows)]
774        {
775            d3d11::device(&self.shared.state).map(|inner| D3D11Device { inner })
776        }
777        #[cfg(not(windows))]
778        {
779            Err(SurfaceError::NotSupported(NO_D3D))
780        }
781    }
782
783    /// Presents an `ID3D11Texture2D` made on [`Self::d3d11_device`]: `B8G8R8A8_UNORM`, `_UNORM_SRGB`
784    /// or `_TYPELESS` (`R16G16B16A16_FLOAT` on a [`SurfaceFormat::Rgba16Float`] surface), straight
785    /// alpha, mip 0, any sample count. The texture is copied on the GPU before this returns, so the
786    /// producer may render its next frame into it at once.
787    ///
788    /// # Safety
789    /// `texture` is a live `ID3D11Texture2D` COM pointer, or null.
790    pub unsafe fn present_d3d11_texture(&self, texture: *mut c_void) -> Result<u64, SurfaceError> {
791        #[cfg(windows)]
792        {
793            // SAFETY: the caller's.
794            let frame = unsafe { d3d11::present_texture(&self.shared.state, texture) }?;
795            sk_runtime::frames::wake();
796            Ok(frame)
797        }
798        #[cfg(not(windows))]
799        {
800            let _ = texture;
801            Err(SurfaceError::NotSupported(NO_D3D))
802        }
803    }
804
805    /// The renderer's D3D12 device and direct queue, under the D3D12 renderer.
806    pub fn d3d12_device(&self) -> Result<D3D12Device, SurfaceError> {
807        #[cfg(windows)]
808        {
809            d3d12::device(&self.shared.state).map(|inner| D3D12Device { inner })
810        }
811        #[cfg(not(windows))]
812        {
813            Err(SurfaceError::NotSupported(NO_D3D))
814        }
815    }
816
817    /// This surface's fence, which [`Self::present_d3d12`] signals once it has copied a frame out
818    /// of the producer's resource.
819    pub fn release_fence(&self) -> Result<D3D12Fence, SurfaceError> {
820        #[cfg(windows)]
821        {
822            d3d12::release_fence(&self.shared.state).map(|inner| D3D12Fence { inner })
823        }
824        #[cfg(not(windows))]
825        {
826            Err(SurfaceError::NotSupported(NO_D3D))
827        }
828    }
829
830    /// Presents an `ID3D12Resource` made on [`Self::d3d12_device`]: a 2D `B8G8R8A8_UNORM` (or
831    /// `_UNORM_SRGB`, `_TYPELESS`; `R16G16B16A16_FLOAT` on a [`SurfaceFormat::Rgba16Float`] surface)
832    /// texture, single-sampled, straight alpha, in `resource_state` (a
833    /// `D3D12_RESOURCE_STATES`, left as it is). The copy runs on a queue of the surface's own after
834    /// a GPU wait for `ready` (fence, value); without `ready` the resource must already be written.
835    /// Nothing blocks. Returns the frame's id and the value [`Self::release_fence`] reaches once the
836    /// resource is free to reuse.
837    ///
838    /// # Safety
839    /// `resource` is null or a live `ID3D12Resource`; `ready`'s fence is a live `ID3D12Fence`.
840    pub unsafe fn present_d3d12(
841        &self,
842        resource: *mut c_void,
843        resource_state: i32,
844        ready: Option<(*mut c_void, u64)>,
845    ) -> Result<FramePresent, SurfaceError> {
846        #[cfg(windows)]
847        {
848            // SAFETY: the caller's.
849            let (frame, release) =
850                unsafe { d3d12::present(&self.shared.state, resource, resource_state, ready) }?;
851            sk_runtime::frames::wake();
852            Ok(FramePresent { frame, release })
853        }
854        #[cfg(not(windows))]
855        {
856            let _ = (resource, resource_state, ready);
857            Err(SurfaceError::NotSupported(NO_D3D))
858        }
859    }
860
861    /// Presents a shared texture from another device or process (see [`SharedTexture`]); one
862    /// opened with a fence takes [`Self::present_shared_fenced`] instead.
863    pub fn present_shared(&self, texture: &SharedTexture) -> Result<u64, SurfaceError> {
864        #[cfg(windows)]
865        {
866            if texture.inner.fenced {
867                return Err(SurfaceError::Format(
868                    "the shared texture has a fence: present it with present_shared_fenced".into(),
869                ));
870            }
871            let sync = match texture.keys {
872                Some((acquire, release)) => d3d11::SharedSync::Keyed(acquire, release),
873                None => d3d11::SharedSync::None,
874            };
875            let frame = texture
876                .inner
877                .present(&self.shared.state, sync, texture.timeout_ms)?;
878            sk_runtime::frames::wake();
879            Ok(frame)
880        }
881        #[cfg(target_os = "macos")]
882        {
883            if texture.keyed {
884                return Err(SurfaceError::NotSupported(
885                    "a keyed mutex is a Direct3D object; on macOS synchronise with an \
886                     MTLSharedEvent (SharedTexture::with_shared_event)",
887                ));
888            }
889            if texture.inner.fenced() {
890                return Err(SurfaceError::Format(
891                    "the shared texture has a shared event: present it with present_shared_fenced"
892                        .into(),
893                ));
894            }
895            let frame = metal::present_shared(&self.shared.state, &texture.inner, None)?;
896            sk_runtime::frames::wake();
897            Ok(frame)
898        }
899        #[cfg(not(any(windows, target_os = "macos")))]
900        {
901            match texture.never {}
902        }
903    }
904
905    /// Presents a shared texture opened [`SharedTexture::with_fence`] (Windows) or
906    /// [`SharedTexture::with_shared_event`] (macOS): the copy waits until the fence or event
907    /// reaches `wait`, then it is signalled to `release` (the producer may write the texture again
908    /// once it gets there).
909    pub fn present_shared_fenced(
910        &self,
911        texture: &SharedTexture,
912        wait: u64,
913        release: u64,
914    ) -> Result<u64, SurfaceError> {
915        #[cfg(windows)]
916        {
917            if !texture.inner.fenced {
918                return Err(SurfaceError::Format(
919                    "the shared texture has no fence: open it with SharedTexture::with_fence"
920                        .into(),
921                ));
922            }
923            let frame = texture.inner.present(
924                &self.shared.state,
925                d3d11::SharedSync::Fence(wait, release),
926                texture.timeout_ms,
927            )?;
928            sk_runtime::frames::wake();
929            Ok(frame)
930        }
931        #[cfg(target_os = "macos")]
932        {
933            if !texture.inner.fenced() {
934                return Err(SurfaceError::Format(
935                    "the shared texture has no shared event: open it with \
936                     SharedTexture::with_shared_event"
937                        .into(),
938                ));
939            }
940            let frame =
941                metal::present_shared(&self.shared.state, &texture.inner, Some((wait, release)))?;
942            sk_runtime::frames::wake();
943            Ok(frame)
944        }
945        #[cfg(not(any(windows, target_os = "macos")))]
946        {
947            let _ = (wait, release);
948            match texture.never {}
949        }
950    }
951
952    /// The renderer's `MTLDevice`, on macOS. Textures for [`Self::present_metal_texture`] are made
953    /// on it.
954    pub fn metal_device(&self) -> Result<MetalDevice, SurfaceError> {
955        #[cfg(target_os = "macos")]
956        {
957            metal::device(&self.shared.state).map(|inner| MetalDevice { inner })
958        }
959        #[cfg(not(target_os = "macos"))]
960        {
961            Err(SurfaceError::NotSupported(NO_METAL))
962        }
963    }
964
965    /// This surface's `MTLSharedEvent`, which [`Self::present_metal_texture`] signals once it has
966    /// copied a frame out of the producer's texture.
967    pub fn release_event(&self) -> Result<MetalEvent, SurfaceError> {
968        #[cfg(target_os = "macos")]
969        {
970            metal::release_event(&self.shared.state).map(|inner| MetalEvent { inner })
971        }
972        #[cfg(not(target_os = "macos"))]
973        {
974            Err(SurfaceError::NotSupported(NO_METAL))
975        }
976    }
977
978    /// Presents an `id<MTLTexture>` made on [`Self::metal_device`]: 2D, `BGRA8Unorm` (or
979    /// `BGRA8Unorm_sRGB`; `RGBA16Float` on a [`SurfaceFormat::Rgba16Float`] surface),
980    /// single-sampled, straight alpha. The copy runs on a queue of the
981    /// surface's own after a GPU wait for `ready` (an `id<MTLSharedEvent>` and the value the
982    /// producer signals after its last write); without `ready` the texture must already be
983    /// written. Nothing blocks. Returns the frame's id and the value [`Self::release_event`]
984    /// reaches once the texture is free to reuse.
985    ///
986    /// # Safety
987    /// `texture` is null or a live `id<MTLTexture>`; `ready`'s event is a live
988    /// `id<MTLSharedEvent>`.
989    pub unsafe fn present_metal_texture(
990        &self,
991        texture: *mut c_void,
992        ready: Option<(*mut c_void, u64)>,
993    ) -> Result<FramePresent, SurfaceError> {
994        #[cfg(target_os = "macos")]
995        {
996            // SAFETY: the caller's.
997            let (frame, release) = unsafe { metal::present(&self.shared.state, texture, ready) }?;
998            sk_runtime::frames::wake();
999            Ok(FramePresent { frame, release })
1000        }
1001        #[cfg(not(target_os = "macos"))]
1002        {
1003            let _ = (texture, ready);
1004            Err(SurfaceError::NotSupported(NO_METAL))
1005        }
1006    }
1007
1008    /// Presents a `CVPixelBufferRef` (VideoToolbox, AVFoundation, ScreenCaptureKit): BGRA
1009    /// (`kCVPixelFormatType_32BGRA`) or 4:2:0 bi-planar (`420v`, `420f`, converted with the
1010    /// buffer's YCbCr matrix, BT.709 when it names none); `RGhA` (`kCVPixelFormatType_64RGBAHalf`)
1011    /// on a [`SurfaceFormat::Rgba16Float`] surface. The buffer is retained until the GPU copied it;
1012    /// a BGRA or RGhA one with no IOSurface is copied on the CPU. It must be fully written.
1013    ///
1014    /// # Safety
1015    /// `buffer` is null or a live `CVPixelBufferRef`.
1016    pub unsafe fn present_cv_pixel_buffer(&self, buffer: *mut c_void) -> Result<u64, SurfaceError> {
1017        #[cfg(target_os = "macos")]
1018        {
1019            let cpu = |cpu: metal::Cpu<'_>| match cpu.format {
1020                SurfaceFormat::Bgra8 => {
1021                    self.present_cpu(cpu.pixels, cpu.width, cpu.height, cpu.stride, false)
1022                }
1023                SurfaceFormat::Rgba16Float => {
1024                    if cpu.pixels.as_ptr().align_offset(2) != 0 || cpu.stride % 2 != 0 {
1025                        return Err(SurfaceError::Platform(
1026                            "a misaligned RGhA CVPixelBuffer".into(),
1027                        ));
1028                    }
1029                    // SAFETY: aligned above; the buffer stays locked while this runs.
1030                    let halves = unsafe {
1031                        std::slice::from_raw_parts(
1032                            cpu.pixels.as_ptr().cast::<u16>(),
1033                            cpu.pixels.len() / 2,
1034                        )
1035                    };
1036                    self.present_rgba16f(halves, cpu.width, cpu.height, cpu.stride / 2)
1037                }
1038            };
1039            // SAFETY: the caller's.
1040            let frame = unsafe { metal::present_pixel_buffer(&self.shared.state, buffer, cpu) }?;
1041            sk_runtime::frames::wake();
1042            Ok(frame)
1043        }
1044        #[cfg(not(target_os = "macos"))]
1045        {
1046            let _ = buffer;
1047            Err(SurfaceError::NotSupported(NO_METAL))
1048        }
1049    }
1050
1051    fn state(&self) -> MutexGuard<'_, State> {
1052        lock(&self.shared.state)
1053    }
1054
1055    pub(crate) fn shared(&self) -> &Arc<Shared> {
1056        &self.shared
1057    }
1058
1059    pub(crate) fn lock_state(&self) -> MutexGuard<'_, State> {
1060        self.state()
1061    }
1062
1063    /// Records what the elements report and tells the watchers when it changed. A display that is
1064    /// unknown, or within [`SurfaceDisplay::differs`]' margin of the last one, is not taken.
1065    pub(crate) fn set_info(&self, mut info: SurfaceInfo) {
1066        let (changed, display) = {
1067            let mut st = self.state();
1068            let old = st.info;
1069            let display = info.display.known && info.display.differs(&old.display);
1070            if !display {
1071                info.display = old.display;
1072            }
1073            st.info = info;
1074            if st.watched {
1075                let key = st.key;
1076                feedback::with(|t| t.visibility(key, info.visible));
1077            }
1078            (
1079                info != SurfaceInfo {
1080                    display: info.display,
1081                    ..old
1082                },
1083                display,
1084            )
1085        };
1086        if changed {
1087            self.notify(SurfaceEvent::Changed(info));
1088        }
1089        if display {
1090            self.notify(SurfaceEvent::DisplayChanged(self.with_clock(info.display)));
1091        }
1092    }
1093
1094    pub(crate) fn notify(&self, event: SurfaceEvent) {
1095        let watchers: Vec<Watcher> = lock(&self.shared.watchers)
1096            .iter()
1097            .map(|(_, w)| w.clone())
1098            .collect();
1099        for watcher in watchers {
1100            watcher(self, event);
1101        }
1102    }
1103
1104    /// The renderer replaced its device: a GPU frame and its texture are gone.
1105    pub(crate) fn device_lost(&self) {
1106        #[cfg(windows)]
1107        {
1108            let mut st = self.state();
1109            if matches!(st.frame, Some(Frame::Gpu { .. } | Frame::D3D12 { .. })) {
1110                st.frame = None;
1111                st.seq += 1;
1112                st.lost = "device";
1113            }
1114            st.gpu.forget();
1115            st.gpu12.forget();
1116        }
1117        #[cfg(target_os = "macos")]
1118        {
1119            let mut st = self.state();
1120            if matches!(st.frame, Some(Frame::Metal { .. })) {
1121                st.frame = None;
1122                st.seq += 1;
1123                st.lost = "device";
1124            }
1125            st.metal.forget();
1126        }
1127        self.notify(SurfaceEvent::DeviceLost);
1128    }
1129}
1130
1131fn check_size(width: u32, height: u32) -> Result<(), SurfaceError> {
1132    if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE {
1133        return Err(SurfaceError::Size(format!(
1134            "a {width}x{height} frame: each side must be 1 to {MAX_SIDE} pixels"
1135        )));
1136    }
1137    Ok(())
1138}
1139
1140/// Ends an [`SurfaceHandle::on_change`] subscription when dropped.
1141#[must_use = "dropping the guard ends the subscription"]
1142pub struct SurfaceWatch {
1143    shared: Weak<Shared>,
1144    id: u64,
1145}
1146
1147impl Drop for SurfaceWatch {
1148    fn drop(&mut self) {
1149        if let Some(shared) = self.shared.upgrade() {
1150            lock(&shared.watchers).retain(|(id, _)| *id != self.id);
1151        }
1152    }
1153}
1154
1155/// Ends an [`SurfaceHandle::on_frame`] subscription when dropped. Frames of a surface nobody
1156/// listens to are not tracked.
1157#[must_use = "dropping the guard ends the subscription"]
1158pub struct FrameWatch {
1159    shared: Weak<Shared>,
1160    id: u64,
1161}
1162
1163impl Drop for FrameWatch {
1164    fn drop(&mut self) {
1165        let Some(shared) = self.shared.upgrade() else {
1166            return;
1167        };
1168        let mut st = lock(&shared.state);
1169        let mut frames = lock(&shared.frames);
1170        frames.retain(|(id, _)| *id != self.id);
1171        if frames.is_empty() && st.watched {
1172            st.watched = false;
1173            feedback::unwatch(&shared);
1174        }
1175    }
1176}
1177
1178/// The renderer's `ID3D11Device`, referenced while this lives. Multithread-protected: use it and its
1179/// immediate context from any thread. Raw, so any `windows` crate version can wrap it
1180/// (`ID3D11Device::from_raw_borrowed(&device.as_raw())`).
1181pub struct D3D11Device {
1182    #[cfg(windows)]
1183    inner: d3d11::Device,
1184    #[cfg(not(windows))]
1185    never: std::convert::Infallible,
1186}
1187
1188impl D3D11Device {
1189    /// The `ID3D11Device*`, borrowed from this value.
1190    pub fn as_raw(&self) -> *mut c_void {
1191        #[cfg(windows)]
1192        {
1193            self.inner.as_raw()
1194        }
1195        #[cfg(not(windows))]
1196        {
1197            match self.never {}
1198        }
1199    }
1200
1201    /// Changes when the renderer recreates its device.
1202    pub fn generation(&self) -> u64 {
1203        #[cfg(windows)]
1204        {
1205            self.inner.generation()
1206        }
1207        #[cfg(not(windows))]
1208        {
1209            match self.never {}
1210        }
1211    }
1212}
1213
1214impl fmt::Debug for D3D11Device {
1215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1216        f.debug_struct("D3D11Device")
1217            .field("raw", &self.as_raw())
1218            .field("generation", &self.generation())
1219            .finish()
1220    }
1221}
1222
1223/// The renderer's `ID3D12Device` and its direct `ID3D12CommandQueue`, referenced while this lives.
1224/// Raw, so any `windows` crate version can wrap them.
1225pub struct D3D12Device {
1226    #[cfg(windows)]
1227    inner: d3d12::Device,
1228    #[cfg(not(windows))]
1229    never: std::convert::Infallible,
1230}
1231
1232impl D3D12Device {
1233    /// The `ID3D12Device*`, borrowed from this value.
1234    pub fn as_raw(&self) -> *mut c_void {
1235        #[cfg(windows)]
1236        {
1237            self.inner.as_raw()
1238        }
1239        #[cfg(not(windows))]
1240        {
1241            match self.never {}
1242        }
1243    }
1244
1245    /// The renderer's `ID3D12CommandQueue*`. Work submitted there delays the next frame; a producer
1246    /// with its own queue does not.
1247    pub fn queue(&self) -> *mut c_void {
1248        #[cfg(windows)]
1249        {
1250            self.inner.queue()
1251        }
1252        #[cfg(not(windows))]
1253        {
1254            match self.never {}
1255        }
1256    }
1257
1258    /// Changes when the renderer recreates its device.
1259    pub fn generation(&self) -> u64 {
1260        #[cfg(windows)]
1261        {
1262            self.inner.generation()
1263        }
1264        #[cfg(not(windows))]
1265        {
1266            match self.never {}
1267        }
1268    }
1269}
1270
1271impl fmt::Debug for D3D12Device {
1272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1273        f.debug_struct("D3D12Device")
1274            .field("raw", &self.as_raw())
1275            .field("generation", &self.generation())
1276            .finish()
1277    }
1278}
1279
1280/// The `ID3D12Fence` a surface signals when [`SurfaceHandle::present_d3d12`] is done with a
1281/// resource. Shared (`D3D12_FENCE_FLAG_SHARED`), so a queue on the same device can wait on it too.
1282pub struct D3D12Fence {
1283    #[cfg(windows)]
1284    inner: d3d12::Fence,
1285    #[cfg(not(windows))]
1286    never: std::convert::Infallible,
1287}
1288
1289impl D3D12Fence {
1290    /// The `ID3D12Fence*`, borrowed from this value.
1291    pub fn as_raw(&self) -> *mut c_void {
1292        #[cfg(windows)]
1293        {
1294            self.inner.as_raw()
1295        }
1296        #[cfg(not(windows))]
1297        {
1298            match self.never {}
1299        }
1300    }
1301
1302    pub fn completed_value(&self) -> u64 {
1303        #[cfg(windows)]
1304        {
1305            self.inner.completed()
1306        }
1307        #[cfg(not(windows))]
1308        {
1309            match self.never {}
1310        }
1311    }
1312
1313    /// Blocks until the fence reaches `value` or `timeout` passes; whether it got there.
1314    pub fn wait(&self, value: u64, timeout: Duration) -> bool {
1315        #[cfg(windows)]
1316        {
1317            self.inner.wait(value, timeout)
1318        }
1319        #[cfg(not(windows))]
1320        {
1321            let _ = (value, timeout);
1322            match self.never {}
1323        }
1324    }
1325
1326    /// Changes when the renderer recreates its device.
1327    pub fn generation(&self) -> u64 {
1328        #[cfg(windows)]
1329        {
1330            self.inner.generation()
1331        }
1332        #[cfg(not(windows))]
1333        {
1334            match self.never {}
1335        }
1336    }
1337}
1338
1339impl fmt::Debug for D3D12Fence {
1340    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1341        f.debug_struct("D3D12Fence")
1342            .field("raw", &self.as_raw())
1343            .field("completed", &self.completed_value())
1344            .finish()
1345    }
1346}
1347
1348/// The renderer's `id<MTLDevice>` and the `id<MTLCommandQueue>` of its first window, retained
1349/// while this lives. Raw, so any `objc2` or `metal` crate version can wrap them.
1350pub struct MetalDevice {
1351    #[cfg(target_os = "macos")]
1352    inner: metal::Device,
1353    #[cfg(not(target_os = "macos"))]
1354    never: std::convert::Infallible,
1355}
1356
1357impl MetalDevice {
1358    /// The `id<MTLDevice>`, borrowed from this value.
1359    pub fn as_raw(&self) -> *mut c_void {
1360        #[cfg(target_os = "macos")]
1361        {
1362            self.inner.as_raw()
1363        }
1364        #[cfg(not(target_os = "macos"))]
1365        {
1366            match self.never {}
1367        }
1368    }
1369
1370    /// The renderer's `id<MTLCommandQueue>`. Work committed there delays the next frame; a
1371    /// producer with its own queue does not.
1372    pub fn queue(&self) -> *mut c_void {
1373        #[cfg(target_os = "macos")]
1374        {
1375            self.inner.queue()
1376        }
1377        #[cfg(not(target_os = "macos"))]
1378        {
1379            match self.never {}
1380        }
1381    }
1382
1383    /// Changes when the renderer moves to another device.
1384    pub fn generation(&self) -> u64 {
1385        #[cfg(target_os = "macos")]
1386        {
1387            self.inner.generation()
1388        }
1389        #[cfg(not(target_os = "macos"))]
1390        {
1391            match self.never {}
1392        }
1393    }
1394}
1395
1396impl fmt::Debug for MetalDevice {
1397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1398        f.debug_struct("MetalDevice")
1399            .field("raw", &self.as_raw())
1400            .field("generation", &self.generation())
1401            .finish()
1402    }
1403}
1404
1405/// The `id<MTLSharedEvent>` a surface signals when [`SurfaceHandle::present_metal_texture`] is
1406/// done with a texture. A command buffer on any device can `encodeWaitForEvent` on it.
1407pub struct MetalEvent {
1408    #[cfg(target_os = "macos")]
1409    inner: metal::Event,
1410    #[cfg(not(target_os = "macos"))]
1411    never: std::convert::Infallible,
1412}
1413
1414impl MetalEvent {
1415    /// The `id<MTLSharedEvent>`, borrowed from this value.
1416    pub fn as_raw(&self) -> *mut c_void {
1417        #[cfg(target_os = "macos")]
1418        {
1419            self.inner.as_raw()
1420        }
1421        #[cfg(not(target_os = "macos"))]
1422        {
1423            match self.never {}
1424        }
1425    }
1426
1427    pub fn signaled_value(&self) -> u64 {
1428        #[cfg(target_os = "macos")]
1429        {
1430            self.inner.signaled()
1431        }
1432        #[cfg(not(target_os = "macos"))]
1433        {
1434            match self.never {}
1435        }
1436    }
1437
1438    /// Blocks until the event reaches `value` or `timeout` passes; whether it got there.
1439    pub fn wait(&self, value: u64, timeout: Duration) -> bool {
1440        #[cfg(target_os = "macos")]
1441        {
1442            self.inner.wait(value, timeout)
1443        }
1444        #[cfg(not(target_os = "macos"))]
1445        {
1446            let _ = (value, timeout);
1447            match self.never {}
1448        }
1449    }
1450
1451    /// Changes when the renderer moves to another device.
1452    pub fn generation(&self) -> u64 {
1453        #[cfg(target_os = "macos")]
1454        {
1455            self.inner.generation()
1456        }
1457        #[cfg(not(target_os = "macos"))]
1458        {
1459            match self.never {}
1460        }
1461    }
1462}
1463
1464impl fmt::Debug for MetalEvent {
1465    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1466        f.debug_struct("MetalEvent")
1467            .field("raw", &self.as_raw())
1468            .field("signaled", &self.signaled_value())
1469            .finish()
1470    }
1471}
1472
1473/// A shared BGRA8 or half-float texture opened on the renderer's device, from another device, API
1474/// or process.
1475/// On Windows: D3D11, D3D12, or Vulkan rendering into D3D12 memory it imports. On macOS: an
1476/// IOSurface from another `MTLDevice`, process or framework. Reopen it after
1477/// [`SurfaceError::DeviceChanged`].
1478pub struct SharedTexture {
1479    #[cfg(windows)]
1480    inner: shared::Opened,
1481    #[cfg(windows)]
1482    keys: Option<(u64, u64)>,
1483    #[cfg(windows)]
1484    timeout_ms: u32,
1485    #[cfg(target_os = "macos")]
1486    inner: metal::Opened,
1487    #[cfg(target_os = "macos")]
1488    keyed: bool,
1489    #[cfg(not(any(windows, target_os = "macos")))]
1490    never: std::convert::Infallible,
1491}
1492
1493#[cfg(target_os = "macos")]
1494const NT_HANDLES: &str = "NT handles are Windows-only; on macOS open an IOSurface \
1495                          (SharedTexture::from_iosurface, SharedTexture::from_mach_port)";
1496
1497impl SharedTexture {
1498    #[cfg(windows)]
1499    fn new(inner: shared::Opened) -> Self {
1500        Self {
1501            inner,
1502            keys: None,
1503            timeout_ms: 100,
1504        }
1505    }
1506
1507    #[cfg(target_os = "macos")]
1508    fn new(inner: metal::Opened) -> Self {
1509        Self {
1510            inner,
1511            keyed: false,
1512        }
1513    }
1514
1515    /// Opens a handle this process holds: an NT handle (`CreateSharedHandle` in D3D11 or D3D12)
1516    /// or a legacy one (`IDXGIResource::GetSharedHandle`). The handle stays the caller's to close.
1517    pub fn open(handle: u64) -> Result<Self, SurfaceError> {
1518        #[cfg(windows)]
1519        {
1520            shared::open(handle).map(Self::new)
1521        }
1522        #[cfg(target_os = "macos")]
1523        {
1524            let _ = handle;
1525            Err(SurfaceError::NotSupported(NT_HANDLES))
1526        }
1527        #[cfg(not(any(windows, target_os = "macos")))]
1528        {
1529            let _ = handle;
1530            Err(SurfaceError::NotSupported(NO_D3D))
1531        }
1532    }
1533
1534    /// Duplicates the NT handle `handle` of process `pid` into this process and opens it. Needs
1535    /// `PROCESS_DUP_HANDLE` on that process, which a child or a same-user process grants.
1536    pub fn open_from_process(pid: u32, handle: u64) -> Result<Self, SurfaceError> {
1537        #[cfg(windows)]
1538        {
1539            shared::open_from_process(pid, handle).map(Self::new)
1540        }
1541        #[cfg(target_os = "macos")]
1542        {
1543            let _ = (pid, handle);
1544            Err(SurfaceError::NotSupported(NT_HANDLES))
1545        }
1546        #[cfg(not(any(windows, target_os = "macos")))]
1547        {
1548            let _ = (pid, handle);
1549            Err(SurfaceError::NotSupported(NO_D3D))
1550        }
1551    }
1552
1553    /// Opens an `IOSurfaceRef` this process holds (macOS): pixel format `'BGRA'` (or `'RGhA'`), made
1554    /// by any `MTLDevice` or framework. It is retained while this lives.
1555    ///
1556    /// # Safety
1557    /// `surface` is null or a live `IOSurfaceRef`.
1558    pub unsafe fn from_iosurface(surface: *mut c_void) -> Result<Self, SurfaceError> {
1559        #[cfg(target_os = "macos")]
1560        {
1561            // SAFETY: the caller's.
1562            unsafe { metal::open_raw(surface) }.map(Self::new)
1563        }
1564        #[cfg(not(target_os = "macos"))]
1565        {
1566            let _ = surface;
1567            Err(SurfaceError::NotSupported(NO_METAL))
1568        }
1569    }
1570
1571    /// Opens the IOSurface another process sent as a mach port (`IOSurfaceCreateMachPort`), a
1572    /// send right this process holds and stays the caller's to deallocate.
1573    pub fn from_mach_port(port: u32) -> Result<Self, SurfaceError> {
1574        #[cfg(target_os = "macos")]
1575        {
1576            metal::open_mach_port(port).map(Self::new)
1577        }
1578        #[cfg(not(target_os = "macos"))]
1579        {
1580            let _ = port;
1581            Err(SurfaceError::NotSupported(NO_METAL))
1582        }
1583    }
1584
1585    /// Synchronises through the texture's `IDXGIKeyedMutex`: each present acquires `acquire` and
1586    /// releases `release`. Required for a texture made with `SHARED_KEYEDMUTEX`. Windows only; on
1587    /// macOS a present of it fails with [`SurfaceError::NotSupported`].
1588    pub fn with_keyed_mutex(self, acquire: u64, release: u64) -> Self {
1589        #[cfg(windows)]
1590        {
1591            let mut this = self;
1592            this.inner.need_d3d11();
1593            this.keys = Some((acquire, release));
1594            this
1595        }
1596        #[cfg(target_os = "macos")]
1597        {
1598            let _ = (acquire, release);
1599            Self {
1600                keyed: true,
1601                ..self
1602            }
1603        }
1604        #[cfg(not(any(windows, target_os = "macos")))]
1605        {
1606            let _ = (acquire, release);
1607            match self.never {}
1608        }
1609    }
1610
1611    /// Synchronises through a shared fence, an NT handle this process holds: a D3D12 fence made
1612    /// `D3D12_FENCE_FLAG_SHARED`, an `ID3D11Fence` made `D3D11_FENCE_FLAG_SHARED`, or a Vulkan
1613    /// semaphore exported as `D3D12_FENCE`. Present it with
1614    /// [`SurfaceHandle::present_shared_fenced`]. The handle stays the caller's to close.
1615    pub fn with_fence(self, fence: u64) -> Result<Self, SurfaceError> {
1616        #[cfg(windows)]
1617        {
1618            let mut this = self;
1619            this.inner.open_fence(fence)?;
1620            Ok(this)
1621        }
1622        #[cfg(target_os = "macos")]
1623        {
1624            let _ = (self, fence);
1625            Err(SurfaceError::NotSupported(NT_HANDLES))
1626        }
1627        #[cfg(not(any(windows, target_os = "macos")))]
1628        {
1629            let _ = fence;
1630            match self.never {}
1631        }
1632    }
1633
1634    /// [`Self::with_fence`] for a fence handle of process `pid`.
1635    pub fn with_fence_from_process(self, pid: u32, fence: u64) -> Result<Self, SurfaceError> {
1636        #[cfg(windows)]
1637        {
1638            let mut this = self;
1639            this.inner.open_fence_from_process(pid, fence)?;
1640            Ok(this)
1641        }
1642        #[cfg(target_os = "macos")]
1643        {
1644            let _ = (self, pid, fence);
1645            Err(SurfaceError::NotSupported(NT_HANDLES))
1646        }
1647        #[cfg(not(any(windows, target_os = "macos")))]
1648        {
1649            let _ = (pid, fence);
1650            match self.never {}
1651        }
1652    }
1653
1654    /// Synchronises through an `id<MTLSharedEvent>` of this process (macOS), from any device:
1655    /// present it with [`SurfaceHandle::present_shared_fenced`]. It is retained while this lives.
1656    ///
1657    /// # Safety
1658    /// `event` is null or a live `id<MTLSharedEvent>`.
1659    pub unsafe fn with_shared_event(self, event: *mut c_void) -> Result<Self, SurfaceError> {
1660        #[cfg(target_os = "macos")]
1661        {
1662            let mut this = self;
1663            // SAFETY: the caller's.
1664            unsafe { this.inner.set_event(event) }?;
1665            Ok(this)
1666        }
1667        #[cfg(not(target_os = "macos"))]
1668        {
1669            let _ = (self, event);
1670            Err(SurfaceError::NotSupported(NO_METAL))
1671        }
1672    }
1673
1674    /// [`Self::with_shared_event`] for an event of another process: the `MTLSharedEventHandle`
1675    /// it made (`newSharedEventHandle`) and sent over XPC.
1676    ///
1677    /// # Safety
1678    /// `handle` is null or a live `MTLSharedEventHandle`.
1679    pub unsafe fn with_shared_event_handle(
1680        self,
1681        handle: *mut c_void,
1682    ) -> Result<Self, SurfaceError> {
1683        #[cfg(target_os = "macos")]
1684        {
1685            let mut this = self;
1686            // SAFETY: the caller's.
1687            unsafe { this.inner.set_event_handle(handle) }?;
1688            Ok(this)
1689        }
1690        #[cfg(not(target_os = "macos"))]
1691        {
1692            let _ = (self, handle);
1693            Err(SurfaceError::NotSupported(NO_METAL))
1694        }
1695    }
1696
1697    /// How long a present waits for the acquire key, or (under the D3D11 renderer) for the fence;
1698    /// 100 ms by default. Under the D3D12 renderer and on macOS the GPU waits instead.
1699    pub fn with_timeout(self, timeout: Duration) -> Self {
1700        #[cfg(windows)]
1701        {
1702            let mut this = self;
1703            this.timeout_ms = timeout.as_millis().min(u128::from(u32::MAX - 1)) as u32;
1704            this
1705        }
1706        #[cfg(target_os = "macos")]
1707        {
1708            let _ = timeout;
1709            self
1710        }
1711        #[cfg(not(any(windows, target_os = "macos")))]
1712        {
1713            let _ = timeout;
1714            match self.never {}
1715        }
1716    }
1717
1718    pub fn size(&self) -> (u32, u32) {
1719        #[cfg(any(windows, target_os = "macos"))]
1720        {
1721            self.inner.size
1722        }
1723        #[cfg(not(any(windows, target_os = "macos")))]
1724        {
1725            match self.never {}
1726        }
1727    }
1728
1729    /// The texture's pixels, which the surface it is presented to must be set to.
1730    pub fn format(&self) -> SurfaceFormat {
1731        #[cfg(any(windows, target_os = "macos"))]
1732        {
1733            self.inner.format
1734        }
1735        #[cfg(not(any(windows, target_os = "macos")))]
1736        {
1737            match self.never {}
1738        }
1739    }
1740}
1741
1742impl fmt::Debug for SharedTexture {
1743    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1744        f.debug_struct("SharedTexture")
1745            .field("size", &self.size())
1746            .finish()
1747    }
1748}
1749
1750/// Set while the renderer's device is removed, until it has a new one.
1751#[cfg(windows)]
1752static REMOVED: AtomicBool = AtomicBool::new(false);
1753
1754#[cfg(windows)]
1755const REMOVED_DEVICE: &str = "the renderer's GPU device was removed; it makes a new one once \
1756                              nothing references the old one, so drop every texture, fence and \
1757                              device you have from it, and get them again on the next \
1758                              SurfaceEvent::DeviceLost";
1759
1760#[cfg(windows)]
1761fn removed() -> bool {
1762    REMOVED.load(Ordering::Acquire)
1763}
1764
1765/// The renderer's device was removed: every surface lets go of everything it holds on it, frames
1766/// still waiting drop, and producers hear [`SurfaceEvent::DeviceLost`]. GPU presents are refused
1767/// until [`device_changed`] reports the new device.
1768#[cfg(windows)]
1769pub(crate) fn device_removed() {
1770    REMOVED.store(true, Ordering::Release);
1771    shared::release_all();
1772    forget_gpu();
1773}
1774
1775/// The renderer recreated its device: every surface drops its GPU frame and texture.
1776pub(crate) fn device_changed() {
1777    #[cfg(windows)]
1778    REMOVED.store(false, Ordering::Release);
1779    forget_gpu();
1780}
1781
1782fn forget_gpu() {
1783    #[cfg(windows)]
1784    {
1785        d3d11::forget_device();
1786        d3d12::forget_device();
1787    }
1788    #[cfg(target_os = "macos")]
1789    metal::forget_device();
1790    feedback::with(|t| t.device_lost());
1791    for surface in all() {
1792        surface.device_lost();
1793    }
1794}
1795
1796#[cfg(test)]
1797mod tests {
1798    use super::*;
1799
1800    #[test]
1801    fn one_name_is_one_surface() {
1802        let a = surface("tests:one-name");
1803        let b = surface("tests:one-name");
1804        a.present_bgra(&[1, 2, 3, 4], 1, 1, 4).unwrap();
1805        assert_eq!(b.stats().presented, 1);
1806        assert_eq!(surface("tests:other-name").stats().presented, 0);
1807    }
1808
1809    #[test]
1810    fn a_padded_frame_is_packed_and_a_short_one_refused() {
1811        let s = surface("tests:stride");
1812        let mut pixels = vec![0u8; 12 * 2];
1813        pixels[..8].copy_from_slice(&[1, 1, 1, 1, 2, 2, 2, 2]);
1814        pixels[12..20].copy_from_slice(&[3, 3, 3, 3, 4, 4, 4, 4]);
1815        s.present_bgra(&pixels, 2, 2, 12).unwrap();
1816        match s.state().frame.clone() {
1817            Some(Frame::Cpu { bgra, .. }) => {
1818                assert_eq!(&*bgra, &[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4])
1819            }
1820            _ => panic!("a CPU frame"),
1821        }
1822        assert!(matches!(
1823            s.present_bgra(&pixels[..19], 2, 2, 12),
1824            Err(SurfaceError::Size(_))
1825        ));
1826        assert!(matches!(
1827            s.present_bgra(&pixels, 4, 2, 12),
1828            Err(SurfaceError::Size(_))
1829        ));
1830        assert!(matches!(
1831            s.present_bgra(&[], 0, 0, 0),
1832            Err(SurfaceError::Size(_))
1833        ));
1834        assert_eq!(s.stats().presented, 1);
1835        s.present_bgrx(&pixels, 2, 2, 12).unwrap();
1836        let frame = s.state().frame.clone();
1837        match frame {
1838            Some(Frame::Cpu { bgra, .. }) => {
1839                assert_eq!(
1840                    &*bgra,
1841                    &[1, 1, 1, 255, 2, 2, 2, 255, 3, 3, 3, 255, 4, 4, 4, 255]
1842                )
1843            }
1844            _ => panic!("a CPU frame"),
1845        }
1846    }
1847
1848    #[test]
1849    fn watchers_hear_changes_once_and_stop_when_dropped() {
1850        let s = surface("tests:watch");
1851        let heard = Arc::new(Mutex::new(Vec::new()));
1852        let sink = heard.clone();
1853        let watch = s.on_change(move |_, e| lock(&sink).push(e));
1854        let info = SurfaceInfo {
1855            width: 640,
1856            height: 360,
1857            scale: 1.5,
1858            visible: true,
1859            ..Default::default()
1860        };
1861        s.set_info(info);
1862        s.set_info(info);
1863        s.device_lost();
1864        drop(watch);
1865        s.set_info(SurfaceInfo::default());
1866        assert_eq!(
1867            *lock(&heard),
1868            vec![SurfaceEvent::Changed(info), SurfaceEvent::DeviceLost]
1869        );
1870        assert_eq!(s.info(), SurfaceInfo::default());
1871    }
1872
1873    #[test]
1874    fn hiding_the_page_makes_a_surface_invisible_at_once() {
1875        let s = surface("tests:page-hidden");
1876        let heard = Arc::new(Mutex::new(Vec::new()));
1877        let sink = heard.clone();
1878        let _watch = s.on_change(move |_, e| lock(&sink).push(e));
1879        let shown = SurfaceInfo {
1880            width: 64,
1881            height: 64,
1882            visible: true,
1883            ..Default::default()
1884        };
1885        s.set_info(shown);
1886        page_hidden();
1887        let hidden = SurfaceInfo {
1888            visible: false,
1889            ..shown
1890        };
1891        assert_eq!(s.info(), hidden);
1892        assert_eq!(
1893            *lock(&heard),
1894            vec![SurfaceEvent::Changed(shown), SurfaceEvent::Changed(hidden)]
1895        );
1896    }
1897
1898    #[test]
1899    fn a_display_is_reported_when_it_moves_past_the_margin_and_kept_when_unknown() {
1900        let s = surface("tests:display");
1901        let heard = Arc::new(Mutex::new(Vec::new()));
1902        let sink = heard.clone();
1903        let _watch = s.on_change(move |_, e| lock(&sink).push(e));
1904        let hdr = SurfaceDisplay {
1905            known: true,
1906            hdr: true,
1907            headroom: 4.0,
1908            potential_headroom: 4.0,
1909            refresh_hz: Some(60.0),
1910            ..Default::default()
1911        };
1912        let with = |display| SurfaceInfo {
1913            display,
1914            ..Default::default()
1915        };
1916        s.set_info(with(hdr));
1917        s.set_info(with(SurfaceDisplay {
1918            headroom: 4.02,
1919            refresh_hz: Some(59.94),
1920            ..hdr
1921        }));
1922        s.set_info(with(SurfaceDisplay::default()));
1923        let faster = SurfaceDisplay {
1924            refresh_hz: Some(120.0),
1925            ..hdr
1926        };
1927        s.set_info(with(faster));
1928        let drawing_hdr = SurfaceDisplay {
1929            output_hdr: true,
1930            ..faster
1931        };
1932        s.set_info(with(drawing_hdr));
1933        // The display clock is read live; a known display always has a period.
1934        let unclocked = |d: SurfaceDisplay| {
1935            assert!(d.refresh_period.is_some());
1936            SurfaceDisplay {
1937                refresh_period: None,
1938                last_vblank: None,
1939                ..d
1940            }
1941        };
1942        let heard: Vec<SurfaceEvent> = lock(&heard)
1943            .iter()
1944            .map(|e| match *e {
1945                SurfaceEvent::DisplayChanged(d) => SurfaceEvent::DisplayChanged(unclocked(d)),
1946                other => other,
1947            })
1948            .collect();
1949        assert_eq!(
1950            heard,
1951            vec![
1952                SurfaceEvent::DisplayChanged(hdr),
1953                SurfaceEvent::DisplayChanged(faster),
1954                SurfaceEvent::DisplayChanged(drawing_hdr)
1955            ]
1956        );
1957        assert_eq!(unclocked(s.info().display), drawing_hdr);
1958    }
1959
1960    #[test]
1961    fn a_frame_of_the_other_format_is_refused_and_half_floats_are_mapped() {
1962        let s = surface("tests:format");
1963        assert_eq!(s.format(), SurfaceFormat::Bgra8);
1964        assert_eq!(
1965            s.present_rgba16f(&[0; 4], 1, 1, 4),
1966            Err(SurfaceError::FormatMismatch {
1967                surface: SurfaceFormat::Bgra8,
1968                frame: SurfaceFormat::Rgba16Float
1969            })
1970        );
1971        s.set_format(SurfaceFormat::Rgba16Float);
1972        assert!(matches!(
1973            s.present_bgra(&[0; 4], 1, 1, 4),
1974            Err(SurfaceError::FormatMismatch { .. })
1975        ));
1976        assert_eq!(s.stats().presented, 0);
1977        let h = color::tests::f32_to_half;
1978        s.present_rgba16f(&[h(2.0), h(0.5), h(0.0), h(1.0)], 1, 1, 4)
1979            .unwrap();
1980        let frame = s.state().frame.clone();
1981        match frame {
1982            Some(Frame::Cpu { bgra, .. }) => assert_eq!(&*bgra, &[0, 188, 255, 255]),
1983            _ => panic!("a CPU frame"),
1984        }
1985    }
1986
1987    #[test]
1988    fn each_present_returns_its_id_and_a_hidden_surface_drops_it_at_once() {
1989        let s = surface("tests:frame-ids");
1990        let heard = Arc::new(Mutex::new(Vec::new()));
1991        let sink = heard.clone();
1992        let watch = s.on_frame(move |e| lock(&sink).push(e));
1993        let first = s.present_bgra(&[0; 4], 1, 1, 4).unwrap();
1994        let second = s.present_bgrx(&[0; 4], 1, 1, 4).unwrap();
1995        assert!(second > first);
1996        feedback::deliver();
1997        let hidden = |frame| FrameEvent::Dropped {
1998            frame,
1999            reason: FrameDropReason::Hidden,
2000        };
2001        assert_eq!(*lock(&heard), [hidden(first), hidden(second)]);
2002        drop(watch);
2003        s.present_bgra(&[0; 4], 1, 1, 4).unwrap();
2004        feedback::deliver();
2005        assert_eq!(lock(&heard).len(), 2, "nobody listens any more");
2006    }
2007
2008    #[test]
2009    fn clearing_withdraws_the_frame_once() {
2010        let s = surface("tests:clear");
2011        s.present_bgra(&[0; 4], 1, 1, 4).unwrap();
2012        let seq = s.state().seq;
2013        s.clear();
2014        s.clear();
2015        let st = s.state();
2016        assert!(st.frame.is_none());
2017        assert_eq!(st.lost, "cleared");
2018        assert_eq!(st.seq, seq + 1);
2019    }
2020}