Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Better audio support, step one (#159)
PJ38ebea99f1e2
diff --git a/Cargo.lock b/Cargo.lockindex f025fdecf..a63ba98e6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -754,9 +754,10 @@ version = "0.1.0"dependencies = ["axum","cap-ffmpeg-cli",+ "cap-media","cap-project","cap-rendering",- "cpal",+ "cpal 0.15.3 (git+https://github.com/RustAudio/cpal?rev=f43d36e55494993bbbde3299af0c53e5cdf4d4cf)","ffmpeg-next","serde","serde_json",@@ -802,7 +803,7 @@ dependencies = ["cocoa 0.26.0","core-foundation 0.10.0","core-graphics 0.24.0",- "cpal",+ "cpal 0.15.3 (git+https://github.com/RustAudio/cpal?rev=f43d36e55494993bbbde3299af0c53e5cdf4d4cf)","ffmpeg-hw-device","ffmpeg-next","ffmpeg-sys-next",@@ -811,9 +812,11 @@ dependencies = ["indexmap 2.5.0","nokhwa","nokhwa-bindings-macos",+ "num-traits","objc","objc-foundation","objc2-foundation",+ "ringbuf","scap","serde","specta",@@ -1401,6 +1404,28 @@ dependencies = ["windows 0.54.0",]+[[package]]+name = "cpal"+version = "0.15.3"+source = "git+https://github.com/RustAudio/cpal?rev=f43d36e55494993bbbde3299af0c53e5cdf4d4cf#f43d36e55494993bbbde3299af0c53e5cdf4d4cf"+dependencies = [+ "alsa",+ "core-foundation-sys 0.8.7",+ "coreaudio-rs",+ "dasp_sample",+ "jni",+ "js-sys",+ "libc",+ "mach2",+ "ndk 0.8.0",+ "ndk-context",+ "oboe",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "windows 0.54.0",+]+[[package]]name = "cpufeatures"version = "0.2.13"@@ -1628,7 +1653,7 @@ dependencies = [[[package]]name = "desktop"-version = "0.3.0-beta.8"+version = "0.3.0-beta.9-audio-rc"dependencies = ["anyhow","axum",@@ -1645,7 +1670,6 @@ dependencies = ["cocoa 0.26.0","core-foundation 0.10.0","core-graphics 0.24.0",- "cpal","device_query","dotenvy_macro","fast_image_resize",@@ -4970,6 +4994,12 @@ dependencies = ["windows-sys 0.59.0",]+[[package]]+name = "portable-atomic"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc9c68a3f6da06753e9335d63e27f6b9754dd1920d941135b7ea8224f141adb2"+[[package]]name = "powerfmt"version = "0.2.0"@@ -5519,6 +5549,16 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "ringbuf"+version = "0.4.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "726bb493fe9cac765e8f96a144c3a8396bdf766dedad22e504b70b908dcbceb4"+dependencies = [+ "crossbeam-utils",+ "portable-atomic",+]+[[package]]name = "rodio"version = "0.19.0"@@ -5526,7 +5566,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6006a627c1a38d37f3d3a85c6575418cfe34a5392d60a686d0071e1c8d427acb"dependencies = ["claxon",- "cpal",+ "cpal 0.15.3 (registry+https://github.com/rust-lang/crates.io-index)","hound","lewton","symphonia",diff --git a/Cargo.toml b/Cargo.tomlindex 29b82b2b9..580dd7d74 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -4,6 +4,9 @@ members = ["apps/desktop/src-tauri", "crates/*"][workspace.dependencies]anyhow = "1.0.86"+# This includes a currently-unreleased fix that ensures the audio stream is actually+# stopped and released on drop on macOS+cpal = { git = "https://github.com/RustAudio/cpal", rev = "f43d36e55494993bbbde3299af0c53e5cdf4d4cf" }ffmpeg = { package = "ffmpeg-next", git = "https://github.com/CapSoftware/rust-ffmpeg", rev = "91b29d09a8c7cb4f5659c38f1f0924b980a30cba" }ffmpeg-sys-next = "7.1.0"tokio = { version = "1.39.3", features = [diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex f2f1273dd..5be87f7c5 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "desktop"-version = "0.3.0-beta.8"+version = "0.3.0-beta.9-audio-rc"description = "Beautiful, shareable screen recordings."authors = ["you"]edition = "2021"@@ -56,7 +56,6 @@ mp4 = "0.14.0"futures = "0.3.30"axum = { version = "0.7.5", features = ["ws"] }tracing = "0.1.40"-cpal = "0.15.3"indexmap = "2.5.0"num-traits = "0.2.19"tempfile = "3.12.0"diff --git a/apps/desktop/src-tauri/Info.plist b/apps/desktop/src-tauri/Info.plistindex b6bcad2c9..dd740dcf9 100644--- a/apps/desktop/src-tauri/Info.plist+++ b/apps/desktop/src-tauri/Info.plist@@ -27,5 +27,7 @@<string>Cap uses your microphone to record you in your Caps</string><key>NSScreenCaptureUsageDescription</key><string>Cap captures your screen as part of recording your Caps</string>+ <key>NSCameraUseContinuityCameraDeviceType</key>+ <true/></dict></plist>diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 7fce99ff9..24c81747d 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -17,11 +17,11 @@ mod windows;use audio::AppSounds;use auth::{AuthStore, AuthenticationInvalid};-use cap_editor::{AudioData, EditorState, ProjectRecordings};use cap_editor::{EditorInstance, FRAMES_WS_PATH};+use cap_editor::{EditorState, ProjectRecordings};use cap_media::sources::CaptureScreen;use cap_media::{- feeds::{CameraFeed, CameraFrameSender},+ feeds::{AudioData, AudioFrameBuffer, CameraFeed, CameraFrameSender},platform::Bounds,sources::{AudioInputSource, ScreenCaptureTarget},};@@ -955,8 +955,8 @@ async fn open_file_path(app: AppHandle, path: PathBuf) -> Result<(), String> {}struct AudioRender {- data: AudioData,- pipe_tx: tokio::sync::mpsc::Sender<Vec<f64>>,+ buffer: AudioFrameBuffer,+ pipe_tx: tokio::sync::mpsc::Sender<Vec<u8>>,}async fn render_to_file_impl(@@ -1017,7 +1017,7 @@ async fn render_to_file_impl(tx};- let audio = if let Some(audio_data) = audio.lock().unwrap().as_ref() {+ let mut audio = if let Some(audio_data) = audio.lock().unwrap().as_ref() {let pipe_path = audio_dir.path().join("audio.pipe");#[cfg(target_os = "macos")]@@ -1026,29 +1026,26 @@ async fn render_to_file_impl(ffmpeg.add_input(cap_ffmpeg_cli::FFmpegRawAudioInput {input: pipe_path.clone().into_os_string(),sample_format: "f64le".to_string(),- sample_rate: audio_data.sample_rate,- channels: 1,+ sample_rate: audio_data.info.sample_rate,+ channels: audio_data.info.channels as u16,});- let (tx, mut rx) = tokio::sync::mpsc::channel::<Vec<f64>>(30);+ let (tx, mut rx) = tokio::sync::mpsc::channel::<Vec<u8>>(30);tokio::spawn(async move {let mut file = std::fs::File::create(&pipe_path).unwrap();println!("audio pipe opened");while let Some(bytes) = rx.recv().await {- let bytes = bytes- .iter()- .flat_map(|f| f.to_le_bytes())- .collect::<Vec<_>>();file.write_all(&bytes).unwrap();}println!("done writing to audio pipe");});+ let buffer = AudioFrameBuffer::new(audio_data.clone());Some(AudioRender {- data: audio_data.clone(),+ buffer,pipe_tx: tx,})} else {@@ -1078,29 +1075,20 @@ async fn render_to_file_impl(first_frame = Some(frame.clone());}- if let Some(audio) = &audio {- let samples_per_frame = audio.data.sample_rate as f64 / FPS as f64;-- let start_samples = match project.timeline() {- Some(timeline) => timeline- .get_recording_time(frame_count as f64 / FPS as f64)- .map(|recording_time| {- recording_time * audio.data.sample_rate as f64- }),- None => Some(frame_count as f64 * samples_per_frame),- };-- if let Some(start) = start_samples {- let end = start + samples_per_frame;-- let samples = &audio.data.buffer[start as usize..end as usize];- let mut samples_iter = samples.iter().copied();+ if let Some(audio) = &mut audio {+ if frame_count == 0 {+ audio.buffer.set_playhead(0., project.timeline());+ }- let mut frame_samples = Vec::new();- for _ in 0..samples_per_frame as usize {- frame_samples.push(samples_iter.next().unwrap_or(0.0));- }+ let audio_info = audio.buffer.info();+ let estimated_samples_per_frame =+ f64::from(audio_info.sample_rate) / f64::from(FPS);+ let samples = estimated_samples_per_frame.ceil() as usize;+ if let Some((_, frame_data)) =+ audio.buffer.next_frame_data(samples, project.timeline())+ {+ let frame_samples = frame_data.to_vec();audio.pipe_tx.send(frame_samples).await.unwrap();}}diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 8d0021a1b..cbad0e821 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -41,7 +41,7 @@ pub struct InProgressRecording {pub id: String,pub recording_dir: PathBuf,#[serde(skip)]- pub pipeline: Pipeline<SynchronisedClock<()>>,+ pub pipeline: Pipeline<RealTimeClock<()>>,#[serde(skip)]pub display_output_path: PathBuf,#[serde(skip)]@@ -194,7 +194,7 @@ pub async fn start(std::fs::create_dir_all(&content_dir).unwrap();std::fs::create_dir_all(&cursors_dir).unwrap();- let clock = SynchronisedClock::<()>::new();+ let clock = RealTimeClock::<()>::new();let mut pipeline_builder = Pipeline::builder(clock);let display_output_path = content_dir.join("display.mp4");diff --git a/crates/editor/Cargo.toml b/crates/editor/Cargo.tomlindex 240fa47c3..ec8c9c08d 100644--- a/crates/editor/Cargo.toml+++ b/crates/editor/Cargo.toml@@ -4,13 +4,15 @@ version = "0.1.0"edition = "2021"[dependencies]++cap-media = { path = "../media" }cap-project = { path = "../project" }cap-ffmpeg-cli = { path = "../ffmpeg-cli" }cap-rendering = { path = "../rendering" }tokio = { version = "1.39.2", features = ["macros", "process", "fs"] }tracing = "0.1.40"-cpal = "0.15.3"+cpal.workspace = trueserde_json = "1.0.128"axum = { version = "0.7.5", features = ["ws"] }ffmpeg.workspace = truediff --git a/crates/editor/src/audio.rs b/crates/editor/src/audio.rsdeleted file mode 100644index 1eb72a46e..000000000--- a/crates/editor/src/audio.rs+++ /dev/null@@ -1,8 +0,0 @@-use std::sync::Arc;--#[derive(Clone)]-pub struct AudioData {- pub buffer: Arc<Vec<f64>>,- pub sample_rate: u32,- // pub channels: u18-}diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex 1dbd65e8b..16bb6987b 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -1,8 +1,7 @@-use crate::audio::AudioData;use crate::editor;use crate::playback::{self, PlaybackHandle};use crate::project_recordings::ProjectRecordings;-use cap_ffmpeg_cli::FFmpeg;+use cap_media::feeds::AudioData;use cap_project::{CursorData, ProjectConfiguration, RecordingMeta, XY};use cap_rendering::decoder::AsyncVideoDecoder;use cap_rendering::{ProjectUniforms, RecordingDecoders, RenderOptions, RenderVideoConstants};@@ -74,37 +73,11 @@ impl EditorInstance {.as_ref().map(|camera| AsyncVideoDecoder::spawn(project_path.join(&camera.path).clone()));- let audio = meta- .audio- .as_ref()- .zip(recordings.audio)- .map(|(meta, recording)| {- let audio_path = project_path.join(&meta.path);-- // TODO: Use ffmpeg crate instead of command line- let stdout = FFmpeg::new()- .command- .arg("-i")- .arg(audio_path)- .args(["-f", "f64le", "-acodec", "pcm_f64le"])- .args(["-ar", &recording.sample_rate.to_string()])- .args(["-ac", &recording.channels.to_string(), "-"])- .output()- .unwrap()- .stdout;-- let buffer = stdout- .chunks_exact(8)- .map(|c| f64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]))- .collect::<Vec<_>>();-- println!("audio buffer length: {}", buffer.len());-- AudioData {- buffer: Arc::new(buffer),- sample_rate: recording.sample_rate,- }- });+ let audio = meta.audio.as_ref().map(|meta| {+ let audio_path = project_path.join(&meta.path);++ AudioData::from_file(audio_path).unwrap()+ });let (frame_tx, frame_rx) = tokio::sync::mpsc::unbounded_channel();diff --git a/crates/editor/src/lib.rs b/crates/editor/src/lib.rsindex 37c400383..4329334c5 100644--- a/crates/editor/src/lib.rs+++ b/crates/editor/src/lib.rs@@ -1,9 +1,7 @@-mod audio;mod editor;mod editor_instance;mod playback;mod project_recordings;-pub use audio::AudioData;pub use editor_instance::{EditorInstance, EditorState, FRAMES_WS_PATH};pub use project_recordings::ProjectRecordings;diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rsindex b60981a42..0298acd26 100644--- a/crates/editor/src/playback.rs+++ b/crates/editor/src/playback.rs@@ -1,14 +1,16 @@use std::{sync::Arc, sync::Mutex as StdMutex, time::Duration};+use cap_media::data::{AudioInfo, FromSampleBytes};+use cap_media::feeds::{AudioData, AudioPlaybackBuffer};use cap_project::ProjectConfiguration;use cap_rendering::{ProjectUniforms, RecordingDecoders, RenderVideoConstants};use cpal::{traits::{DeviceTrait, HostTrait, StreamTrait},- SampleFormat, SizedSample,+ BufferSize, SampleFormat,};use tokio::{sync::watch, time::Instant};-use crate::{audio::AudioData, editor, project_recordings::ProjectRecordings};+use crate::{editor, project_recordings::ProjectRecordings};pub struct Playback {pub audio: Arc<StdMutex<Option<AudioData>>>,@@ -148,102 +150,84 @@ struct AudioPlayback {}impl AudioPlayback {- fn spawn(mut self) {+ fn spawn(self) {let handle = tokio::runtime::Handle::current();std::thread::spawn(move || {- let audio = self.audio;-let host = cpal::default_host();let device = host.default_output_device().unwrap();+ println!("Output device: {}", device.name().unwrap());let supported_config = device.default_output_config().expect("Failed to get default output format");- let mut config = supported_config.config();- config.channels = 1;-- let data = audio.buffer.clone();- let duration = data.len() as f64 / audio.sample_rate as f64;- let mut time = self.start_frame_number as f64 / FPS as f64;-- let time_inc = 1.0 / config.sample_rate.0 as f64;-- let mut clock =- data.len() as f64 * self.start_frame_number as f64 / (FPS as f64 * self.duration);-- let resample_ratio = audio.sample_rate as f64 / config.sample_rate.0 as f64;-- let next_sample = move || {- time += time_inc;- let time = self.project.borrow().timeline()?.get_recording_time(time)?;-- let index = time / duration * data.len() as f64;-- clock += resample_ratio;-- if clock >= data.len() as f64 {- return None;- }-- // Add a check to prevent index_int from going out of bounds- let index_int = index as usize;- if index_int >= data.len() - 1 {- return None;- }-- let frac = index.fract();- let current = data[index_int];- let next = data[(index_int + 1) % data.len()];- Some(current * (1.0 - frac) + next * frac)- };- let shared_data = (&device, &config, next_sample);- let stream = match supported_config.sample_format() {- SampleFormat::I8 => create_stream::<i8>(shared_data),- SampleFormat::I16 => create_stream::<i16>(shared_data),- SampleFormat::I32 => create_stream::<i32>(shared_data),- SampleFormat::I64 => create_stream::<i64>(shared_data),- SampleFormat::U8 => create_stream::<u8>(shared_data),- SampleFormat::U16 => create_stream::<u16>(shared_data),- SampleFormat::U32 => create_stream::<u32>(shared_data),- SampleFormat::U64 => create_stream::<u64>(shared_data),- SampleFormat::F32 => create_stream::<f32>(shared_data),- SampleFormat::F64 => create_stream::<f64>(shared_data),+ let (mut stop_rx, stream) = match supported_config.sample_format() {+ // SampleFormat::I8 => create_stream::<i8>(shared_data),+ SampleFormat::I16 => self.create_stream::<i16>(device, supported_config),+ SampleFormat::I32 => self.create_stream::<i32>(device, supported_config),+ SampleFormat::I64 => self.create_stream::<i64>(device, supported_config),+ SampleFormat::U8 => self.create_stream::<u8>(device, supported_config),+ // SampleFormat::U16 => create_stream::<u16>(shared_data),+ // SampleFormat::U32 => create_stream::<u32>(shared_data),+ // SampleFormat::U64 => create_stream::<u64>(shared_data),+ SampleFormat::F32 => self.create_stream::<f32>(device, supported_config),+ SampleFormat::F64 => self.create_stream::<f64>(device, supported_config),_ => unimplemented!(),};- fn create_stream<T: SizedSample + cpal::FromSample<f64> + 'static>(- (device, config, mut next_sample): (- &cpal::Device,- &cpal::StreamConfig,- impl FnMut() -> Option<f64> + Send + 'static,- ),- ) -> cpal::Stream {- device- .build_output_stream(- config,- move |buffer: &mut [T], _info| {- for sample in buffer.iter_mut() {- let Some(s) = next_sample() else {- *sample = T::EQUILIBRIUM;- continue;- };- let value = cpal::Sample::from_sample::<f64>(s);- *sample = value;- }- },- |_| {},- None,- )- .unwrap()- }-stream.play().unwrap();- handle.block_on(self.stop_rx.changed()).ok();+ handle.block_on(stop_rx.changed()).ok();stream.pause().ok();drop(stream);});}++ fn create_stream<T: FromSampleBytes>(+ self,+ device: cpal::Device,+ supported_config: cpal::SupportedStreamConfig,+ ) -> (watch::Receiver<bool>, cpal::Stream) {+ let AudioPlayback {+ audio,+ stop_rx,+ start_frame_number,+ project,+ ..+ } = self;++ let mut output_info = AudioInfo::from_stream_config(&supported_config);+ output_info.sample_format = output_info.sample_format.packed();++ // TODO: Get fps and duration from video (once we start supporting other frame rates)+ // Also, it's a bit weird that self.duration can ever be infinity to begin with, since+ // pre-recorded videos are obviously a fixed size+ let mut audio_renderer = AudioPlaybackBuffer::new(audio, output_info);+ let playhead = f64::from(start_frame_number) / f64::from(FPS);+ audio_renderer.set_playhead(playhead, project.borrow().timeline());++ // Prerender enough for smooth playback+ while !audio_renderer.buffer_reaching_limit() {+ audio_renderer.render(project.borrow().timeline());+ }++ let mut config = supported_config.config();+ // Low-latency playback+ config.buffer_size = BufferSize::Fixed(AudioPlaybackBuffer::<T>::PLAYBACK_SAMPLES_COUNT);++ let stream = device+ .build_output_stream(+ &config,+ move |buffer: &mut [T], _info| {+ audio_renderer.render(project.borrow().timeline());+ audio_renderer.fill(buffer);+ },+ |_| {},+ None,+ )+ .unwrap();++ (stop_rx, stream)+ }}diff --git a/crates/editor/src/project_recordings.rs b/crates/editor/src/project_recordings.rsindex d78e9a05c..04906f6c9 100644--- a/crates/editor/src/project_recordings.rs+++ b/crates/editor/src/project_recordings.rs@@ -42,7 +42,7 @@ impl Audio {let input = ffmpeg::format::input(path).unwrap();let stream = input.streams().best(ffmpeg::media::Type::Audio).unwrap();- let video_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters())+ let audio_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters()).unwrap().decoder().audio()@@ -50,8 +50,8 @@ impl Audio {Audio {duration: input.duration() as f64 / 1_000_000.0,- sample_rate: video_decoder.rate(),- channels: video_decoder.channels(),+ sample_rate: audio_decoder.rate(),+ channels: audio_decoder.channels(),}}}diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.tomlindex 4e3182d83..6e5b2d22e 100644--- a/crates/media/Cargo.toml+++ b/crates/media/Cargo.toml@@ -10,14 +10,16 @@ anyhow.workspace = truecap-project = { path = "../project" }cap-flags = { path = "../flags" }cap-gpu-converters = { path = "../gpu-converters" }-cpal = "0.15.3"+cpal.workspace = trueffmpeg.workspace = trueffmpeg-sys-next.workspace = trueffmpeg-hw-device = { path = "../ffmpeg-hw-device" }flume = "0.11.0"indexmap = "2.5.0"-scap.workspace = truenokhwa = { workspace = true, features = ["input-native", "serialize"] }+num-traits = "0.2.19"+ringbuf = "0.4.7"+scap.workspace = trueserde = { version = "1", features = ["derive"] }specta.workspace = truetempfile = "3.12.0"diff --git a/crates/media/src/data.rs b/crates/media/src/data.rsindex f594bb2a5..131ce1190 100644--- a/crates/media/src/data.rs+++ b/crates/media/src/data.rs@@ -1,3 +1,4 @@+use cpal::{SampleFormat, SupportedBufferSize, SupportedStreamConfig};pub use ffmpeg::format::{pixel::Pixel,sample::{Sample, Type},@@ -8,16 +9,7 @@ pub use ffmpeg::util::{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 use ffmpeg::{error::EAGAIN, Error as FFError, Packet as FFPacket};pub enum RawVideoFormat {Bgra,@@ -29,46 +21,108 @@ pub enum RawVideoFormat {YUYV420,}-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),+pub fn ffmpeg_sample_format_for(sample_format: SampleFormat) -> Option<Sample> {+ match sample_format {+ SampleFormat::U8 => Some(Sample::U8(Type::Planar)),+ SampleFormat::I16 => Some(Sample::I16(Type::Planar)),+ SampleFormat::I32 => Some(Sample::I32(Type::Planar)),+ SampleFormat::I64 => Some(Sample::I64(Type::Planar)),+ SampleFormat::F32 => Some(Sample::F32(Type::Planar)),+ SampleFormat::F64 => Some(Sample::F64(Type::Planar)),+ _ => None,+ }+}++pub trait PlanarData {+ fn plane_data(&self, index: usize) -> &[u8];++ fn plane_data_mut(&mut self, index: usize) -> &mut [u8];+}++// The ffmpeg crate's implementation of the `data_mut` function is wrong for audio;+// per [the FFmpeg docs](https://www.ffmpeg.org/doxygen/7.0/structAVFrame.html]) only+// the linesize of the first plane may be set for planar audio, and so we need to use+// that linesize for the rest of the planes (else they will appear to be empty slices).+impl PlanarData for FFAudio {+ #[inline]+ fn plane_data(&self, index: usize) -> &[u8] {+ if index >= self.planes() {+ panic!("out of bounds");+ }++ unsafe {+ std::slice::from_raw_parts(+ (*self.as_ptr()).data[index],+ (*self.as_ptr()).linesize[0] as usize,+ )+ }+ }++ #[inline]+ fn plane_data_mut(&mut self, index: usize) -> &mut [u8] {+ if index >= self.planes() {+ panic!("out of bounds");+ }++ unsafe {+ std::slice::from_raw_parts_mut(+ (*self.as_mut_ptr()).data[index],+ (*self.as_ptr()).linesize[0] as usize,+ )}}}-#[derive(Debug, Copy, Clone)]+#[derive(Debug, Copy, Clone, PartialEq, Eq)]pub struct AudioInfo {pub sample_format: Sample,- sample_rate: u32,- channels: usize,+ pub sample_rate: u32,+ pub 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 {+ pub fn new(sample_format: Sample, sample_rate: u32, channel_count: u16) -> Self {Self {- sample_format: format.into(),+ sample_format,sample_rate,- channels: channels.into(),+ channels: channel_count.into(),+ time_base: FFRational(1, 1_000_000),+ buffer_size: 1024,+ }+ }++ pub fn from_stream_config(config: &SupportedStreamConfig) -> Self {+ let sample_format = ffmpeg_sample_format_for(config.sample_format()).unwrap();+ let buffer_size = match config.buffer_size() {+ SupportedBufferSize::Range { max, .. } => *max,+ // TODO: Different buffer sizes for different contexts?+ SupportedBufferSize::Unknown => 1024,+ };++ Self {+ sample_format,+ sample_rate: config.sample_rate().0,+ channels: config.channels().into(),time_base: FFRational(1, 1_000_000),buffer_size,}}+ pub fn from_decoder(decoder: &ffmpeg::codec::decoder::Audio) -> Self {+ Self {+ sample_format: decoder.format(),+ sample_rate: decoder.rate(),+ // TODO: Use channel layout when we support more than just mono/stereo+ channels: usize::from(decoder.channels()),+ time_base: decoder.time_base(),+ buffer_size: decoder.frame_size(),+ }+ }+pub fn sample_size(&self) -> usize {- self.sample_format.bytes() * self.channels+ self.sample_format.bytes()}pub fn rate(&self) -> i32 {@@ -85,14 +139,44 @@ impl AudioInfo {}}+ pub fn empty_frame(&self, sample_count: usize) -> FFAudio {+ let mut frame = FFAudio::new(self.sample_format, sample_count, self.channel_layout());+ frame.set_rate(self.sample_rate);++ frame+ }+pub fn wrap_frame(&self, data: &[u8], timestamp: i64) -> FFAudio {- let samples = data.len() / self.sample_size();+ let sample_size = self.sample_size();+ let interleaved_chunk_size = sample_size * self.channels;+ let samples = data.len() / interleaved_chunk_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);++ match self.channels {+ 0 => unreachable!(),+ 1 => frame.plane_data_mut(0)[0..data.len()].copy_from_slice(data),+ // cpal *always* returns interleaved data (i.e. the first sample from every channel, followed+ // by the second sample from every channel, et cetera). Many audio codecs work better/primarily+ // with planar data, so we de-interleave it here if there is more than one channel.+ channel_count => {+ for (chunk_index, interleaved_chunk) in+ data.chunks(interleaved_chunk_size).enumerate()+ {+ let start = chunk_index * sample_size;+ let end = start + sample_size;++ for channel in 0..channel_count {+ let channel_start = channel * sample_size;+ let channel_end = channel_start + sample_size;+ frame.plane_data_mut(channel)[start..end]+ .copy_from_slice(&interleaved_chunk[channel_start..channel_end]);+ }+ }+ }+ }frame}@@ -164,3 +248,25 @@ impl VideoInfo {frame}}++pub trait FromSampleBytes: cpal::SizedSample + std::fmt::Debug + Send + 'static {+ const BYTE_SIZE: usize;++ fn from_bytes(bytes: &[u8]) -> Self;+}++macro_rules! sample_bytes {+ ( $( $num:ty, $size:literal ),* ) => (+ $(+ impl FromSampleBytes for $num {+ const BYTE_SIZE: usize = $size;++ fn from_bytes(bytes: &[u8]) -> Self {+ Self::from_le_bytes(bytes.try_into().expect("Incorrect byte slice length"))+ }+ }+ )*+ )+}++sample_bytes!(u8, 1, i16, 2, i32, 4, i64, 8, f32, 4, f64, 8);diff --git a/crates/media/src/encoders/mp3.rs b/crates/media/src/encoders/mp3.rsindex 1ef27ae49..8215ac50b 100644--- a/crates/media/src/encoders/mp3.rs+++ b/crates/media/src/encoders/mp3.rs@@ -6,7 +6,7 @@ use ffmpeg::{use std::collections::VecDeque;use crate::{- data::{AudioInfo, FFAudio, FFPacket, FFRational},+ data::{AudioInfo, FFAudio, FFPacket, FFRational, PlanarData},pipeline::task::PipelineSinkTask,MediaError,};@@ -17,10 +17,7 @@ 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,+ buffer: AudioBuffer,}impl MP3Encoder {@@ -29,7 +26,6 @@ impl MP3Encoder {pub fn init(tag: &'static str, config: AudioInfo, output: Output) -> Result<Self, MediaError> {let Output::File(destination) = output;let mut output_ctx = format::output(&destination)?;- println!("Sample format: {:#?}", config.sample_format);let codec = encoder::find(ffmpeg::codec::Id::MP3).ok_or(MediaError::TaskLaunch("Could not find MP3 codec".into()))?;@@ -50,47 +46,19 @@ impl MP3Encoder {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,+ buffer: AudioBuffer::new(config, &audio_encoder),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();+ self.buffer.consume(frame);+ while let Some(buffered_frame) = self.buffer.next_frame() {+ self.encoder.send_frame(&buffered_frame).unwrap();+ self.process_packets();}}@@ -110,7 +78,6 @@ impl MP3Encoder {}fn finish(&mut self) {- // self.queue_frames_from_buffer();self.encoder.send_eof().unwrap();self.process_packets();self.output_ctx.write_trailer().unwrap();@@ -138,3 +105,70 @@ impl PipelineSinkTask for MP3Encoder {println!("Shutting down {} audio encoding thread", self.tag);}}++#[derive(Debug)]+struct AudioBuffer {+ current_pts: i64,+ data: Vec<VecDeque<u8>>,+ frame_size: usize,+ config: AudioInfo,+}++impl AudioBuffer {+ fn new(config: AudioInfo, encoder: &encoder::Audio) -> Self {+ let sample_size = config.sample_size();+ let frame_buffer_size = usize::try_from(config.buffer_size).unwrap() * sample_size;++ Self {+ current_pts: 0,+ data: vec![VecDeque::with_capacity(frame_buffer_size); config.channels],+ frame_size: encoder.frame_size().try_into().unwrap(),+ config,+ }+ }++ fn is_empty(&self) -> bool {+ self.data[0].is_empty()+ }++ fn len(&self) -> usize {+ self.data[0].len()+ }++ fn consume(&mut self, frame: FFAudio) {+ // TODO: Set PTS from frame with ffmpeg::sys::av_rescale_q??+ // if let Some(pts) = frame.pts() {+ // self.current_pts = pts;+ // }+ for channel in 0..self.config.channels {+ // if self.current_pts == 0 {+ // println!("Data in channel {channel}: {:?}", frame.data(channel));+ // }+ self.data[channel].extend(frame.plane_data(channel));+ }+ }++ fn next_frame(&mut self) -> Option<FFAudio> {+ if self.is_empty() {+ return None;+ }++ let frame_size = self.frame_size * self.config.sample_size();++ if self.len() < frame_size {+ return None;+ }++ let mut frame = self.config.empty_frame(self.frame_size);+ frame.set_pts(Some(self.current_pts));++ for channel in 0..self.config.channels {+ for (index, byte) in self.data[channel].drain(0..frame_size).enumerate() {+ frame.plane_data_mut(channel)[index] = byte;+ }+ }++ self.current_pts += i64::try_from(frame_size / self.config.sample_size()).unwrap();+ Some(frame)+ }+}diff --git a/crates/media/src/feeds/audio.rs b/crates/media/src/feeds/audio.rsnew file mode 100644index 000000000..9c0d87b84--- /dev/null+++ b/crates/media/src/feeds/audio.rs@@ -0,0 +1,361 @@+use cap_project::TimelineConfiguration;+use ffmpeg::{+ codec::{context, decoder},+ format::sample::{Sample, Type},+ software::resampling,+};+use ringbuf::{+ traits::{Consumer, Observer, Producer},+ HeapRb,+};+use std::{path::PathBuf, sync::Arc};++use crate::{+ data::{AudioInfo, FFAudio, FromSampleBytes},+ MediaError,+};++#[derive(Clone, PartialEq, Eq)]+pub struct AudioData {+ pub buffer: Arc<Vec<u8>>,+ pub info: AudioInfo,+}++impl AudioData {+ pub const FORMAT: Sample = Sample::F64(Type::Packed);++ pub fn from_file(path: PathBuf) -> Result<Self, MediaError> {+ let input_ctx = ffmpeg::format::input(&path)?;+ let input_stream = input_ctx+ .streams()+ .best(ffmpeg::media::Type::Audio)+ .ok_or(MediaError::MissingMedia("audio"))?;++ let decoder_ctx = context::Context::from_parameters(input_stream.parameters())?;+ let mut decoder = decoder_ctx.decoder().audio()?;+ decoder.set_parameters(input_stream.parameters())?;+ decoder.set_packet_time_base(input_stream.time_base());++ let input_info = AudioInfo::from_decoder(&decoder);+ let mut output_info = input_info.clone();+ output_info.sample_format = Self::FORMAT;++ let resampler = AudioResampler::new(input_info, output_info)?;++ let reader = AudioFileReader {+ stream_index: input_stream.index(),+ info: input_info,+ resampler,+ decoder,+ first: true,+ };++ reader.read(input_ctx)+ }+}++pub struct AudioFrameBuffer {+ data: AudioData,+ cursor: usize,+ elapsed_samples: usize,+ sample_size: usize,+}++impl AudioFrameBuffer {+ pub fn new(data: AudioData) -> Self {+ let sample_size = data.info.channels * data.info.sample_format.bytes();++ Self {+ data,+ cursor: 0,+ elapsed_samples: 0,+ sample_size,+ }+ }++ pub fn info(&self) -> AudioInfo {+ self.data.info+ }++ pub fn set_playhead(&mut self, playhead: f64, maybe_timeline: Option<&TimelineConfiguration>) {+ self.elapsed_samples = self.playhead_to_samples(playhead);++ self.cursor = match maybe_timeline {+ Some(timeline) => match timeline.get_recording_time(playhead) {+ Some(time) => self.playhead_to_samples(time) * self.sample_size,+ None => self.data.buffer.len(),+ },+ None => self.elapsed_samples * self.sample_size,+ };+ }++ fn adjust_cursor(&mut self, timeline: &TimelineConfiguration) {+ let playhead = self.elapsed_samples_to_playhead();++ // ! Basically, to allow for some slop in the float -> usize and back conversions,+ // this will only seek if there is a significant change in actual vs expected next sample+ // (corresponding to a trim or split point). Currently this change is at least 0.2 seconds+ // - not sure we offer that much precision in the editor even!+ let new_cursor = match timeline.get_recording_time(playhead) {+ Some(time) => self.playhead_to_samples(time) * self.sample_size,+ None => self.data.buffer.len(),+ };++ let cursor_diff = new_cursor as isize - self.cursor as isize;+ if cursor_diff.abs() as usize > (self.data.info.sample_rate as usize) / 5 {+ self.cursor = new_cursor;+ }+ }++ fn playhead_to_samples(&self, playhead: f64) -> usize {+ let estimated_start_sample = playhead * f64::from(self.data.info.sample_rate);+ num_traits::cast(estimated_start_sample).unwrap()+ }++ fn elapsed_samples_to_playhead(&self) -> f64 {+ self.elapsed_samples as f64 / f64::from(self.data.info.sample_rate)+ }++ pub fn next_frame(+ &mut self,+ requested_samples: usize,+ timeline: Option<&TimelineConfiguration>,+ ) -> Option<FFAudio> {+ let format = self.data.info.sample_format;+ let channels = self.data.info.channel_layout();+ let sample_rate = self.data.info.sample_rate;++ self.next_frame_data(requested_samples, timeline)+ .map(move |(samples, data)| {+ let mut raw_frame = FFAudio::new(format, samples, channels);+ raw_frame.set_rate(sample_rate);+ raw_frame.data_mut(0)[0..data.len()].copy_from_slice(data);++ raw_frame+ })+ }++ pub fn next_frame_data<'a>(+ &'a mut self,+ mut samples: usize,+ maybe_timeline: Option<&TimelineConfiguration>,+ ) -> Option<(usize, &'a [u8])> {+ if let Some(timeline) = maybe_timeline {+ self.adjust_cursor(timeline);+ }++ if self.cursor >= self.data.buffer.len() {+ return None;+ }++ let mut bytes_size = self.sample_size * samples;++ let remaining_data = self.data.buffer.len() - self.cursor;+ if remaining_data < bytes_size {+ bytes_size = remaining_data;+ samples = remaining_data / self.sample_size;+ }++ let start = self.cursor;+ self.elapsed_samples += samples;+ self.cursor += bytes_size;+ Some((samples, &self.data.buffer[start..self.cursor]))+ }+}++pub struct AudioPlaybackBuffer<T: FromSampleBytes> {+ frame_buffer: AudioFrameBuffer,+ resampler: AudioResampler,+ resampled_buffer: HeapRb<T>,+}++impl<T: FromSampleBytes> AudioPlaybackBuffer<T> {+ pub const PLAYBACK_SAMPLES_COUNT: u32 = 256;+ const PROCESSING_SAMPLES_COUNT: u32 = 1024;++ pub fn new(data: AudioData, output_info: AudioInfo) -> Self {+ println!("Input info: {:?}", data.info);+ println!("Output info: {:?}", output_info);++ let resampler = AudioResampler::new(data.info, output_info).unwrap();++ // Up to 1 second of pre-rendered audio+ let capacity = (output_info.sample_rate as usize)+ * (output_info.channels as usize)+ * output_info.sample_format.bytes();+ let resampled_buffer = HeapRb::new(capacity);++ let frame_buffer = AudioFrameBuffer::new(data);++ Self {+ frame_buffer,+ resampler,+ resampled_buffer,+ }+ }++ pub fn set_playhead(&mut self, playhead: f64, maybe_timeline: Option<&TimelineConfiguration>) {+ self.resampler.reset();+ self.resampled_buffer.clear();+ self.frame_buffer.set_playhead(playhead, maybe_timeline);++ println!("Successful seek to sample {}", self.frame_buffer.cursor);+ }++ pub fn buffer_reaching_limit(&self) -> bool {+ self.resampled_buffer.vacant_len()+ <= 2 * (Self::PROCESSING_SAMPLES_COUNT as usize)+ * (self.resampler.output.channels as usize)+ * self.resampler.output.sample_format.bytes()+ }++ pub fn render(&mut self, timeline: Option<&TimelineConfiguration>) {+ if self.buffer_reaching_limit() {+ return;+ }++ let bytes_per_sample = self.resampler.output.sample_size();+ let maybe_rendered = match self+ .frame_buffer+ .next_frame(Self::PROCESSING_SAMPLES_COUNT as usize, timeline)+ {+ Some(frame) => Some(self.resampler.queue_and_process_frame(&frame)),+ None => self.resampler.flush_frame(),+ };++ if let Some(rendered) = maybe_rendered {+ let mut typed_data = vec![T::EQUILIBRIUM; rendered.len() / bytes_per_sample];++ for (src, dest) in std::iter::zip(rendered.chunks(bytes_per_sample), &mut typed_data) {+ *dest = T::from_bytes(src);+ }+ self.resampled_buffer.push_slice(&typed_data);+ }+ }++ pub fn fill(&mut self, playback_buffer: &mut [T]) {+ let filled = self.resampled_buffer.pop_slice(playback_buffer);+ playback_buffer[filled..].fill(T::EQUILIBRIUM);+ }+}++struct AudioFileReader {+ decoder: decoder::Audio,+ resampler: AudioResampler,+ stream_index: usize,+ info: AudioInfo,+ first: bool,+}++impl AudioFileReader {+ fn read(+ mut self,+ mut input_ctx: ffmpeg::format::context::Input,+ ) -> Result<AudioData, MediaError> {+ let mut buffer = Vec::new();+ let output_info = self.resampler.output;++ for (stream, mut packet) in input_ctx.packets() {+ if stream.index() == self.stream_index {+ packet.rescale_ts(stream.time_base(), self.info.time_base);+ self.decoder.send_packet(&packet).unwrap();+ self.decode_packets(&mut buffer);+ }+ }++ self.finish_resampling(&mut buffer);++ Ok(AudioData {+ buffer: Arc::new(buffer),+ info: output_info,+ })+ }++ fn decode_packets(&mut self, data: &mut Vec<u8>) {+ let mut decoded_frame = FFAudio::empty();++ while self.decoder.receive_frame(&mut decoded_frame).is_ok() {+ let timestamp = decoded_frame.timestamp();+ if self.first {+ println!(+ "First timestamp: {timestamp:?}, time base {}",+ self.decoder.time_base()+ );+ self.first = false;+ }+ decoded_frame.set_pts(timestamp);+ let resampled = self.resampler.queue_and_process_frame(&decoded_frame);+ // println!("Resampled: {:?}", resampled);+ data.extend_from_slice(resampled);+ decoded_frame = FFAudio::empty();+ }+ }++ fn finish_resampling(&mut self, data: &mut Vec<u8>) {+ self.decoder.send_eof().unwrap();+ self.decode_packets(data);++ while let Some(resampled) = self.resampler.flush_frame() {+ data.extend_from_slice(resampled);+ }+ }+}++pub struct AudioResampler {+ context: resampling::Context,+ output_frame: FFAudio,+ delay: Option<resampling::Delay>,+ input: AudioInfo,+ output: AudioInfo,+}++impl AudioResampler {+ pub fn new(input_info: AudioInfo, output_info: AudioInfo) -> Result<Self, MediaError> {+ let context = ffmpeg::software::resampler(+ (+ input_info.sample_format,+ input_info.channel_layout(),+ input_info.sample_rate,+ ),+ (+ output_info.sample_format,+ output_info.channel_layout(),+ output_info.sample_rate,+ ),+ )?;++ Ok(Self {+ input: input_info,+ output: output_info,+ context,+ output_frame: FFAudio::empty(),+ delay: None,+ })+ }++ pub fn reset(&mut self) {+ *self = Self::new(self.input, self.output).unwrap();+ }++ fn current_frame_data<'a>(&'a self) -> &'a [u8] {+ let end = self.output_frame.samples() * self.output.channels * self.output.sample_size();+ &self.output_frame.data(0)[0..end]+ }++ pub fn queue_and_process_frame<'a>(&'a mut self, frame: &FFAudio) -> &'a [u8] {+ self.delay = self.context.run(frame, &mut self.output_frame).unwrap();++ // Teeechnically this doesn't work for planar output+ self.current_frame_data()+ }++ pub fn flush_frame<'a>(&'a mut self) -> Option<&'a [u8]> {+ if self.delay.is_none() {+ return None;+ };++ self.delay = self.context.flush(&mut self.output_frame).unwrap();++ Some(self.current_frame_data())+ }+}diff --git a/crates/media/src/feeds/mod.rs b/crates/media/src/feeds/mod.rsindex 68bffd7df..4b3bf3581 100644--- a/crates/media/src/feeds/mod.rs+++ b/crates/media/src/feeds/mod.rs@@ -1,3 +1,5 @@+mod audio;mod camera;+pub use audio::*;pub use camera::*;diff --git a/crates/media/src/filters/audio.rs b/crates/media/src/filters/audio.rsindex 8e2c0d43b..480eacc99 100644--- a/crates/media/src/filters/audio.rs+++ b/crates/media/src/filters/audio.rs@@ -13,20 +13,37 @@ pub struct AudioFilter {}impl AudioFilter {- pub fn init(tag: &'static str, config: AudioInfo, spec: &str) -> Result<Self, MediaError> {+ pub fn init(+ tag: &'static str,+ input_config: AudioInfo,+ output_config: AudioInfo,+ ) -> 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()+ input_config.time_base,+ input_config.rate(),+ input_config.sample_format.name(),+ input_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)?;+ // let mut output = filter_graph.get("out").unwrap();+ // output.sink().set_frame_size(2048);++ let spec = format!(+ "aformat=sample_fmts={}:sample_rates={}:channel_layouts=0x{}",+ output_config.sample_format.name(),+ output_config.rate(),+ output_config.channel_layout().bits(),+ );++ filter_graph+ .output("in", 0)?+ .input("out", 0)?+ .parse(&spec)?;filter_graph.validate()?;Ok(Self { filter_graph, tag })diff --git a/crates/media/src/filters/video.rs b/crates/media/src/filters/video.rsindex 34b6e8dc8..104878c62 100644--- a/crates/media/src/filters/video.rs+++ b/crates/media/src/filters/video.rs@@ -39,7 +39,6 @@ impl VideoFilter {let mut output = filter_graph.get("out").unwrap();output.set_pixel_format(output_config.pixel_format);- // TODO: Remove fps hardcoding?let spec = format!("scale={}x{}:flags=bilinear,fps=fps={}",output_config.width,diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rsindex 54748b150..6bad83ed6 100644--- a/crates/media/src/lib.rs+++ b/crates/media/src/lib.rs@@ -45,4 +45,7 @@ pub enum MediaError {#[error("Device {0} is unreachable. It may have been disconnected")]DeviceUnreachable(String),++ #[error("Could not find a suitable {0} stream in this file")]+ MissingMedia(&'static str),}diff --git a/crates/media/src/pipeline/clock/mod.rs b/crates/media/src/pipeline/clock/mod.rsnew file mode 100644index 000000000..27e5583bd--- /dev/null+++ b/crates/media/src/pipeline/clock/mod.rs@@ -0,0 +1,31 @@+mod real_time;+mod recorded;++pub use real_time::*;+pub use recorded::*;++pub trait PipelineClock: Clone + Send + 'static {+ fn start(&mut self);++ fn stop(&mut self);++ fn running(&self) -> bool;+}++// 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()+ }+}diff --git a/crates/media/src/pipeline/clock.rs b/crates/media/src/pipeline/clock/real_time.rssimilarity index 79%rename from crates/media/src/pipeline/clock.rsrename to crates/media/src/pipeline/clock/real_time.rsindex ae885a896..9192136b7 100644--- a/crates/media/src/pipeline/clock.rs+++ b/crates/media/src/pipeline/clock/real_time.rs@@ -4,30 +4,7 @@ use std::sync::{};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);-}+use super::{CloneInto, PipelineClock};pub trait LocalTimestamp: Sized + Clone {fn elapsed_since(&self, other: &Self) -> Duration;@@ -55,7 +32,7 @@ impl LocalTimestamp for RawNanoseconds {}#[derive(Debug, Clone)]-pub struct SynchronisedClock<T: LocalTimestamp> {+pub struct RealTimeClock<T: LocalTimestamp> {local_start_time: Option<Instant>,global_start_time: Arc<RwLock<Instant>>,first_local_timestamp: Option<T>,@@ -64,18 +41,18 @@ pub struct SynchronisedClock<T: LocalTimestamp> {running: Arc<AtomicBool>,}-impl<Source: LocalTimestamp, Target: LocalTimestamp> CloneInto<SynchronisedClock<Target>>- for SynchronisedClock<Source>+impl<Source: LocalTimestamp, Target: LocalTimestamp> CloneInto<RealTimeClock<Target>>+ for RealTimeClock<Source>{- fn clone_into(&self) -> SynchronisedClock<Target> {- let SynchronisedClock {+ fn clone_into(&self) -> RealTimeClock<Target> {+ let RealTimeClock {global_start_time,resume_offset_nanoseconds,running,..} = self.clone();- SynchronisedClock {+ RealTimeClock {global_start_time,resume_offset_nanoseconds,running,@@ -85,15 +62,15 @@ impl<Source: LocalTimestamp, Target: LocalTimestamp> CloneInto<SynchronisedClock}}-impl<T: LocalTimestamp> Default for SynchronisedClock<T> {+impl<T: LocalTimestamp> Default for RealTimeClock<T> {fn default() -> Self {Self::new()}}-impl<T: LocalTimestamp> SynchronisedClock<T> {- pub fn init() -> SynchronisedClock<()> {- SynchronisedClock::<()>::new()+impl<T: LocalTimestamp> RealTimeClock<T> {+ pub fn init() -> RealTimeClock<()> {+ RealTimeClock::<()>::new()}pub fn new() -> Self {@@ -106,10 +83,6 @@ impl<T: LocalTimestamp> SynchronisedClock<T> {}}- pub fn running(&self) -> bool {- self.running.load(Ordering::Acquire)- }-fn set_running(&self, value: bool) {self.running.store(value, Ordering::Release);}@@ -129,7 +102,7 @@ impl<T: LocalTimestamp> SynchronisedClock<T> {pub fn timestamp_for(&mut self, local: T) -> Option<i64> {let now = Instant::now();- if !self.running() {+ if !self.running.load(Ordering::Acquire) {return None;}@@ -139,7 +112,7 @@ impl<T: LocalTimestamp> SynchronisedClock<T> {if self.local_start_time.is_none()|| self.local_start_time.unwrap() < *global_start_time{- tracing::info!("Just resumed, resetting local state");+ println!("Just resumed, resetting local state");self.local_start_time = Some(now);self.first_local_timestamp = Some(local.clone());}@@ -160,7 +133,11 @@ impl<T: LocalTimestamp> SynchronisedClock<T> {}}-impl PipelineClock for SynchronisedClock<()> {+impl PipelineClock for RealTimeClock<()> {+ fn running(&self) -> bool {+ self.running.load(Ordering::Acquire)+ }+fn start(&mut self) {if !self.running() {let mut start_time = self.global_start_time.write().unwrap();diff --git a/crates/media/src/pipeline/clock/recorded.rs b/crates/media/src/pipeline/clock/recorded.rsnew file mode 100644index 000000000..8c5238f4d--- /dev/null+++ b/crates/media/src/pipeline/clock/recorded.rs@@ -0,0 +1,56 @@+use std::sync::{+ atomic::{AtomicBool, AtomicU32, Ordering},+ Arc,+};++use super::{CloneInto, PipelineClock};++#[derive(Debug, Clone)]+pub struct RecordedClock {+ running: Arc<AtomicBool>,+ start_frame_offset: Arc<AtomicU32>,+ total_frame_duration: f64,+}++impl RecordedClock {+ pub fn new(duration: f64, fps: u32) -> Self {+ Self {+ running: Arc::new(AtomicBool::new(false)),+ start_frame_offset: Arc::new(AtomicU32::new(0)),+ total_frame_duration: duration * f64::from(fps),+ }+ }++ pub fn seek(&mut self, playhead: u32) {+ self.start_frame_offset.store(playhead, Ordering::Release);+ }++ pub fn playhead_ratio(&self) -> f64 {+ let playhead = self.start_frame_offset.load(Ordering::Acquire);+ f64::from(playhead) / self.total_frame_duration+ }++ fn set_running(&self, value: bool) {+ self.running.store(value, Ordering::Release);+ }+}++impl CloneInto<RecordedClock> for RecordedClock {+ fn clone_into(&self) -> RecordedClock {+ self.clone()+ }+}++impl PipelineClock for RecordedClock {+ fn running(&self) -> bool {+ self.running.load(Ordering::Acquire)+ }++ fn start(&mut self) {+ self.set_running(true);+ }++ fn stop(&mut self) {+ self.set_running(false);+ }+}diff --git a/crates/media/src/pipeline/control.rs b/crates/media/src/pipeline/control.rsindex 05a7dd28a..67917f1a3 100644--- a/crates/media/src/pipeline/control.rs+++ b/crates/media/src/pipeline/control.rs@@ -17,8 +17,16 @@ pub struct PipelineControlSignal {impl PipelineControlSignal {pub fn last(&mut self) -> Option<Control> {+ self.blocking_last_if(false)+ }++ pub fn blocking_last(&mut self) -> Option<Control> {+ self.blocking_last_if(true)+ }++ pub fn blocking_last_if(&mut self, should_block: bool) -> Option<Control> {match self.last_value {- Some(Control::Play) => {+ Some(Control::Play) if !should_block => {// Only peek for a new signal, else relinquish control to the callermatch self.receiver.try_recv() {Ok(control) => {@@ -34,17 +42,13 @@ impl PipelineControlSignal {_ => {// 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()+ println!("Waiting for play signal...");+ self.last_value = self.receiver.recv().ok();++ self.last_value}}}-- pub fn blocking_last(&mut self) -> Option<Control> {- println!("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,diff --git a/crates/media/src/sources/audio_input.rs b/crates/media/src/sources/audio_input.rsindex e164a103c..94f6f91e3 100644--- a/crates/media/src/sources/audio_input.rs+++ b/crates/media/src/sources/audio_input.rs@@ -9,9 +9,9 @@ use flume::Sender;use indexmap::IndexMap;use crate::{- data::{AudioInfo, FFAudio, RawAudioFormat},+ data::{ffmpeg_sample_format_for, AudioInfo, FFAudio},pipeline::{- clock::{LocalTimestamp, SynchronisedClock},+ clock::{LocalTimestamp, RealTimeClock},control::Control,task::PipelineSourceTask,},@@ -50,17 +50,7 @@ impl AudioInputSource {}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,- )+ AudioInfo::from_stream_config(&self.config)}pub fn get_devices() -> AudioInputDeviceMap {@@ -72,7 +62,9 @@ impl AudioInputSource {.supported_input_configs().map_err(|error| eprintln!("Error: {error}")).ok()- .and_then(|mut configs| configs.find(|c| format_for(c.sample_format()).is_some()))+ .and_then(|mut configs| {+ configs.find(|c| ffmpeg_sample_format_for(c.sample_format()).is_some())+ }).and_then(|config| {device.name()@@ -104,7 +96,7 @@ impl AudioInputSource {pub fn build_stream(&self,- mut clock: SynchronisedClock<StreamInstant>,+ mut clock: RealTimeClock<StreamInstant>,output: Arc<Mutex<Option<Sender<FFAudio>>>>,) -> Result<Stream, MediaError> {let audio_info = self.info();@@ -155,22 +147,10 @@ impl AudioInputSource {}}-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>;+ type Clock = RealTimeClock<StreamInstant>;// #[tracing::instrument(skip_all)]fn run(@@ -206,6 +186,9 @@ impl PipelineSourceTask for AudioInputSource {.expect("Failed to pause audio input recording");}Some(Control::Shutdown) | None => {+ if let Err(error) = stream.pause() {+ eprintln!("Error while stopping audio stream: {error}");+ }output.lock().unwrap().take();drop(stream);break;diff --git a/crates/media/src/sources/camera.rs b/crates/media/src/sources/camera.rsindex 2b6175405..e15d023c0 100644--- a/crates/media/src/sources/camera.rs+++ b/crates/media/src/sources/camera.rs@@ -4,7 +4,7 @@ use std::time::Instant;use crate::{data::{FFVideo, VideoInfo},feeds::{CameraConnection, CameraFeed, RawCameraFrame},- pipeline::{clock::SynchronisedClock, control::Control, task::PipelineSourceTask},+ pipeline::{clock::RealTimeClock, control::Control, task::PipelineSourceTask},MediaError,};@@ -27,7 +27,7 @@ impl CameraSource {fn process_frame(&self,- clock: &mut SynchronisedClock<Instant>,+ clock: &mut RealTimeClock<Instant>,output: &Sender<FFVideo>,camera_frame: RawCameraFrame,) -> Result<(), MediaError> {@@ -52,7 +52,7 @@ impl CameraSource {fn pause_and_drain_frames(&self,- clock: &mut SynchronisedClock<Instant>,+ clock: &mut RealTimeClock<Instant>,output: &Sender<FFVideo>,frames_rx: Receiver<RawCameraFrame>,) {@@ -71,7 +71,7 @@ impl CameraSource {impl PipelineSourceTask for CameraSource {type Output = FFVideo;- type Clock = SynchronisedClock<Instant>;+ type Clock = RealTimeClock<Instant>;// #[tracing::instrument(skip_all)]fn run(diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rsindex 0282de5ec..277f5eb20 100644--- a/crates/media/src/sources/screen_capture.rs+++ b/crates/media/src/sources/screen_capture.rs@@ -209,7 +209,7 @@ impl ScreenCaptureSource {}impl PipelineSourceTask for ScreenCaptureSource {- type Clock = SynchronisedClock<RawNanoseconds>;+ type Clock = RealTimeClock<RawNanoseconds>;type Output = FFVideo;fn run(diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 4b024b0d7..8b8561b0d 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -12,8 +12,8 @@ use wgpu::util::DeviceExt;use wgpu::{CommandEncoder, COPY_BYTES_PER_ROW_ALIGNMENT};use cap_project::{- AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop,- CursorData, CursorMoveEvent, ProjectConfiguration, XY,+ AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, CursorData,+ CursorMoveEvent, ProjectConfiguration, XY,};use image::GenericImageView;