Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Squash cherry-picked changes from pipeline-based experiment
PJ8321696bdcfa
diff --git a/Cargo.lock b/Cargo.lockindex 68e42f6f0..c5aa35b35 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -260,6 +260,17 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "async-net"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7"+dependencies = [+ "async-io",+ "blocking",+ "futures-lite",+]+[[package]]name = "async-process"version = "2.2.4"@@ -705,6 +716,31 @@ dependencies = ["tauri-plugin-shell",]+[[package]]+name = "cap-media"+version = "0.1.0"+dependencies = [+ "anyhow",+ "cap-project",+ "core-foundation 0.10.0",+ "core-graphics 0.24.0",+ "cpal",+ "ctrlc",+ "ffmpeg-next",+ "ffmpeg-sys-next",+ "flume 0.11.0",+ "indexmap 2.5.0",+ "nokhwa 0.10.3 (git+https://github.com/Brendonovich/nokhwa?rev=2de5a760d5f1)",+ "nokhwa-bindings-macos 0.2.0 (git+https://github.com/Brendonovich/nokhwa?rev=2de5a760d5f1)",+ "scap 0.0.5",+ "serde",+ "smol",+ "specta",+ "thiserror",+ "tracing",+ "tracing-subscriber",+]+[[package]]name = "cap-project"version = "0.1.0"@@ -1332,6 +1368,16 @@ dependencies = ["syn 2.0.75",]+[[package]]+name = "ctrlc"+version = "3.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90eeab0aa92f3f9b4e87f258c72b139c207d251f9cbc1080a0086b86a8870dd3"+dependencies = [+ "nix 0.29.0",+ "windows-sys 0.59.0",+]+[[package]]name = "d3d12"version = "22.0.0"@@ -1455,6 +1501,7 @@ dependencies = ["bytemuck","cap-editor","cap-ffmpeg",+ "cap-media","cap-project","cap-rendering","cap-utils",@@ -1475,7 +1522,7 @@ dependencies = ["indexmap 2.5.0","mp4","nix 0.29.0",- "nokhwa",+ "nokhwa 0.10.3 (git+https://github.com/CapSoftware/nokhwa?branch=brendonovich-fork)","nokhwa-bindings-macos 0.2.0 (git+https://github.com/Brendonovich/nokhwa?rev=2de5a760d5f1)","num-traits","objc",@@ -1483,7 +1530,7 @@ dependencies = ["png","reqwest","rodio",- "scap",+ "scap 0.0.5 (git+https://github.com/CapSoftware/scap?rev=691bd88798d3)","serde","serde_json","specta",@@ -1938,6 +1985,9 @@ version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "55ac459de2512911e4b674ce33cf20befaba382d05b62b008afc1c8b57cbf181"dependencies = [+ "futures-core",+ "futures-sink",+ "nanorand","spin",]@@ -3724,6 +3774,20 @@ dependencies = ["thiserror",]+[[package]]+name = "nokhwa"+version = "0.10.3"+source = "git+https://github.com/Brendonovich/nokhwa?rev=2de5a760d5f1#2de5a760d5f1abfc062bf7d7fec155e8a0eafdcd"+dependencies = [+ "flume 0.10.14",+ "image 0.24.9",+ "nokhwa-bindings-macos 0.2.0 (git+https://github.com/Brendonovich/nokhwa?rev=2de5a760d5f1)",+ "nokhwa-core 0.1.0 (git+https://github.com/Brendonovich/nokhwa?rev=2de5a760d5f1)",+ "paste",+ "serde",+ "thiserror",+]+[[package]]name = "nokhwa-bindings-macos"version = "0.2.0"@@ -3773,6 +3837,8 @@ source = "git+https://github.com/Brendonovich/nokhwa?rev=2de5a760d5f1#2de5a760d5dependencies = ["bytes","image 0.24.9",+ "mozjpeg",+ "serde","thiserror",]@@ -5201,6 +5267,24 @@ dependencies = ["winapi-util",]+[[package]]+name = "scap"+version = "0.0.5"+dependencies = [+ "cocoa 0.25.0",+ "core-graphics-helmer-fork",+ "dbus",+ "objc",+ "pipewire",+ "rand 0.8.5",+ "screencapturekit",+ "screencapturekit-sys",+ "sysinfo",+ "tao-core-video-sys",+ "windows 0.52.0",+ "windows-capture",+]+[[package]]name = "scap"version = "0.0.5"@@ -5601,6 +5685,23 @@ version = "1.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"+[[package]]+name = "smol"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a33bd3e260892199c3ccfc487c88b2da2265080acb316cd920da72fdfd7c599f"+dependencies = [+ "async-channel",+ "async-executor",+ "async-fs",+ "async-io",+ "async-lock",+ "async-net",+ "async-process",+ "blocking",+ "futures-lite",+]+[[package]]name = "socket2"version = "0.5.7"diff --git a/Cargo.toml b/Cargo.tomlindex 6ab43810f..5e15b8d01 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -4,11 +4,23 @@ members = ["apps/desktop/src-tauri","crates/rendering","crates/ffmpeg",+ "crates/media","crates/utils","crates/project","crates/editor",][workspace.dependencies]+anyhow = "1.0.86"ffmpeg = { package = "ffmpeg-next", git = "https://github.com/CapSoftware/rust-ffmpeg", rev = "11f8d264bbc0" }+ffmpeg-sys-next = "7.0.2"+tokio = { version = "1.39.3", features = [+ "macros",+ "process",+ "fs",+ "sync",+ "rt",+ "rt-multi-thread",+ "time"+] }tauri = { version = "2.0.0-rc" }diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 2bf507946..c7493d01a 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -41,7 +41,7 @@ specta = "=2.0.0-rc.19"specta-typescript = "0.0.6"swift-rs = "1.0.6"nix = { version = "0.29.0", features = ["fs"] }-tokio = { version = "1.39.2", features = ["macros", "process", "fs"] }+tokio.workspace = trueuuid = { version = "1.10.0", features = ["v4"] }scap = { git = "https://github.com/CapSoftware/scap", rev = "691bd88798d3" }ffmpeg-sidecar = { git = "https://github.com/CapSoftware/ffmpeg-sidecar", branch = "main" }@@ -50,7 +50,7 @@ bytemuck = { version = "1.7", features = ["derive"] }image = "0.25.2"tauri-plugin-fs = "2.0.0-rc.0"futures-intrusive = "0.5.0"-anyhow = "1.0.86"+anyhow.workspace = truemp4 = "0.14.0"futures = "0.3.30"nokhwa = { git = "https://github.com/CapSoftware/nokhwa", branch = "brendonovich-fork", features = [@@ -75,6 +75,7 @@ cap-project = { path = "../../../crates/project" }cap-rendering = { path = "../../../crates/rendering" }cap-ffmpeg = { path = "../../../crates/ffmpeg" }cap-editor = { path = "../../../crates/editor" }+cap-media = { path = "../../../crates/media" }reqwest = { version = "0.12.7", features = ["json", "stream", "multipart"] }dotenvy_macro = "0.15.7"global-hotkey = "0.5.5"diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.tomlnew file mode 100644index 000000000..90793c359--- /dev/null+++ b/crates/media/Cargo.toml@@ -0,0 +1,35 @@+[package]+name = "cap-media"+version = "0.1.0"+description = "A modular multimedia processing library"+edition = "2021"+rust-version = "1.80"++[dependencies]+anyhow.workspace = true+cap-project = { path = "../project" }+cpal = "0.15.3"+ffmpeg.workspace = true+ffmpeg-sys-next.workspace = true+flume = "0.11.0"+indexmap = "2.5.0"+nokhwa = { git = "https://github.com/Brendonovich/nokhwa", rev = "2de5a760d5f1", features = [+ "input-avfoundation",+ "serialize",+] }+scap = { path = "../../../scap" }+# scap = { git = "https://github.com/CapSoftware/scap", rev = "691bd88798d3" }+serde = { version = "1", features = ["derive"] }+specta = "=2.0.0-rc.19"+thiserror = "1.0"+tracing = "0.1"++[target.'cfg(target_os = "macos")'.dependencies]+core-graphics = "0.24.0"+core-foundation = "0.10.0"+nokhwa-bindings-macos = { git = "https://github.com/Brendonovich/nokhwa", rev = "2de5a760d5f1" }++[dev-dependencies]+ctrlc = "3.4"+smol = "2.0"+tracing-subscriber = "0.3"diff --git a/crates/media/src/data.rs b/crates/media/src/data.rsnew file mode 100644index 000000000..7aa4c7057--- /dev/null+++ b/crates/media/src/data.rs@@ -0,0 +1,139 @@+pub use ffmpeg::format::{+ pixel::Pixel,+ sample::{Sample, Type},+};+use ffmpeg::sys::AVPixelFormat;+pub use ffmpeg::util::{+ channel_layout::ChannelLayout,+ frame::{Audio as FFAudio, Frame as FFFrame, Video as FFVideo},+ rational::Rational as FFRational,+};+pub use ffmpeg::{Error as FFError, Packet as FFPacket};++pub enum RawAudioFormat {+ U8,+ I16,+ I32,+ I64,+ F32,+ F64,+}++pub enum RawVideoFormat {+ Bgra,+ Yuyv,+ RawRgb,+ Nv12,+}++impl From<RawAudioFormat> for Sample {+ fn from(value: RawAudioFormat) -> Self {+ match value {+ RawAudioFormat::U8 => Self::U8(Type::Packed),+ RawAudioFormat::I16 => Self::I16(Type::Packed),+ RawAudioFormat::I32 => Self::I32(Type::Packed),+ RawAudioFormat::I64 => Self::I64(Type::Packed),+ RawAudioFormat::F32 => Self::F32(Type::Packed),+ RawAudioFormat::F64 => Self::F64(Type::Packed),+ }+ }+}++#[derive(Debug, Copy, Clone)]+pub struct AudioInfo {+ pub sample_format: Sample,+ sample_rate: u32,+ channels: usize,+ pub time_base: FFRational,+ pub buffer_size: u32,+}++impl AudioInfo {+ pub fn from_raw(+ format: RawAudioFormat,+ sample_rate: u32,+ channels: u16,+ buffer_size: u32,+ ) -> Self {+ Self {+ sample_format: format.into(),+ sample_rate,+ channels: channels.into(),+ time_base: FFRational(1, 1_000_000),+ buffer_size,+ }+ }++ pub fn sample_size(&self) -> usize {+ self.sample_format.bytes() * self.channels+ }++ pub fn rate(&self) -> i32 {+ self.sample_rate.try_into().unwrap()+ }++ pub fn channel_layout(&self) -> ChannelLayout {+ // TODO: Something other than panic. Pretty much all mics I know are either mono or stereo though.+ // Also need to test the audio data capture with a stereo mic at some point.+ match self.channels {+ 1 => ChannelLayout::MONO,+ 2 => ChannelLayout::STEREO,+ _ => panic!("Unsupported number of audio channels"),+ }+ }++ pub fn wrap_frame(&self, data: &[u8], timestamp: i64) -> FFAudio {+ let samples = data.len() / self.sample_size();++ let mut frame = FFAudio::new(self.sample_format, samples, self.channel_layout());++ frame.set_pts(Some(timestamp));+ frame.set_rate(self.sample_rate);+ frame.data_mut(0)[0..data.len()].copy_from_slice(data);++ frame+ }+}++#[derive(Debug, Copy, Clone)]+pub struct VideoInfo {+ pub pixel_format: Pixel,+ pub width: u32,+ pub height: u32,+ pub time_base: FFRational,+ pub frame_rate: FFRational,+}++impl VideoInfo {+ pub fn from_raw(format: RawVideoFormat, width: u32, height: u32, fps: u32) -> Self {+ Self {+ pixel_format: match format {+ RawVideoFormat::Bgra => Pixel::BGRA,+ RawVideoFormat::Yuyv => Pixel::UYVY422,+ RawVideoFormat::RawRgb => Pixel::RGB24,+ RawVideoFormat::Nv12 => Pixel::NV12,+ },+ width,+ height,+ time_base: FFRational(1, 1_000_000),+ frame_rate: FFRational(fps.try_into().unwrap(), 1),+ }+ }++ pub fn pixel_format_int(&self) -> i32 {+ // This is necessary because the AVPixelFormat C enum has specific integer values that+ // the Rust PixelFormat enum doesn't replicate. But there is a From/Into conversion+ // between them that we can use to get the right format code.+ let av_pix_fmt: AVPixelFormat = self.pixel_format.into();+ av_pix_fmt as i32+ }++ pub fn wrap_frame(&self, data: &[u8], timestamp: i64) -> FFVideo {+ let mut frame = FFVideo::new(self.pixel_format, self.width, self.height);++ frame.set_pts(Some(timestamp));+ frame.data_mut(0)[0..data.len()].copy_from_slice(data);++ frame+ }+}diff --git a/crates/media/src/encoders/h264.rs b/crates/media/src/encoders/h264.rsnew file mode 100644index 000000000..b3be5954e--- /dev/null+++ b/crates/media/src/encoders/h264.rs@@ -0,0 +1,127 @@+use ffmpeg::{+ codec::{codec::Codec, context, encoder},+ format::{self, pixel::Pixel},+ threading::Config,+ Dictionary,+};++use crate::{+ data::{FFPacket, FFVideo, VideoInfo},+ pipeline::task::PipelineSinkTask,+ MediaError,+};++use super::Output;++pub struct H264Encoder {+ tag: &'static str,+ encoder: encoder::Video,+ output_ctx: format::context::Output,+}++impl H264Encoder {+ pub fn init(tag: &'static str, config: VideoInfo, output: Output) -> Result<Self, MediaError> {+ let destination = match output {+ Output::File(path) => path,+ };+ let mut output_ctx = format::output(&destination)?;++ let (codec, options) = get_codec_and_options(&config)?;++ let mut encoder_ctx = context::Context::new_with_codec(codec);+ // TODO: Configure this per system+ encoder_ctx.set_threading(Config::count(4));+ let mut encoder = encoder_ctx.encoder().video()?;++ encoder.set_width(config.width);+ encoder.set_height(config.height);+ encoder.set_format(Pixel::YUV420P);+ encoder.set_time_base(config.time_base);++ let video_encoder = encoder.open_with(options)?;++ let mut output_stream = output_ctx.add_stream(codec)?;+ output_stream.set_time_base(config.frame_rate.invert());+ output_stream.set_parameters(&video_encoder);+ // TODO: Move this to after pipeline start maybe?+ output_ctx.write_header()?;++ Ok(Self {+ tag,+ encoder: video_encoder,+ output_ctx,+ })+ }++ fn queue_frame(&mut self, frame: FFVideo) {+ self.encoder.send_frame(&frame).unwrap();+ }++ fn process_frame(&mut self) {+ let mut encoded_packet = FFPacket::empty();++ // TODO: Handle errors that are not EGAIN/"needs more data"+ while self.encoder.receive_packet(&mut encoded_packet).is_ok() {+ encoded_packet.set_stream(0);+ encoded_packet.rescale_ts(+ self.encoder.time_base(),+ self.output_ctx.stream(0).unwrap().time_base(),+ );+ // TODO: Possibly move writing to disk to its own file, to increase encoding throughput?+ encoded_packet+ .write_interleaved(&mut self.output_ctx)+ .unwrap();+ }+ }++ fn finish(&mut self) {+ self.encoder.send_eof().unwrap();+ self.process_frame();+ self.output_ctx.write_trailer().unwrap();+ }+}++impl PipelineSinkTask for H264Encoder {+ type Input = FFVideo;++ fn run(+ &mut self,+ ready_signal: crate::pipeline::task::PipelineReadySignal,+ input: flume::Receiver<Self::Input>,+ ) {+ tracing::info!("Starting {} video encoding thread", self.tag);+ ready_signal.send(Ok(())).unwrap();++ while let Ok(frame) = input.recv() {+ self.queue_frame(frame);+ self.process_frame();+ }++ tracing::info!("Received last {} frame. Finishing up encoding.", self.tag);+ self.finish();++ tracing::info!("Shutting down {} video encoding thread", self.tag);+ }+}++fn get_codec_and_options(config: &VideoInfo) -> Result<(Codec, Dictionary), MediaError> {+ if let Some(codec) = encoder::find_by_name("libx264") {+ let mut options = Dictionary::new();++ let keyframe_interval_secs = 2;+ let keyframe_interval = keyframe_interval_secs * config.frame_rate.numerator();+ let keyframe_interval_str = keyframe_interval.to_string();++ options.set("preset", "ultrafast");+ options.set("tune", "zerolatency");+ options.set("vsync", "1");+ options.set("g", &keyframe_interval_str);+ options.set("keyint_min", &keyframe_interval_str);+ // TODO: Is it worth limiting quality? Maybe make this configurable+ // options.set("crf", "23");++ return Ok((codec, options));+ }++ Err(MediaError::MissingCodec("H264 video"))+}diff --git a/crates/media/src/encoders/mod.rs b/crates/media/src/encoders/mod.rsnew file mode 100644index 000000000..bc184da53--- /dev/null+++ b/crates/media/src/encoders/mod.rs@@ -0,0 +1,11 @@+use std::path::PathBuf;++mod h264;+mod mp3;++pub use h264::*;+pub use mp3::*;++pub enum Output {+ File(PathBuf),+}diff --git a/crates/media/src/encoders/mp3.rs b/crates/media/src/encoders/mp3.rsnew file mode 100644index 000000000..7852647ed--- /dev/null+++ b/crates/media/src/encoders/mp3.rs@@ -0,0 +1,142 @@+use ffmpeg::{+ codec::{context, encoder},+ format,+ threading::Config,+};+use std::collections::VecDeque;++use crate::{+ data::{AudioInfo, FFAudio, FFPacket, FFRational},+ pipeline::task::PipelineSinkTask,+ MediaError,+};++use super::Output;++pub struct MP3Encoder {+ tag: &'static str,+ encoder: encoder::Audio,+ output_ctx: format::context::Output,+ frame_size: usize,+ sample_size: usize,+ frame_buffer: VecDeque<u8>,+ next_pts: i64,+}++impl MP3Encoder {+ const OUTPUT_BITRATE: usize = 192 * 1000; // 192k++ pub fn init(tag: &'static str, config: AudioInfo, output: Output) -> Result<Self, MediaError> {+ let destination = match output {+ Output::File(path) => path,+ };+ let mut output_ctx = format::output(&destination)?;+ tracing::info!("Sample format: {:#?}", config.sample_format);++ let codec = encoder::find(ffmpeg::codec::Id::MP3)+ .ok_or(MediaError::TaskLaunch("Could not find MP3 codec".into()))?;+ let mut encoder_ctx = context::Context::new_with_codec(codec);+ encoder_ctx.set_threading(Config::count(4));+ let mut encoder = encoder_ctx.encoder().audio()?;++ encoder.set_bit_rate(Self::OUTPUT_BITRATE);+ encoder.set_rate(config.rate());+ encoder.set_format(config.sample_format);+ encoder.set_channel_layout(config.channel_layout());+ encoder.set_time_base(config.time_base);++ let audio_encoder = encoder.open()?;++ let mut output_stream = output_ctx.add_stream(codec)?;+ output_stream.set_time_base(FFRational(1, config.rate()));+ output_stream.set_parameters(&audio_encoder);+ output_ctx.write_header()?;++ let sample_size = config.sample_size();+ let frame_buffer_size = usize::try_from(config.buffer_size).unwrap() * sample_size;+ Ok(Self {+ tag,+ frame_size: audio_encoder.frame_size().try_into().unwrap(),+ sample_size,+ encoder: audio_encoder,+ output_ctx,+ frame_buffer: VecDeque::with_capacity(frame_buffer_size * 2),+ next_pts: 0,+ })+ }++ fn queue_frames_from_buffer(&mut self) {+ if self.frame_buffer.is_empty() {+ return;+ }++ let data_size = self.frame_size * self.sample_size;+ // let data_size = std::cmp::min(self.frame_size * self.sample_size, self.frame_buffer.len());+ let mut frame = FFAudio::new(+ self.encoder.format(),+ self.frame_size,+ self.encoder.channel_layout(),+ );+ frame.set_rate(self.encoder.rate());+ // TODO: Set first PTS with ffmpeg::sys::av_rescale_q??+ frame.set_pts(Some(self.next_pts));+ for (index, byte) in self.frame_buffer.drain(0..data_size).enumerate() {+ frame.data_mut(0)[index] = byte;+ }++ self.encoder.send_frame(&frame).unwrap();+ self.process_packets();+ }++ fn queue_frame(&mut self, frame: FFAudio) {+ self.frame_buffer.extend(frame.data(0));+ while self.frame_buffer.len() >= self.frame_size * self.sample_size {+ self.queue_frames_from_buffer();+ self.next_pts += i64::try_from(self.frame_size).unwrap();+ }+ }++ fn process_packets(&mut self) {+ let mut encoded_packet = FFPacket::empty();++ while self.encoder.receive_packet(&mut encoded_packet).is_ok() {+ encoded_packet.set_stream(0);+ encoded_packet.rescale_ts(+ encoded_packet.time_base(),+ self.output_ctx.stream(0).unwrap().time_base(),+ );+ encoded_packet+ .write_interleaved(&mut self.output_ctx)+ .unwrap();+ }+ }++ fn finish(&mut self) {+ // self.queue_frames_from_buffer();+ self.encoder.send_eof().unwrap();+ self.process_packets();+ self.output_ctx.write_trailer().unwrap();+ }+}++impl PipelineSinkTask for MP3Encoder {+ type Input = FFAudio;++ fn run(+ &mut self,+ ready_signal: crate::pipeline::task::PipelineReadySignal,+ input: flume::Receiver<Self::Input>,+ ) {+ tracing::info!("Starting {} audio encoding thread", self.tag);+ ready_signal.send(Ok(())).unwrap();++ while let Ok(frame) = input.recv() {+ self.queue_frame(frame);+ }++ tracing::info!("Received last {} sample. Finishing up encoding.", self.tag);+ self.finish();++ tracing::info!("Shutting down {} audio encoding thread", self.tag);+ }+}diff --git a/crates/media/src/filters/audio.rs b/crates/media/src/filters/audio.rsnew file mode 100644index 000000000..81175b98f--- /dev/null+++ b/crates/media/src/filters/audio.rs@@ -0,0 +1,98 @@+use ffmpeg::filter;+use flume::{Receiver, Sender};++use crate::{+ data::{AudioInfo, FFAudio},+ pipeline::task::PipelinePipeTask,+ MediaError,+};++pub struct AudioFilter {+ tag: &'static str,+ filter_graph: filter::Graph,+}++impl AudioFilter {+ pub fn init(tag: &'static str, config: AudioInfo, spec: &str) -> Result<Self, MediaError> {+ let mut filter_graph = filter::Graph::new();++ let input_args = format!(+ "time_base={}:sample_rate={}:sample_fmt={}:channel_layout=0x{:x}",+ config.time_base,+ config.rate(),+ config.sample_format.name(),+ config.channel_layout().bits()+ );+ filter_graph.add(&filter::find("abuffer").unwrap(), "in", &input_args)?;+ filter_graph.add(&filter::find("abuffersink").unwrap(), "out", "")?;++ filter_graph.output("in", 0)?.input("out", 0)?.parse(spec)?;+ filter_graph.validate()?;++ Ok(Self { filter_graph, tag })+ }++ fn queue_frame(&mut self, frame: FFAudio) {+ self.filter_graph+ .get("in")+ .unwrap()+ .source()+ .add(&frame)+ .unwrap();+ }++ fn process_frame(&mut self, output: &Sender<FFAudio>) {+ let mut filtered_frame = FFAudio::empty();++ while self+ .filter_graph+ .get("out")+ .unwrap()+ .sink()+ .frame(&mut filtered_frame)+ .is_ok()+ {+ output.send(filtered_frame).unwrap();+ filtered_frame = FFAudio::empty();+ }+ }++ fn finish(&mut self, output: &Sender<FFAudio>) {+ self.filter_graph+ .get("in")+ .unwrap()+ .source()+ .flush()+ .unwrap();++ self.process_frame(output);+ }+}++impl PipelinePipeTask for AudioFilter {+ type Input = FFAudio;+ type Output = FFAudio;++ fn run(+ &mut self,+ ready_signal: crate::pipeline::task::PipelineReadySignal,+ input: Receiver<Self::Input>,+ output: Sender<Self::Output>,+ ) {+ tracing::info!("Starting {} audio filtering thread", self.tag);+ ready_signal.send(Ok(())).unwrap();++ while let Ok(raw_frame) = input.recv() {+ self.queue_frame(raw_frame);+ self.process_frame(&output);+ }++ tracing::info!(+ "Received last raw {} sample. Finishing up filtering.",+ self.tag+ );+ self.finish(&output);++ tracing::info!("Shutting down {} audio filtering thread", self.tag);+ }+}diff --git a/crates/media/src/filters/mod.rs b/crates/media/src/filters/mod.rsnew file mode 100644index 000000000..66b5297e3--- /dev/null+++ b/crates/media/src/filters/mod.rs@@ -0,0 +1,5 @@+mod audio;+mod video;++pub use audio::AudioFilter;+pub use video::VideoFilter;diff --git a/crates/media/src/filters/video.rs b/crates/media/src/filters/video.rsnew file mode 100644index 000000000..9845269fb--- /dev/null+++ b/crates/media/src/filters/video.rs@@ -0,0 +1,106 @@+use ffmpeg::{filter, format::pixel::Pixel};++use crate::{+ data::{FFVideo, VideoInfo},+ pipeline::task::PipelinePipeTask,+ MediaError,+};+use flume::Sender;++pub struct VideoFilter {+ tag: &'static str,+ filter_graph: filter::Graph,+}++impl VideoFilter {+ pub fn init(tag: &'static str, config: VideoInfo, spec: &str) -> Result<Self, MediaError> {+ let mut filter_graph = filter::Graph::new();++ let input_args = format!(+ "pix_fmt={}:width={}:height={}:time_base={}/{}",+ config.pixel_format_int(),+ config.width,+ config.height,+ config.time_base.numerator(),+ config.time_base.denominator()+ );+ filter_graph.add(&filter::find("buffer").unwrap(), "in", &input_args)?;+ filter_graph.add(&filter::find("buffersink").unwrap(), "out", "")?;++ let mut input = filter_graph.get("in").unwrap();+ input.set_pixel_format(config.pixel_format);++ let mut output = filter_graph.get("out").unwrap();+ output.set_pixel_format(Pixel::YUV420P);++ filter_graph.output("in", 0)?.input("out", 0)?.parse(spec)?;+ filter_graph.validate()?;++ Ok(Self { filter_graph, tag })+ }++ fn queue_frame(&mut self, frame: FFVideo) {+ self.filter_graph+ .get("in")+ .unwrap()+ .source()+ .add(&frame)+ .unwrap();+ }++ fn process_frame(&mut self, output: &Sender<FFVideo>) {+ let mut filtered_frame = FFVideo::empty();++ // TODO: Handle errors that are not EGAIN/"needs more data"+ while self+ .filter_graph+ .get("out")+ .unwrap()+ .sink()+ .frame(&mut filtered_frame)+ .is_ok()+ {+ output.send(filtered_frame).unwrap();+ filtered_frame = FFVideo::empty();+ }+ }++ fn finish(&mut self, output: &Sender<FFVideo>) {+ self.filter_graph+ .get("in")+ .unwrap()+ .source()+ .flush()+ .unwrap();++ self.process_frame(output);+ }+}++impl PipelinePipeTask for VideoFilter {+ type Input = FFVideo;+ type Output = FFVideo;++ fn run(+ &mut self,+ ready_signal: crate::pipeline::task::PipelineReadySignal,+ input: flume::Receiver<Self::Input>,+ output: Sender<Self::Output>,+ ) {+ tracing::info!("Starting {} video filtering thread", self.tag);+ ready_signal.send(Ok(())).unwrap();++ while let Ok(raw_frame) = input.recv() {+ self.queue_frame(raw_frame);+ self.process_frame(&output);+ }++ tracing::info!(+ "Received last raw {} frame. Finishing up filtering.",+ self.tag+ );+ self.finish(&output);++ tracing::info!("Shutting down {} video filtering thread", self.tag);+ }+}diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rsnew file mode 100644index 000000000..9a153c30f--- /dev/null+++ b/crates/media/src/lib.rs@@ -0,0 +1,38 @@+//! A modular multimedia processing framework, based on FFmpeg.+//!+//! It provides a `pipeline` abstraction for creating and controlling an entire operation,+//! as well as implementations of pipeline stages for individual tasks (encoding/decoding,+//! editing frames, composition, muxing, etc).++use thiserror::Error;++pub mod data;+pub mod encoders;+pub mod filters;+pub mod pipeline;+mod platform;+pub mod sources;++pub fn init() -> Result<(), MediaError> {+ ffmpeg::init()?;++ Ok(())+}++#[derive(Error, Debug)]+pub enum MediaError {+ #[error("Media error: {0}")]+ Any(&'static str),++ #[error("Cannot build a pipeline without any tasks")]+ EmptyPipeline,++ #[error("Failed to launch task: #{0}")]+ TaskLaunch(String),++ #[error("FFmpeg error: {0}")]+ FFmpeg(#[from] ffmpeg::Error),++ #[error("Could not find a suitable codec for {0}")]+ MissingCodec(&'static str),+}diff --git a/crates/media/src/pipeline/builder.rs b/crates/media/src/pipeline/builder.rsnew file mode 100644index 000000000..429651fc1--- /dev/null+++ b/crates/media/src/pipeline/builder.rs@@ -0,0 +1,154 @@+use flume::Receiver;+use indexmap::IndexMap;+use std::thread::{self, JoinHandle};++use crate::pipeline::{+ clock::CloneFrom,+ control::ControlBroadcast,+ task::{PipelinePipeTask, PipelineReadySignal, PipelineSinkTask, PipelineSourceTask},+ MediaError, Pipeline, PipelineClock,+};++struct Task {+ ready_signal: Receiver<Result<(), MediaError>>,+ join_handle: JoinHandle<()>,+}++pub struct PipelineBuilder<T: PipelineClock> {+ clock: T,+ control: ControlBroadcast,+ tasks: IndexMap<String, Task>,+}++impl<T: PipelineClock> PipelineBuilder<T> {+ pub fn new(clock: T) -> Self {+ Self {+ clock,+ control: ControlBroadcast::default(),+ tasks: IndexMap::new(),+ }+ }++ pub fn source<O: Send + 'static, C: CloneFrom<T> + Send + 'static>(+ mut self,+ name: impl Into<String>,+ mut task: impl PipelineSourceTask<Output = O, Clock = C> + 'static,+ ) -> PipelinePathBuilder<T, O> {+ let name = name.into();+ let (output, next_input) = flume::bounded(task.queue_size());+ let clock = C::clone_from(&self.clock);+ let control_signal = self.control.add_listener(name.clone());++ self.spawn_task(name, move |ready_signal| {+ task.run(clock, ready_signal, control_signal, output);+ });++ PipelinePathBuilder {+ pipeline: self,+ next_input,+ }+ }++ fn spawn_task(+ &mut self,+ name: String,+ launch: impl FnOnce(PipelineReadySignal) + Send + 'static,+ ) {+ if self.tasks.contains_key(&name) {+ panic!("A task with the name {name} has already been added to the pipeline");+ }++ let (ready_sender, ready_signal) = flume::bounded(1);++ let join_handle = thread::spawn(move || {+ launch(ready_sender);+ });+ self.tasks.insert(+ name,+ Task {+ ready_signal,+ join_handle,+ },+ );+ }++ pub async fn build(self) -> Result<Pipeline<T>, MediaError> {+ let Self {+ clock,+ control,+ tasks,+ } = self;++ if tasks.is_empty() {+ return Err(MediaError::EmptyPipeline);+ }++ let mut task_handles = IndexMap::new();++ // TODO: Shut down tasks if launch failed.+ for (name, task) in tasks.into_iter() {+ // TODO: Wait for these in parallel?+ let _ = task+ .ready_signal+ .recv_async()+ .await+ .map_err(|_| MediaError::TaskLaunch(name.clone()))??;++ task_handles.insert(name, task.join_handle);+ }++ Ok(Pipeline {+ clock,+ control,+ task_handles,+ })+ }+}++pub struct PipelinePathBuilder<Clock: PipelineClock, PreviousOutput: Send> {+ pipeline: PipelineBuilder<Clock>,+ next_input: Receiver<PreviousOutput>,+}++impl<Clock: PipelineClock, PreviousOutput: Send + 'static>+ PipelinePathBuilder<Clock, PreviousOutput>+{+ pub fn pipe<Output: Send + 'static>(+ self,+ name: impl Into<String>,+ mut task: impl PipelinePipeTask<Input = PreviousOutput, Output = Output> + Send + 'static,+ ) -> PipelinePathBuilder<Clock, Output> {+ let Self {+ mut pipeline,+ next_input: input,+ } = self;++ let (output, next_input) = flume::bounded(task.queue_size());++ pipeline.spawn_task(name.into(), move |ready_signal| {+ task.run(ready_signal, input, output);+ });++ PipelinePathBuilder {+ pipeline,+ next_input,+ }+ }++ pub fn sink(+ self,+ name: impl Into<String>,+ mut task: impl PipelineSinkTask<Input = PreviousOutput> + Send + 'static,+ ) -> PipelineBuilder<Clock> {+ let Self {+ mut pipeline,+ next_input: input,+ } = self;++ pipeline.spawn_task(name.into(), move |ready_signal| {+ task.run(ready_signal, input);+ });++ pipeline+ }+}diff --git a/crates/media/src/pipeline/clock.rs b/crates/media/src/pipeline/clock.rsnew file mode 100644index 000000000..e85952b79--- /dev/null+++ b/crates/media/src/pipeline/clock.rs@@ -0,0 +1,176 @@+use std::sync::{+ atomic::{AtomicBool, AtomicU64, Ordering},+ Arc, RwLock,+};+use std::time::{Duration, Instant};++// TODO: Move to utils mod?++pub trait CloneFrom<T> {+ fn clone_from(value: &T) -> Self;+}++pub trait CloneInto<T> {+ fn clone_into(&self) -> T;+}++impl<S, T> CloneFrom<T> for S+where+ T: CloneInto<S>,+{+ fn clone_from(value: &T) -> Self {+ value.clone_into()+ }+}++pub trait PipelineClock: Clone + Send + 'static {+ fn start(&mut self);++ fn stop(&mut self);+}++pub trait LocalTimestamp: Sized + Clone {+ fn elapsed_since(&self, other: &Self) -> Duration;+}++impl LocalTimestamp for () {+ fn elapsed_since(&self, _other: &Self) -> Duration {+ Duration::ZERO+ }+}++impl LocalTimestamp for Instant {+ fn elapsed_since(&self, other: &Self) -> Duration {+ self.duration_since(*other)+ }+}++#[derive(Debug, Clone)]+pub struct RawNanoseconds(pub u64);++impl LocalTimestamp for RawNanoseconds {+ fn elapsed_since(&self, other: &Self) -> Duration {+ Duration::from_nanos(self.0) - Duration::from_nanos(other.0)+ }+}++#[derive(Debug, Clone)]+pub struct SynchronisedClock<T: LocalTimestamp> {+ local_start_time: Option<Instant>,+ global_start_time: Arc<RwLock<Instant>>,+ first_local_timestamp: Option<T>,+ // We could store the `Duration` here, but that would be more expensive than using an atomic integer.+ resume_offset_nanoseconds: Arc<AtomicU64>,+ running: Arc<AtomicBool>,+}++impl<Source: LocalTimestamp, Target: LocalTimestamp> CloneInto<SynchronisedClock<Target>>+ for SynchronisedClock<Source>+{+ fn clone_into(&self) -> SynchronisedClock<Target> {+ let SynchronisedClock {+ global_start_time,+ resume_offset_nanoseconds,+ running,+ ..+ } = self.clone();++ SynchronisedClock {+ global_start_time,+ resume_offset_nanoseconds,+ running,+ local_start_time: None,+ first_local_timestamp: None,+ }+ }+}++impl<T: LocalTimestamp> SynchronisedClock<T> {+ pub fn init() -> SynchronisedClock<()> {+ SynchronisedClock::<()>::new()+ }++ pub fn new() -> Self {+ Self {+ local_start_time: None,+ global_start_time: Arc::new(RwLock::new(Instant::now())),+ first_local_timestamp: None,+ resume_offset_nanoseconds: Arc::new(AtomicU64::new(0)),+ running: Arc::new(AtomicBool::new(false)),+ }+ }++ pub fn running(&self) -> bool {+ self.running.load(Ordering::Acquire)+ }++ fn set_running(&self, value: bool) {+ self.running.store(value, Ordering::Release);+ }++ fn resume_offset(&self) -> Duration {+ let nanos = self.resume_offset_nanoseconds.load(Ordering::Acquire);++ Duration::from_nanos(nanos)+ }++ fn update_resume_offset(&self, delta: Duration) {+ let delta_nanos = delta.as_nanos().try_into().unwrap();+ self.resume_offset_nanoseconds+ .fetch_add(delta_nanos, Ordering::AcqRel);+ }++ pub fn timestamp_for(&mut self, local: T) -> Option<i64> {+ let now = Instant::now();++ if !self.running() {+ return None;+ }++ if let Ok(global_start_time) = self.global_start_time.read() {+ // TODO: Cache some of this calculation thread-locally?++ if self.local_start_time.is_none()+ || self.local_start_time.unwrap() < *global_start_time+ {+ tracing::info!("Just resumed, resetting local state");+ self.local_start_time = Some(now);+ self.first_local_timestamp = Some(local.clone());+ }++ let local_start_time = self.local_start_time.as_ref().unwrap();+ let first_local_timestamp = self.first_local_timestamp.as_ref().unwrap();++ let total_offset =+ local_start_time.duration_since(*global_start_time) + self.resume_offset();+ let elapsed_time = local.elapsed_since(first_local_timestamp) + total_offset;+ let timestamp = elapsed_time.as_micros().try_into().unwrap();++ Some(timestamp)+ } else {+ // TODO: Try clearing poison? Right now just re-panic if the panic that caused the poison somehow did not stop the app+ panic!("Pipeline clock has been poisoned!")+ }+ }+}++impl PipelineClock for SynchronisedClock<()> {+ fn start(&mut self) {+ if !self.running() {+ let mut start_time = self.global_start_time.write().unwrap();++ *start_time = Instant::now();+ self.set_running(true);+ }+ }++ fn stop(&mut self) {+ if self.running() {+ self.set_running(false);++ let now = Instant::now();+ let start_time = self.global_start_time.read().unwrap();+ self.update_resume_offset(now - *start_time);+ }+ }+}diff --git a/crates/media/src/pipeline/control.rs b/crates/media/src/pipeline/control.rsnew file mode 100644index 000000000..411ba9e8b--- /dev/null+++ b/crates/media/src/pipeline/control.rs@@ -0,0 +1,89 @@+use flume::{Receiver, Sender, TryRecvError};+use indexmap::IndexMap;++use crate::pipeline::MediaError;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Control {+ Play,+ Pause,+ Shutdown,+}++pub struct PipelineControlSignal {+ last_value: Option<Control>,+ receiver: Receiver<Control>,+}++impl PipelineControlSignal {+ pub fn last(&mut self) -> Option<Control> {+ match self.last_value {+ Some(Control::Play) => {+ // Only peek for a new signal, else relinquish control to the caller+ match self.receiver.try_recv() {+ Ok(control) => {+ tracing::info!("Received new signal: {control:?}");+ self.last_value = Some(control)+ }+ Err(TryRecvError::Empty) => {}+ Err(TryRecvError::Disconnected) => self.last_value = None,+ };++ self.last_value+ }+ _ => {+ // For all else, block until a signal is sent.+ // TODO: Maybe also spin down until the signal is different from the last value we have?+ self.blocking_last()+ }+ }+ }++ pub fn blocking_last(&mut self) -> Option<Control> {+ tracing::info!("Waiting for play signal...");+ self.last_value = self.receiver.recv().ok();++ self.last_value+ }+}++/// An extremely naive broadcast channel. Sends values synchronously to all receivers,+/// might block if one receiver takes too long to receive value.+#[derive(Debug, Default)]+pub(super) struct ControlBroadcast {+ listeners: IndexMap<String, Sender<Control>>,+}++impl ControlBroadcast {+ pub fn add_listener(&mut self, name: String) -> PipelineControlSignal {+ let (sender, receiver) = flume::bounded(1);+ self.listeners.insert(name, sender);+ PipelineControlSignal {+ last_value: None,+ receiver,+ }+ }++ pub async fn broadcast(&mut self, value: Control) -> Result<(), MediaError> {+ let mut any_dropped = false;++ if self.listeners.is_empty() {+ tracing::warn!("Attempting to broadcast value without any listeners");+ }++ for (name, listener) in self.listeners.iter() {+ tracing::info!("Sending signal {value:?} to {name}");+ if let Err(_) = listener.send_async(value).await {+ tracing::warn!("{name} is unreachable!");+ any_dropped = true;+ }+ }++ match any_dropped {+ false => Ok(()),+ true => Err(MediaError::Any(+ "Attempted to broadcast value to a listener that has been dropped. Pipeline execution may be compromised.",+ )),+ }+ }+}diff --git a/crates/media/src/pipeline/mod.rs b/crates/media/src/pipeline/mod.rsnew file mode 100644index 000000000..975ddf107--- /dev/null+++ b/crates/media/src/pipeline/mod.rs@@ -0,0 +1,54 @@+use indexmap::IndexMap;+use std::thread::JoinHandle;++pub mod builder;+pub mod clock;+pub mod control;+pub mod task;++use crate::MediaError;++use builder::PipelineBuilder;+use clock::PipelineClock;+use control::{Control, ControlBroadcast, PipelineControlSignal};++pub struct Pipeline<T: PipelineClock> {+ clock: T,+ control: ControlBroadcast,+ task_handles: IndexMap<String, JoinHandle<()>>,+}++impl<T: PipelineClock> Pipeline<T> {+ pub fn builder(clock: T) -> PipelineBuilder<T> {+ PipelineBuilder::new(clock)+ }++ pub async fn play(&mut self) -> Result<(), MediaError> {+ tracing::info!("Starting pipeline execution");+ self.clock.start();+ self.control.broadcast(Control::Play).await+ }++ pub async fn pause(&mut self) -> Result<(), MediaError> {+ tracing::info!("Pausing pipeline execution");+ self.clock.stop();+ self.control.broadcast(Control::Pause).await+ }++ pub async fn shutdown(self) -> Result<(), MediaError> {+ tracing::info!("Shutting down pipeline execution");+ let Self {+ mut control,+ task_handles,+ ..+ } = self;++ let _ = control.broadcast(Control::Shutdown).await;+ for task in task_handles.into_values() {+ let _ = task.join();+ }+ tracing::info!("Pipeline has been stopped.");+ // TODO: Collect shutdown errors?+ Ok(())+ }+}diff --git a/crates/media/src/pipeline/task.rs b/crates/media/src/pipeline/task.rsnew file mode 100644index 000000000..072b977e3--- /dev/null+++ b/crates/media/src/pipeline/task.rs@@ -0,0 +1,46 @@+use flume::{Receiver, Sender};++use crate::pipeline::{MediaError, PipelineControlSignal};++const DEFAULT_QUEUE_SIZE: usize = 2048;++pub type PipelineReadySignal = Sender<Result<(), MediaError>>;++pub trait PipelineSourceTask: Send {+ type Output;+ type Clock;++ fn run(+ &mut self,+ clock: Self::Clock,+ ready_signal: PipelineReadySignal,+ control_signal: PipelineControlSignal,+ output: Sender<Self::Output>,+ );++ fn queue_size(&self) -> usize {+ DEFAULT_QUEUE_SIZE+ }+}++pub trait PipelinePipeTask: Send {+ type Input;+ type Output;++ fn run(+ &mut self,+ ready_signal: PipelineReadySignal,+ input: Receiver<Self::Input>,+ output: Sender<Self::Output>,+ );++ fn queue_size(&self) -> usize {+ DEFAULT_QUEUE_SIZE+ }+}++pub trait PipelineSinkTask: Send {+ type Input;++ fn run(&mut self, ready_signal: PipelineReadySignal, input: Receiver<Self::Input>);+}diff --git a/crates/media/src/platform/macos.rs b/crates/media/src/platform/macos.rsnew file mode 100644index 000000000..9a802f93d--- /dev/null+++ b/crates/media/src/platform/macos.rs@@ -0,0 +1,144 @@+use core_foundation::{+ array::CFArrayGetCount,+ base::FromVoid,+ dictionary::CFDictionaryGetValue,+ number::{kCFNumberIntType, CFNumberGetValue, CFNumberRef},+ string::{CFString, CFStringRef},+};+use core_graphics::{+ base::boolean_t,+ display::{CFArrayGetValueAtIndex, CFDictionaryRef, CGRect},+ window::{+ kCGNullWindowID, kCGWindowBounds, kCGWindowLayer, kCGWindowListExcludeDesktopElements,+ kCGWindowListOptionOnScreenOnly, kCGWindowName, kCGWindowNumber, kCGWindowOwnerName,+ kCGWindowOwnerPID, CGWindowListCopyWindowInfo,+ },+};+use std::ffi::c_void;++use crate::platform::{Bounds, Window};++#[link(name = "CoreGraphics", kind = "framework")]+extern "C" {+ fn CGRectMakeWithDictionaryRepresentation(+ dict: CFDictionaryRef,+ rect: *mut CGRect,+ ) -> boolean_t;+}++pub fn get_on_screen_windows() -> Vec<Window> {+ let mut windows = Vec::new();++ unsafe {+ let cf_win_array = CGWindowListCopyWindowInfo(+ kCGWindowListExcludeDesktopElements | kCGWindowListOptionOnScreenOnly,+ kCGNullWindowID,+ );++ let window_count = match cf_win_array.is_null() {+ true => 0,+ false => CFArrayGetCount(cf_win_array),+ };++ for i in 0..window_count {+ let window_cf_dictionary_ref =+ CFArrayGetValueAtIndex(cf_win_array, i) as CFDictionaryRef;++ if window_cf_dictionary_ref.is_null() {+ continue;+ }++ let level = match get_number_value_from_dict(window_cf_dictionary_ref, kCGWindowLayer) {+ Some(value) => value,+ None => continue,+ };++ let window_id =+ match get_number_value_from_dict(window_cf_dictionary_ref, kCGWindowNumber) {+ Some(value) => value,+ None => continue,+ };++ let name = match get_string_value_from_dict(window_cf_dictionary_ref, kCGWindowName) {+ Some(value) => value,+ None => continue,+ };++ let owner_name =+ match get_string_value_from_dict(window_cf_dictionary_ref, kCGWindowOwnerName) {+ Some(value) => value,+ None => continue,+ };++ if owner_name != "Window Server" && level == 0 && !name.is_empty() {+ let process_id =+ match get_number_value_from_dict(window_cf_dictionary_ref, kCGWindowOwnerPID) {+ Some(value) => value,+ None => continue,+ };+ if let Some(bounds) = get_window_bounds(window_cf_dictionary_ref) {+ windows.push(Window {+ window_id,+ name,+ owner_name,+ process_id,+ bounds,+ });+ }+ }+ }+ }++ windows+}++unsafe fn get_nullable_value_from_dict(+ cf_dictionary_ref: CFDictionaryRef,+ key: CFStringRef,+) -> Option<*const c_void> {+ let value_ref = CFDictionaryGetValue(cf_dictionary_ref, key as *const c_void);+ if value_ref.is_null() {+ return None;+ }++ Some(value_ref)+}++unsafe fn get_number_value_from_dict(+ cf_dictionary_ref: CFDictionaryRef,+ key: CFStringRef,+) -> Option<u32> {+ get_nullable_value_from_dict(cf_dictionary_ref, key).and_then(|value_ref| {+ let mut value: u32 = 0;+ let value_ptr = &mut value as *mut _ as *mut c_void;+ match CFNumberGetValue(value_ref as CFNumberRef, kCFNumberIntType, value_ptr) {+ true => Some(value),+ false => None,+ }+ })+}++unsafe fn get_string_value_from_dict(+ cf_dictionary_ref: CFDictionaryRef,+ key: CFStringRef,+) -> Option<String> {+ get_nullable_value_from_dict(cf_dictionary_ref, key)+ .map(|value_ref| CFString::from_void(value_ref).to_string())+}++unsafe fn get_window_bounds(window_cf_dictionary_ref: CFDictionaryRef) -> Option<Bounds> {+ get_nullable_value_from_dict(window_cf_dictionary_ref, kCGWindowBounds).map(|value_ref| {+ let rect: CGRect = {+ let mut rect = std::mem::zeroed();+ CGRectMakeWithDictionaryRepresentation(value_ref.cast(), &mut rect);+ rect+ };++ Bounds {+ x: rect.origin.x as u32,+ y: rect.origin.y as u32,+ width: rect.size.width as u32,+ height: rect.size.height as u32,+ }+ })+}diff --git a/crates/media/src/platform/mod.rs b/crates/media/src/platform/mod.rsnew file mode 100644index 000000000..a63b2d184--- /dev/null+++ b/crates/media/src/platform/mod.rs@@ -0,0 +1,22 @@+#[cfg(target_os = "macos")]+#[path = "macos.rs"]+mod platform_impl;++pub use platform_impl::*;++#[derive(Debug)]+pub struct Bounds {+ pub x: u32,+ pub y: u32,+ pub width: u32,+ pub height: u32,+}++#[derive(Debug)]+pub struct Window {+ pub window_id: u32,+ pub name: String,+ pub owner_name: String,+ pub process_id: u32,+ pub bounds: Bounds,+}diff --git a/crates/media/src/sources/audio_input.rs b/crates/media/src/sources/audio_input.rsnew file mode 100644index 000000000..8697e9dd2--- /dev/null+++ b/crates/media/src/sources/audio_input.rs@@ -0,0 +1,207 @@+use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};+use cpal::{+ BufferSize, Device, SampleFormat, Stream, StreamConfig, StreamInstant, SupportedBufferSize,+ SupportedStreamConfig,+};+use flume::Sender;+use indexmap::IndexMap;++use crate::{+ data::{AudioInfo, FFAudio, RawAudioFormat},+ pipeline::{+ clock::{LocalTimestamp, SynchronisedClock},+ control::Control,+ task::PipelineSourceTask,+ },+ MediaError,+};++pub type AudioInputDeviceMap = IndexMap<String, (Device, SupportedStreamConfig)>;++impl LocalTimestamp for StreamInstant {+ fn elapsed_since(&self, other: &Self) -> std::time::Duration {+ self.duration_since(other).unwrap()+ }+}++pub struct AudioInputSource {+ device: Device,+ device_name: String,+ config: SupportedStreamConfig,+}++impl AudioInputSource {+ pub fn init(selected_audio_input: Option<&str>) -> Option<Self> {+ tracing::debug!("Selected audio input: {:?}", selected_audio_input);++ let mut devices = Self::get_devices();++ selected_audio_input+ .and_then(|device_name| devices.swap_remove_entry(device_name))+ .map(|(device_name, (device, config))| {+ tracing::info!("Using audio device: {}", device_name);++ Self {+ device,+ device_name,+ config,+ }+ })+ }++ pub fn info(&self) -> AudioInfo {+ let format = format_for(self.config.sample_format()).unwrap();+ let buffer_size = match self.config.buffer_size() {+ SupportedBufferSize::Range { max, .. } => *max,+ SupportedBufferSize::Unknown => todo!("What's a decent default value for this?"),+ };+ AudioInfo::from_raw(+ format,+ self.config.sample_rate().0,+ self.config.channels(),+ buffer_size,+ )+ }++ pub fn get_devices() -> AudioInputDeviceMap {+ let host = cpal::default_host();+ let mut device_map = IndexMap::new();++ let get_usable_device = |device: Device| {+ device+ .supported_input_configs()+ .map_err(|error| tracing::debug!("Error: {error}"))+ .ok()+ .and_then(|mut configs| configs.find(|c| format_for(c.sample_format()).is_some()))+ .and_then(|config| {+ device+ .name()+ .ok()+ .map(|name| (name, device, config.with_max_sample_rate()))+ })+ };++ if let Some((name, device, config)) =+ host.default_input_device().and_then(get_usable_device)+ {+ device_map.insert(name, (device, config));+ }++ match host.input_devices() {+ Ok(devices) => {+ for (name, device, config) in devices.filter_map(get_usable_device) {+ device_map.entry(name).or_insert((device, config));+ }+ }+ Err(error) => {+ tracing::warn!("Could not access audio input devices");+ tracing::debug!("{error}");+ }+ }++ device_map+ }++ pub fn build_stream(+ &self,+ mut clock: SynchronisedClock<StreamInstant>,+ output: Sender<FFAudio>,+ ) -> Result<Stream, MediaError> {+ let audio_info = self.info();+ let mut stream_config: StreamConfig = self.config.clone().into();+ stream_config.buffer_size = BufferSize::Fixed(audio_info.buffer_size);+ let sample_format = self.config.sample_format();++ let data_callback = move |data: &cpal::Data, info: &cpal::InputCallbackInfo| {+ let capture_time = info.timestamp().capture;+ match clock.timestamp_for(capture_time) {+ None => tracing::warn!("Clock is currently stopped. Dropping samples."),+ Some(timestamp) => {+ let buffer = audio_info.wrap_frame(data.bytes(), timestamp.try_into().unwrap());+ if let Err(_) = output.send(buffer) {+ tracing::debug!("Pipeline is unreachable. Recording will shut down.");+ }+ }+ };+ };++ let error_callback = |err| {+ // TODO: Handle errors such as device being disconnected. Some kind of fallback or pop-up?+ tracing::error!("An error occurred on the audio stream: {}", err);+ };++ self.device+ .build_input_stream_raw(+ &stream_config,+ sample_format,+ data_callback,+ error_callback,+ None,+ )+ .map_err(|error| {+ tracing::error!("Error while preparing audio capture: {error}");+ MediaError::TaskLaunch("Failed to start audio capture".into())+ })+ }+}++fn format_for(format: SampleFormat) -> Option<RawAudioFormat> {+ match format {+ SampleFormat::U8 => Some(RawAudioFormat::U8),+ SampleFormat::I16 => Some(RawAudioFormat::I16),+ SampleFormat::I32 => Some(RawAudioFormat::I32),+ SampleFormat::I64 => Some(RawAudioFormat::I64),+ SampleFormat::F32 => Some(RawAudioFormat::F32),+ SampleFormat::F64 => Some(RawAudioFormat::F64),+ _ => None,+ }+}++impl PipelineSourceTask for AudioInputSource {+ type Output = FFAudio;++ type Clock = SynchronisedClock<StreamInstant>;++ #[tracing::instrument(skip_all)]+ fn run(+ &mut self,+ clock: Self::Clock,+ ready_signal: crate::pipeline::task::PipelineReadySignal,+ mut control_signal: crate::pipeline::control::PipelineControlSignal,+ output: Sender<Self::Output>,+ ) {+ tracing::info!("Preparing audio input source thread...");++ match self.build_stream(clock, output) {+ Err(error) => ready_signal.send(Err(error)).unwrap(),+ Ok(stream) => {+ tracing::info!("Using audio input device {}", self.device_name);+ ready_signal.send(Ok(())).unwrap();++ loop {+ // TODO: Handle these more gracefully than crashing (e.g. if user unplugged mic between pausing and resuming).+ // Some kind of error stream?+ match control_signal.blocking_last() {+ Some(Control::Play) => {+ stream+ .play()+ .expect("Failed to start audio input recording");+ tracing::info!("Audio input recording started.");+ }+ Some(Control::Pause) => {+ stream+ .pause()+ .expect("Failed to pause audio input recording");+ }+ Some(Control::Shutdown) | None => {+ drop(stream);+ break;+ }+ }+ }++ tracing::info!("Shutting down audio input source thread.")+ }+ }+ }+}diff --git a/crates/media/src/sources/camera.rs b/crates/media/src/sources/camera.rsnew file mode 100644index 000000000..45b0c1ceb--- /dev/null+++ b/crates/media/src/sources/camera.rs@@ -0,0 +1,159 @@+use flume::Sender;+use nokhwa::{pixel_format::*, utils::*, Camera};+use std::time::Instant;++use crate::{+ data::{FFVideo, RawVideoFormat, VideoInfo},+ pipeline::{clock::SynchronisedClock, control::Control, task::PipelineSourceTask},+ MediaError,+};++fn create_camera(camera_info: &CameraInfo) -> Result<Camera, ()> {+ let format = RequestedFormat::new::<RgbFormat>(RequestedFormatType::AbsoluteHighestFrameRate);+ Camera::new(camera_info.index().clone(), format).map_err(|error| {+ tracing::error!("Error while initializing camera: {error}");+ })+}++pub struct CameraSource {+ info: CameraInfo,+ format: CameraFormat,+}++impl CameraSource {+ pub fn init(selected_camera: Option<&str>) -> Option<Self> {+ tracing::debug!("Selected camera: {:?}", selected_camera);++ let cameras = nokhwa::query(ApiBackend::Auto).unwrap();++ selected_camera+ .and_then(|camera_name| cameras.into_iter().find(|c| &c.human_name() == camera_name))+ .and_then(|camera_info| create_camera(&camera_info).ok())+ .and_then(|camera| {+ let format = camera.camera_format();+ if format_for(format.format()).is_some() {+ return Some(Self {+ info: camera.info().clone(),+ format,+ });+ }++ None+ })+ }++ pub fn list_cameras() -> Vec<String> {+ nokhwa::query(ApiBackend::Auto)+ .unwrap()+ .into_iter()+ .map(|i| i.human_name().to_string())+ .collect()+ }++ pub fn info(&self) -> VideoInfo {+ VideoInfo::from_raw(+ format_for(self.format.format()).unwrap(),+ self.format.width(),+ self.format.height(),+ self.format.frame_rate(),+ )+ }+}++fn format_for(format: FrameFormat) -> Option<RawVideoFormat> {+ match format {+ FrameFormat::YUYV => Some(RawVideoFormat::Yuyv),+ FrameFormat::RAWRGB => Some(RawVideoFormat::RawRgb),+ FrameFormat::NV12 => Some(RawVideoFormat::Nv12),+ _ => None,+ }+}++impl PipelineSourceTask for CameraSource {+ type Output = FFVideo;++ type Clock = SynchronisedClock<Instant>;++ #[tracing::instrument(skip_all)]+ fn run(+ &mut self,+ mut clock: Self::Clock,+ ready_signal: crate::pipeline::task::PipelineReadySignal,+ mut control_signal: crate::pipeline::control::PipelineControlSignal,+ output: Sender<Self::Output>,+ ) {+ tracing::info!("Preparing camera source thread...");++ match create_camera(&self.info) {+ Ok(mut camera) if camera.camera_format() == self.format => {+ ready_signal.send(Ok(())).unwrap();+ let mut capturing = false;+ let info = self.info();++ loop {+ match control_signal.last() {+ Some(Control::Play) => {+ if !capturing {+ camera+ .open_stream()+ .expect("Failed to start camera recording");+ capturing = true;++ tracing::info!("Camera recording started.");+ }++ match camera.frame() {+ // TODO: Set PTS in nokhwa library+ Ok(frame) => match clock.timestamp_for(Instant::now()) {+ None => {+ tracing::warn!(+ "Clock is currently stopped. Dropping frames."+ )+ }+ Some(timestamp) => {+ let buffer = info.wrap_frame(+ frame.buffer(),+ timestamp.try_into().unwrap(),+ );+ if let Err(_) = output.send(buffer) {+ tracing::warn!(+ "Pipeline is unreachable. Dropping samples."+ )+ }+ }+ },+ Err(error) => {+ tracing::error!("Capture error: {error}");+ break;+ }+ }+ }+ Some(Control::Pause) => {+ if capturing {+ camera+ .stop_stream()+ .expect("Failed to halt camera recording");+ capturing = false;+ }+ }+ Some(Control::Shutdown) | None => {+ if capturing {+ camera+ .stop_stream()+ .expect("Failed to halt camera recording");+ }+ break;+ }+ }+ }+ }+ _ => ready_signal+ .send(Err(MediaError::TaskLaunch(+ "Failed to create camera stream".into(),+ )))+ .unwrap(),+ };++ tracing::info!("Shutting down screen capture source thread.");+ }+}diff --git a/crates/media/src/sources/mod.rs b/crates/media/src/sources/mod.rsnew file mode 100644index 000000000..926c0f48c--- /dev/null+++ b/crates/media/src/sources/mod.rs@@ -0,0 +1,7 @@+mod audio_input;+mod camera;+mod screen_capture;++pub use audio_input::*;+pub use camera::*;+pub use screen_capture::*;diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rsnew file mode 100644index 000000000..d33bf3639--- /dev/null+++ b/crates/media/src/sources/screen_capture.rs@@ -0,0 +1,201 @@+use flume::Sender;+use scap::{+ capturer::{get_output_frame_size, Capturer, Options, Resolution},+ frame::{Frame, FrameType},+ Target,+};+use serde::Serialize;+use specta::Type;+use std::collections::HashSet;++use crate::data::{FFVideo, RawVideoFormat, VideoInfo};+use crate::pipeline::{clock::*, control::Control, task::PipelineSourceTask};++static EXCLUDED_WINDOWS: [&'static str; 4] = [+ "Cap",+ "Cap Camera",+ "Cap Recordings",+ "Cap In Progress Recording",+];++#[derive(Serialize, Type)]+pub enum CaptureTarget {+ Window { id: u32, name: String },+ Screen { id: u32, name: String },+}++impl PartialEq<Target> for CaptureTarget {+ fn eq(&self, other: &Target) -> bool {+ match (self, other) {+ (Self::Window { id, .. }, Target::Window(window)) => window.id == *id,+ (Self::Screen { id, .. }, Target::Display(display)) => display.id == *id,+ _ => false,+ }+ }+}++pub struct ScreenCaptureSource {+ options: Options,+ video_info: VideoInfo,+}++impl ScreenCaptureSource {+ pub const DEFAULT_FPS: u32 = 30;++ // TODO: Settings that can be passed here to control video quality+ pub fn init(+ capture_target: &CaptureTarget,+ fps: Option<u32>,+ resolution: Option<Resolution>,+ ) -> Self {+ let fps = fps.unwrap_or(Self::DEFAULT_FPS);+ let output_resolution = resolution.unwrap_or(Resolution::Captured);+ let targets = scap::get_all_targets();++ // warning: this will fall back to the default display if the selected capture target+ // is not in the current list+ let target = targets+ .iter()+ .find(|target| capture_target.eq(target))+ .cloned();+ let excluded_targets: Vec<scap::Target> = targets+ .into_iter()+ .filter(|target| match target {+ Target::Window(scap_window)+ if EXCLUDED_WINDOWS.contains(&scap_window.title.as_str()) =>+ {+ true+ }+ _ => false,+ })+ .collect();++ let options = Options {+ fps,+ target,+ show_cursor: true,+ show_highlight: true,+ excluded_targets: Some(excluded_targets),+ output_type: FrameType::BGRAFrame,+ output_resolution,+ crop_area: None,+ };++ let [frame_width, frame_height] = get_output_frame_size(&options);++ Self {+ options,+ video_info: VideoInfo::from_raw(RawVideoFormat::Bgra, frame_width, frame_height, fps),+ }+ }++ pub fn list_targets() -> Vec<CaptureTarget> {+ if !scap::has_permission() {+ return vec![];+ }++ let targets = scap::get_all_targets();++ let valid_window_ids: HashSet<u32> = crate::platform::get_on_screen_windows()+ .iter()+ .map(|window| window.window_id)+ .collect();++ targets+ .into_iter()+ .filter_map(|target| match target {+ Target::Window(window) => match valid_window_ids.contains(&window.id) {+ true => Some(CaptureTarget::Window {+ id: window.id,+ name: window.title,+ }),+ false => None,+ },+ Target::Display(display) => Some(CaptureTarget::Screen {+ id: display.id,+ name: display.title,+ }),+ })+ .collect()+ }++ pub fn info(&self) -> VideoInfo {+ self.video_info+ }+}++impl PipelineSourceTask for ScreenCaptureSource {+ type Clock = SynchronisedClock<RawNanoseconds>;+ type Output = FFVideo;++ #[tracing::instrument(skip_all)]+ fn run(+ &mut self,+ mut clock: Self::Clock,+ ready_signal: crate::pipeline::task::PipelineReadySignal,+ mut control_signal: crate::pipeline::control::PipelineControlSignal,+ output: Sender<Self::Output>,+ ) {+ tracing::info!("Preparing screen capture source thread...");++ let mut capturer = Capturer::new(self.options.clone());+ let mut capturing = false;+ let _ = ready_signal.send(Ok(())).unwrap();++ loop {+ match control_signal.last() {+ Some(Control::Play) => {+ if !capturing {+ capturer.start_capture();+ capturing = true;++ tracing::info!("Screen recording started.");+ }++ match capturer.get_next_frame() {+ Ok(Frame::BGRA(frame)) => {+ let raw_timestamp = RawNanoseconds(frame.display_time);+ match clock.timestamp_for(raw_timestamp) {+ None => {+ tracing::warn!("Clock is currently stopped. Dropping frames.")+ }+ Some(timestamp) => {+ // TODO: I wonder if we should do stride adjustments here or leave it for later (as it is now).+ let buffer = self.video_info.wrap_frame(&frame.data, timestamp);++ if let Err(_) = output.send(buffer) {+ tracing::error!(+ "Pipeline is unreachable. Shutting down recording."+ );+ break;+ }+ }+ };+ }+ Ok(_) => unreachable!(),+ Err(error) => {+ tracing::error!("Capture error: {error}");+ break;+ }+ }+ }+ Some(Control::Pause) => {+ tracing::info!("Received pause signal");+ if capturing {+ capturer.stop_capture();+ capturing = false;+ }+ }+ Some(Control::Shutdown) | None => {+ tracing::info!("Received shutdown signal");+ if capturing {+ capturer.stop_capture();+ }+ break;+ }+ }+ }++ tracing::info!("Shutting down screen capture source thread.");+ }+}diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.tomlindex 1e4db5cbf..57a018e17 100644--- a/crates/rendering/Cargo.toml+++ b/crates/rendering/Cargo.toml@@ -4,7 +4,7 @@ version = "0.1.0"edition = "2021"[dependencies]-anyhow = "1.0.86"+anyhow.workspace = truebytemuck = { version = "1.7", features = ["derive"] }futures-intrusive = "0.5.0"serde = "1.0.209"@@ -13,15 +13,10 @@ wgpu = "22.1.0"cap-ffmpeg = { path = "../ffmpeg" }cap-project = { path = "../project" }-tokio = { version = "1.39.3", features = [- "macros",- "sync",- "rt",- "rt-multi-thread",-] }+tokio.workspace = truenix = { version = "0.29.0", features = ["fs"] }serde_json = "1.0.127"ffmpeg.workspace = truelru = "0.12.4"-ffmpeg-sys-next = "7.0.2"+ffmpeg-sys-next.workspace = truefutures = "0.3.30"