screencapturekit/cm/
iosurface.rs

1//! `IOSurface` - Hardware-accelerated surface
2//!
3//! Provides safe Rust bindings for Apple's `IOSurface` framework.
4//! `IOSurface` objects are framebuffers suitable for sharing across process boundaries
5//! and are the primary mechanism for zero-copy frame delivery in `ScreenCaptureKit`.
6//!
7//! # Safety
8//!
9//! Base address access is only available through lock guards to ensure proper
10//! memory synchronization. The surface must be locked before accessing pixel data.
11
12use super::ffi;
13use std::ffi::c_void;
14use std::fmt;
15use std::io;
16
17/// Lock options for `IOSurface`
18///
19/// This is a bitmask type that supports combining multiple options using the `|` operator.
20///
21/// # Examples
22///
23/// ```
24/// use screencapturekit::cm::IOSurfaceLockOptions;
25///
26/// // Single option
27/// let read_only = IOSurfaceLockOptions::READ_ONLY;
28///
29/// // Combined options
30/// let combined = IOSurfaceLockOptions::READ_ONLY | IOSurfaceLockOptions::AVOID_SYNC;
31/// assert!(combined.contains(IOSurfaceLockOptions::READ_ONLY));
32/// assert!(combined.contains(IOSurfaceLockOptions::AVOID_SYNC));
33/// ```
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
35pub struct IOSurfaceLockOptions(u32);
36
37impl IOSurfaceLockOptions {
38    /// No special options (read-write lock with sync)
39    pub const NONE: Self = Self(0);
40
41    /// Read-only lock - use when you only need to read data.
42    /// This allows the system to keep caches valid.
43    pub const READ_ONLY: Self = Self(0x0000_0001);
44
45    /// Avoid synchronization - use with caution.
46    /// Skip waiting for pending operations before completing the lock.
47    pub const AVOID_SYNC: Self = Self(0x0000_0002);
48
49    /// Create from a raw u32 value
50    #[must_use]
51    pub const fn from_bits(bits: u32) -> Self {
52        Self(bits)
53    }
54
55    /// Convert to u32 for FFI
56    #[must_use]
57    pub const fn as_u32(self) -> u32 {
58        self.0
59    }
60
61    /// Check if these options contain the given option
62    #[must_use]
63    pub const fn contains(self, other: Self) -> bool {
64        (self.0 & other.0) == other.0
65    }
66
67    /// Check if this is a read-only lock
68    #[must_use]
69    pub const fn is_read_only(self) -> bool {
70        self.contains(Self::READ_ONLY)
71    }
72
73    /// Check if this avoids synchronization
74    #[must_use]
75    pub const fn is_avoid_sync(self) -> bool {
76        self.contains(Self::AVOID_SYNC)
77    }
78
79    /// Check if no options are set
80    #[must_use]
81    pub const fn is_empty(self) -> bool {
82        self.0 == 0
83    }
84}
85
86impl std::ops::BitOr for IOSurfaceLockOptions {
87    type Output = Self;
88
89    fn bitor(self, rhs: Self) -> Self::Output {
90        Self(self.0 | rhs.0)
91    }
92}
93
94impl std::ops::BitOrAssign for IOSurfaceLockOptions {
95    fn bitor_assign(&mut self, rhs: Self) {
96        self.0 |= rhs.0;
97    }
98}
99
100impl std::ops::BitAnd for IOSurfaceLockOptions {
101    type Output = Self;
102
103    fn bitand(self, rhs: Self) -> Self::Output {
104        Self(self.0 & rhs.0)
105    }
106}
107
108impl std::ops::BitAndAssign for IOSurfaceLockOptions {
109    fn bitand_assign(&mut self, rhs: Self) {
110        self.0 &= rhs.0;
111    }
112}
113
114impl From<IOSurfaceLockOptions> for u32 {
115    fn from(options: IOSurfaceLockOptions) -> Self {
116        options.0
117    }
118}
119
120/// Properties for a single plane in a multi-planar `IOSurface`
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub struct PlaneProperties {
123    /// Width of this plane in pixels
124    pub width: usize,
125    /// Height of this plane in pixels
126    pub height: usize,
127    /// Bytes per row for this plane
128    pub bytes_per_row: usize,
129    /// Bytes per element for this plane
130    pub bytes_per_element: usize,
131    /// Offset from the start of the surface allocation
132    pub offset: usize,
133    /// Size of this plane in bytes
134    pub size: usize,
135}
136
137/// Hardware-accelerated surface for efficient frame delivery
138///
139/// `IOSurface` is Apple's cross-process framebuffer type. It provides:
140/// - Zero-copy sharing between processes
141/// - Direct GPU texture creation via Metal
142/// - Multi-planar format support (YCbCr, etc.)
143///
144/// # Memory Access Safety
145///
146/// The surface must be locked before accessing pixel data. Use [`lock`](Self::lock)
147/// to get a RAII guard that ensures proper locking/unlocking.
148///
149/// # Examples
150///
151/// ```no_run
152/// use screencapturekit::cm::{IOSurface, IOSurfaceLockOptions};
153///
154/// fn access_surface(surface: &IOSurface) -> Result<(), i32> {
155///     // Lock for read-only access
156///     let guard = surface.lock(IOSurfaceLockOptions::READ_ONLY)?;
157///     
158///     // Access pixel data through the guard
159///     let data = guard.as_slice();
160///     println!("Surface has {} bytes", data.len());
161///     
162///     // Surface automatically unlocked when guard drops
163///     Ok(())
164/// }
165/// ```
166pub struct IOSurface(*mut c_void);
167
168impl PartialEq for IOSurface {
169    fn eq(&self, other: &Self) -> bool {
170        self.0 == other.0
171    }
172}
173
174impl Eq for IOSurface {}
175
176impl std::hash::Hash for IOSurface {
177    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
178        unsafe {
179            let hash_value = ffi::io_surface_hash(self.0);
180            hash_value.hash(state);
181        }
182    }
183}
184
185impl IOSurface {
186    /// Create a new `IOSurface` with the given dimensions and pixel format
187    ///
188    /// # Arguments
189    ///
190    /// * `width` - Width in pixels
191    /// * `height` - Height in pixels
192    /// * `pixel_format` - Pixel format as a `FourCC` code (e.g., 0x42475241 for 'BGRA')
193    /// * `bytes_per_element` - Bytes per pixel (e.g., 4 for BGRA)
194    ///
195    /// # Returns
196    ///
197    /// `Some(IOSurface)` if creation succeeded, `None` otherwise.
198    ///
199    /// # Examples
200    ///
201    /// ```
202    /// use screencapturekit::cm::IOSurface;
203    ///
204    /// // Create a 100x100 BGRA IOSurface
205    /// let surface = IOSurface::create(100, 100, 0x42475241, 4)
206    ///     .expect("Failed to create IOSurface");
207    /// assert_eq!(surface.width(), 100);
208    /// assert_eq!(surface.height(), 100);
209    /// ```
210    #[must_use]
211    pub fn create(
212        width: usize,
213        height: usize,
214        pixel_format: u32,
215        bytes_per_element: usize,
216    ) -> Option<Self> {
217        let mut ptr: *mut c_void = std::ptr::null_mut();
218        let status = unsafe {
219            crate::ffi::io_surface_create(width, height, pixel_format, bytes_per_element, &mut ptr)
220        };
221        if status == 0 && !ptr.is_null() {
222            Some(Self(ptr))
223        } else {
224            None
225        }
226    }
227
228    /// Create an `IOSurface` with full properties including multi-planar support
229    ///
230    /// This is the general API for creating `IOSurface`s with any pixel format,
231    /// including multi-planar formats like YCbCr 4:2:0.
232    ///
233    /// # Arguments
234    ///
235    /// * `width` - Width in pixels
236    /// * `height` - Height in pixels
237    /// * `pixel_format` - Pixel format as `FourCC` (e.g., 0x42475241 for BGRA)
238    /// * `bytes_per_element` - Bytes per pixel element
239    /// * `bytes_per_row` - Bytes per row (should be 16-byte aligned for Metal)
240    /// * `alloc_size` - Total allocation size in bytes
241    /// * `planes` - Optional slice of plane info for multi-planar formats
242    ///
243    /// # Examples
244    ///
245    /// ```
246    /// use screencapturekit::cm::iosurface::PlaneProperties;
247    /// use screencapturekit::cm::IOSurface;
248    ///
249    /// // Create a YCbCr 420v biplanar surface
250    /// let width = 1920usize;
251    /// let height = 1080usize;
252    /// let plane0_bpr = (width + 15) & !15;  // 16-byte aligned
253    /// let plane1_bpr = (width + 15) & !15;
254    /// let plane0_size = plane0_bpr * height;
255    /// let plane1_size = plane1_bpr * (height / 2);
256    ///
257    /// let planes = [
258    ///     PlaneProperties {
259    ///         width,
260    ///         height,
261    ///         bytes_per_row: plane0_bpr,
262    ///         bytes_per_element: 1,
263    ///         offset: 0,
264    ///         size: plane0_size,
265    ///     },
266    ///     PlaneProperties {
267    ///         width: width / 2,
268    ///         height: height / 2,
269    ///         bytes_per_row: plane1_bpr,
270    ///         bytes_per_element: 2,
271    ///         offset: plane0_size,
272    ///         size: plane1_size,
273    ///     },
274    /// ];
275    ///
276    /// let surface = IOSurface::create_with_properties(
277    ///     width,
278    ///     height,
279    ///     0x34323076,  // '420v'
280    ///     1,
281    ///     plane0_bpr,
282    ///     plane0_size + plane1_size,
283    ///     Some(&planes),
284    /// );
285    /// ```
286    #[must_use]
287    #[allow(clippy::option_if_let_else)]
288    pub fn create_with_properties(
289        width: usize,
290        height: usize,
291        pixel_format: u32,
292        bytes_per_element: usize,
293        bytes_per_row: usize,
294        alloc_size: usize,
295        planes: Option<&[PlaneProperties]>,
296    ) -> Option<Self> {
297        let mut ptr: *mut c_void = std::ptr::null_mut();
298
299        let (
300            plane_count,
301            plane_widths,
302            plane_heights,
303            plane_row_bytes,
304            plane_elem_bytes,
305            plane_offsets,
306            plane_sizes,
307        ) = if let Some(p) = planes {
308            let widths: Vec<usize> = p.iter().map(|x| x.width).collect();
309            let heights: Vec<usize> = p.iter().map(|x| x.height).collect();
310            let row_bytes: Vec<usize> = p.iter().map(|x| x.bytes_per_row).collect();
311            let elem_bytes: Vec<usize> = p.iter().map(|x| x.bytes_per_element).collect();
312            let offsets: Vec<usize> = p.iter().map(|x| x.offset).collect();
313            let sizes: Vec<usize> = p.iter().map(|x| x.size).collect();
314            (
315                p.len(),
316                widths,
317                heights,
318                row_bytes,
319                elem_bytes,
320                offsets,
321                sizes,
322            )
323        } else {
324            (0, vec![], vec![], vec![], vec![], vec![], vec![])
325        };
326
327        let status = unsafe {
328            crate::ffi::io_surface_create_with_properties(
329                width,
330                height,
331                pixel_format,
332                bytes_per_element,
333                bytes_per_row,
334                alloc_size,
335                plane_count,
336                if plane_count > 0 {
337                    plane_widths.as_ptr()
338                } else {
339                    std::ptr::null()
340                },
341                if plane_count > 0 {
342                    plane_heights.as_ptr()
343                } else {
344                    std::ptr::null()
345                },
346                if plane_count > 0 {
347                    plane_row_bytes.as_ptr()
348                } else {
349                    std::ptr::null()
350                },
351                if plane_count > 0 {
352                    plane_elem_bytes.as_ptr()
353                } else {
354                    std::ptr::null()
355                },
356                if plane_count > 0 {
357                    plane_offsets.as_ptr()
358                } else {
359                    std::ptr::null()
360                },
361                if plane_count > 0 {
362                    plane_sizes.as_ptr()
363                } else {
364                    std::ptr::null()
365                },
366                &mut ptr,
367            )
368        };
369
370        if status == 0 && !ptr.is_null() {
371            Some(Self(ptr))
372        } else {
373            None
374        }
375    }
376
377    /// Create from raw pointer
378    pub fn from_raw(ptr: *mut c_void) -> Option<Self> {
379        if ptr.is_null() {
380            None
381        } else {
382            Some(Self(ptr))
383        }
384    }
385
386    /// # Safety
387    /// The caller must ensure the pointer is a valid `IOSurface` pointer.
388    pub unsafe fn from_ptr(ptr: *mut c_void) -> Self {
389        Self(ptr)
390    }
391
392    /// Get the raw pointer
393    pub fn as_ptr(&self) -> *mut c_void {
394        self.0
395    }
396
397    /// Get the width of the surface in pixels
398    pub fn width(&self) -> usize {
399        unsafe { ffi::io_surface_get_width(self.0) }
400    }
401
402    /// Get the height of the surface in pixels
403    pub fn height(&self) -> usize {
404        unsafe { ffi::io_surface_get_height(self.0) }
405    }
406
407    /// Get the bytes per row of the surface
408    pub fn bytes_per_row(&self) -> usize {
409        unsafe { ffi::io_surface_get_bytes_per_row(self.0) }
410    }
411
412    /// Get the total allocation size of the surface in bytes
413    pub fn alloc_size(&self) -> usize {
414        unsafe { ffi::io_surface_get_alloc_size(self.0) }
415    }
416
417    /// Get the data size of the surface in bytes (alias for `alloc_size`)
418    ///
419    /// This method provides API parity with `CVPixelBuffer::data_size()`.
420    pub fn data_size(&self) -> usize {
421        self.alloc_size()
422    }
423
424    /// Get the pixel format of the surface (OSType/FourCC)
425    pub fn pixel_format(&self) -> u32 {
426        unsafe { ffi::io_surface_get_pixel_format(self.0) }
427    }
428
429    /// Get the unique `IOSurfaceID` for this surface
430    pub fn id(&self) -> u32 {
431        unsafe { ffi::io_surface_get_id(self.0) }
432    }
433
434    /// Get the modification seed value
435    ///
436    /// This value changes each time the surface is modified, useful for
437    /// detecting whether the surface contents have changed.
438    pub fn seed(&self) -> u32 {
439        unsafe { ffi::io_surface_get_seed(self.0) }
440    }
441
442    /// Get the number of planes in this surface
443    ///
444    /// Multi-planar formats like YCbCr 420 have multiple planes:
445    /// - Plane 0: Y (luminance)
446    /// - Plane 1: `CbCr` (chrominance)
447    ///
448    /// Single-plane formats like BGRA return 0.
449    pub fn plane_count(&self) -> usize {
450        unsafe { ffi::io_surface_get_plane_count(self.0) }
451    }
452
453    /// Get the width of a specific plane
454    ///
455    /// For YCbCr 4:2:0 formats, plane 1 (`CbCr`) is half the width of plane 0 (Y).
456    pub fn width_of_plane(&self, plane_index: usize) -> usize {
457        unsafe { ffi::io_surface_get_width_of_plane(self.0, plane_index) }
458    }
459
460    /// Get the height of a specific plane
461    ///
462    /// For YCbCr 4:2:0 formats, plane 1 (`CbCr`) is half the height of plane 0 (Y).
463    pub fn height_of_plane(&self, plane_index: usize) -> usize {
464        unsafe { ffi::io_surface_get_height_of_plane(self.0, plane_index) }
465    }
466
467    /// Get the bytes per row of a specific plane
468    pub fn bytes_per_row_of_plane(&self, plane_index: usize) -> usize {
469        unsafe { ffi::io_surface_get_bytes_per_row_of_plane(self.0, plane_index) }
470    }
471
472    /// Get the bytes per element of the surface
473    pub fn bytes_per_element(&self) -> usize {
474        unsafe { ffi::io_surface_get_bytes_per_element(self.0) }
475    }
476
477    /// Get the element width of the surface
478    pub fn element_width(&self) -> usize {
479        unsafe { ffi::io_surface_get_element_width(self.0) }
480    }
481
482    /// Get the element height of the surface
483    pub fn element_height(&self) -> usize {
484        unsafe { ffi::io_surface_get_element_height(self.0) }
485    }
486
487    /// Check if the surface is currently in use
488    pub fn is_in_use(&self) -> bool {
489        unsafe { ffi::io_surface_is_in_use(self.0) }
490    }
491
492    /// Increment the use count of the surface
493    pub fn increment_use_count(&self) {
494        unsafe { ffi::io_surface_increment_use_count(self.0) }
495    }
496
497    /// Decrement the use count of the surface
498    pub fn decrement_use_count(&self) {
499        unsafe { ffi::io_surface_decrement_use_count(self.0) }
500    }
501
502    /// Get the base address (internal use only)
503    ///
504    /// # Safety
505    /// Caller must ensure the surface is locked before accessing the returned pointer.
506    pub(crate) fn base_address_raw(&self) -> *mut u8 {
507        unsafe { ffi::io_surface_get_base_address(self.0).cast::<u8>() }
508    }
509
510    /// Get the base address of a specific plane (internal use only)
511    ///
512    /// # Safety
513    /// Caller must ensure the surface is locked before accessing the returned pointer.
514    pub(crate) fn base_address_of_plane_raw(&self, plane_index: usize) -> Option<*mut u8> {
515        let plane_count = self.plane_count();
516        if plane_count == 0 || plane_index >= plane_count {
517            return None;
518        }
519        let ptr = unsafe { ffi::io_surface_get_base_address_of_plane(self.0, plane_index) };
520        if ptr.is_null() {
521            None
522        } else {
523            Some(ptr.cast::<u8>())
524        }
525    }
526
527    /// Lock the surface for CPU access (low-level API)
528    ///
529    /// Prefer using [`lock`](Self::lock) for RAII-style access.
530    ///
531    /// # Arguments
532    /// * `options` - Lock options (e.g., `IOSurfaceLockOptions::READ_ONLY`)
533    ///
534    /// # Errors
535    /// Returns `kern_return_t` error code if the lock fails.
536    pub fn lock_raw(&self, options: IOSurfaceLockOptions) -> Result<u32, i32> {
537        let mut seed: u32 = 0;
538        let status = unsafe { ffi::io_surface_lock(self.0, options.as_u32(), &mut seed) };
539        if status == 0 {
540            Ok(seed)
541        } else {
542            Err(status)
543        }
544    }
545
546    /// Unlock the surface after CPU access (low-level API)
547    ///
548    /// # Arguments
549    /// * `options` - Must match the options used in the corresponding `lock_raw()` call
550    ///
551    /// # Errors
552    /// Returns `kern_return_t` error code if the unlock fails.
553    pub fn unlock_raw(&self, options: IOSurfaceLockOptions) -> Result<u32, i32> {
554        let mut seed: u32 = 0;
555        let status = unsafe { ffi::io_surface_unlock(self.0, options.as_u32(), &mut seed) };
556        if status == 0 {
557            Ok(seed)
558        } else {
559            Err(status)
560        }
561    }
562
563    /// Lock the surface and return a guard for RAII-style access
564    ///
565    /// This is the recommended way to access surface memory. The guard ensures
566    /// the surface is properly unlocked when it goes out of scope.
567    ///
568    /// # Arguments
569    /// * `options` - Lock options (e.g., `IOSurfaceLockOptions::READ_ONLY`)
570    ///
571    /// # Errors
572    /// Returns `kern_return_t` error code if the lock fails.
573    ///
574    /// # Examples
575    ///
576    /// ```no_run
577    /// use screencapturekit::cm::{IOSurface, IOSurfaceLockOptions};
578    ///
579    /// fn read_surface(surface: &IOSurface) -> Result<(), i32> {
580    ///     let guard = surface.lock(IOSurfaceLockOptions::READ_ONLY)?;
581    ///     let data = guard.as_slice();
582    ///     println!("Read {} bytes", data.len());
583    ///     Ok(())
584    /// }
585    /// ```
586    pub fn lock(&self, options: IOSurfaceLockOptions) -> Result<IOSurfaceLockGuard<'_>, i32> {
587        self.lock_raw(options)?;
588        Ok(IOSurfaceLockGuard {
589            surface: self,
590            options,
591        })
592    }
593
594    /// Lock the surface for read-only access
595    ///
596    /// This is a convenience method equivalent to `lock(IOSurfaceLockOptions::READ_ONLY)`.
597    ///
598    /// # Errors
599    /// Returns `kern_return_t` error code if the lock fails.
600    pub fn lock_read_only(&self) -> Result<IOSurfaceLockGuard<'_>, i32> {
601        self.lock(IOSurfaceLockOptions::READ_ONLY)
602    }
603
604    /// Lock the surface for read-write access
605    ///
606    /// This is a convenience method equivalent to `lock(IOSurfaceLockOptions::NONE)`.
607    ///
608    /// # Errors
609    /// Returns `kern_return_t` error code if the lock fails.
610    pub fn lock_read_write(&self) -> Result<IOSurfaceLockGuard<'_>, i32> {
611        self.lock(IOSurfaceLockOptions::NONE)
612    }
613}
614
615/// RAII guard for locked `IOSurface`
616///
617/// Provides safe access to surface memory while the lock is held.
618/// The surface is automatically unlocked when this guard is dropped.
619///
620/// # Memory Access
621///
622/// All base address access is through this guard to ensure proper locking.
623///
624/// # Examples
625///
626/// ```no_run
627/// use screencapturekit::cm::{IOSurface, IOSurfaceLockOptions};
628///
629/// fn access_surface(surface: &IOSurface) -> Result<(), i32> {
630///     let guard = surface.lock(IOSurfaceLockOptions::READ_ONLY)?;
631///     
632///     // Access the entire buffer
633///     let data = guard.as_slice();
634///     
635///     // Access a specific row
636///     if let Some(row) = guard.row(0) {
637///         println!("First row: {} bytes", row.len());
638///     }
639///     
640///     // Access a specific plane (for multi-planar formats)
641///     if let Some(plane_data) = guard.plane_data(0) {
642///         println!("Plane 0: {} bytes", plane_data.len());
643///     }
644///     
645///     Ok(())
646/// }
647/// ```
648pub struct IOSurfaceLockGuard<'a> {
649    surface: &'a IOSurface,
650    options: IOSurfaceLockOptions,
651}
652
653impl IOSurfaceLockGuard<'_> {
654    /// Get the width of the surface in pixels
655    pub fn width(&self) -> usize {
656        self.surface.width()
657    }
658
659    /// Get the height of the surface in pixels
660    pub fn height(&self) -> usize {
661        self.surface.height()
662    }
663
664    /// Get the bytes per row of the surface
665    pub fn bytes_per_row(&self) -> usize {
666        self.surface.bytes_per_row()
667    }
668
669    /// Get the total allocation size in bytes
670    pub fn alloc_size(&self) -> usize {
671        self.surface.alloc_size()
672    }
673
674    /// Get the data size of the surface (alias for `alloc_size`)
675    pub fn data_size(&self) -> usize {
676        self.alloc_size()
677    }
678
679    /// Get the pixel format of the surface
680    pub fn pixel_format(&self) -> u32 {
681        self.surface.pixel_format()
682    }
683
684    /// Get the number of planes in the surface
685    pub fn plane_count(&self) -> usize {
686        self.surface.plane_count()
687    }
688
689    /// Get the base address of the locked surface
690    ///
691    /// # Safety
692    ///
693    /// The returned pointer is only valid while this guard is held.
694    pub fn base_address(&self) -> *const u8 {
695        self.surface.base_address_raw().cast_const()
696    }
697
698    /// Get the mutable base address (only valid for read-write locks)
699    ///
700    /// Returns `None` if this is a read-only lock.
701    ///
702    /// # Safety
703    ///
704    /// The returned pointer is only valid while this guard is held.
705    pub fn base_address_mut(&mut self) -> Option<*mut u8> {
706        if self.options.is_read_only() {
707            None
708        } else {
709            Some(self.surface.base_address_raw())
710        }
711    }
712
713    /// Get the base address of a specific plane
714    ///
715    /// For multi-planar formats like YCbCr 4:2:0:
716    /// - Plane 0: Y (luminance) data
717    /// - Plane 1: `CbCr` (chrominance) data
718    ///
719    /// Returns `None` if the plane index is out of bounds.
720    ///
721    /// # Safety
722    ///
723    /// The returned pointer is only valid while this guard is held.
724    pub fn base_address_of_plane(&self, plane_index: usize) -> Option<*const u8> {
725        self.surface
726            .base_address_of_plane_raw(plane_index)
727            .map(<*mut u8>::cast_const)
728    }
729
730    /// Get the mutable base address of a specific plane
731    ///
732    /// Returns `None` if this is a read-only lock or the plane index is out of bounds.
733    pub fn base_address_of_plane_mut(&mut self, plane_index: usize) -> Option<*mut u8> {
734        if self.options.is_read_only() {
735            return None;
736        }
737        self.surface.base_address_of_plane_raw(plane_index)
738    }
739
740    /// Get a slice view of the surface data
741    ///
742    /// The lock guard ensures the surface is locked for the lifetime of the slice.
743    pub fn as_slice(&self) -> &[u8] {
744        let ptr = self.base_address();
745        let len = self.alloc_size();
746        if ptr.is_null() || len == 0 {
747            &[]
748        } else {
749            unsafe { std::slice::from_raw_parts(ptr, len) }
750        }
751    }
752
753    /// Get a mutable slice view of the surface data (only valid for read-write locks)
754    ///
755    /// Returns `None` if this is a read-only lock.
756    pub fn as_slice_mut(&mut self) -> Option<&mut [u8]> {
757        if self.options.is_read_only() {
758            return None;
759        }
760        let ptr = self.base_address_mut()?;
761        let len = self.alloc_size();
762        if ptr.is_null() || len == 0 {
763            Some(&mut [])
764        } else {
765            Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
766        }
767    }
768
769    /// Get a specific row as a slice
770    ///
771    /// Returns `None` if the row index is out of bounds.
772    pub fn row(&self, row_index: usize) -> Option<&[u8]> {
773        if row_index >= self.height() {
774            return None;
775        }
776        let ptr = self.base_address();
777        if ptr.is_null() {
778            return None;
779        }
780        unsafe {
781            let row_ptr = ptr.add(row_index * self.bytes_per_row());
782            Some(std::slice::from_raw_parts(row_ptr, self.bytes_per_row()))
783        }
784    }
785
786    /// Get a slice of plane data
787    ///
788    /// Returns the data for a specific plane as a byte slice. The slice size is
789    /// calculated from the plane's height and bytes per row.
790    ///
791    /// Returns `None` if the plane index is out of bounds.
792    pub fn plane_data(&self, plane_index: usize) -> Option<&[u8]> {
793        let base = self.base_address_of_plane(plane_index)?;
794        let height = self.surface.height_of_plane(plane_index);
795        let bytes_per_row = self.surface.bytes_per_row_of_plane(plane_index);
796        Some(unsafe { std::slice::from_raw_parts(base, height * bytes_per_row) })
797    }
798
799    /// Get a specific row from a plane as a slice
800    ///
801    /// Returns `None` if the plane or row index is out of bounds.
802    pub fn plane_row(&self, plane_index: usize, row_index: usize) -> Option<&[u8]> {
803        let height = self.surface.height_of_plane(plane_index);
804        if row_index >= height {
805            return None;
806        }
807        let base = self.base_address_of_plane(plane_index)?;
808        let bytes_per_row = self.surface.bytes_per_row_of_plane(plane_index);
809        Some(unsafe {
810            std::slice::from_raw_parts(base.add(row_index * bytes_per_row), bytes_per_row)
811        })
812    }
813
814    /// Access surface with a standard `std::io::Cursor`
815    ///
816    /// Returns a cursor over the surface data that implements `Read` and `Seek`.
817    ///
818    /// # Examples
819    ///
820    /// ```no_run
821    /// use std::io::{Read, Seek, SeekFrom};
822    /// use screencapturekit::cm::{IOSurface, IOSurfaceLockOptions};
823    ///
824    /// fn read_surface(surface: &IOSurface) {
825    ///     let guard = surface.lock(IOSurfaceLockOptions::READ_ONLY).unwrap();
826    ///     let mut cursor = guard.cursor();
827    ///
828    ///     // Read first 4 bytes
829    ///     let mut pixel = [0u8; 4];
830    ///     cursor.read_exact(&mut pixel).unwrap();
831    ///
832    ///     // Seek to row 10
833    ///     let offset = 10 * guard.bytes_per_row();
834    ///     cursor.seek(SeekFrom::Start(offset as u64)).unwrap();
835    /// }
836    /// ```
837    pub fn cursor(&self) -> io::Cursor<&[u8]> {
838        io::Cursor::new(self.as_slice())
839    }
840
841    /// Get raw pointer to surface data
842    pub fn as_ptr(&self) -> *const u8 {
843        self.base_address()
844    }
845
846    /// Get mutable raw pointer to surface data (only valid for read-write locks)
847    ///
848    /// Returns `None` if this is a read-only lock.
849    pub fn as_mut_ptr(&mut self) -> Option<*mut u8> {
850        self.base_address_mut()
851    }
852
853    /// Check if this is a read-only lock
854    pub const fn is_read_only(&self) -> bool {
855        self.options.is_read_only()
856    }
857
858    /// Get the lock options
859    pub const fn options(&self) -> IOSurfaceLockOptions {
860        self.options
861    }
862}
863
864impl std::ops::Deref for IOSurfaceLockGuard<'_> {
865    type Target = [u8];
866
867    fn deref(&self) -> &Self::Target {
868        self.as_slice()
869    }
870}
871
872impl Drop for IOSurfaceLockGuard<'_> {
873    fn drop(&mut self) {
874        let _ = self.surface.unlock_raw(self.options);
875    }
876}
877
878impl std::fmt::Debug for IOSurfaceLockGuard<'_> {
879    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
880        f.debug_struct("IOSurfaceLockGuard")
881            .field("options", &self.options)
882            .field(
883                "surface_size",
884                &(self.surface.width(), self.surface.height()),
885            )
886            .finish()
887    }
888}
889
890impl Drop for IOSurface {
891    fn drop(&mut self) {
892        unsafe {
893            ffi::io_surface_release(self.0);
894        }
895    }
896}
897
898impl Clone for IOSurface {
899    fn clone(&self) -> Self {
900        unsafe {
901            let ptr = ffi::io_surface_retain(self.0);
902            Self(ptr)
903        }
904    }
905}
906
907unsafe impl Send for IOSurface {}
908unsafe impl Sync for IOSurface {}
909
910impl fmt::Debug for IOSurface {
911    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
912        f.debug_struct("IOSurface")
913            .field("id", &self.id())
914            .field("width", &self.width())
915            .field("height", &self.height())
916            .field("bytes_per_row", &self.bytes_per_row())
917            .field("pixel_format", &self.pixel_format())
918            .field("plane_count", &self.plane_count())
919            .finish()
920    }
921}
922
923impl fmt::Display for IOSurface {
924    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
925        write!(
926            f,
927            "IOSurface({}x{}, {} bytes/row)",
928            self.width(),
929            self.height(),
930            self.bytes_per_row()
931        )
932    }
933}