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 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#[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,
228 pub potential_headroom: f32,
230 pub output_headroom: f32,
233 pub output_hdr: bool,
236 pub sdr_white_nits: Option<f32>,
238 pub peak_nits: Option<f32>,
240 pub full_frame_nits: Option<f32>,
241 pub refresh_hz: Option<f32>,
243 pub variable_refresh: Option<bool>,
245 pub refresh_period: Option<Duration>,
248 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 pub fn nits(&self, value: f32) -> Option<f32> {
277 self.sdr_white_nits.map(|white| value * white)
278 }
279
280 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#[derive(Clone, Copy, Debug, PartialEq)]
303pub enum SurfaceEvent {
304 Changed(SurfaceInfo),
306 DeviceLost,
309 DisplayChanged(SurfaceDisplay),
312}
313
314#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
316pub struct SurfaceStats {
317 pub presented: u64,
318 pub shown: u64,
321}
322
323#[derive(Clone, Copy, Debug, PartialEq, Eq)]
326pub enum FrameEvent {
327 Presented {
330 frame: u64,
331 shown_at: u64,
332 refresh_interval: Duration,
333 precision: FramePrecision,
334 },
335 Dropped { frame: u64, reason: FrameDropReason },
337}
338
339impl FrameEvent {
340 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
354pub enum FramePrecision {
355 Exact,
357 Estimated,
359}
360
361#[derive(Clone, Copy, Debug, PartialEq, Eq)]
363pub enum FrameDropReason {
364 Superseded,
366 Hidden,
369 DeviceLost,
371 Closed,
373}
374
375#[derive(Clone, Copy, Debug, PartialEq, Eq)]
377pub struct FramePresent {
378 pub frame: u64,
380 pub release: u64,
382}
383
384type FrameCallback = Arc<Mutex<Box<dyn FnMut(FrameEvent) + Send>>>;
385
386#[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 pub(crate) frame_id: u64,
425 key: feedback::Key,
426 watched: bool,
428 pub(crate) lost: &'static str,
430 presented: u64,
431 shown: u64,
432 shown_seq: u64,
433 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 Cpu {
450 width: u32,
451 height: u32,
452 bgra: Arc<[u8]>,
453 halves: Option<Arc<[u16]>>,
454 },
455 #[cfg(windows)]
457 Gpu { width: u32, height: u32 },
458 #[cfg(windows)]
460 D3D12 { width: u32, height: u32 },
461 #[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 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 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 #[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
548pub(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
557pub(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 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 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 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 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 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 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 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 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 pub unsafe fn present_d3d11_texture(&self, texture: *mut c_void) -> Result<u64, SurfaceError> {
791 #[cfg(windows)]
792 {
793 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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#[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#[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
1178pub struct D3D11Device {
1182 #[cfg(windows)]
1183 inner: d3d11::Device,
1184 #[cfg(not(windows))]
1185 never: std::convert::Infallible,
1186}
1187
1188impl D3D11Device {
1189 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 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
1223pub struct D3D12Device {
1226 #[cfg(windows)]
1227 inner: d3d12::Device,
1228 #[cfg(not(windows))]
1229 never: std::convert::Infallible,
1230}
1231
1232impl D3D12Device {
1233 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 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 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
1280pub struct D3D12Fence {
1283 #[cfg(windows)]
1284 inner: d3d12::Fence,
1285 #[cfg(not(windows))]
1286 never: std::convert::Infallible,
1287}
1288
1289impl D3D12Fence {
1290 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 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 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
1348pub 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 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 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 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
1405pub 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 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 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 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
1473pub 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 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 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 pub unsafe fn from_iosurface(surface: *mut c_void) -> Result<Self, SurfaceError> {
1559 #[cfg(target_os = "macos")]
1560 {
1561 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 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 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 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 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 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 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 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 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 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 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#[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#[cfg(windows)]
1769pub(crate) fn device_removed() {
1770 REMOVED.store(true, Ordering::Release);
1771 shared::release_all();
1772 forget_gpu();
1773}
1774
1775pub(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 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}