Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Introduce camera-avfoundation (#751)
Brendan Allan586bf20266e6
diff --git a/Cargo.lock b/Cargo.lockindex f41ca9088..ddc2a029e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -916,7 +916,7 @@ dependencies = ["cap-recording","cap-rendering","cap-utils",- "clap 4.5.23",+ "clap 4.5.40","editor","ffmpeg-next","flume 0.11.0",@@ -941,6 +941,15 @@ dependencies = ["tokio",]+[[package]]+name = "cap-camera-avfoundation"+version = "0.1.0"+dependencies = [+ "cidre",+ "clap 4.5.40",+ "inquire",+]+[[package]]name = "cap-cursor-capture"version = "0.1.0"@@ -1452,9 +1461,9 @@ dependencies = [[[package]]name = "clap"-version = "4.5.23"+version = "4.5.40"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84"+checksum = "40b6887a1d8685cebccf115538db5c0efe625ccac9696ad45c409d96566e910f"dependencies = ["clap_builder","clap_derive",@@ -1462,9 +1471,9 @@ dependencies = [[[package]]name = "clap_builder"-version = "4.5.23"+version = "4.5.40"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838"+checksum = "e0c66c08ce9f0c698cbce5c0279d0bb6ac936d8674174fe48f736533b964f59e"dependencies = ["anstream","anstyle",@@ -1474,9 +1483,9 @@ dependencies = [[[package]]name = "clap_derive"-version = "4.5.18"+version = "4.5.40"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab"+checksum = "d2c7947ae4cc3d851207c1adb5b5e260ff0cca11446b1d6d1423788e442257ce"dependencies = ["heck 0.5.0","proc-macro2",@@ -2074,6 +2083,22 @@ version = "0.8.20"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"+[[package]]+name = "crossterm"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67"+dependencies = [+ "bitflags 1.3.2",+ "crossterm_winapi",+ "libc",+ "mio 0.8.11",+ "parking_lot",+ "signal-hook",+ "signal-hook-mio",+ "winapi",+]+[[package]]name = "crossterm"version = "0.27.0"@@ -2480,7 +2505,7 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3effaacc281d186774006894b787746c6870484cd08834ff42bfa2a6aa60ab6e"dependencies = [- "crossterm",+ "crossterm 0.27.0","derive_more","glam",]@@ -2988,6 +3013,15 @@ dependencies = ["slab",]+[[package]]+name = "fuzzy-matcher"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "54614a3312934d066701a80f20f15fa3b56d67ac7722b39eea5b4c9dd1d66c94"+dependencies = [+ "thread_local",+]+[[package]]name = "fxhash"version = "0.2.1"@@ -3878,6 +3912,23 @@ dependencies = ["cfb",]+[[package]]+name = "inquire"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fddf93031af70e75410a2511ec04d49e758ed2f26dad3404a934e0fb45cc12a"+dependencies = [+ "bitflags 2.9.0",+ "crossterm 0.25.0",+ "dyn-clone",+ "fuzzy-matcher",+ "fxhash",+ "newline-converter",+ "once_cell",+ "unicode-segmentation",+ "unicode-width",+]+[[package]]name = "interpolate_name"version = "0.2.4"@@ -4730,6 +4781,15 @@ version = "1.0.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"+[[package]]+name = "newline-converter"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47b6b097ecb1cbfed438542d16e84fd7ad9b0c76c8a65b7f9039212a3d14dc7f"+dependencies = [+ "unicode-segmentation",+]+[[package]]name = "nix"version = "0.27.1"@@ -9563,7 +9623,7 @@ version = "1.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6001b777f61cafce437201de46a019ed7f4afed3b669f02e5ce4e0759164cb3e"dependencies = [- "clap 4.5.23",+ "clap 4.5.40","ctrlc","parking_lot","rayon",diff --git a/crates/camera-avfoundation/Cargo.toml b/crates/camera-avfoundation/Cargo.tomlnew file mode 100644index 000000000..4fc054025--- /dev/null+++ b/crates/camera-avfoundation/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "cap-camera-avfoundation"+version = "0.1.0"+edition = "2024"++[dependencies]+cidre = "0.9.2"++[lints]+workspace = true++[dev-dependencies]+clap = { version = "4.5.40", features = ["derive"] }+inquire = "0.7.5"diff --git a/crates/camera-avfoundation/examples/cli.rs b/crates/camera-avfoundation/examples/cli.rsnew file mode 100644index 000000000..c4b4ffda2--- /dev/null+++ b/crates/camera-avfoundation/examples/cli.rs@@ -0,0 +1,210 @@+use cap_camera_avfoundation::{YCbCrMatrix, list_video_devices};+use cidre::{+ av::capture::{VideoDataOutputSampleBufDelegate, VideoDataOutputSampleBufDelegateImpl},+ cv::pixel_buffer::LockFlags,+ *,+};+use clap::{Args, Parser, Subcommand};+use inquire::Select;+use std::{+ fmt::Display,+ ops::{Deref, DerefMut},+};++#[derive(Parser)]+struct Cli {+ #[command(subcommand)]+ command: Commands,+}++#[derive(Subcommand)]+enum Commands {+ /// Print details of a device+ Device,+}++pub fn main() {+ let _devices = list_video_devices();+ let devices = _devices+ .iter()+ .enumerate()+ .map(|(i, v)| CaptureDeviceSelectOption(v, i))+ .collect::<Vec<_>>();++ let selected = Select::new("Select a device", devices).prompt().unwrap();+ let mut selected_device = _devices.get(selected.1).unwrap();++ println!(+ "Info for device '{}'",+ selected_device.localized_name().to_string()+ );++ let formats = selected_device.formats();++ let mut _formats = vec![];++ for (i, format) in formats.iter().enumerate() {+ let desc = format.format_desc();++ let color_space = desc+ .ext(cm::FormatDescExtKey::ycbcr_matrix())+ .map(|v| {+ v.try_as_string()+ .and_then(|v| YCbCrMatrix::try_from(v).ok())+ })+ .unwrap_or(Some(YCbCrMatrix::Rec601));++ let fr_ranges = format.video_supported_frame_rate_ranges();++ for fr_range in fr_ranges.iter() {+ _formats.push(Format {+ index: i,+ width: desc.dimensions().width,+ height: desc.dimensions().height,+ fourcc: desc.media_sub_type(),+ color_space,+ max_frame_rate: (+ fr_range.min_frame_duration().value,+ fr_range.min_frame_duration().scale,+ ),+ });+ }+ }++ let selected_format = if _formats.len() > 1 {+ inquire::Select::new("Select a format", _formats)+ .prompt()+ .unwrap()+ } else {+ _formats.remove(0)+ };++ let input = av::capture::DeviceInput::with_device(&selected_device).unwrap();+ let queue = dispatch::Queue::new();+ let delegate = OutputDelegate::new();+ let mut output = av::capture::VideoDataOutput::new();++ let mut session = av::capture::Session::new();++ session.configure(|s| {+ if s.can_add_input(&input) {+ s.add_input(&input);+ } else {+ panic!("can't add input");+ }++ s.add_output(&output);+ });++ output.set_sample_buf_delegate(Some(delegate.as_ref()), Some(&queue));++ let video_settings = ns::Dictionary::with_keys_values(+ &[cv::pixel_buffer_keys::pixel_format().as_ns()],+ &[ns::Number::with_u32(selected_format.fourcc).as_id_ref()],+ );+ output+ .set_video_settings(Some(video_settings.as_ref()))+ .unwrap();++ // The device config must stay locked while running starts,+ // otherwise start_running can overwrite the active format on macOS+ // https://stackoverflow.com/questions/36689578/avfoundation-capturing-video-with-custom-resolution+ {+ let mut _lock = selected_device.config_lock().unwrap();++ _lock.set_active_format(&formats[selected_format.index]);++ session.start_running();+ }++ std::thread::sleep(std::time::Duration::from_secs(10));++ session.stop_running();+}++struct Format {+ index: usize,+ width: i32,+ height: i32,+ fourcc: FourCharCode,+ color_space: Option<YCbCrMatrix>,+ max_frame_rate: (i64, i32),+}++impl Display for Format {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "{}x{}, {} max fps ({}/{}) {}",+ self.width,+ self.height,+ self.max_frame_rate.1 as f32 / self.max_frame_rate.0 as f32,+ self.max_frame_rate.0,+ self.max_frame_rate.1,+ four_cc_to_string(self.fourcc.to_be_bytes())+ )+ }+}++define_obj_type!(+ OutputDelegate + VideoDataOutputSampleBufDelegateImpl,+ (),+ OUTPUT_DELEGATE+);++impl VideoDataOutputSampleBufDelegate for OutputDelegate {}++#[objc::add_methods]+impl VideoDataOutputSampleBufDelegateImpl for OutputDelegate {+ extern "C" fn impl_capture_output_did_output_sample_buf_from_connection(+ &mut self,+ _cmd: Option<&cidre::objc::Sel>,+ _output: &av::CaptureOutput,+ sample_buf: &cm::SampleBuf,+ _connection: &av::CaptureConnection,+ ) {+ let Some(image_buf) = sample_buf.image_buf() else {+ return;+ };++ let total_bytes = if image_buf.plane_count() > 0 {+ (0..image_buf.plane_count())+ .map(|i| image_buf.plane_bytes_per_row(i) * image_buf.plane_height(i))+ .sum::<usize>()+ } else {+ image_buf.plane_bytes_per_row(0) * image_buf.plane_height(0)+ };++ let mut format = image_buf.pixel_format().0.to_be_bytes();+ let format_fourcc = four_cc_to_str(&mut format);++ println!(+ "New frame: {}x{}, {:.2}pts, {total_bytes} bytes, format={format_fourcc}",+ image_buf.width(),+ image_buf.height(),+ sample_buf.pts().value as f64 / sample_buf.pts().scale as f64,+ )+ }+}++struct CaptureDeviceSelectOption<'a>(&'a av::CaptureDevice, usize);++impl<'a> Display for CaptureDeviceSelectOption<'a> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.0.localized_name().to_string())+ }+}++impl AsRef<av::CaptureDevice> for CaptureDeviceSelectOption<'_> {+ fn as_ref(&self) -> &av::CaptureDevice {+ &self.0+ }+}++impl Deref for CaptureDeviceSelectOption<'_> {+ type Target = av::CaptureDevice;++ fn deref(&self) -> &Self::Target {+ &self.0+ }+}diff --git a/crates/camera-avfoundation/src/lib.rs b/crates/camera-avfoundation/src/lib.rsnew file mode 100644index 000000000..cb6df39e4--- /dev/null+++ b/crates/camera-avfoundation/src/lib.rs@@ -0,0 +1,50 @@+use std::{fmt::Display, str::FromStr};++use cidre::*;++pub fn list_video_devices() -> arc::R<ns::Array<av::CaptureDevice>> {+ let device_types = ns::Array::from_slice(&[+ av::CaptureDeviceType::built_in_wide_angle_camera(),+ av::CaptureDeviceType::external(),+ av::CaptureDeviceType::desk_view_camera(),+ ]);++ let video_discovery_session =+ av::CaptureDeviceDiscoverySession::with_device_types_media_and_pos(+ &device_types,+ Some(av::MediaType::video()),+ av::CaptureDevicePos::Unspecified,+ );++ video_discovery_session.devices()+}++#[derive(Clone, Copy)]+pub enum YCbCrMatrix {+ Rec601,+ Rec709,+ Rec2020,+}++impl Display for YCbCrMatrix {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Rec601 => write!(f, "Rec601"),+ Self::Rec709 => write!(f, "Rec709"),+ Self::Rec2020 => write!(f, "Rec2020"),+ }+ }+}++impl TryFrom<&cf::String> for YCbCrMatrix {+ type Error = ();++ fn try_from(s: &cf::String) -> Result<Self, Self::Error> {+ Ok(match s {+ s if s == cv::image_buf_attachment::ycbcr_matrix::itu_r_601_4() => Self::Rec601,+ s if s == cv::image_buf_attachment::ycbcr_matrix::itu_r_709_2() => Self::Rec709,+ s if s == cv::image_buf_attachment::ycbcr_matrix::itu_r_2020() => Self::Rec2020,+ s => return Err(()),+ })+ }+}