apple-metal 0.8.4

Safe Rust bindings for Apple's Metal framework — devices, resources, command encoding, advanced GPU objects, and IOSurface interop on macOS, backed by a Swift bridge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
#![doc = include_str!("../README.md")]
//!
//! ---
//!
//! # API Documentation

#![cfg_attr(docsrs, feature(doc_cfg))]
#![allow(clippy::missing_const_for_fn)]

use core::ffi::c_void;
use core::ptr;

pub(crate) mod advanced;
pub(crate) mod argument;
pub(crate) mod command;
pub(crate) mod exhaustive;
/// Groups `Metal` framework constants for `ffi`.
pub mod ffi;
pub(crate) mod metalfx;
pub(crate) mod pipeline;
pub(crate) mod render;
pub(crate) mod state;
pub(crate) mod util;

/// Re-exports the `Metal` framework surface for this item.
pub use advanced::*;
/// Re-exports the `Metal` framework surface for this item.
pub use argument::*;
/// Re-exports the `Metal` framework surface for this item.
pub use command::*;
/// Re-exports the `Metal` framework surface for this item.
pub use exhaustive::*;
/// Re-exports the `Metal` framework surface for this item.
pub use metalfx::*;
/// Re-exports the `Metal` framework surface for this item.
pub use pipeline::*;
/// Re-exports the `Metal` framework surface for this item.
pub use render::*;
/// Re-exports the `Metal` framework surface for this item.
pub use state::*;

/// Common `MTLPixelFormat` constants.
pub mod pixel_format {
/// Mirrors the `Metal` framework constant `A8UNORM`.
    pub const A8UNORM: usize = 1;
/// Mirrors the `Metal` framework constant `R8UNORM`.
    pub const R8UNORM: usize = 10;
/// Mirrors the `Metal` framework constant `R8SNORM`.
    pub const R8SNORM: usize = 12;
/// Mirrors the `Metal` framework constant `R8UINT`.
    pub const R8UINT: usize = 13;
/// Mirrors the `Metal` framework constant `R8SINT`.
    pub const R8SINT: usize = 14;
/// Mirrors the `Metal` framework constant `R16UNORM`.
    pub const R16UNORM: usize = 20;
/// Mirrors the `Metal` framework constant `R16SNORM`.
    pub const R16SNORM: usize = 22;
/// Mirrors the `Metal` framework constant `R16UINT`.
    pub const R16UINT: usize = 23;
/// Mirrors the `Metal` framework constant `R16SINT`.
    pub const R16SINT: usize = 24;
/// Mirrors the `Metal` framework constant `R16FLOAT`.
    pub const R16FLOAT: usize = 25;
/// Mirrors the `Metal` framework constant `RG8UNORM`.
    pub const RG8UNORM: usize = 30;
/// Mirrors the `Metal` framework constant `RG8SNORM`.
    pub const RG8SNORM: usize = 32;
/// Mirrors the `Metal` framework constant `RG8UINT`.
    pub const RG8UINT: usize = 33;
/// Mirrors the `Metal` framework constant `RG8SINT`.
    pub const RG8SINT: usize = 34;
/// Mirrors the `Metal` framework constant `RGBA8UNORM`.
    pub const RGBA8UNORM: usize = 70;
/// Mirrors the `Metal` framework constant `RGBA8UNORM_SRGB`.
    pub const RGBA8UNORM_SRGB: usize = 71;
/// Mirrors the `Metal` framework constant `RGBA8SNORM`.
    pub const RGBA8SNORM: usize = 72;
/// Mirrors the `Metal` framework constant `RGBA8UINT`.
    pub const RGBA8UINT: usize = 73;
/// Mirrors the `Metal` framework constant `RGBA8SINT`.
    pub const RGBA8SINT: usize = 74;
/// Mirrors the `Metal` framework constant `BGRA8UNORM`.
    pub const BGRA8UNORM: usize = 80;
/// Mirrors the `Metal` framework constant `BGRA8UNORM_SRGB`.
    pub const BGRA8UNORM_SRGB: usize = 81;
/// Mirrors the `Metal` framework constant `R32FLOAT`.
    pub const R32FLOAT: usize = 55;
/// Mirrors the `Metal` framework constant `RG16FLOAT`.
    pub const RG16FLOAT: usize = 65;
/// Mirrors the `Metal` framework constant `RGBA16FLOAT`.
    pub const RGBA16FLOAT: usize = 115;
/// Mirrors the `Metal` framework constant `RGBA32FLOAT`.
    pub const RGBA32FLOAT: usize = 125;
/// Mirrors the `Metal` framework constant `DEPTH32FLOAT`.
    pub const DEPTH32FLOAT: usize = 252;
/// Mirrors the `Metal` framework constant `STENCIL8`.
    pub const STENCIL8: usize = 253;
/// Mirrors the `Metal` framework constant `BGRA10_XR`.
    pub const BGRA10_XR: usize = 552;
/// Mirrors the `Metal` framework constant `BGR10_XR`.
    pub const BGR10_XR: usize = 554;
}

