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
#![cfg(target_os = "macos")]
#![cfg(feature = "metal")]

use metal::foreign_types::ForeignType;
use objc2::msg_send;
use objc2::runtime::AnyObject;
use objc2::Encode;
use objc2::Encoding;

use crate::platform::platform_impl::objc_wrap::CVPixelFormat;
use crate::prelude::{CaptureStream, VideoFrame};

use std::error::Error;
use std::fmt::Display;
use std::os::raw::c_void;

use crate::platform::macos::frame::MacosVideoFrame;

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
/// Identifies planes of a video frame
pub enum MetalVideoFramePlaneTexture {
    /// The single RGBA plane for an RGBA format frame
    Rgba,
    /// The Luminance (Y, Brightness) plane for a YCbCr format frame
    Luminance,
    /// The Chrominance (CbCr, Blue/Red) plane for a YCbCr format frame
    Chroma
}

/// Represents an error getting the texture from a video frame
#[derive(Clone, Debug)]
pub enum MacosVideoFrameError {
    // Could not retreive the IOSurface for this frame
    NoIoSurface,
    // Could not retreive the image buffer for this frame
    NoImageBuffer,
    // The requested plane isn't valid for this frame
    InvalidVideoPlaneTexture,
    Other(String)
}


impl Display for MacosVideoFrameError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoIoSurface => f.write_str("MacosVideoFrameError::NoIoSurface"),
            Self::NoImageBuffer => f.write_str("MacosVideoFrameError::NoImageBuffer"),
            Self::InvalidVideoPlaneTexture => f.write_str("MacosVideoFrameError::InvalidVideoPlaneTexture"),
            Self::Other(error) => f.write_fmt(format_args!("MacosVideoFrameError::Other(\"{}\")", error)),
        }
    }
}

impl Error for MacosVideoFrameError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }

    fn description(&self) -> &str {
        "description() is deprecated; use Display"
    }

    fn cause(&self) -> Option<&dyn Error> {
        self.source()
    }
}

/// A video frame which can be used to create metal textures
pub trait MetalVideoFrameExt {
    /// Get the texture for the given plane of the video frame
    fn get_metal_texture(&self, plane: MetalVideoFramePlaneTexture) -> Result<metal::Texture, MacosVideoFrameError>;
}

#[repr(C)]
struct IOSurfacePtrEncoded(*const c_void);

unsafe impl Encode for IOSurfacePtrEncoded {
    const ENCODING: objc2::Encoding = Encoding::Pointer(&Encoding::Struct("__IOSurface", &[]));
}

#[cfg(feature="metal")]
impl MetalVideoFrameExt for VideoFrame {
    fn get_metal_texture(&self, plane: MetalVideoFramePlaneTexture) -> Result<metal::Texture, MacosVideoFrameError> {
        let iosurface_and_metal_device = match &self.impl_video_frame {
            MacosVideoFrame::SCStream(frame) => {
                match frame.sample_buffer.get_image_buffer() {
                    Some(image_buffer) => {
                        match image_buffer.get_iosurface() {
                            Some(iosurface) => {
                                Ok((iosurface, frame.metal_device.clone()))
                            },
                            None => Err(MacosVideoFrameError::NoIoSurface)
                        }
                    },
                    None => Err(MacosVideoFrameError::NoImageBuffer)
                }
            },
            MacosVideoFrame::CGDisplayStream(frame) => {
                Ok((frame.io_surface.clone(), Some(frame.metal_device.clone())))
            }
        }?;
        let (iosurface, metal_device) = iosurface_and_metal_device;
        let pixel_format = match iosurface.get_pixel_format() {
            None => return Err(MacosVideoFrameError::Other("Unable to get pixel format from iosurface".to_string())),
            Some(format) => format
        };
        match pixel_format {
            CVPixelFormat::BGRA8888 => {
                match plane {
                    MetalVideoFramePlaneTexture::Rgba => {},
                    _ => return Err(MacosVideoFrameError::InvalidVideoPlaneTexture),
                }
                unsafe {
                    let device_ref = metal_device.as_ref().unwrap().as_ptr();
                    let texture_descriptor = metal::TextureDescriptor::new();
                    texture_descriptor.set_texture_type(metal::MTLTextureType::D2);
                    texture_descriptor.set_pixel_format(metal::MTLPixelFormat::BGRA8Unorm);
                    texture_descriptor.set_width(iosurface.get_width() as u64);
                    texture_descriptor.set_height(iosurface.get_height() as u64);
                    texture_descriptor.set_sample_count(1);
                    texture_descriptor.set_mipmap_level_count(1);
                    texture_descriptor.set_storage_mode(metal::MTLStorageMode::Shared);
                    texture_descriptor.set_cpu_cache_mode(metal::MTLCPUCacheMode::DefaultCache);
                    let texture_ptr: *mut AnyObject = msg_send![device_ref as *mut AnyObject, newTextureWithDescriptor: texture_descriptor.as_ptr() as *mut AnyObject, iosurface: IOSurfacePtrEncoded(iosurface.0), plane: 0usize];
                    if texture_ptr.is_null() {
                        Err(MacosVideoFrameError::Other("Failed to create metal texture".to_string()))
                    } else {
                        Ok((metal::Texture::from_ptr(texture_ptr as *mut metal::MTLTexture)).to_owned())
                    }
                }
            },
            CVPixelFormat::V420 | CVPixelFormat::F420 => {
                let (plane, pixel_format) = match plane {
                    MetalVideoFramePlaneTexture::Luminance => (0, metal::MTLPixelFormat::R8Uint),
                    MetalVideoFramePlaneTexture::Chroma => (1, metal::MTLPixelFormat::RG8Uint),
                    _ => return Err(MacosVideoFrameError::InvalidVideoPlaneTexture),
                };
                unsafe {
                    let device_ref = metal_device.as_ref().unwrap().as_ptr();
                    let texture_descriptor = metal::TextureDescriptor::new();
                    texture_descriptor.set_texture_type(metal::MTLTextureType::D2);
                    texture_descriptor.set_pixel_format(pixel_format);
                    texture_descriptor.set_width(iosurface.get_width() as u64);
                    texture_descriptor.set_height(iosurface.get_height_of_plane(plane) as u64);
                    texture_descriptor.set_sample_count(1);
                    texture_descriptor.set_mipmap_level_count(1);
                    texture_descriptor.set_storage_mode(metal::MTLStorageMode::Shared);
                    texture_descriptor.set_cpu_cache_mode(metal::MTLCPUCacheMode::DefaultCache);
                    let texture_ptr: *mut AnyObject = msg_send![device_ref as *mut AnyObject, newTextureWithDescriptor: texture_descriptor.as_ptr() as *mut AnyObject, iosurface: iosurface.0, plane: plane];
                    if texture_ptr.is_null() {
                        Err(MacosVideoFrameError::Other("Failed to create metal texture".to_string()))
                    } else {
                        Ok((metal::Texture::from_ptr(texture_ptr as *mut metal::MTLTexture)).to_owned())
                    }
                }
            },
            _ => Err(MacosVideoFrameError::Other("Unknown pixel format on iosurface".to_string())),
        }
    }
}

/// A capture stream which inter-operates with Metal
pub trait MetalCaptureStreamExt {
    /// Get the metal device used for frame capture
    fn get_metal_device(&self) -> metal::Device;
}

impl MetalCaptureStreamExt for CaptureStream {
    fn get_metal_device(&self) -> metal::Device {
        self.impl_capture_stream.metal_device.clone()
    }
}