Skip to main content

core_graphics2/
display_stream.rs

1use std::slice::from_raw_parts;
2
3use block::{Block, ConcreteBlock, RcBlock};
4use core_foundation::{
5    base::{CFType, CFTypeID, TCFType},
6    declare_TCFType,
7    dictionary::{CFDictionary, CFDictionaryRef},
8    impl_CFTypeDescription, impl_TCFType,
9    runloop::{CFRunLoopSource, CFRunLoopSourceRef},
10    string::{CFString, CFStringRef},
11};
12use dispatch2::{ffi::dispatch_queue_t, Queue};
13use io_surface::{IOSurface, IOSurfaceRef};
14use libc::{c_void, size_t};
15
16use crate::{base::CGFloat, display::CGDirectDisplayID, error::CGError, geometry::CGRect};
17
18#[repr(C)]
19pub struct __CGDisplayStream(c_void);
20
21pub type CGDisplayStreamRef = *mut __CGDisplayStream;
22
23#[repr(C)]
24pub struct __CGDisplayStreamUpdate(c_void);
25
26pub type CGDisplayStreamUpdateRef = *const __CGDisplayStreamUpdate;
27
28#[repr(i32)]
29#[derive(PartialEq, Eq, Debug, Clone, Copy)]
30pub enum CGDisplayStreamUpdateRectType {
31    #[doc(alias = "kCGDisplayStreamUpdateRefreshedRects")]
32    RefreshedRects    = 0,
33    #[doc(alias = "kCGDisplayStreamUpdateMovedRects")]
34    MovedRects        = 1,
35    #[doc(alias = "kCGDisplayStreamUpdateDirtyRects")]
36    DirtyRects        = 2,
37    #[doc(alias = "kCGDisplayStreamUpdateReducedDirtyRects")]
38    ReducedDirtyRects = 3,
39}
40
41#[repr(i32)]
42#[derive(PartialEq, Eq, Debug, Clone, Copy)]
43pub enum CGDisplayStreamFrameStatus {
44    #[doc(alias = "kCGDisplayStreamFrameStatusFrameComplete")]
45    FrameComplete = 0,
46    #[doc(alias = "kCGDisplayStreamFrameStatusFrameIdle")]
47    FrameIdle     = 1,
48    #[doc(alias = "kCGDisplayStreamFrameStatusFrameBlank")]
49    FrameBlank    = 2,
50    #[doc(alias = "kCGDisplayStreamFrameStatusStopped")]
51    Stopped       = 3,
52}
53
54pub type CGDisplayStreamFrameAvailableHandler = *const Block<(CGDisplayStreamFrameStatus, u64, IOSurfaceRef, CGDisplayStreamUpdateRef), ()>;
55
56extern "C" {
57    pub fn CGDisplayStreamUpdateGetTypeID() -> CFTypeID;
58    pub fn CGDisplayStreamUpdateGetRects(
59        update: CGDisplayStreamUpdateRef,
60        rectType: CGDisplayStreamUpdateRectType,
61        rectCount: *mut usize,
62    ) -> *const CGRect;
63    pub fn CGDisplayStreamUpdateCreateMergedUpdate(
64        firstUpdate: CGDisplayStreamUpdateRef,
65        secondUpdate: CGDisplayStreamUpdateRef,
66    ) -> CGDisplayStreamUpdateRef;
67    pub fn CGDisplayStreamUpdateGetMovedRectsDelta(updateRef: CGDisplayStreamUpdateRef, dx: *mut CGFloat, dy: *mut CGFloat);
68    pub fn CGDisplayStreamUpdateGetDropCount(updateRef: CGDisplayStreamUpdateRef) -> size_t;
69
70    pub static kCGDisplayStreamSourceRect: CFStringRef;
71    pub static kCGDisplayStreamDestinationRect: CFStringRef;
72    pub static kCGDisplayStreamPreserveAspectRatio: CFStringRef;
73    pub static kCGDisplayStreamColorSpace: CFStringRef;
74    pub static kCGDisplayStreamMinimumFrameTime: CFStringRef;
75    pub static kCGDisplayStreamShowCursor: CFStringRef;
76    pub static kCGDisplayStreamQueueDepth: CFStringRef;
77    pub static kCGDisplayStreamYCbCrMatrix: CFStringRef;
78    pub static kCGDisplayStreamYCbCrMatrix_ITU_R_709_2: CFStringRef;
79    pub static kCGDisplayStreamYCbCrMatrix_ITU_R_601_4: CFStringRef;
80    pub static kCGDisplayStreamYCbCrMatrix_SMPTE_240M_1995: CFStringRef;
81
82    pub fn CGDisplayStreamGetTypeID() -> CFTypeID;
83    pub fn CGDisplayStreamCreate(
84        display: CGDirectDisplayID,
85        outputWidth: size_t,
86        outputHeight: size_t,
87        pixelFormat: i32,
88        properties: CFDictionaryRef,
89        handler: CGDisplayStreamFrameAvailableHandler,
90    ) -> CGDisplayStreamRef;
91    pub fn CGDisplayStreamCreateWithDispatchQueue(
92        display: CGDirectDisplayID,
93        outputWidth: size_t,
94        outputHeight: size_t,
95        pixelFormat: i32,
96        properties: CFDictionaryRef,
97        queue: dispatch_queue_t,
98        handler: CGDisplayStreamFrameAvailableHandler,
99    ) -> CGDisplayStreamRef;
100    pub fn CGDisplayStreamStart(stream: CGDisplayStreamRef) -> CGError;
101    pub fn CGDisplayStreamStop(stream: CGDisplayStreamRef) -> CGError;
102    pub fn CGDisplayStreamGetRunLoopSource(stream: CGDisplayStreamRef) -> CFRunLoopSourceRef;
103}
104
105declare_TCFType! {
106    CGDisplayStreamUpdate, CGDisplayStreamUpdateRef
107}
108impl_TCFType!(CGDisplayStreamUpdate, CGDisplayStreamUpdateRef, CGDisplayStreamUpdateGetTypeID);
109impl_CFTypeDescription!(CGDisplayStreamUpdate);
110
111impl CGDisplayStreamUpdate {
112    pub fn new_merged_update(&self, other: &CGDisplayStreamUpdate) -> Result<CGDisplayStreamUpdate, ()> {
113        unsafe {
114            let update = CGDisplayStreamUpdateCreateMergedUpdate(self.as_concrete_TypeRef(), other.as_concrete_TypeRef());
115            if update.is_null() {
116                Err(())
117            } else {
118                Ok(TCFType::wrap_under_create_rule(update))
119            }
120        }
121    }
122
123    pub fn rects(&self, rect_type: CGDisplayStreamUpdateRectType) -> &[CGRect] {
124        unsafe {
125            let mut rect_count = 0;
126            let rects = CGDisplayStreamUpdateGetRects(self.as_concrete_TypeRef(), rect_type, &mut rect_count);
127            if rects.is_null() || rect_count == 0 {
128                &[]
129            } else {
130                from_raw_parts(rects, rect_count)
131            }
132        }
133    }
134
135    pub fn moved_rects_delta(&self) -> (CGFloat, CGFloat) {
136        unsafe {
137            let mut dx = 0.0;
138            let mut dy = 0.0;
139            CGDisplayStreamUpdateGetMovedRectsDelta(self.as_concrete_TypeRef(), &mut dx, &mut dy);
140            (dx, dy)
141        }
142    }
143
144    pub fn drop_count(&self) -> usize {
145        unsafe { CGDisplayStreamUpdateGetDropCount(self.as_concrete_TypeRef()) }
146    }
147}
148
149declare_TCFType! {
150    CGDisplayStream, CGDisplayStreamRef
151}
152impl_TCFType!(CGDisplayStream, CGDisplayStreamRef, CGDisplayStreamGetTypeID);
153impl_CFTypeDescription!(CGDisplayStream);
154
155impl CGDisplayStream {
156    fn new_frame_available_handler<F>(closure: F) -> RcBlock<(CGDisplayStreamFrameStatus, u64, IOSurfaceRef, CGDisplayStreamUpdateRef), ()>
157    where
158        F: Fn(CGDisplayStreamFrameStatus, u64, Option<IOSurface>, Option<CGDisplayStreamUpdate>) + 'static,
159    {
160        ConcreteBlock::new(move |status: CGDisplayStreamFrameStatus, timestamp: u64, surface: IOSurfaceRef, update: CGDisplayStreamUpdateRef| {
161            let surface = if surface.is_null() {
162                None
163            } else {
164                Some(unsafe { IOSurface::wrap_under_get_rule(surface as IOSurfaceRef) })
165            };
166            let update = if update.is_null() {
167                None
168            } else {
169                Some(unsafe { CGDisplayStreamUpdate::wrap_under_get_rule(update as CGDisplayStreamUpdateRef) })
170            };
171            closure(status, timestamp, surface, update);
172        })
173        .copy()
174    }
175
176    pub fn new<F>(
177        display: CGDirectDisplayID,
178        output_width: size_t,
179        output_height: size_t,
180        pixel_format: i32,
181        properties: &CFDictionary<CFString, CFType>,
182        closure: F,
183    ) -> Result<CGDisplayStream, ()>
184    where
185        F: Fn(CGDisplayStreamFrameStatus, u64, Option<IOSurface>, Option<CGDisplayStreamUpdate>) + 'static,
186    {
187        let stream = unsafe {
188            CGDisplayStreamCreate(
189                display,
190                output_width,
191                output_height,
192                pixel_format,
193                properties.as_concrete_TypeRef(),
194                &*Self::new_frame_available_handler(closure),
195            )
196        };
197        if stream.is_null() {
198            Err(())
199        } else {
200            Ok(unsafe { TCFType::wrap_under_create_rule(stream) })
201        }
202    }
203
204    pub fn new_with_dispatch_queue<F>(
205        display: CGDirectDisplayID,
206        output_width: size_t,
207        output_height: size_t,
208        pixel_format: i32,
209        properties: &CFDictionary<CFString, CFType>,
210        queue: &Queue,
211        closure: F,
212    ) -> Result<CGDisplayStream, ()>
213    where
214        F: Fn(CGDisplayStreamFrameStatus, u64, Option<IOSurface>, Option<CGDisplayStreamUpdate>) + 'static,
215    {
216        let stream = unsafe {
217            CGDisplayStreamCreateWithDispatchQueue(
218                display,
219                output_width,
220                output_height,
221                pixel_format,
222                properties.as_concrete_TypeRef(),
223                queue.as_raw(),
224                &*Self::new_frame_available_handler(closure),
225            )
226        };
227        if stream.is_null() {
228            Err(())
229        } else {
230            Ok(unsafe { TCFType::wrap_under_create_rule(stream) })
231        }
232    }
233
234    pub fn start(&self) -> CGError {
235        unsafe { CGDisplayStreamStart(self.as_concrete_TypeRef()) }
236    }
237
238    pub fn stop(&self) -> CGError {
239        unsafe { CGDisplayStreamStop(self.as_concrete_TypeRef()) }
240    }
241
242    pub fn run_loop_source(&self) -> Option<CFRunLoopSource> {
243        unsafe {
244            let source = CGDisplayStreamGetRunLoopSource(self.as_concrete_TypeRef());
245            if source.is_null() {
246                None
247            } else {
248                Some(TCFType::wrap_under_create_rule(source))
249            }
250        }
251    }
252}
253
254pub enum CGDisplayStreamProperties {
255    SourceRect,
256    DestinationRect,
257    PreserveAspectRatio,
258    ColorSpace,
259    MinimumFrameTime,
260    ShowCursor,
261    QueueDepth,
262    YCbCrMatrix,
263}
264
265impl From<CGDisplayStreamProperties> for CFStringRef {
266    fn from(key: CGDisplayStreamProperties) -> Self {
267        unsafe {
268            match key {
269                CGDisplayStreamProperties::SourceRect => kCGDisplayStreamSourceRect,
270                CGDisplayStreamProperties::DestinationRect => kCGDisplayStreamDestinationRect,
271                CGDisplayStreamProperties::PreserveAspectRatio => kCGDisplayStreamPreserveAspectRatio,
272                CGDisplayStreamProperties::ColorSpace => kCGDisplayStreamColorSpace,
273                CGDisplayStreamProperties::MinimumFrameTime => kCGDisplayStreamMinimumFrameTime,
274                CGDisplayStreamProperties::ShowCursor => kCGDisplayStreamShowCursor,
275                CGDisplayStreamProperties::QueueDepth => kCGDisplayStreamQueueDepth,
276                CGDisplayStreamProperties::YCbCrMatrix => kCGDisplayStreamYCbCrMatrix,
277            }
278        }
279    }
280}
281
282impl From<CGDisplayStreamProperties> for CFString {
283    fn from(key: CGDisplayStreamProperties) -> Self {
284        unsafe { CFString::wrap_under_get_rule(CFStringRef::from(key)) }
285    }
286}
287
288pub enum CGDisplayStreamYCbCrMatrices {
289    ITU_R_709_2,
290    ITU_R_601_4,
291    SMPTE_240M_1995,
292}
293
294impl From<CGDisplayStreamYCbCrMatrices> for CFStringRef {
295    fn from(matrix: CGDisplayStreamYCbCrMatrices) -> Self {
296        unsafe {
297            match matrix {
298                CGDisplayStreamYCbCrMatrices::ITU_R_709_2 => kCGDisplayStreamYCbCrMatrix_ITU_R_709_2,
299                CGDisplayStreamYCbCrMatrices::ITU_R_601_4 => kCGDisplayStreamYCbCrMatrix_ITU_R_601_4,
300                CGDisplayStreamYCbCrMatrices::SMPTE_240M_1995 => kCGDisplayStreamYCbCrMatrix_SMPTE_240M_1995,
301            }
302        }
303    }
304}
305
306impl From<CGDisplayStreamYCbCrMatrices> for CFString {
307    fn from(matrix: CGDisplayStreamYCbCrMatrices) -> Self {
308        unsafe { CFString::wrap_under_get_rule(CFStringRef::from(matrix)) }
309    }
310}