/// `MTLStorageMode` enum values — memory residency hints.
pub mod storage_mode {
/// Mirrors the `Metal` framework constant `SHARED`.
    pub const SHARED: usize = 0;
/// Mirrors the `Metal` framework constant `MANAGED`.
    pub const MANAGED: usize = 1;
/// Mirrors the `Metal` framework constant `PRIVATE`.
    pub const PRIVATE: usize = 2;
/// Mirrors the `Metal` framework constant `MEMORYLESS`.
    pub const MEMORYLESS: usize = 3;
}

/// `MTLCPUCacheMode` enum values.
pub mod cpu_cache_mode {
/// Mirrors the `Metal` framework constant `DEFAULT_CACHE`.
    pub const DEFAULT_CACHE: usize = 0;
/// Mirrors the `Metal` framework constant `WRITE_COMBINED`.
    pub const WRITE_COMBINED: usize = 1;
}

/// `MTLHazardTrackingMode` enum values.
pub mod hazard_tracking_mode {
/// Mirrors the `Metal` framework constant `DEFAULT`.
    pub const DEFAULT: usize = 0;
/// Mirrors the `Metal` framework constant `UNTRACKED`.
    pub const UNTRACKED: usize = 1;
/// Mirrors the `Metal` framework constant `TRACKED`.
    pub const TRACKED: usize = 2;
}

/// `MTLResourceOptions` bitmask values.
pub mod resource_options {
/// Mirrors the `Metal` framework constant `CPU_CACHE_MODE_DEFAULT`.
    pub const CPU_CACHE_MODE_DEFAULT: usize = 0;
/// Mirrors the `Metal` framework constant `CPU_CACHE_MODE_WRITE_COMBINED`.
    pub const CPU_CACHE_MODE_WRITE_COMBINED: usize = 1;
/// Mirrors the `Metal` framework constant `STORAGE_MODE_SHARED`.
    pub const STORAGE_MODE_SHARED: usize = 0;
/// Mirrors the `Metal` framework constant `STORAGE_MODE_MANAGED`.
    pub const STORAGE_MODE_MANAGED: usize = 1 << 4;
/// Mirrors the `Metal` framework constant `STORAGE_MODE_PRIVATE`.
    pub const STORAGE_MODE_PRIVATE: usize = 2 << 4;
/// Mirrors the `Metal` framework constant `HAZARD_TRACKING_MODE_DEFAULT`.
    pub const HAZARD_TRACKING_MODE_DEFAULT: usize = 0;
/// Mirrors the `Metal` framework constant `HAZARD_TRACKING_MODE_UNTRACKED`.
    pub const HAZARD_TRACKING_MODE_UNTRACKED: usize = 1 << 8;
/// Mirrors the `Metal` framework constant `HAZARD_TRACKING_MODE_TRACKED`.
    pub const HAZARD_TRACKING_MODE_TRACKED: usize = 2 << 8;
}

