Skip to main content

apple_cf/iosurface/
mod.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 apple_cf::iosurface::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 apple_cf::iosurface::{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 apple_cf::iosurface::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 apple_cf::iosurface::PlaneProperties;
247    /// use apple_cf::iosurface::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 const unsafe fn from_ptr(ptr: *mut c_void) -> Self {
389        Self(ptr)
390    }
391
392    /// Get the raw pointer
393    #[must_use]
394    pub const fn as_ptr(&self) -> *mut c_void {
395        self.0
396    }
397
398    /// Get the width of the surface in pixels
399    #[must_use]
400    pub fn width(&self) -> usize {
401        unsafe { ffi::io_surface_get_width(self.0) }
402    }
403
404    /// Get the height of the surface in pixels
405    #[must_use]
406    pub fn height(&self) -> usize {
407        unsafe { ffi::io_surface_get_height(self.0) }
408    }
409
410    /// Get the bytes per row of the surface
411    #[must_use]
412    pub fn bytes_per_row(&self) -> usize {
413        unsafe { ffi::io_surface_get_bytes_per_row(self.0) }
414    }
415
416    /// Get the total allocation size of the surface in bytes
417    #[must_use]
418    pub fn alloc_size(&self) -> usize {
419        unsafe { ffi::io_surface_get_alloc_size(self.0) }
420    }
421
422    /// Get the data size of the surface in bytes (alias for `alloc_size`)
423    ///
424    /// This method provides API parity with `CVPixelBuffer::data_size()`.
425    #[must_use]
426    pub fn data_size(&self) -> usize {
427        self.alloc_size()
428    }
429
430    /// Get the pixel format of the surface (OSType/FourCC)
431    #[must_use]
432    pub fn pixel_format(&self) -> u32 {
433        unsafe { ffi::io_surface_get_pixel_format(self.0) }
434    }
435
436    /// Get the unique `IOSurfaceID` for this surface
437    #[must_use]
438    pub fn id(&self) -> u32 {
439        unsafe { ffi::io_surface_get_id(self.0) }
440    }
441
442    /// Get the modification seed value
443    ///
444    /// This value changes each time the surface is modified, useful for
445    /// detecting whether the surface contents have changed.
446    #[must_use]
447    pub fn seed(&self) -> u32 {
448        unsafe { ffi::io_surface_get_seed(self.0) }
449    }
450
451    /// Get the number of planes in this surface
452    ///
453    /// Multi-planar formats like YCbCr 420 have multiple planes:
454    /// - Plane 0: Y (luminance)
455    /// - Plane 1: `CbCr` (chrominance)
456    ///
457    /// Single-plane formats like BGRA return 0.
458    #[must_use]
459    pub fn plane_count(&self) -> usize {
460        unsafe { ffi::io_surface_get_plane_count(self.0) }
461    }
462
463    /// Get the width of a specific plane
464    ///
465    /// For YCbCr 4:2:0 formats, plane 1 (`CbCr`) is half the width of plane 0 (Y).
466    #[must_use]
467    pub fn width_of_plane(&self, plane_index: usize) -> usize {
468        unsafe { ffi::io_surface_get_width_of_plane(self.0, plane_index) }
469    }
470
471    /// Get the height of a specific plane
472    ///
473    /// For YCbCr 4:2:0 formats, plane 1 (`CbCr`) is half the height of plane 0 (Y).
474    #[must_use]
475    pub fn height_of_plane(&self, plane_index: usize) -> usize {
476        unsafe { ffi::io_surface_get_height_of_plane(self.0, plane_index) }
477    }
478
479    /// Get the bytes per row of a specific plane
480    #[must_use]
481    pub fn bytes_per_row_of_plane(&self, plane_index: usize) -> usize {
482        unsafe { ffi::io_surface_get_bytes_per_row_of_plane(self.0, plane_index) }
483    }
484
485    /// Get the bytes per element of the surface
486    #[must_use]
487    pub fn bytes_per_element(&self) -> usize {
488        unsafe { ffi::io_surface_get_bytes_per_element(self.0) }
489    }
490
491    /// Get the element width of the surface
492    #[must_use]
493    pub fn element_width(&self) -> usize {
494        unsafe { ffi::io_surface_get_element_width(self.0) }
495    }
496
497    /// Get the element height of the surface
498    #[must_use]
499    pub fn element_height(&self) -> usize {
500        unsafe { ffi::io_surface_get_element_height(self.0) }
501    }
502
503    /// Check if the surface is currently in use
504    #[must_use]
505    pub fn is_in_use(&self) -> bool {
506        unsafe { ffi::io_surface_is_in_use(self.0) }
507    }
508
509    /// Increment the use count of the surface
510    pub fn increment_use_count(&self) {
511        unsafe { ffi::io_surface_increment_use_count(self.0) }
512    }
513
514    /// Decrement the use count of the surface
515    pub fn decrement_use_count(&self) {
516        unsafe { ffi::io_surface_decrement_use_count(self.0) }
517    }
518
519    /// Get the base address (internal use only)
520    ///
521    /// # Safety
522    /// Caller must ensure the surface is locked before accessing the returned pointer.
523    pub(crate) fn base_address_raw(&self) -> *mut u8 {
524        unsafe { ffi::io_surface_get_base_address(self.0).cast::<u8>() }
525    }
526
527    /// Get the base address of a specific plane (internal use only)
528    ///
529    /// # Safety
530    /// Caller must ensure the surface is locked before accessing the returned pointer.
531    pub(crate) fn base_address_of_plane_raw(&self, plane_index: usize) -> Option<*mut u8> {
532        let plane_count = self.plane_count();
533        if plane_count == 0 || plane_index >= plane_count {
534            return None;
535        }
536        let ptr = unsafe { ffi::io_surface_get_base_address_of_plane(self.0, plane_index) };
537        if ptr.is_null() {
538            None
539        } else {
540            Some(ptr.cast::<u8>())
541        }
542    }
543
544    /// Lock the surface for CPU access (low-level API)
545    ///
546    /// Prefer using [`lock`](Self::lock) for RAII-style access.
547    ///
548    /// # Arguments
549    /// * `options` - Lock options (e.g., `IOSurfaceLockOptions::READ_ONLY`)
550    ///
551    /// # Errors
552    /// Returns `kern_return_t` error code if the lock fails.
553    pub fn lock_raw(&self, options: IOSurfaceLockOptions) -> Result<u32, i32> {
554        let mut seed: u32 = 0;
555        let status = unsafe { ffi::io_surface_lock(self.0, options.as_u32(), &mut seed) };
556        if status == 0 {
557            Ok(seed)
558        } else {
559            Err(status)
560        }
561    }
562
563    /// Unlock the surface after CPU access (low-level API)
564    ///
565    /// # Arguments
566    /// * `options` - Must match the options used in the corresponding `lock_raw()` call
567    ///
568    /// # Errors
569    /// Returns `kern_return_t` error code if the unlock fails.
570    pub fn unlock_raw(&self, options: IOSurfaceLockOptions) -> Result<u32, i32> {
571        let mut seed: u32 = 0;
572        let status = unsafe { ffi::io_surface_unlock(self.0, options.as_u32(), &mut seed) };
573        if status == 0 {
574            Ok(seed)
575        } else {
576            Err(status)
577        }
578    }
579
580    /// Lock the surface and return a guard for RAII-style access
581    ///
582    /// This is the recommended way to access surface memory. The guard ensures
583    /// the surface is properly unlocked when it goes out of scope.
584    ///
585    /// # Arguments
586    /// * `options` - Lock options (e.g., `IOSurfaceLockOptions::READ_ONLY`)
587    ///
588    /// # Errors
589    /// Returns `kern_return_t` error code if the lock fails.
590    ///
591    /// # Examples
592    ///
593    /// ```no_run
594    /// use apple_cf::iosurface::{IOSurface, IOSurfaceLockOptions};
595    ///
596    /// fn read_surface(surface: &IOSurface) -> Result<(), i32> {
597    ///     let guard = surface.lock(IOSurfaceLockOptions::READ_ONLY)?;
598    ///     let data = guard.as_slice();
599    ///     println!("Read {} bytes", data.len());
600    ///     Ok(())
601    /// }
602    /// ```
603    pub fn lock(&self, options: IOSurfaceLockOptions) -> Result<IOSurfaceLockGuard<'_>, i32> {
604        self.lock_raw(options)?;
605        Ok(IOSurfaceLockGuard {
606            surface: self,
607            options,
608        })
609    }
610
611    /// Lock the surface for read-only access
612    ///
613    /// This is a convenience method equivalent to `lock(IOSurfaceLockOptions::READ_ONLY)`.
614    ///
615    /// # Errors
616    /// Returns `kern_return_t` error code if the lock fails.
617    pub fn lock_read_only(&self) -> Result<IOSurfaceLockGuard<'_>, i32> {
618        self.lock(IOSurfaceLockOptions::READ_ONLY)
619    }
620
621    /// Lock the surface for read-write access
622    ///
623    /// This is a convenience method equivalent to `lock(IOSurfaceLockOptions::NONE)`.
624    ///
625    /// # Errors
626    /// Returns `kern_return_t` error code if the lock fails.
627    pub fn lock_read_write(&self) -> Result<IOSurfaceLockGuard<'_>, i32> {
628        self.lock(IOSurfaceLockOptions::NONE)
629    }
630}
631
632/// RAII guard for locked `IOSurface`
633///
634/// Provides safe access to surface memory while the lock is held.
635/// The surface is automatically unlocked when this guard is dropped.
636///
637/// # Memory Access
638///
639/// All base address access is through this guard to ensure proper locking.
640///
641/// # Examples
642///
643/// ```no_run
644/// use apple_cf::iosurface::{IOSurface, IOSurfaceLockOptions};
645///
646/// fn access_surface(surface: &IOSurface) -> Result<(), i32> {
647///     let guard = surface.lock(IOSurfaceLockOptions::READ_ONLY)?;
648///     
649///     // Access the entire buffer
650///     let data = guard.as_slice();
651///     
652///     // Access a specific row
653///     if let Some(row) = guard.row(0) {
654///         println!("First row: {} bytes", row.len());
655///     }
656///     
657///     // Access a specific plane (for multi-planar formats)
658///     if let Some(plane_data) = guard.plane_data(0) {
659///         println!("Plane 0: {} bytes", plane_data.len());
660///     }
661///     
662///     Ok(())
663/// }
664/// ```
665pub struct IOSurfaceLockGuard<'a> {
666    surface: &'a IOSurface,
667    options: IOSurfaceLockOptions,
668}
669
670impl IOSurfaceLockGuard<'_> {
671    /// Get the width of the surface in pixels
672    #[must_use]
673    pub fn width(&self) -> usize {
674        self.surface.width()
675    }
676
677    /// Get the height of the surface in pixels
678    #[must_use]
679    pub fn height(&self) -> usize {
680        self.surface.height()
681    }
682
683    /// Get the bytes per row of the surface
684    #[must_use]
685    pub fn bytes_per_row(&self) -> usize {
686        self.surface.bytes_per_row()
687    }
688
689    /// Get the total allocation size in bytes
690    #[must_use]
691    pub fn alloc_size(&self) -> usize {
692        self.surface.alloc_size()
693    }
694
695    /// Get the data size of the surface (alias for `alloc_size`)
696    #[must_use]
697    pub fn data_size(&self) -> usize {
698        self.alloc_size()
699    }
700
701    /// Get the pixel format of the surface
702    #[must_use]
703    pub fn pixel_format(&self) -> u32 {
704        self.surface.pixel_format()
705    }
706
707    /// Get the number of planes in the surface
708    #[must_use]
709    pub fn plane_count(&self) -> usize {
710        self.surface.plane_count()
711    }
712
713    /// Get the base address of the locked surface
714    ///
715    /// # Safety
716    ///
717    /// The returned pointer is only valid while this guard is held.
718    #[must_use]
719    pub fn base_address(&self) -> *const u8 {
720        self.surface.base_address_raw().cast_const()
721    }
722
723    /// Get the mutable base address (only valid for read-write locks)
724    ///
725    /// Returns `None` if this is a read-only lock.
726    ///
727    /// # Safety
728    ///
729    /// The returned pointer is only valid while this guard is held.
730    pub fn base_address_mut(&mut self) -> Option<*mut u8> {
731        if self.options.is_read_only() {
732            None
733        } else {
734            Some(self.surface.base_address_raw())
735        }
736    }
737
738    /// Get the base address of a specific plane
739    ///
740    /// For multi-planar formats like YCbCr 4:2:0:
741    /// - Plane 0: Y (luminance) data
742    /// - Plane 1: `CbCr` (chrominance) data
743    ///
744    /// Returns `None` if the plane index is out of bounds.
745    ///
746    /// # Safety
747    ///
748    /// The returned pointer is only valid while this guard is held.
749    pub fn base_address_of_plane(&self, plane_index: usize) -> Option<*const u8> {
750        self.surface
751            .base_address_of_plane_raw(plane_index)
752            .map(<*mut u8>::cast_const)
753    }
754
755    /// Get the mutable base address of a specific plane
756    ///
757    /// Returns `None` if this is a read-only lock or the plane index is out of bounds.
758    pub fn base_address_of_plane_mut(&mut self, plane_index: usize) -> Option<*mut u8> {
759        if self.options.is_read_only() {
760            return None;
761        }
762        self.surface.base_address_of_plane_raw(plane_index)
763    }
764
765    /// Get a slice view of the surface data
766    ///
767    /// The lock guard ensures the surface is locked for the lifetime of the slice.
768    #[must_use]
769    pub fn as_slice(&self) -> &[u8] {
770        let ptr = self.base_address();
771        let len = self.alloc_size();
772        if ptr.is_null() || len == 0 {
773            &[]
774        } else {
775            unsafe { std::slice::from_raw_parts(ptr, len) }
776        }
777    }
778
779    /// Get a mutable slice view of the surface data (only valid for read-write locks)
780    ///
781    /// Returns `None` if this is a read-only lock.
782    pub fn as_slice_mut(&mut self) -> Option<&mut [u8]> {
783        if self.options.is_read_only() {
784            return None;
785        }
786        let ptr = self.base_address_mut()?;
787        let len = self.alloc_size();
788        if ptr.is_null() || len == 0 {
789            Some(&mut [])
790        } else {
791            Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
792        }
793    }
794
795    /// Get a specific row as a slice
796    ///
797    /// Returns `None` if the row index is out of bounds.
798    #[must_use]
799    pub fn row(&self, row_index: usize) -> Option<&[u8]> {
800        if row_index >= self.height() {
801            return None;
802        }
803        let ptr = self.base_address();
804        if ptr.is_null() {
805            return None;
806        }
807        unsafe {
808            let row_ptr = ptr.add(row_index * self.bytes_per_row());
809            Some(std::slice::from_raw_parts(row_ptr, self.bytes_per_row()))
810        }
811    }
812
813    /// Get a slice of plane data
814    ///
815    /// Returns the data for a specific plane as a byte slice. The slice size is
816    /// calculated from the plane's height and bytes per row.
817    ///
818    /// Returns `None` if the plane index is out of bounds.
819    #[must_use]
820    pub fn plane_data(&self, plane_index: usize) -> Option<&[u8]> {
821        let base = self.base_address_of_plane(plane_index)?;
822        let height = self.surface.height_of_plane(plane_index);
823        let bytes_per_row = self.surface.bytes_per_row_of_plane(plane_index);
824        Some(unsafe { std::slice::from_raw_parts(base, height * bytes_per_row) })
825    }
826
827    /// Get a specific row from a plane as a slice
828    ///
829    /// Returns `None` if the plane or row index is out of bounds.
830    #[must_use]
831    pub fn plane_row(&self, plane_index: usize, row_index: usize) -> Option<&[u8]> {
832        let height = self.surface.height_of_plane(plane_index);
833        if row_index >= height {
834            return None;
835        }
836        let base = self.base_address_of_plane(plane_index)?;
837        let bytes_per_row = self.surface.bytes_per_row_of_plane(plane_index);
838        Some(unsafe {
839            std::slice::from_raw_parts(base.add(row_index * bytes_per_row), bytes_per_row)
840        })
841    }
842
843    /// Access surface with a standard `std::io::Cursor`
844    ///
845    /// Returns a cursor over the surface data that implements `Read` and `Seek`.
846    ///
847    /// # Examples
848    ///
849    /// ```no_run
850    /// use std::io::{Read, Seek, SeekFrom};
851    /// use apple_cf::iosurface::{IOSurface, IOSurfaceLockOptions};
852    ///
853    /// fn read_surface(surface: &IOSurface) {
854    ///     let guard = surface.lock(IOSurfaceLockOptions::READ_ONLY).unwrap();
855    ///     let mut cursor = guard.cursor();
856    ///
857    ///     // Read first 4 bytes
858    ///     let mut pixel = [0u8; 4];
859    ///     cursor.read_exact(&mut pixel).unwrap();
860    ///
861    ///     // Seek to row 10
862    ///     let offset = 10 * guard.bytes_per_row();
863    ///     cursor.seek(SeekFrom::Start(offset as u64)).unwrap();
864    /// }
865    /// ```
866    #[must_use]
867    pub fn cursor(&self) -> io::Cursor<&[u8]> {
868        io::Cursor::new(self.as_slice())
869    }
870
871    /// Get raw pointer to surface data
872    #[must_use]
873    pub fn as_ptr(&self) -> *const u8 {
874        self.base_address()
875    }
876
877    /// Get mutable raw pointer to surface data (only valid for read-write locks)
878    ///
879    /// Returns `None` if this is a read-only lock.
880    pub fn as_mut_ptr(&mut self) -> Option<*mut u8> {
881        self.base_address_mut()
882    }
883
884    /// Check if this is a read-only lock
885    #[must_use]
886    pub const fn is_read_only(&self) -> bool {
887        self.options.is_read_only()
888    }
889
890    /// Get the lock options
891    #[must_use]
892    pub const fn options(&self) -> IOSurfaceLockOptions {
893        self.options
894    }
895}
896
897impl std::ops::Deref for IOSurfaceLockGuard<'_> {
898    type Target = [u8];
899
900    fn deref(&self) -> &Self::Target {
901        self.as_slice()
902    }
903}
904
905impl Drop for IOSurfaceLockGuard<'_> {
906    fn drop(&mut self) {
907        let _ = self.surface.unlock_raw(self.options);
908    }
909}
910
911impl std::fmt::Debug for IOSurfaceLockGuard<'_> {
912    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
913        f.debug_struct("IOSurfaceLockGuard")
914            .field("options", &self.options)
915            .field(
916                "surface_size",
917                &(self.surface.width(), self.surface.height()),
918            )
919            .finish()
920    }
921}
922
923impl Drop for IOSurface {
924    fn drop(&mut self) {
925        if !self.0.is_null() {
926            unsafe {
927                ffi::io_surface_release(self.0);
928            }
929        }
930    }
931}
932
933impl Clone for IOSurface {
934    fn clone(&self) -> Self {
935        unsafe {
936            let ptr = ffi::io_surface_retain(self.0);
937            Self(ptr)
938        }
939    }
940}
941
942// SAFETY: `IOSurfaceRef` is a Core Foundation type documented by Apple as safe
943// to share across threads (it is the primary cross-process frame-delivery
944// mechanism).  Our wrapper holds only the opaque pointer; all mutation
945// (lock/unlock) goes through Apple's thread-safe primitives.
946unsafe impl Send for IOSurface {}
947unsafe impl Sync for IOSurface {}
948
949impl fmt::Debug for IOSurface {
950    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
951        f.debug_struct("IOSurface")
952            .field("id", &self.id())
953            .field("width", &self.width())
954            .field("height", &self.height())
955            .field("bytes_per_row", &self.bytes_per_row())
956            .field("pixel_format", &self.pixel_format())
957            .field("plane_count", &self.plane_count())
958            .finish()
959    }
960}
961
962impl fmt::Display for IOSurface {
963    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
964        write!(
965            f,
966            "IOSurface({}x{}, {} bytes/row)",
967            self.width(),
968            self.height(),
969            self.bytes_per_row()
970        )
971    }
972}