1mod 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#[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
58const MAX_SIDE: u32 = 16384;
60
61const _: () = {
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
74pub 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#[derive(Debug, Clone, PartialEq, Eq)]
96#[non_exhaustive]
97pub enum SurfaceError {
98 NotSupported(&'static str),
101 NoDevice(String),
103 DeviceChanged,
106 WrongDevice,
108 Format(String),
110 Size(String),
112 Timeout,
115 Busy,
117 Platform(String),
119 FormatMismatch {
121 surface: SurfaceFormat,
122 frame: SurfaceFormat,
123 },
124}
125
126#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
128#[non_exhaustive]
129pub enum SurfaceFormat {
130 #[default]
133 Bgra8,
134 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 surface texture is still in use: the producer presents faster than the \
177 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#[derive(Clone, Copy, Debug, Default, PartialEq)]
193pub struct SurfaceInfo {
194 pub width: u32,
196 pub height: u32,
197 pub scale: f32,
199 pub visible: bool,
201 pub display: SurfaceDisplay,
203 pub dynamic_range_limit: sk_css::DynamicRangeLimit,
205}
206
207impl SurfaceInfo {
208 pub fn content_headroom(&self) -> f32 {
212 self.dynamic_range_limit
213 .headroom(self.display.output_headroom)
214 }
215}
216
217#[derive(Clone, Copy, Debug, PartialEq)]
220pub struct SurfaceDisplay {
221 pub known: bool,
223 pub hdr: bool,
225 pub headroom: f32,
227 pub potential_headroom: f32,
229 pub output_headroom: f32,
232 pub sdr_white_nits: Option<f32>,
234 pub peak_nits: Option<f32>,
236 pub full_frame_nits: Option<f32>,
237 pub refresh_hz: Option<f32>,
239 pub variable_refresh: Option<bool>,
241 pub refresh_period: Option<Duration>,
243 pub last_vblank: Option<u64>,
246}
247
248impl Default for SurfaceDisplay {
249 fn default() -> Self {
250 Self {
251 known: false,
252 hdr: false,
253 headroom: 1.0,
254 potential_headroom: 1.0,
255 output_headroom: 1.0,
256 sdr_white_nits: None,
257 peak_nits: None,
258 full_frame_nits: None,
259 refresh_hz: None,
260 variable_refresh: None,
261 refresh_period: None,
262 last_vblank: None,
263 }
264 }
265}
266
267impl SurfaceDisplay {
268 pub fn nits(&self, value: f32) -> Option<f32> {
270 self.sdr_white_nits.map(|white| value * white)
271 }
272
273 fn differs(&self, other: &SurfaceDisplay) -> bool {
275 let level = |a: f32, b: f32| (a - b).abs() > 0.01 * a.abs().max(b.abs()).max(1.0);
276 let maybe = |a: Option<f32>, b: Option<f32>| match (a, b) {
277 (Some(a), Some(b)) => level(a, b),
278 (a, b) => a.is_some() != b.is_some(),
279 };
280 self.known != other.known
281 || self.hdr != other.hdr
282 || self.variable_refresh != other.variable_refresh
283 || level(self.headroom, other.headroom)
284 || level(self.potential_headroom, other.potential_headroom)
285 || level(self.output_headroom, other.output_headroom)
286 || maybe(self.sdr_white_nits, other.sdr_white_nits)
287 || maybe(self.peak_nits, other.peak_nits)
288 || maybe(self.full_frame_nits, other.full_frame_nits)
289 || maybe(self.refresh_hz, other.refresh_hz)
290 }
291}
292
293#[derive(Clone, Copy, Debug, PartialEq)]
295pub enum SurfaceEvent {
296 Changed(SurfaceInfo),
298 DeviceLost,
300 DisplayChanged(SurfaceDisplay),
303}
304
305#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
307pub struct SurfaceStats {
308 pub presented: u64,
309 pub shown: u64,
312}
313
314#[derive(Clone, Copy, Debug, PartialEq, Eq)]
317pub enum FrameEvent {
318 Presented {
321 frame: u64,
322 shown_at: u64,
323 refresh_interval: Duration,
324 precision: FramePrecision,
325 },
326 Dropped { frame: u64, reason: FrameDropReason },
328}
329
330impl FrameEvent {
331 pub fn frame(&self) -> u64 {
333 match *self {
334 Self::Presented { frame, .. } | Self::Dropped { frame, .. } => frame,
335 }
336 }
337
338 fn dropped(frame: u64, reason: FrameDropReason) -> Self {
339 Self::Dropped { frame, reason }
340 }
341}
342
343#[derive(Clone, Copy, Debug, PartialEq, Eq)]
345pub enum FramePrecision {
346 Exact,
348 Estimated,
350}
351
352#[derive(Clone, Copy, Debug, PartialEq, Eq)]
354pub enum FrameDropReason {
355 Superseded,
357 Hidden,
360 DeviceLost,
362 Closed,
364}
365
366#[derive(Clone, Copy, Debug, PartialEq, Eq)]
368pub struct FramePresent {
369 pub frame: u64,
371 pub release: u64,
373}
374
375type FrameCallback = Arc<Mutex<Box<dyn FnMut(FrameEvent) + Send>>>;
376
377#[derive(Clone)]
379pub struct SurfaceHandle {
380 shared: Arc<Shared>,
381}
382
383impl fmt::Debug for SurfaceHandle {
384 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385 f.debug_struct("SurfaceHandle")
386 .field("name", &self.shared.name)
387 .finish()
388 }
389}
390
391type Watcher = Arc<dyn Fn(&SurfaceHandle, SurfaceEvent) + Send + Sync>;
392
393pub(crate) struct Shared {
394 name: Arc<str>,
395 state: Mutex<State>,
396 watchers: Mutex<Vec<(u64, Watcher)>>,
397 frames: Mutex<Vec<(u64, FrameCallback)>>,
398}
399
400impl Shared {
401 fn frame_event(&self, event: FrameEvent) {
402 let callbacks: Vec<FrameCallback> =
403 lock(&self.frames).iter().map(|(_, f)| f.clone()).collect();
404 for callback in callbacks {
405 (lock(&callback))(event);
406 }
407 }
408}
409
410#[derive(Default)]
411pub(crate) struct State {
412 pub(crate) seq: u64,
413 pub(crate) frame: Option<Frame>,
414 pub(crate) frame_id: u64,
416 key: feedback::Key,
417 watched: bool,
419 pub(crate) lost: &'static str,
421 presented: u64,
422 shown: u64,
423 shown_seq: u64,
424 info: SurfaceInfo,
425 pub(crate) format: SurfaceFormat,
426 #[cfg(windows)]
427 gpu: d3d11::SurfaceGpu,
428 #[cfg(windows)]
429 gpu12: d3d12::SurfaceGpu,
430 #[cfg(target_os = "macos")]
431 metal: metal::SurfaceGpu,
432}
433
434#[derive(Clone)]
435pub(crate) enum Frame {
436 Cpu {
439 width: u32,
440 height: u32,
441 bgra: Arc<[u8]>,
442 halves: Option<Arc<[u16]>>,
443 },
444 #[cfg(windows)]
446 Gpu { width: u32, height: u32 },
447 #[cfg(windows)]
449 D3D12 { width: u32, height: u32 },
450 #[cfg(target_os = "macos")]
452 Metal { width: u32, height: u32 },
453}
454
455impl Frame {
456 pub(crate) fn size(&self) -> (u32, u32) {
457 match self {
458 Frame::Cpu { width, height, .. } => (*width, *height),
459 #[cfg(windows)]
460 Frame::Gpu { width, height } | Frame::D3D12 { width, height } => (*width, *height),
461 #[cfg(target_os = "macos")]
462 Frame::Metal { width, height } => (*width, *height),
463 }
464 }
465}
466
467impl State {
468 fn put(&mut self, frame: Frame) -> u64 {
469 self.seq += 1;
470 self.presented += 1;
471 self.frame = Some(frame);
472 self.lost = "";
473 self.frame_id += 1;
474 if self.watched {
475 let (key, id, visible) = (self.key, self.frame_id, self.info.visible);
476 feedback::with(|t| t.put(key, id, visible));
477 }
478 self.frame_id
479 }
480
481 pub(crate) fn note_shown(&mut self, seq: u64) {
482 if seq > self.shown_seq {
483 self.shown_seq = seq;
484 self.shown += 1;
485 }
486 }
487
488 #[cfg(windows)]
491 pub(crate) fn gpu_texture(
492 &mut self,
493 hdr: bool,
494 ) -> Result<Option<d3d11::Texture>, SurfaceError> {
495 self.gpu.texture(hdr)
496 }
497}
498
499fn registry() -> &'static Mutex<HashMap<String, Arc<Shared>>> {
500 static REGISTRY: std::sync::OnceLock<Mutex<HashMap<String, Arc<Shared>>>> =
501 std::sync::OnceLock::new();
502 REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
503}
504
505static ANY: AtomicBool = AtomicBool::new(false);
506
507pub(crate) fn dynamic_range_high(key: crate::windows::WinKey) -> bool {
509 display::dynamic_range_high(key)
510}
511
512pub(crate) fn any() -> bool {
513 ANY.load(Ordering::Relaxed)
514}
515
516pub(crate) fn all() -> Vec<SurfaceHandle> {
517 lock(registry())
518 .values()
519 .map(|shared| SurfaceHandle {
520 shared: shared.clone(),
521 })
522 .collect()
523}
524
525fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
526 m.lock().unwrap_or_else(|p| p.into_inner())
527}
528
529impl SurfaceHandle {
530 pub fn name(&self) -> &str {
531 &self.shared.name
532 }
533
534 pub fn info(&self) -> SurfaceInfo {
535 let mut info = self.state().info;
536 info.display = self.with_clock(info.display);
537 info
538 }
539
540 fn with_clock(&self, mut display: SurfaceDisplay) -> SurfaceDisplay {
541 if display.known {
542 (display.last_vblank, display.refresh_period) =
543 feedback::display_clock(feedback::key(&self.shared), display.refresh_hz);
544 }
545 display
546 }
547
548 pub fn on_frame(&self, f: impl FnMut(FrameEvent) + Send + 'static) -> FrameWatch {
552 static NEXT: AtomicU64 = AtomicU64::new(1);
553 let id = NEXT.fetch_add(1, Ordering::Relaxed);
554 lock(&self.shared.frames).push((id, Arc::new(Mutex::new(Box::new(f)))));
555 let mut st = self.state();
556 if !st.watched {
557 st.watched = true;
558 feedback::watch(&self.shared);
559 }
560 FrameWatch {
561 shared: Arc::downgrade(&self.shared),
562 id,
563 }
564 }
565
566 pub fn stats(&self) -> SurfaceStats {
567 let st = self.state();
568 SurfaceStats {
569 presented: st.presented,
570 shown: st.shown,
571 }
572 }
573
574 pub fn on_change(
577 &self,
578 f: impl Fn(&SurfaceHandle, SurfaceEvent) + Send + Sync + 'static,
579 ) -> SurfaceWatch {
580 static NEXT: AtomicU64 = AtomicU64::new(1);
581 let id = NEXT.fetch_add(1, Ordering::Relaxed);
582 lock(&self.shared.watchers).push((id, Arc::new(f)));
583 SurfaceWatch {
584 shared: Arc::downgrade(&self.shared),
585 id,
586 }
587 }
588
589 pub fn set_format(&self, format: SurfaceFormat) {
592 self.state().format = format;
593 }
594
595 pub fn format(&self) -> SurfaceFormat {
596 self.state().format
597 }
598
599 pub fn present_bgra(
602 &self,
603 pixels: &[u8],
604 width: u32,
605 height: u32,
606 stride: usize,
607 ) -> Result<u64, SurfaceError> {
608 self.present_cpu(pixels, width, height, stride, false)
609 }
610
611 pub fn present_rgba16f(
615 &self,
616 pixels: &[u16],
617 width: u32,
618 height: u32,
619 stride: usize,
620 ) -> Result<u64, SurfaceError> {
621 check_format(self.format(), SurfaceFormat::Rgba16Float)?;
622 check_size(width, height)?;
623 let row = width as usize * 4;
624 let need = stride * (height as usize - 1) + row;
625 if stride < row || pixels.len() < need {
626 return Err(SurfaceError::Size(format!(
627 "a {width}x{height} half-float frame with stride {stride} needs {need} values and \
628 a stride of at least {row}; got {}",
629 pixels.len()
630 )));
631 }
632 let bgra = color::rgba16f_to_bgra8(pixels, width, height, stride);
633 let halves = display::any_capable().then(|| {
634 (0..height as usize)
635 .flat_map(|y| &pixels[y * stride..y * stride + row])
636 .copied()
637 .collect()
638 });
639 let frame = self.state().put(Frame::Cpu {
640 width,
641 height,
642 bgra: bgra.into(),
643 halves,
644 });
645 sk_runtime::frames::wake();
646 Ok(frame)
647 }
648
649 pub fn present_bgrx(
651 &self,
652 pixels: &[u8],
653 width: u32,
654 height: u32,
655 stride: usize,
656 ) -> Result<u64, SurfaceError> {
657 self.present_cpu(pixels, width, height, stride, true)
658 }
659
660 fn present_cpu(
661 &self,
662 pixels: &[u8],
663 width: u32,
664 height: u32,
665 stride: usize,
666 opaque: bool,
667 ) -> Result<u64, SurfaceError> {
668 check_format(self.format(), SurfaceFormat::Bgra8)?;
669 check_size(width, height)?;
670 let row = width as usize * 4;
671 let need = stride * (height as usize - 1) + row;
672 if stride < row || pixels.len() < need {
673 return Err(SurfaceError::Size(format!(
674 "a {width}x{height} BGRA frame with stride {stride} needs {need} bytes and a stride \
675 of at least {row}; got {} bytes",
676 pixels.len()
677 )));
678 }
679 let mut packed = Vec::with_capacity(row * height as usize);
680 for y in 0..height as usize {
681 packed.extend_from_slice(&pixels[y * stride..y * stride + row]);
682 }
683 if opaque {
684 for alpha in packed.iter_mut().skip(3).step_by(4) {
685 *alpha = 255;
686 }
687 }
688 let frame = self.state().put(Frame::Cpu {
689 width,
690 height,
691 bgra: packed.into(),
692 halves: None,
693 });
694 sk_runtime::frames::wake();
695 Ok(frame)
696 }
697
698 pub fn clear(&self) {
700 let mut st = self.state();
701 if st.frame.take().is_some() {
702 st.seq += 1;
703 st.lost = "cleared";
704 if st.watched {
705 let key = st.key;
706 feedback::with(|t| t.cleared(key));
707 }
708 }
709 drop(st);
710 sk_runtime::frames::wake();
711 }
712
713 pub fn d3d11_device(&self) -> Result<D3D11Device, SurfaceError> {
715 #[cfg(windows)]
716 {
717 d3d11::device(&self.shared.state).map(|inner| D3D11Device { inner })
718 }
719 #[cfg(not(windows))]
720 {
721 Err(SurfaceError::NotSupported(NO_D3D))
722 }
723 }
724
725 pub unsafe fn present_d3d11_texture(&self, texture: *mut c_void) -> Result<u64, SurfaceError> {
733 #[cfg(windows)]
734 {
735 let frame = unsafe { d3d11::present_texture(&self.shared.state, texture) }?;
737 sk_runtime::frames::wake();
738 Ok(frame)
739 }
740 #[cfg(not(windows))]
741 {
742 let _ = texture;
743 Err(SurfaceError::NotSupported(NO_D3D))
744 }
745 }
746
747 pub fn d3d12_device(&self) -> Result<D3D12Device, SurfaceError> {
749 #[cfg(windows)]
750 {
751 d3d12::device(&self.shared.state).map(|inner| D3D12Device { inner })
752 }
753 #[cfg(not(windows))]
754 {
755 Err(SurfaceError::NotSupported(NO_D3D))
756 }
757 }
758
759 pub fn release_fence(&self) -> Result<D3D12Fence, SurfaceError> {
762 #[cfg(windows)]
763 {
764 d3d12::release_fence().map(|inner| D3D12Fence { inner })
765 }
766 #[cfg(not(windows))]
767 {
768 Err(SurfaceError::NotSupported(NO_D3D))
769 }
770 }
771
772 pub unsafe fn present_d3d12(
783 &self,
784 resource: *mut c_void,
785 resource_state: i32,
786 ready: Option<(*mut c_void, u64)>,
787 ) -> Result<FramePresent, SurfaceError> {
788 #[cfg(windows)]
789 {
790 let (frame, release) =
792 unsafe { d3d12::present(&self.shared.state, resource, resource_state, ready) }?;
793 sk_runtime::frames::wake();
794 Ok(FramePresent { frame, release })
795 }
796 #[cfg(not(windows))]
797 {
798 let _ = (resource, resource_state, ready);
799 Err(SurfaceError::NotSupported(NO_D3D))
800 }
801 }
802
803 pub fn present_shared(&self, texture: &SharedTexture) -> Result<u64, SurfaceError> {
806 #[cfg(windows)]
807 {
808 if texture.inner.fenced {
809 return Err(SurfaceError::Format(
810 "the shared texture has a fence: present it with present_shared_fenced".into(),
811 ));
812 }
813 let sync = match texture.keys {
814 Some((acquire, release)) => d3d11::SharedSync::Keyed(acquire, release),
815 None => d3d11::SharedSync::None,
816 };
817 let frame = texture
818 .inner
819 .present(&self.shared.state, sync, texture.timeout_ms)?;
820 sk_runtime::frames::wake();
821 Ok(frame)
822 }
823 #[cfg(target_os = "macos")]
824 {
825 if texture.keyed {
826 return Err(SurfaceError::NotSupported(
827 "a keyed mutex is a Direct3D object; on macOS synchronise with an \
828 MTLSharedEvent (SharedTexture::with_shared_event)",
829 ));
830 }
831 if texture.inner.fenced() {
832 return Err(SurfaceError::Format(
833 "the shared texture has a shared event: present it with present_shared_fenced"
834 .into(),
835 ));
836 }
837 let frame = metal::present_shared(&self.shared.state, &texture.inner, None)?;
838 sk_runtime::frames::wake();
839 Ok(frame)
840 }
841 #[cfg(not(any(windows, target_os = "macos")))]
842 {
843 match texture.never {}
844 }
845 }
846
847 pub fn present_shared_fenced(
852 &self,
853 texture: &SharedTexture,
854 wait: u64,
855 release: u64,
856 ) -> Result<u64, SurfaceError> {
857 #[cfg(windows)]
858 {
859 if !texture.inner.fenced {
860 return Err(SurfaceError::Format(
861 "the shared texture has no fence: open it with SharedTexture::with_fence"
862 .into(),
863 ));
864 }
865 let frame = texture.inner.present(
866 &self.shared.state,
867 d3d11::SharedSync::Fence(wait, release),
868 texture.timeout_ms,
869 )?;
870 sk_runtime::frames::wake();
871 Ok(frame)
872 }
873 #[cfg(target_os = "macos")]
874 {
875 if !texture.inner.fenced() {
876 return Err(SurfaceError::Format(
877 "the shared texture has no shared event: open it with \
878 SharedTexture::with_shared_event"
879 .into(),
880 ));
881 }
882 let frame =
883 metal::present_shared(&self.shared.state, &texture.inner, Some((wait, release)))?;
884 sk_runtime::frames::wake();
885 Ok(frame)
886 }
887 #[cfg(not(any(windows, target_os = "macos")))]
888 {
889 let _ = (wait, release);
890 match texture.never {}
891 }
892 }
893
894 pub fn metal_device(&self) -> Result<MetalDevice, SurfaceError> {
897 #[cfg(target_os = "macos")]
898 {
899 metal::device(&self.shared.state).map(|inner| MetalDevice { inner })
900 }
901 #[cfg(not(target_os = "macos"))]
902 {
903 Err(SurfaceError::NotSupported(NO_METAL))
904 }
905 }
906
907 pub fn release_event(&self) -> Result<MetalEvent, SurfaceError> {
910 #[cfg(target_os = "macos")]
911 {
912 metal::release_event().map(|inner| MetalEvent { inner })
913 }
914 #[cfg(not(target_os = "macos"))]
915 {
916 Err(SurfaceError::NotSupported(NO_METAL))
917 }
918 }
919
920 pub unsafe fn present_metal_texture(
932 &self,
933 texture: *mut c_void,
934 ready: Option<(*mut c_void, u64)>,
935 ) -> Result<FramePresent, SurfaceError> {
936 #[cfg(target_os = "macos")]
937 {
938 let (frame, release) = unsafe { metal::present(&self.shared.state, texture, ready) }?;
940 sk_runtime::frames::wake();
941 Ok(FramePresent { frame, release })
942 }
943 #[cfg(not(target_os = "macos"))]
944 {
945 let _ = (texture, ready);
946 Err(SurfaceError::NotSupported(NO_METAL))
947 }
948 }
949
950 pub unsafe fn present_cv_pixel_buffer(&self, buffer: *mut c_void) -> Result<u64, SurfaceError> {
959 #[cfg(target_os = "macos")]
960 {
961 let cpu = |cpu: metal::Cpu<'_>| match cpu.format {
962 SurfaceFormat::Bgra8 => {
963 self.present_cpu(cpu.pixels, cpu.width, cpu.height, cpu.stride, false)
964 }
965 SurfaceFormat::Rgba16Float => {
966 if cpu.pixels.as_ptr().align_offset(2) != 0 || cpu.stride % 2 != 0 {
967 return Err(SurfaceError::Platform(
968 "a misaligned RGhA CVPixelBuffer".into(),
969 ));
970 }
971 let halves = unsafe {
973 std::slice::from_raw_parts(
974 cpu.pixels.as_ptr().cast::<u16>(),
975 cpu.pixels.len() / 2,
976 )
977 };
978 self.present_rgba16f(halves, cpu.width, cpu.height, cpu.stride / 2)
979 }
980 };
981 let frame = unsafe { metal::present_pixel_buffer(&self.shared.state, buffer, cpu) }?;
983 sk_runtime::frames::wake();
984 Ok(frame)
985 }
986 #[cfg(not(target_os = "macos"))]
987 {
988 let _ = buffer;
989 Err(SurfaceError::NotSupported(NO_METAL))
990 }
991 }
992
993 fn state(&self) -> MutexGuard<'_, State> {
994 lock(&self.shared.state)
995 }
996
997 pub(crate) fn shared(&self) -> &Arc<Shared> {
998 &self.shared
999 }
1000
1001 pub(crate) fn lock_state(&self) -> MutexGuard<'_, State> {
1002 self.state()
1003 }
1004
1005 pub(crate) fn set_info(&self, mut info: SurfaceInfo) {
1008 let (changed, display) = {
1009 let mut st = self.state();
1010 let old = st.info;
1011 let display = info.display.known && info.display.differs(&old.display);
1012 if !display {
1013 info.display = old.display;
1014 }
1015 st.info = info;
1016 if st.watched {
1017 let key = st.key;
1018 feedback::with(|t| t.visibility(key, info.visible));
1019 }
1020 (
1021 info != SurfaceInfo {
1022 display: info.display,
1023 ..old
1024 },
1025 display,
1026 )
1027 };
1028 if changed {
1029 self.notify(SurfaceEvent::Changed(info));
1030 }
1031 if display {
1032 self.notify(SurfaceEvent::DisplayChanged(self.with_clock(info.display)));
1033 }
1034 }
1035
1036 pub(crate) fn notify(&self, event: SurfaceEvent) {
1037 let watchers: Vec<Watcher> = lock(&self.shared.watchers)
1038 .iter()
1039 .map(|(_, w)| w.clone())
1040 .collect();
1041 for watcher in watchers {
1042 watcher(self, event);
1043 }
1044 }
1045
1046 pub(crate) fn device_lost(&self) {
1048 #[cfg(windows)]
1049 {
1050 let mut st = self.state();
1051 if matches!(st.frame, Some(Frame::Gpu { .. } | Frame::D3D12 { .. })) {
1052 st.frame = None;
1053 st.seq += 1;
1054 st.lost = "device";
1055 }
1056 st.gpu.forget();
1057 st.gpu12.forget();
1058 }
1059 #[cfg(target_os = "macos")]
1060 {
1061 let mut st = self.state();
1062 if matches!(st.frame, Some(Frame::Metal { .. })) {
1063 st.frame = None;
1064 st.seq += 1;
1065 st.lost = "device";
1066 }
1067 st.metal.forget();
1068 }
1069 self.notify(SurfaceEvent::DeviceLost);
1070 }
1071}
1072
1073fn check_size(width: u32, height: u32) -> Result<(), SurfaceError> {
1074 if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE {
1075 return Err(SurfaceError::Size(format!(
1076 "a {width}x{height} frame: each side must be 1 to {MAX_SIDE} pixels"
1077 )));
1078 }
1079 Ok(())
1080}
1081
1082#[must_use = "dropping the guard ends the subscription"]
1084pub struct SurfaceWatch {
1085 shared: Weak<Shared>,
1086 id: u64,
1087}
1088
1089impl Drop for SurfaceWatch {
1090 fn drop(&mut self) {
1091 if let Some(shared) = self.shared.upgrade() {
1092 lock(&shared.watchers).retain(|(id, _)| *id != self.id);
1093 }
1094 }
1095}
1096
1097#[must_use = "dropping the guard ends the subscription"]
1100pub struct FrameWatch {
1101 shared: Weak<Shared>,
1102 id: u64,
1103}
1104
1105impl Drop for FrameWatch {
1106 fn drop(&mut self) {
1107 let Some(shared) = self.shared.upgrade() else {
1108 return;
1109 };
1110 let mut st = lock(&shared.state);
1111 let mut frames = lock(&shared.frames);
1112 frames.retain(|(id, _)| *id != self.id);
1113 if frames.is_empty() && st.watched {
1114 st.watched = false;
1115 feedback::unwatch(&shared);
1116 }
1117 }
1118}
1119
1120pub struct D3D11Device {
1124 #[cfg(windows)]
1125 inner: d3d11::Device,
1126 #[cfg(not(windows))]
1127 never: std::convert::Infallible,
1128}
1129
1130impl D3D11Device {
1131 pub fn as_raw(&self) -> *mut c_void {
1133 #[cfg(windows)]
1134 {
1135 self.inner.as_raw()
1136 }
1137 #[cfg(not(windows))]
1138 {
1139 match self.never {}
1140 }
1141 }
1142
1143 pub fn generation(&self) -> u64 {
1145 #[cfg(windows)]
1146 {
1147 self.inner.generation()
1148 }
1149 #[cfg(not(windows))]
1150 {
1151 match self.never {}
1152 }
1153 }
1154}
1155
1156impl fmt::Debug for D3D11Device {
1157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1158 f.debug_struct("D3D11Device")
1159 .field("raw", &self.as_raw())
1160 .field("generation", &self.generation())
1161 .finish()
1162 }
1163}
1164
1165pub struct D3D12Device {
1168 #[cfg(windows)]
1169 inner: d3d12::Device,
1170 #[cfg(not(windows))]
1171 never: std::convert::Infallible,
1172}
1173
1174impl D3D12Device {
1175 pub fn as_raw(&self) -> *mut c_void {
1177 #[cfg(windows)]
1178 {
1179 self.inner.as_raw()
1180 }
1181 #[cfg(not(windows))]
1182 {
1183 match self.never {}
1184 }
1185 }
1186
1187 pub fn queue(&self) -> *mut c_void {
1190 #[cfg(windows)]
1191 {
1192 self.inner.queue()
1193 }
1194 #[cfg(not(windows))]
1195 {
1196 match self.never {}
1197 }
1198 }
1199
1200 pub fn generation(&self) -> u64 {
1202 #[cfg(windows)]
1203 {
1204 self.inner.generation()
1205 }
1206 #[cfg(not(windows))]
1207 {
1208 match self.never {}
1209 }
1210 }
1211}
1212
1213impl fmt::Debug for D3D12Device {
1214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215 f.debug_struct("D3D12Device")
1216 .field("raw", &self.as_raw())
1217 .field("generation", &self.generation())
1218 .finish()
1219 }
1220}
1221
1222pub struct D3D12Fence {
1225 #[cfg(windows)]
1226 inner: d3d12::Fence,
1227 #[cfg(not(windows))]
1228 never: std::convert::Infallible,
1229}
1230
1231impl D3D12Fence {
1232 pub fn as_raw(&self) -> *mut c_void {
1234 #[cfg(windows)]
1235 {
1236 self.inner.as_raw()
1237 }
1238 #[cfg(not(windows))]
1239 {
1240 match self.never {}
1241 }
1242 }
1243
1244 pub fn completed_value(&self) -> u64 {
1245 #[cfg(windows)]
1246 {
1247 self.inner.completed()
1248 }
1249 #[cfg(not(windows))]
1250 {
1251 match self.never {}
1252 }
1253 }
1254
1255 pub fn wait(&self, value: u64, timeout: Duration) -> bool {
1257 #[cfg(windows)]
1258 {
1259 self.inner.wait(value, timeout)
1260 }
1261 #[cfg(not(windows))]
1262 {
1263 let _ = (value, timeout);
1264 match self.never {}
1265 }
1266 }
1267
1268 pub fn generation(&self) -> u64 {
1270 #[cfg(windows)]
1271 {
1272 self.inner.generation()
1273 }
1274 #[cfg(not(windows))]
1275 {
1276 match self.never {}
1277 }
1278 }
1279}
1280
1281impl fmt::Debug for D3D12Fence {
1282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1283 f.debug_struct("D3D12Fence")
1284 .field("raw", &self.as_raw())
1285 .field("completed", &self.completed_value())
1286 .finish()
1287 }
1288}
1289
1290pub struct MetalDevice {
1293 #[cfg(target_os = "macos")]
1294 inner: metal::Device,
1295 #[cfg(not(target_os = "macos"))]
1296 never: std::convert::Infallible,
1297}
1298
1299impl MetalDevice {
1300 pub fn as_raw(&self) -> *mut c_void {
1302 #[cfg(target_os = "macos")]
1303 {
1304 self.inner.as_raw()
1305 }
1306 #[cfg(not(target_os = "macos"))]
1307 {
1308 match self.never {}
1309 }
1310 }
1311
1312 pub fn queue(&self) -> *mut c_void {
1315 #[cfg(target_os = "macos")]
1316 {
1317 self.inner.queue()
1318 }
1319 #[cfg(not(target_os = "macos"))]
1320 {
1321 match self.never {}
1322 }
1323 }
1324
1325 pub fn generation(&self) -> u64 {
1327 #[cfg(target_os = "macos")]
1328 {
1329 self.inner.generation()
1330 }
1331 #[cfg(not(target_os = "macos"))]
1332 {
1333 match self.never {}
1334 }
1335 }
1336}
1337
1338impl fmt::Debug for MetalDevice {
1339 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1340 f.debug_struct("MetalDevice")
1341 .field("raw", &self.as_raw())
1342 .field("generation", &self.generation())
1343 .finish()
1344 }
1345}
1346
1347pub struct MetalEvent {
1350 #[cfg(target_os = "macos")]
1351 inner: metal::Event,
1352 #[cfg(not(target_os = "macos"))]
1353 never: std::convert::Infallible,
1354}
1355
1356impl MetalEvent {
1357 pub fn as_raw(&self) -> *mut c_void {
1359 #[cfg(target_os = "macos")]
1360 {
1361 self.inner.as_raw()
1362 }
1363 #[cfg(not(target_os = "macos"))]
1364 {
1365 match self.never {}
1366 }
1367 }
1368
1369 pub fn signaled_value(&self) -> u64 {
1370 #[cfg(target_os = "macos")]
1371 {
1372 self.inner.signaled()
1373 }
1374 #[cfg(not(target_os = "macos"))]
1375 {
1376 match self.never {}
1377 }
1378 }
1379
1380 pub fn wait(&self, value: u64, timeout: Duration) -> bool {
1382 #[cfg(target_os = "macos")]
1383 {
1384 self.inner.wait(value, timeout)
1385 }
1386 #[cfg(not(target_os = "macos"))]
1387 {
1388 let _ = (value, timeout);
1389 match self.never {}
1390 }
1391 }
1392
1393 pub fn generation(&self) -> u64 {
1395 #[cfg(target_os = "macos")]
1396 {
1397 self.inner.generation()
1398 }
1399 #[cfg(not(target_os = "macos"))]
1400 {
1401 match self.never {}
1402 }
1403 }
1404}
1405
1406impl fmt::Debug for MetalEvent {
1407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1408 f.debug_struct("MetalEvent")
1409 .field("raw", &self.as_raw())
1410 .field("signaled", &self.signaled_value())
1411 .finish()
1412 }
1413}
1414
1415pub struct SharedTexture {
1421 #[cfg(windows)]
1422 inner: shared::Opened,
1423 #[cfg(windows)]
1424 keys: Option<(u64, u64)>,
1425 #[cfg(windows)]
1426 timeout_ms: u32,
1427 #[cfg(target_os = "macos")]
1428 inner: metal::Opened,
1429 #[cfg(target_os = "macos")]
1430 keyed: bool,
1431 #[cfg(not(any(windows, target_os = "macos")))]
1432 never: std::convert::Infallible,
1433}
1434
1435#[cfg(target_os = "macos")]
1436const NT_HANDLES: &str = "NT handles are Windows-only; on macOS open an IOSurface \
1437 (SharedTexture::from_iosurface, SharedTexture::from_mach_port)";
1438
1439impl SharedTexture {
1440 #[cfg(windows)]
1441 fn new(inner: shared::Opened) -> Self {
1442 Self {
1443 inner,
1444 keys: None,
1445 timeout_ms: 100,
1446 }
1447 }
1448
1449 #[cfg(target_os = "macos")]
1450 fn new(inner: metal::Opened) -> Self {
1451 Self {
1452 inner,
1453 keyed: false,
1454 }
1455 }
1456
1457 pub fn open(handle: u64) -> Result<Self, SurfaceError> {
1460 #[cfg(windows)]
1461 {
1462 shared::open(handle).map(Self::new)
1463 }
1464 #[cfg(target_os = "macos")]
1465 {
1466 let _ = handle;
1467 Err(SurfaceError::NotSupported(NT_HANDLES))
1468 }
1469 #[cfg(not(any(windows, target_os = "macos")))]
1470 {
1471 let _ = handle;
1472 Err(SurfaceError::NotSupported(NO_D3D))
1473 }
1474 }
1475
1476 pub fn open_from_process(pid: u32, handle: u64) -> Result<Self, SurfaceError> {
1479 #[cfg(windows)]
1480 {
1481 shared::open_from_process(pid, handle).map(Self::new)
1482 }
1483 #[cfg(target_os = "macos")]
1484 {
1485 let _ = (pid, handle);
1486 Err(SurfaceError::NotSupported(NT_HANDLES))
1487 }
1488 #[cfg(not(any(windows, target_os = "macos")))]
1489 {
1490 let _ = (pid, handle);
1491 Err(SurfaceError::NotSupported(NO_D3D))
1492 }
1493 }
1494
1495 pub unsafe fn from_iosurface(surface: *mut c_void) -> Result<Self, SurfaceError> {
1501 #[cfg(target_os = "macos")]
1502 {
1503 unsafe { metal::open_raw(surface) }.map(Self::new)
1505 }
1506 #[cfg(not(target_os = "macos"))]
1507 {
1508 let _ = surface;
1509 Err(SurfaceError::NotSupported(NO_METAL))
1510 }
1511 }
1512
1513 pub fn from_mach_port(port: u32) -> Result<Self, SurfaceError> {
1516 #[cfg(target_os = "macos")]
1517 {
1518 metal::open_mach_port(port).map(Self::new)
1519 }
1520 #[cfg(not(target_os = "macos"))]
1521 {
1522 let _ = port;
1523 Err(SurfaceError::NotSupported(NO_METAL))
1524 }
1525 }
1526
1527 pub fn with_keyed_mutex(self, acquire: u64, release: u64) -> Self {
1531 #[cfg(windows)]
1532 {
1533 let mut this = self;
1534 this.inner.need_d3d11();
1535 this.keys = Some((acquire, release));
1536 this
1537 }
1538 #[cfg(target_os = "macos")]
1539 {
1540 let _ = (acquire, release);
1541 Self {
1542 keyed: true,
1543 ..self
1544 }
1545 }
1546 #[cfg(not(any(windows, target_os = "macos")))]
1547 {
1548 let _ = (acquire, release);
1549 match self.never {}
1550 }
1551 }
1552
1553 pub fn with_fence(self, fence: u64) -> Result<Self, SurfaceError> {
1558 #[cfg(windows)]
1559 {
1560 let mut this = self;
1561 this.inner.open_fence(fence)?;
1562 Ok(this)
1563 }
1564 #[cfg(target_os = "macos")]
1565 {
1566 let _ = (self, fence);
1567 Err(SurfaceError::NotSupported(NT_HANDLES))
1568 }
1569 #[cfg(not(any(windows, target_os = "macos")))]
1570 {
1571 let _ = fence;
1572 match self.never {}
1573 }
1574 }
1575
1576 pub fn with_fence_from_process(self, pid: u32, fence: u64) -> Result<Self, SurfaceError> {
1578 #[cfg(windows)]
1579 {
1580 let mut this = self;
1581 this.inner.open_fence_from_process(pid, fence)?;
1582 Ok(this)
1583 }
1584 #[cfg(target_os = "macos")]
1585 {
1586 let _ = (self, pid, fence);
1587 Err(SurfaceError::NotSupported(NT_HANDLES))
1588 }
1589 #[cfg(not(any(windows, target_os = "macos")))]
1590 {
1591 let _ = (pid, fence);
1592 match self.never {}
1593 }
1594 }
1595
1596 pub unsafe fn with_shared_event(self, event: *mut c_void) -> Result<Self, SurfaceError> {
1602 #[cfg(target_os = "macos")]
1603 {
1604 let mut this = self;
1605 unsafe { this.inner.set_event(event) }?;
1607 Ok(this)
1608 }
1609 #[cfg(not(target_os = "macos"))]
1610 {
1611 let _ = (self, event);
1612 Err(SurfaceError::NotSupported(NO_METAL))
1613 }
1614 }
1615
1616 pub unsafe fn with_shared_event_handle(
1622 self,
1623 handle: *mut c_void,
1624 ) -> Result<Self, SurfaceError> {
1625 #[cfg(target_os = "macos")]
1626 {
1627 let mut this = self;
1628 unsafe { this.inner.set_event_handle(handle) }?;
1630 Ok(this)
1631 }
1632 #[cfg(not(target_os = "macos"))]
1633 {
1634 let _ = (self, handle);
1635 Err(SurfaceError::NotSupported(NO_METAL))
1636 }
1637 }
1638
1639 pub fn with_timeout(self, timeout: Duration) -> Self {
1642 #[cfg(windows)]
1643 {
1644 let mut this = self;
1645 this.timeout_ms = timeout.as_millis().min(u128::from(u32::MAX - 1)) as u32;
1646 this
1647 }
1648 #[cfg(target_os = "macos")]
1649 {
1650 let _ = timeout;
1651 self
1652 }
1653 #[cfg(not(any(windows, target_os = "macos")))]
1654 {
1655 let _ = timeout;
1656 match self.never {}
1657 }
1658 }
1659
1660 pub fn size(&self) -> (u32, u32) {
1661 #[cfg(any(windows, target_os = "macos"))]
1662 {
1663 self.inner.size
1664 }
1665 #[cfg(not(any(windows, target_os = "macos")))]
1666 {
1667 match self.never {}
1668 }
1669 }
1670
1671 pub fn format(&self) -> SurfaceFormat {
1673 #[cfg(any(windows, target_os = "macos"))]
1674 {
1675 self.inner.format
1676 }
1677 #[cfg(not(any(windows, target_os = "macos")))]
1678 {
1679 match self.never {}
1680 }
1681 }
1682}
1683
1684impl fmt::Debug for SharedTexture {
1685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1686 f.debug_struct("SharedTexture")
1687 .field("size", &self.size())
1688 .finish()
1689 }
1690}
1691
1692pub(crate) fn device_changed() {
1694 #[cfg(windows)]
1695 {
1696 d3d11::forget_device();
1697 d3d12::forget_device();
1698 }
1699 #[cfg(target_os = "macos")]
1700 metal::forget_device();
1701 feedback::with(|t| t.device_lost());
1702 for surface in all() {
1703 surface.device_lost();
1704 }
1705}
1706
1707#[cfg(test)]
1708mod tests {
1709 use super::*;
1710
1711 #[test]
1712 fn one_name_is_one_surface() {
1713 let a = surface("tests:one-name");
1714 let b = surface("tests:one-name");
1715 a.present_bgra(&[1, 2, 3, 4], 1, 1, 4).unwrap();
1716 assert_eq!(b.stats().presented, 1);
1717 assert_eq!(surface("tests:other-name").stats().presented, 0);
1718 }
1719
1720 #[test]
1721 fn a_padded_frame_is_packed_and_a_short_one_refused() {
1722 let s = surface("tests:stride");
1723 let mut pixels = vec![0u8; 12 * 2];
1724 pixels[..8].copy_from_slice(&[1, 1, 1, 1, 2, 2, 2, 2]);
1725 pixels[12..20].copy_from_slice(&[3, 3, 3, 3, 4, 4, 4, 4]);
1726 s.present_bgra(&pixels, 2, 2, 12).unwrap();
1727 match s.state().frame.clone() {
1728 Some(Frame::Cpu { bgra, .. }) => {
1729 assert_eq!(&*bgra, &[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4])
1730 }
1731 _ => panic!("a CPU frame"),
1732 }
1733 assert!(matches!(
1734 s.present_bgra(&pixels[..19], 2, 2, 12),
1735 Err(SurfaceError::Size(_))
1736 ));
1737 assert!(matches!(
1738 s.present_bgra(&pixels, 4, 2, 12),
1739 Err(SurfaceError::Size(_))
1740 ));
1741 assert!(matches!(
1742 s.present_bgra(&[], 0, 0, 0),
1743 Err(SurfaceError::Size(_))
1744 ));
1745 assert_eq!(s.stats().presented, 1);
1746 s.present_bgrx(&pixels, 2, 2, 12).unwrap();
1747 let frame = s.state().frame.clone();
1748 match frame {
1749 Some(Frame::Cpu { bgra, .. }) => {
1750 assert_eq!(
1751 &*bgra,
1752 &[1, 1, 1, 255, 2, 2, 2, 255, 3, 3, 3, 255, 4, 4, 4, 255]
1753 )
1754 }
1755 _ => panic!("a CPU frame"),
1756 }
1757 }
1758
1759 #[test]
1760 fn watchers_hear_changes_once_and_stop_when_dropped() {
1761 let s = surface("tests:watch");
1762 let heard = Arc::new(Mutex::new(Vec::new()));
1763 let sink = heard.clone();
1764 let watch = s.on_change(move |_, e| lock(&sink).push(e));
1765 let info = SurfaceInfo {
1766 width: 640,
1767 height: 360,
1768 scale: 1.5,
1769 visible: true,
1770 ..Default::default()
1771 };
1772 s.set_info(info);
1773 s.set_info(info);
1774 s.device_lost();
1775 drop(watch);
1776 s.set_info(SurfaceInfo::default());
1777 assert_eq!(
1778 *lock(&heard),
1779 vec![SurfaceEvent::Changed(info), SurfaceEvent::DeviceLost]
1780 );
1781 assert_eq!(s.info(), SurfaceInfo::default());
1782 }
1783
1784 #[test]
1785 fn a_display_is_reported_when_it_moves_past_the_margin_and_kept_when_unknown() {
1786 let s = surface("tests:display");
1787 let heard = Arc::new(Mutex::new(Vec::new()));
1788 let sink = heard.clone();
1789 let _watch = s.on_change(move |_, e| lock(&sink).push(e));
1790 let hdr = SurfaceDisplay {
1791 known: true,
1792 hdr: true,
1793 headroom: 4.0,
1794 potential_headroom: 4.0,
1795 refresh_hz: Some(60.0),
1796 ..Default::default()
1797 };
1798 let with = |display| SurfaceInfo {
1799 display,
1800 ..Default::default()
1801 };
1802 s.set_info(with(hdr));
1803 s.set_info(with(SurfaceDisplay {
1804 headroom: 4.02,
1805 refresh_hz: Some(59.94),
1806 ..hdr
1807 }));
1808 s.set_info(with(SurfaceDisplay::default()));
1809 let faster = SurfaceDisplay {
1810 refresh_hz: Some(120.0),
1811 ..hdr
1812 };
1813 s.set_info(with(faster));
1814 let unclocked = |d: SurfaceDisplay| {
1816 assert!(d.refresh_period.is_some());
1817 SurfaceDisplay {
1818 refresh_period: None,
1819 last_vblank: None,
1820 ..d
1821 }
1822 };
1823 let heard: Vec<SurfaceEvent> = lock(&heard)
1824 .iter()
1825 .map(|e| match *e {
1826 SurfaceEvent::DisplayChanged(d) => SurfaceEvent::DisplayChanged(unclocked(d)),
1827 other => other,
1828 })
1829 .collect();
1830 assert_eq!(
1831 heard,
1832 vec![
1833 SurfaceEvent::DisplayChanged(hdr),
1834 SurfaceEvent::DisplayChanged(faster)
1835 ]
1836 );
1837 assert_eq!(unclocked(s.info().display), faster);
1838 }
1839
1840 #[test]
1841 fn a_frame_of_the_other_format_is_refused_and_half_floats_are_mapped() {
1842 let s = surface("tests:format");
1843 assert_eq!(s.format(), SurfaceFormat::Bgra8);
1844 assert_eq!(
1845 s.present_rgba16f(&[0; 4], 1, 1, 4),
1846 Err(SurfaceError::FormatMismatch {
1847 surface: SurfaceFormat::Bgra8,
1848 frame: SurfaceFormat::Rgba16Float
1849 })
1850 );
1851 s.set_format(SurfaceFormat::Rgba16Float);
1852 assert!(matches!(
1853 s.present_bgra(&[0; 4], 1, 1, 4),
1854 Err(SurfaceError::FormatMismatch { .. })
1855 ));
1856 assert_eq!(s.stats().presented, 0);
1857 let h = color::tests::f32_to_half;
1858 s.present_rgba16f(&[h(2.0), h(0.5), h(0.0), h(1.0)], 1, 1, 4)
1859 .unwrap();
1860 let frame = s.state().frame.clone();
1861 match frame {
1862 Some(Frame::Cpu { bgra, .. }) => assert_eq!(&*bgra, &[0, 188, 255, 255]),
1863 _ => panic!("a CPU frame"),
1864 }
1865 }
1866
1867 #[test]
1868 fn each_present_returns_its_id_and_a_hidden_surface_drops_it_at_once() {
1869 let s = surface("tests:frame-ids");
1870 let heard = Arc::new(Mutex::new(Vec::new()));
1871 let sink = heard.clone();
1872 let watch = s.on_frame(move |e| lock(&sink).push(e));
1873 let first = s.present_bgra(&[0; 4], 1, 1, 4).unwrap();
1874 let second = s.present_bgrx(&[0; 4], 1, 1, 4).unwrap();
1875 assert!(second > first);
1876 feedback::deliver();
1877 let hidden = |frame| FrameEvent::Dropped {
1878 frame,
1879 reason: FrameDropReason::Hidden,
1880 };
1881 assert_eq!(*lock(&heard), [hidden(first), hidden(second)]);
1882 drop(watch);
1883 s.present_bgra(&[0; 4], 1, 1, 4).unwrap();
1884 feedback::deliver();
1885 assert_eq!(lock(&heard).len(), 2, "nobody listens any more");
1886 }
1887
1888 #[test]
1889 fn clearing_withdraws_the_frame_once() {
1890 let s = surface("tests:clear");
1891 s.present_bgra(&[0; 4], 1, 1, 4).unwrap();
1892 let seq = s.state().seq;
1893 s.clear();
1894 s.clear();
1895 let st = s.state();
1896 assert!(st.frame.is_none());
1897 assert_eq!(st.lost, "cleared");
1898 assert_eq!(st.seq, seq + 1);
1899 }
1900}