/// `MTLTextureUsage` bitmask.
pub mod texture_usage {
/// Mirrors the `Metal` framework constant `SHADER_READ`.
    pub const SHADER_READ: usize = 0x01;
/// Mirrors the `Metal` framework constant `SHADER_WRITE`.
    pub const SHADER_WRITE: usize = 0x02;
/// Mirrors the `Metal` framework constant `RENDER_TARGET`.
    pub const RENDER_TARGET: usize = 0x04;
}

/// `MTLGPUFamily` — feature-family identifiers.
pub mod gpu_family {
/// Mirrors the `Metal` framework constant `APPLE1`.
    pub const APPLE1: i64 = 1001;
/// Mirrors the `Metal` framework constant `APPLE2`.
    pub const APPLE2: i64 = 1002;
/// Mirrors the `Metal` framework constant `APPLE3`.
    pub const APPLE3: i64 = 1003;
/// Mirrors the `Metal` framework constant `APPLE4`.
    pub const APPLE4: i64 = 1004;
/// Mirrors the `Metal` framework constant `APPLE5`.
    pub const APPLE5: i64 = 1005;
/// Mirrors the `Metal` framework constant `APPLE6`.
    pub const APPLE6: i64 = 1006;
/// Mirrors the `Metal` framework constant `APPLE7`.
    pub const APPLE7: i64 = 1007;
/// Mirrors the `Metal` framework constant `APPLE8`.
    pub const APPLE8: i64 = 1008;
/// Mirrors the `Metal` framework constant `APPLE9`.
    pub const APPLE9: i64 = 1009;
/// Mirrors the `Metal` framework constant `MAC1`.
    pub const MAC1: i64 = 2001;
/// Mirrors the `Metal` framework constant `MAC2`.
    pub const MAC2: i64 = 2002;
/// Mirrors the `Metal` framework constant `COMMON1`.
    pub const COMMON1: i64 = 3001;
/// Mirrors the `Metal` framework constant `COMMON2`.
    pub const COMMON2: i64 = 3002;
/// Mirrors the `Metal` framework constant `COMMON3`.
    pub const COMMON3: i64 = 3003;
/// Mirrors the `Metal` framework constant `METAL3`.
    pub const METAL3: i64 = 5001;
}

// ---- Device ----

/// Apple's `id<MTLDevice>` — handle to a Metal GPU.
pub struct MetalDevice {
    ptr: *mut c_void,
    drop_on_release: bool,
}

// SAFETY: `id<MTLDevice>` is thread-safe: creation, capability queries, and
// resource allocation all synchronize internally via ObjC ARC + Metal's own locks.
unsafe impl Send for MetalDevice {}
unsafe impl Sync for MetalDevice {}

impl Drop for MetalDevice {
    fn drop(&mut self) {
        if self.drop_on_release && !self.ptr.is_null() {
            unsafe { ffi::am_device_release(self.ptr) };
            self.ptr = ptr::null_mut();
        }
    }
}

impl MetalDevice {
    /// Return the system's default Metal device.
    #[must_use]
    pub fn system_default() -> Option<Self> {
        let p = unsafe { ffi::am_device_system_default() };
        if p.is_null() {
            None
        } else {
            Some(unsafe { Self::from_retained_ptr(p) })
        }
    }

    /// Raw `id<MTLDevice>` pointer.
    #[must_use]
    pub const fn as_ptr(&self) -> *mut c_void {
        self.ptr
    }

    /// True if the GPU uses unified memory (Apple Silicon).
    #[must_use]
    pub fn has_unified_memory(&self) -> bool {
        unsafe { ffi::am_device_has_unified_memory(self.ptr) }
    }

    /// Recommended maximum working-set size in bytes.
    #[must_use]
    pub fn recommended_max_working_set_size(&self) -> u64 {
        unsafe { ffi::am_device_recommended_max_working_set_size(self.ptr) }
    }

    /// True if this device supports the requested feature family —
    /// see [`gpu_family`].
    #[must_use]
    pub fn supports_family(&self, family: i64) -> bool {
        unsafe { ffi::am_device_supports_family(self.ptr, family) }
    }

    /// Allocate a GPU-visible buffer of `length` bytes.
    /// `options` is an `MTLResourceOptions` bitmask (see
    /// [`resource_options`]).
    #[must_use]
    pub fn new_buffer(&self, length: usize, options: usize) -> Option<MetalBuffer> {
        let p = unsafe { ffi::am_device_new_buffer(self.ptr, length, options) };
        if p.is_null() {
            None
        } else {
            Some(MetalBuffer { ptr: p })
        }
    }

    /// Allocate a fresh `MTLTexture` matching `descriptor`.
    #[must_use]
    pub fn new_texture(&self, descriptor: TextureDescriptor) -> Option<MetalTexture> {
        let p = unsafe {
            ffi::am_device_new_texture_2d(
                self.ptr,
                descriptor.pixel_format,
                descriptor.width,
                descriptor.height,
                descriptor.mipmapped,
                descriptor.usage,
                descriptor.storage_mode,
            )
        };
        if p.is_null() {
            None
        } else {
            Some(MetalTexture { ptr: p })
        }
    }

    /// Create a new `MTLCommandQueue` to schedule GPU work.
    #[must_use]
    pub fn new_command_queue(&self) -> Option<CommandQueue> {
        let p = unsafe { ffi::am_device_new_command_queue(self.ptr) };
        if p.is_null() {
            None
        } else {
            Some(CommandQueue { ptr: p })
        }
    }

    /// Compile a Metal Shading Language source string into a runtime
    /// `MTLLibrary`. On error, returns the localized Metal compiler
    /// diagnostic.
    ///
    /// # Errors
    ///
    /// Returns the Metal compiler's localized error string on failure.
    pub fn new_library_with_source(&self, source: &str) -> Result<MetalLibrary, String> {
        let csrc = std::ffi::CString::new(source).map_err(|e| e.to_string())?;
        let mut err_msg: *mut core::ffi::c_char = core::ptr::null_mut();
        let p = unsafe {
            ffi::am_device_new_library_with_source(self.ptr, csrc.as_ptr(), &mut err_msg)
        };
        if p.is_null() {
            let msg = if err_msg.is_null() {
                "MTLDevice.makeLibrary returned nil".to_string()
            } else {
                let s = unsafe { std::ffi::CStr::from_ptr(err_msg) }
                    .to_string_lossy()
                    .into_owned();
                unsafe { libc::free(err_msg.cast()) };
                s
            };
            Err(msg)
        } else {
            Ok(MetalLibrary { ptr: p })
        }
    }

    /// Compile a kernel into a `MTLComputePipelineState` ready for
    /// dispatch on a command buffer.
    ///
    /// # Errors
    ///
    /// Returns the Metal pipeline compiler's localized error string
    /// on failure.
    pub fn new_compute_pipeline_state(
        &self,
        function: &MetalFunction,
    ) -> Result<ComputePipelineState, String> {
        let mut err_msg: *mut core::ffi::c_char = core::ptr::null_mut();
        let p = unsafe {
            ffi::am_device_new_compute_pipeline_state(self.ptr, function.ptr, &mut err_msg)
        };
        if p.is_null() {
            let msg = if err_msg.is_null() {
                "MTLDevice.makeComputePipelineState returned nil".to_string()
            } else {
                let s = unsafe { std::ffi::CStr::from_ptr(err_msg) }
                    .to_string_lossy()
                    .into_owned();
                unsafe { libc::free(err_msg.cast()) };
                s
            };
            Err(msg)
        } else {
            Ok(ComputePipelineState { ptr: p })
        }
    }

    /// Wrap a raw `id<MTLDevice>` pointer **without** taking ownership.
    /// The returned handle will NOT release the underlying object on
    /// drop.
    ///
    /// # Safety
    ///
    /// `ptr` must be a valid `id<MTLDevice>` whose lifetime is managed
    /// by some other owner.
    #[must_use]
    pub unsafe fn from_raw_borrowed(ptr: *mut c_void) -> ManuallyDropDevice {
        ManuallyDropDevice {
            inner: Self {
                ptr,
                drop_on_release: false,
            },
        }
    }
}

/// Borrowed [`MetalDevice`] that does not release on drop.
pub struct ManuallyDropDevice {
    inner: MetalDevice,
}

impl core::ops::Deref for ManuallyDropDevice {
    type Target = MetalDevice;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

// ---- Command queue + command buffer ----

/// Apple's `id<MTLCommandQueue>` — schedules GPU work.
pub struct CommandQueue {
    ptr: *mut c_void,
}

// SAFETY: `id<MTLCommandQueue>` is documented by Apple as thread-safe; multiple
// threads may independently create command buffers from the same queue.
unsafe impl Send for CommandQueue {}
unsafe impl Sync for CommandQueue {}

impl Drop for CommandQueue {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { ffi::am_command_queue_release(self.ptr) };
            self.ptr = ptr::null_mut();
        }
    }
}

impl CommandQueue {
    /// Create a new command buffer for recording GPU commands.
    #[must_use]
    pub fn new_command_buffer(&self) -> Option<CommandBuffer> {
        let p = unsafe { ffi::am_command_queue_new_command_buffer(self.ptr) };
        if p.is_null() {
            None
        } else {
            Some(CommandBuffer { ptr: p })
        }
    }

    /// Raw `id<MTLCommandQueue>` pointer.
    #[must_use]
    pub const fn as_ptr(&self) -> *mut c_void {
        self.ptr
    }
}

/// Apple's `id<MTLCommandBuffer>` — a recorded batch of GPU commands.
pub struct CommandBuffer {
    ptr: *mut c_void,
}

// SAFETY: `id<MTLCommandBuffer>` is safe to move across threads.  Its `&self`
// methods are read-only status queries; mutable encoding operations require
// `&mut CommandEncoder` (a separate type), so Sync is sound.
unsafe impl Send for CommandBuffer {}
unsafe impl Sync for CommandBuffer {}

impl Drop for CommandBuffer {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { ffi::am_command_buffer_release(self.ptr) };
            self.ptr = ptr::null_mut();
        }
    }
}

impl CommandBuffer {
    /// Submit the recorded commands for execution.
    pub fn commit(&self) {
        unsafe { ffi::am_command_buffer_commit(self.ptr) };
    }

    /// Block the current thread until all submitted commands finish.
    pub fn wait_until_completed(&self) {
        unsafe { ffi::am_command_buffer_wait_until_completed(self.ptr) };
    }

    /// Record a blit copy from `src` into `dst` for `size` bytes.
    /// Convenience for GPU↔GPU byte copies.
    #[must_use]
    pub fn blit_copy_buffer(
        &self,
        src: &MetalBuffer,
        src_offset: usize,
        dst: &MetalBuffer,
        dst_offset: usize,
        size: usize,
    ) -> bool {
        unsafe {
            ffi::am_command_buffer_blit_copy_buffer(
                self.ptr,
                src.as_ptr(),
                src_offset,
                dst.as_ptr(),
                dst_offset,
                size,
            )
        }
    }

    /// Record a 1-D compute dispatch: binds `pso`, sets `buffers` at
    /// argument slots `0..buffers.len()`, and dispatches `threadgroups`
    /// of `threads_per_group` threads.
    #[must_use]
    pub fn dispatch_compute_1d(
        &self,
        pso: &ComputePipelineState,
        buffers: &[&MetalBuffer],
        threadgroups: usize,
        threads_per_group: usize,
    ) -> bool {
        let raw: Vec<*mut c_void> = buffers.iter().map(|b| b.as_ptr()).collect();
        unsafe {
            ffi::am_command_buffer_dispatch_compute_1d(
                self.ptr,
                pso.ptr,
                raw.as_ptr(),
                raw.len(),
                threadgroups,
                threads_per_group,
            )
        }
    }

    /// Raw `id<MTLCommandBuffer>` pointer.
    #[must_use]
    pub const fn as_ptr(&self) -> *mut c_void {
        self.ptr
    }
}

// ---- Library + Function + ComputePipelineState ----

/// Apple's `id<MTLLibrary>` — compiled MSL source.
pub struct MetalLibrary {
    ptr: *mut c_void,
}

// SAFETY: `id<MTLLibrary>` is immutable after creation; all its methods are
// thread-safe per Apple documentation.
unsafe impl Send for MetalLibrary {}
unsafe impl Sync for MetalLibrary {}

impl Drop for MetalLibrary {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { ffi::am_library_release(self.ptr) };
            self.ptr = ptr::null_mut();
        }
    }
}

impl MetalLibrary {
    /// Look up a kernel function by its source name.
    #[must_use]
    pub fn new_function(&self, name: &str) -> Option<MetalFunction> {
        let cname = std::ffi::CString::new(name).ok()?;
        let p = unsafe { ffi::am_library_new_function(self.ptr, cname.as_ptr()) };
        if p.is_null() {
            None
        } else {
            Some(MetalFunction { ptr: p })
        }
    }

    /// Raw `id<MTLLibrary>` pointer.
    #[must_use]
    pub const fn as_ptr(&self) -> *mut c_void {
        self.ptr
    }
}

/// Apple's `id<MTLFunction>` — a single compiled shader entry point.
pub struct MetalFunction {
    ptr: *mut c_void,
}

// SAFETY: `id<MTLFunction>` is immutable after creation and its handle is safe
// to share across threads.
unsafe impl Send for MetalFunction {}
unsafe impl Sync for MetalFunction {}

impl Drop for MetalFunction {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { ffi::am_function_release(self.ptr) };
            self.ptr = ptr::null_mut();
        }
    }
}

impl MetalFunction {
    /// Raw `id<MTLFunction>` pointer.
    #[must_use]
    pub const fn as_ptr(&self) -> *mut c_void {
        self.ptr
    }
}

/// Apple's `id<MTLComputePipelineState>` — a compiled compute kernel.
pub struct ComputePipelineState {
    ptr: *mut c_void,
}

// SAFETY: `id<MTLComputePipelineState>` is immutable after creation and
// thread-safe per Apple documentation.
unsafe impl Send for ComputePipelineState {}
unsafe impl Sync for ComputePipelineState {}

impl Drop for ComputePipelineState {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { ffi::am_compute_pipeline_state_release(self.ptr) };
            self.ptr = ptr::null_mut();
        }
    }
}

impl ComputePipelineState {
    /// Raw `id<MTLComputePipelineState>` pointer.
    #[must_use]
    pub const fn as_ptr(&self) -> *mut c_void {
        self.ptr
    }

    pub(crate) const unsafe fn from_retained_ptr(ptr: *mut c_void) -> Self {
        Self { ptr }
    }
}

// ---- Buffer ----

/// Apple's `id<MTLBuffer>` — a GPU-visible byte buffer.
pub struct MetalBuffer {
    ptr: *mut c_void,
}

// SAFETY: `id<MTLBuffer>` is a GPU resource handle.  Reference-count manipulation
// is atomic (ObjC ARC); concurrent reads of immutable state (length, GPU address)
// are safe.  CPU-side writes via `contents()` are the caller's responsibility to
// synchronize — the same rule that applies to any `*mut` slice.
unsafe impl Send for MetalBuffer {}
unsafe impl Sync for MetalBuffer {}

impl Drop for MetalBuffer {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { ffi::am_buffer_release(self.ptr) };
            self.ptr = ptr::null_mut();
        }
    }
}

impl MetalBuffer {
    /// Buffer length in bytes.
    #[must_use]
    pub fn length(&self) -> usize {
        unsafe { ffi::am_buffer_length(self.ptr) }
    }

    /// Raw `void *` to the buffer's CPU-visible bytes. `None` for
    /// `MTLStorageMode::Private` (GPU-only) buffers.
    #[must_use]
    pub fn contents(&self) -> Option<*mut c_void> {
        let p = unsafe { ffi::am_buffer_contents(self.ptr) };
        if p.is_null() {
            None
        } else {
            Some(p)
        }
    }

    /// Copy `src` into this buffer at byte offset `0`. Returns the
    /// number of bytes actually written.
    #[must_use]
    pub fn write_bytes(&self, src: &[u8]) -> usize {
        let Some(dst) = self.contents() else {
            return 0;
        };
        let n = core::cmp::min(src.len(), self.length());
        unsafe { core::ptr::copy_nonoverlapping(src.as_ptr(), dst.cast::<u8>(), n) };
        n
    }

    /// Raw `id<MTLBuffer>` pointer.
    #[must_use]
    pub const fn as_ptr(&self) -> *mut c_void {
        self.ptr
    }
}

// ---- Texture descriptor + texture ----

/// Configuration for `MetalDevice::new_texture`.
#[derive(Debug, Clone, Copy)]
pub struct TextureDescriptor {
/// Mirrors the `Metal` framework property for `pixel_format`.
    pub pixel_format: usize,
/// Mirrors the `Metal` framework property for `width`.
    pub width: usize,
/// Mirrors the `Metal` framework property for `height`.
    pub height: usize,
/// Mirrors the `Metal` framework property for `mipmapped`.
    pub mipmapped: bool,
/// Mirrors the `Metal` framework property for `usage`.
    pub usage: usize,
/// Mirrors the `Metal` framework property for `storage_mode`.
    pub storage_mode: usize,
}

impl TextureDescriptor {
    /// Sensible defaults for a shader-read+write 2D texture in shared storage.
    #[must_use]
    pub const fn new_2d(width: usize, height: usize, pixel_format: usize) -> Self {
        Self {
            pixel_format,
            width,
            height,
            mipmapped: false,
            usage: texture_usage::SHADER_READ | texture_usage::SHADER_WRITE,
            storage_mode: storage_mode::SHARED,
        }
    }
}

/// Apple's `id<MTLTexture>` — a GPU-resident 2D image.
pub struct MetalTexture {
    ptr: *mut c_void,
}

// SAFETY: `id<MTLTexture>` is a GPU resource handle.  ObjC ARC operations are
// atomic; descriptor queries are read-only and thread-safe.
unsafe impl Send for MetalTexture {}
unsafe impl Sync for MetalTexture {}

impl Drop for MetalTexture {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { ffi::am_texture_release(self.ptr) };
            self.ptr = ptr::null_mut();
        }
    }
}

impl MetalTexture {
    /// Texture width in pixels.
    #[must_use]
    pub fn width(&self) -> usize {
        unsafe { ffi::am_texture_width(self.ptr) }
    }

    /// Texture height in pixels.
    #[must_use]
    pub fn height(&self) -> usize {
        unsafe { ffi::am_texture_height(self.ptr) }
    }

    /// Underlying `MTLPixelFormat` enum value — see [`pixel_format`].
    #[must_use]
    pub fn pixel_format(&self) -> usize {
        unsafe { ffi::am_texture_pixel_format(self.ptr) }
    }

    /// Raw `id<MTLTexture>` pointer.
    #[must_use]
    pub const fn as_ptr(&self) -> *mut c_void {
        self.ptr
    }

    /// Wrap a raw `id<MTLTexture>` pointer. Pointer is taken without
    /// retain.
    ///
    /// # Safety
    ///
    /// `ptr` must be a valid `id<MTLTexture>` whose ownership the
    /// caller is transferring.
    #[must_use]
    pub const unsafe fn from_raw(ptr: *mut c_void) -> Self {
        Self { ptr }
    }
}

impl MetalDevice {
    pub(crate) const unsafe fn from_retained_ptr(ptr: *mut c_void) -> Self {
        Self {
            ptr,
            drop_on_release: true,
        }
    }
}

impl CommandQueue {
    pub(crate) const unsafe fn from_retained_ptr(ptr: *mut c_void) -> Self {
        Self { ptr }
    }
}

impl CommandBuffer {
    pub(crate) const unsafe fn from_retained_ptr(ptr: *mut c_void) -> Self {
        Self { ptr }
    }
}

impl MetalBuffer {
    pub(crate) const unsafe fn from_retained_ptr(ptr: *mut c_void) -> Self {
        Self { ptr }
    }
}

// ---- IOSurface extension ----

#[cfg(feature = "iosurface")]
#[cfg_attr(docsrs, doc(cfg(feature = "iosurface")))]
mod iosurface_ext {
    use super::{ffi, pixel_format, MetalDevice, MetalTexture};
    use apple_cf::iosurface::IOSurface;
    use core::ffi::c_void;

    /// Add Metal interop methods to [`IOSurface`].
    pub trait IOSurfaceMetalExt {
        /// Wrap the given plane of this `IOSurface` as a zero-copy
        /// [`MetalTexture`] on the given device.
        fn create_metal_texture(
            &self,
            device: &MetalDevice,
            plane_index: usize,
        ) -> Option<MetalTexture>;
    }

    impl IOSurfaceMetalExt for IOSurface {
        fn create_metal_texture(
            &self,
            device: &MetalDevice,
            plane_index: usize,
        ) -> Option<MetalTexture> {
            let format = pixel_format_for_fourcc(self.pixel_format(), plane_index)?;
            let (width, height) = if plane_index == 0 {
                (self.width(), self.height())
            } else {
                (self.width() / 2, self.height() / 2)
            };
            let p = unsafe {
                ffi::am_device_new_texture_from_iosurface(
                    device.as_ptr(),
                    self.as_ptr().cast::<c_void>(),
                    plane_index,
                    format,
                    width,
                    height,
                )
            };
            if p.is_null() {
                None
            } else {
                Some(unsafe { MetalTexture::from_raw(p) })
            }
        }
    }

    fn pixel_format_for_fourcc(fourcc: u32, plane_index: usize) -> Option<usize> {
        const BGRA: u32 = u32::from_be_bytes(*b"BGRA");
        const L10R: u32 = u32::from_be_bytes(*b"l10r");
        const YUV420V: u32 = u32::from_be_bytes(*b"420v");
        const YUV420F: u32 = u32::from_be_bytes(*b"420f");

        match (fourcc, plane_index) {
            (BGRA, 0) => Some(pixel_format::BGRA8UNORM),
            (L10R, 0) => Some(pixel_format::BGRA10_XR),
            (YUV420V | YUV420F, 0) => Some(pixel_format::R8UNORM),
            (YUV420V | YUV420F, 1) => Some(pixel_format::RG8UNORM),
            _ => None,
        }
    }
}

/// Re-exports the `Metal` framework surface for this item.
#[cfg(feature = "iosurface")]
pub use iosurface_ext::IOSurfaceMetalExt;

/// True if `fourcc` identifies a YCbCr biplanar (`Y` + `CbCr`) format.
#[must_use]
pub const fn is_ycbcr_biplanar(fourcc: u32) -> bool {
    const YUV420V: u32 = u32::from_be_bytes(*b"420v");
    const YUV420F: u32 = u32::from_be_bytes(*b"420f");
    matches!(fourcc, YUV420V | YUV420F)
}