Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

monster rewrite

PJ079f8f0a50f9
diff --git a/Cargo.lock b/Cargo.lock
index fb436e70c..99303b977 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -528,8 +528,10 @@ dependencies = [
"fix-path-env",
"futures",
"image",
+ "indexmap 2.2.6",
"jpeg-encoder",
"nix 0.20.0",
+ "num-traits",
"regex",
"reqwest 0.11.27",
"scap",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index fb9eedc93..63c45efff 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -63,6 +63,8 @@ chrono = "0.4.33"
dotenvy_macro = "0.15.7"
byteorder = "1.4.3"
bytemuck = "1.14.3"
+num-traits = "0.2.19"
+indexmap = "2.2.6"
regex = "1"
# scap = { git = "https://github.com/CapSoftware/scap", rev = "1b7c70df754ee9c2c4e040266f45d16354367bd7" }
capture = { path = "../../../crates/capture" }
diff --git a/apps/desktop/src-tauri/src/media.rs b/apps/desktop/src-tauri/src/media.rs
deleted file mode 100644
index 7289f6173..000000000
--- a/apps/desktop/src-tauri/src/media.rs
+++ /dev/null
@@ -1,819 +0,0 @@
-use byteorder::{ ByteOrder, LittleEndian };
-use cpal::traits::{ DeviceTrait, HostTrait, StreamTrait };
-use cpal::SampleFormat;
-use image::codecs::jpeg::JpegEncoder;
-use image::{ ImageBuffer, ImageFormat, Rgba };
-use std::io::{ Error, ErrorKind::WouldBlock };
-use std::path::{ Path, PathBuf };
-use std::process::Stdio;
-use std::sync::{ atomic::{ AtomicBool, Ordering }, Arc };
-use std::time::{ Duration, Instant };
-use tokio::fs::File;
-
-use tokio::io::AsyncWriteExt;
-use tokio::process::{ Child, ChildStdin, Command };
-use tokio::sync::{ mpsc, Mutex };
-use tokio::try_join;
-
-use crate::app::config;
-use crate::recording::RecordingOptions;
-use crate::upload::{ self, upload_file };
-use crate::utils::{ create_named_pipe, ffmpeg_path_as_str };
-use capture::{ Capturer, Display };
-
-const FRAME_RATE: u64 = 30;
-
-pub struct MediaRecorder {
- pub options: Option<RecordingOptions>,
- ffmpeg_process: Option<tokio::process::Child>,
- ffmpeg_stdin: Option<Arc<Mutex<Option<tokio::process::ChildStdin>>>>,
- device_name: Option<String>,
- audio_stream: Option<cpal::Stream>,
- audio_channel_sender: Option<mpsc::Sender<Vec<u8>>>,
- audio_channel_receiver: Option<mpsc::Receiver<Vec<u8>>>,
- video_channel_sender: Option<mpsc::Sender<Vec<u8>>>,
- video_channel_receiver: Option<mpsc::Receiver<Vec<u8>>>,
- should_stop: Arc<AtomicBool>,
- start_time: Option<Instant>,
- audio_file_path: Option<PathBuf>,
- video_file_path: Option<PathBuf>,
-}
-
-impl MediaRecorder {
- pub fn new() -> Self {
- MediaRecorder {
- options: None,
- ffmpeg_process: None,
- ffmpeg_stdin: None,
- device_name: None,
- audio_stream: None,
- audio_channel_sender: None,
- audio_channel_receiver: None,
- video_channel_sender: None,
- video_channel_receiver: None,
- should_stop: Arc::new(AtomicBool::new(false)),
- start_time: None,
- audio_file_path: None,
- video_file_path: None,
- }
- }
-
- #[tracing::instrument(skip(self))]
- pub async fn start_media_recording(
- &mut self,
- options: RecordingOptions,
- screenshot_dir: &Path,
- audio_chunks_dir: &Path,
- video_chunks_dir: &Path,
- custom_device: Option<&str>,
- max_screen_width: usize,
- max_screen_height: usize
- ) -> Result<(), String> {
- self.options = Some(options.clone());
-
- tracing::debug!("Custom device: {:?}", custom_device);
-
- let host = cpal::default_host();
- let devices = host.devices().expect("Failed to get devices");
- let _display = Display::primary().expect("Failed to find primary display");
- let w = max_screen_width;
- let h = max_screen_height;
-
- let adjusted_width = w & !2;
- let adjusted_height = h & !2;
- let capture_size = adjusted_width * adjusted_height * 4;
- let (audio_tx, audio_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(2048);
- let (video_tx, video_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(2048);
- let calculated_stride = (adjusted_width * 4) as usize;
-
- tracing::debug!("Display width: {}", w);
- tracing::debug!("Display height: {}", h);
- tracing::debug!("Adjusted width: {}", adjusted_width);
- tracing::debug!("Adjusted height: {}", adjusted_height);
- tracing::debug!("Capture size: {}", capture_size);
- tracing::debug!("Calculated stride: {}", calculated_stride);
-
- let audio_start_time = Arc::new(Mutex::new(None));
- let video_start_time = Arc::new(Mutex::new(None));
-
- self.audio_channel_sender = Some(audio_tx);
- self.audio_channel_receiver = Some(audio_rx);
- self.video_channel_sender = Some(video_tx);
- self.video_channel_receiver = Some(video_rx);
- self.ffmpeg_stdin = Some(Arc::new(Mutex::new(None)));
-
- let audio_channel_sender = self.audio_channel_sender.clone();
- let video_channel_sender = self.video_channel_sender.clone();
-
- let audio_channel_receiver = Arc::new(Mutex::new(self.audio_channel_receiver.take()));
- let video_channel_receiver = Arc::new(Mutex::new(self.video_channel_receiver.take()));
-
- let should_stop = Arc::clone(&self.should_stop);
-
- let mut input_devices = devices.filter_map(|device| {
- let supported_input_configs = device.supported_input_configs();
- if supported_input_configs.is_ok() && supported_input_configs.unwrap().count() > 0 {
- Some(device)
- } else {
- None
- }
- });
-
- let device = if let Some(custom_device_name) = custom_device {
- input_devices
- .find(|d| {
- d.name()
- .map(|name| name == custom_device_name)
- .unwrap_or(false)
- })
- .unwrap_or_else(|| {
- host.default_input_device().expect("No default input device available")
- })
- } else {
- host.default_input_device().expect("No default input device available")
- };
-
- tracing::info!("Using audio device: {}", device.name().expect("Failed to get device name"));
-
- let config = device
- .supported_input_configs()
- .expect("Failed to get supported input configs")
- .find(|c| {
- c.sample_format() == SampleFormat::F32 ||
- c.sample_format() == SampleFormat::I16 ||
- c.sample_format() == SampleFormat::I8 ||
- c.sample_format() == SampleFormat::I32
- })
- .unwrap_or_else(|| {
- device
- .supported_input_configs()
- .expect("Failed to get supported input configs")
- .next()
- .expect("No supported input config")
- })
- .with_max_sample_rate();
-
- let sample_rate = config.sample_rate().0;
- let channels = config.channels();
- let sample_format = match config.sample_format() {
- SampleFormat::I8 => "s8",
- SampleFormat::I16 => "s16le",
- SampleFormat::I32 => "s32le",
- SampleFormat::F32 => "f32le",
- _ => panic!("Unsupported sample format."),
- };
-
- tracing::debug!("Sample rate: {}", sample_rate);
- tracing::debug!("Channels: {}", channels);
- tracing::debug!("Sample format: {}", sample_format);
-
- let ffmpeg_binary_path_str = ffmpeg_path_as_str().unwrap().to_owned();
-
- tracing::debug!("FFmpeg binary path: {}", ffmpeg_binary_path_str);
-
- let sample_rate_str = sample_rate.to_string();
- let channels_str = channels.to_string();
-
- let err_fn = move |err| {
- tracing::error!("an error occurred on stream: {}", err);
- };
-
- let needs_audio = custom_device != Some("None");
-
- if needs_audio {
- tracing::trace!("Building input stream...");
-
- let stream_result: Result<cpal::Stream, cpal::BuildStreamError> = match
- config.sample_format()
- {
- SampleFormat::I8 =>
- device.build_input_stream(
- &config.into(),
- {
- let audio_start_time = Arc::clone(&audio_start_time);
- move |data: &[i8], _: &_| {
- let mut first_frame_time_guard = audio_start_time.try_lock();
-
- let bytes = data
- .iter()
- .map(|&sample| sample as u8)
- .collect::<Vec<u8>>();
- if let Some(sender) = &audio_channel_sender {
- if sender.try_send(bytes).is_err() {
- tracing::warn!("Channel send error. Dropping data.");
- }
- }
-
- if let Ok(ref mut start_time_option) = first_frame_time_guard {
- if start_time_option.is_none() {
- **start_time_option = Some(Instant::now());
-
- tracing::trace!("Audio start time captured");
- }
- }
- }
- },
- err_fn,
- None
- ),
- SampleFormat::I16 =>
- device.build_input_stream(
- &config.into(),
- {
- let audio_start_time = Arc::clone(&audio_start_time);
- move |data: &[i16], _: &_| {
- let mut first_frame_time_guard = audio_start_time.try_lock();
-
- let mut bytes = vec![0; data.len() * 2];
- LittleEndian::write_i16_into(data, &mut bytes);
- if let Some(sender) = &audio_channel_sender {
- if sender.try_send(bytes).is_err() {
- tracing::warn!("Channel send error. Dropping data.");
- }
- }
-
- if let Ok(ref mut start_time_option) = first_frame_time_guard {
- if start_time_option.is_none() {
- **start_time_option = Some(Instant::now());
-
- tracing::trace!("Audio start time captured");
- }
- }
- }
- },
- err_fn,
- None
- ),
- SampleFormat::I32 =>
- device.build_input_stream(
- &config.into(),
- {
- let audio_start_time = Arc::clone(&audio_start_time);
- move |data: &[i32], _: &_| {
- let mut first_frame_time_guard = audio_start_time.try_lock();
-
- let mut bytes = vec![0; data.len() * 2];
- LittleEndian::write_i32_into(data, &mut bytes);
- if let Some(sender) = &audio_channel_sender {
- if sender.try_send(bytes).is_err() {
- tracing::warn!("Channel send error. Dropping data.");
- }
- }
-
- if let Ok(ref mut start_time_option) = first_frame_time_guard {
- if start_time_option.is_none() {
- **start_time_option = Some(Instant::now());
-
- tracing::trace!("Audio start time captured");
- }
- }
- }
- },
- err_fn,
- None
- ),
- SampleFormat::F32 =>
- device.build_input_stream(
- &config.into(),
- {
- let audio_start_time = Arc::clone(&audio_start_time);
- move |data: &[f32], _: &_| {
- let mut first_frame_time_guard = audio_start_time.try_lock();
-
- let mut bytes = vec![0; data.len() * 4];
- LittleEndian::write_f32_into(data, &mut bytes);
- if let Some(sender) = &audio_channel_sender {
- if sender.try_send(bytes).is_err() {
- tracing::warn!("Channel send error. Dropping data.");
- }
- }
-
- if let Ok(ref mut start_time_option) = first_frame_time_guard {
- if start_time_option.is_none() {
- **start_time_option = Some(Instant::now());
-
- tracing::trace!("Audio start time captured");
- }
- }
- }
- },
- err_fn,
- None
- ),
- _sample_format => Err(cpal::BuildStreamError::DeviceNotAvailable),
- };
-
- let stream = stream_result.map_err(|_| "Failed to build input stream")?;
- self.audio_stream = Some(stream);
- self.trigger_play()?;
- }
-
- let video_start_time_clone = Arc::clone(&video_start_time);
- let screenshot_file_path = screenshot_dir.join("screen-capture.jpg");
- let capture_frame_at = Duration::from_secs(3);
-
- std::thread::spawn(move || {
- tracing::trace!("Starting video recording capture thread...");
-
- let is_local_mode = config::is_local_mode();
-
- let mut capturer = Capturer::new(
- Display::primary().expect("Failed to find primary display"),
- w.try_into().unwrap(),
- h.try_into().unwrap()
- ).expect("Failed to start capture");
-
- let fps = FRAME_RATE;
- let spf = Duration::from_nanos(1_000_000_000 / fps);
-
- let mut frame_count = 0u32;
- let start_time = Instant::now();
- let mut time_next = Instant::now() + spf;
- let mut screenshot_captured: bool = false;
-
- while !should_stop.load(Ordering::SeqCst) {
- let options_clone = options.clone();
- let now = Instant::now();
-
- if now >= time_next {
- match capturer.frame() {
- Ok(frame) => {
- let mut frame_data = Vec::with_capacity(
- capture_size.try_into().unwrap()
- );
-
- for row in 0..adjusted_height {
- let padded_stride = frame
- .stride_override()
- .unwrap_or(calculated_stride);
- assert!(
- padded_stride >= calculated_stride,
- "Image stride with padding should not be smaller than calculated bytes per row"
- );
- // Each row should skip the padding of the previous row
- let start = row * padded_stride;
- // Each row should stop before/trim off its padding, for compatibility with software that doesn't follow arbitrary padding.
- let end = start + calculated_stride;
- frame_data.extend_from_slice(&frame[start..end]);
- }
-
- if now - start_time >= capture_frame_at && !screenshot_captured {
- screenshot_captured = true;
- let mut frame_data_clone = frame_data.clone();
-
- let screenshot_file_path = screenshot_file_path.clone();
- std::thread::spawn(move || {
- for chunk in frame_data_clone.chunks_mut(4) {
- chunk.swap(0, 2);
- }
-
- let image: ImageBuffer<
- Rgba<u8>,
- Vec<u8>
- > = ImageBuffer::from_raw(
- adjusted_width.try_into().unwrap(),
- adjusted_height.try_into().unwrap(),
- frame_data_clone
- ).expect("Failed to create image buffer");
-
- let mut output_file = std::fs::File
- ::create(&screenshot_file_path)
- .expect("Failed to create output file");
- let mut encoder = JpegEncoder::new_with_quality(
- &mut output_file,
- 20
- );
-
- if let Err(e) = encoder.encode_image(&image) {
- tracing::warn!("Failed to save screenshot: {}", e);
- } else {
- tracing::info!(
- "Screenshot captured and saved to {:?}",
- screenshot_file_path
- );
-
- if !is_local_mode {
- let rt = tokio::runtime::Runtime::new().unwrap();
- rt.block_on(async move {
- let upload_task = tokio::spawn(
- upload_file(
- Some(options_clone),
- screenshot_file_path.clone(),
- upload::FileType::Screenshot
- )
- );
- match upload_task.await {
- Ok(result) =>
- match result {
- Ok(_) =>
- tracing::info!(
- "Screenshot captured and saved to {:?}",
- screenshot_file_path
- ),
- Err(e) =>
- tracing::warn!("Failed to upload file: {}", e),
- }
- Err(e) => {
- tracing::error!("Failed to join task: {}", e)
- }
- }
- });
- }
- }
- });
- }
-
- if let Some(sender) = &video_channel_sender {
- if sender.try_send(frame_data).is_err() {
- tracing::error!("Channel send error. Dropping data.");
- }
- }
-
- let mut first_frame_time_guard = video_start_time_clone.try_lock();
-
- if let Ok(ref mut start_time_option) = first_frame_time_guard {
- if start_time_option.is_none() {
- **start_time_option = Some(Instant::now());
-
- tracing::trace!("Video start time captured");
- }
- }
-
- frame_count += 1;
- }
- Err(error) if error.kind() == WouldBlock => {
- std::thread::sleep(Duration::from_millis(1));
- continue;
- }
- Err(error) => {
- tracing::error!("Capture error: {}", error);
- break;
- }
- }
-
- time_next += spf;
- }
-
- // Sleep until the next frame time
- let now = Instant::now();
- if time_next > now {
- std::thread::sleep(time_next - now);
- }
- }
-
- let elapsed_total_time = start_time.elapsed();
- let fps = (frame_count as f64) / elapsed_total_time.as_secs_f64();
- tracing::trace!("Current FPS: {}", fps);
- });
-
- tracing::info!("Starting audio recording and processing...");
- let audio_chunk_pattern = audio_chunks_dir.join("audio_recording_%03d.aac");
- let video_chunk_pattern = video_chunks_dir.join("video_recording_%03d.ts");
- let audio_segment_list_filename = audio_chunks_dir.join("segment_list.txt");
- let video_segment_list_filename = video_chunks_dir.join("segment_list.txt");
-
- let mut audio_filters = Vec::new();
-
- if channels > 2 {
- audio_filters.push("pan=stereo|FL=FL+0.5*FC|FR=FR+0.5*FC");
- }
-
- audio_filters.push("loudnorm");
-
- let video_pipe_path = video_chunks_dir.join("pipe.pipe");
-
- std::fs::remove_file(&video_pipe_path).ok();
- create_named_pipe(&video_pipe_path).map_err(|e| e.to_string())?;
-
- let audio_pipe_path = audio_chunks_dir.join("pipe.pipe");
-
- std::fs::remove_file(&audio_pipe_path).ok();
- create_named_pipe(&audio_pipe_path).map_err(|e| e.to_string())?;
-
- let time_offset = if needs_audio {
- tracing::trace!("Adjusting FFmpeg commands based on start times...");
- create_time_offset_args(&audio_start_time, &video_start_time).await
- } else {
- None
- };
-
- let size = format!("{}x{}", adjusted_width, adjusted_height);
-
- let mut ffmpeg_command = Command::new(ffmpeg_binary_path_str);
-
- if let Some((TimeOffsetTarget::Video, args)) = &time_offset {
- ffmpeg_command.args(args);
- }
-
- ffmpeg_command
- // video in
- .args(["-f", "rawvideo", "-pix_fmt", "bgra"])
- .args(["-s", &size, "-r", "30"])
- .args(["-thread_queue_size", "4096", "-i"])
- .arg(&video_pipe_path)
- // video out
- .args(["-vf", "fps=30,scale=in_range=full:out_range=limited"])
- .args(["-c:v", "libx264", "-preset", "ultrafast"])
- .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
- .args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
- .args(["-f", "segment", "-movflags", "frag_keyframe+empty_moov"])
- .args(["-reset_timestamps", "1", "-an"])
- .args(["-segment_time", "3"])
- .args(["-segment_format", "ts"])
- .args(["-segment_time_delta", "0.01", "-segment_list"])
- .args([&video_segment_list_filename, &video_chunk_pattern]);
-
- if needs_audio {
- if let Some((TimeOffsetTarget::Audio, args)) = &time_offset {
- ffmpeg_command.args(args);
- }
-
- ffmpeg_command
- // audio in
- .args(["-f", sample_format, "-ar", &sample_rate_str])
- .args(["-ac", &channels_str, "-thread_queue_size", "4096", "-i"])
- .arg(&audio_pipe_path)
- // out
- .args(["-af", "aresample=async=1:min_hard_comp=0.100000:first_pts=0"])
- .args(["-codec:a", "aac", "-b:a", "128k"])
- .args(["-async", "1", "-f", "segment"])
- .args(["-segment_time", "3", "-segment_time_delta", "0.01"])
- .args(["-reset_timestamps", "1", "-vn", "-segment_list"])
- .args([&audio_segment_list_filename, &audio_chunk_pattern]);
- }
-
- tracing::trace!("Starting FFmpeg process...");
-
- let (ffmpeg_child, ffmpeg_stdin) = self
- .start_ffmpeg_process(ffmpeg_command).await
- .map_err(|e| e.to_string())?;
- tracing::trace!("Ffmpeg process started");
-
- if let Some(ffmpeg_stdin_mutex) = &self.ffmpeg_stdin {
- let mut stdin_lock = ffmpeg_stdin_mutex.lock().await;
- *stdin_lock = Some(ffmpeg_stdin);
- drop(stdin_lock);
- tracing::trace!("Ffmpeg stdin set");
- }
-
- if needs_audio {
- tracing::trace!("Starting audio channel senders...");
- let audio_should_stop = Arc::clone(&self.should_stop);
-
- tokio::spawn(async move {
- let mut audio_pipe = File::create(audio_pipe_path).await.unwrap();
-
- while
- let Some(bytes) = &audio_channel_receiver
- .lock().await
- .as_mut()
- .unwrap()
- .recv().await
- {
- if audio_should_stop.load(Ordering::SeqCst) {
- break;
- }
- audio_pipe
- .write_all(&bytes).await
- .expect("Failed to write audio data to FFmpeg stdin");
- }
- });
- }
-
- tracing::trace!("Starting video channel senders...");
- let video_should_stop = Arc::clone(&self.should_stop);
- tokio::spawn(async move {
- let mut pipe = File::create(video_pipe_path).await.unwrap();
-
- while let Some(bytes) = &video_channel_receiver
- .lock().await
- .as_mut()
- .unwrap()
- .recv().await
- {
- if video_should_stop.load(Ordering::SeqCst) {
- break;
- }
- pipe.write_all(&bytes).await.expect("Failed to write video data to FFmpeg stdin");
- }
- });
-
- self.start_time = Some(Instant::now());
- self.audio_file_path = Some(audio_chunks_dir.to_path_buf());
- self.video_file_path = Some(video_chunks_dir.to_path_buf());
- self.ffmpeg_process = Some(ffmpeg_child);
- self.device_name = Some(device.name().expect("Failed to get device name"));
-
- tracing::trace!("End of the start_audio_recording function");
-
- Ok(())
- }
-
- pub fn trigger_play(&mut self) -> Result<(), &'static str> {
- if let Some(ref mut stream) = self.audio_stream {
- stream.play().map_err(|_| "Failed to play stream")?;
- tracing::info!("Audio recording playing.");
- } else {
- return Err("Starting the recording did not work");
- }
-
- Ok(())
- }
-
- #[tracing::instrument(skip(self))]
- pub async fn stop_media_recording(&mut self) -> Result<(), String> {
- if let Some(start_time) = self.start_time {
- let segment_duration = Duration::from_secs(3);
- let recording_duration = start_time.elapsed();
- let expected_segments = recording_duration.as_secs() / segment_duration.as_secs();
- let audio_file_path = self.audio_file_path.as_ref().ok_or("Audio file path not set")?;
- let video_file_path = self.video_file_path.as_ref().ok_or("Video file path not set")?;
- let audio_segment_list_filename = audio_file_path.join("segment_list.txt");
- let video_segment_list_filename = video_file_path.join("segment_list.txt");
-
- loop {
- let audio_segments = std::fs
- ::read_to_string(&audio_segment_list_filename)
- .unwrap_or_default();
- let video_segments = std::fs
- ::read_to_string(&video_segment_list_filename)
- .unwrap_or_default();
-
- let audio_segment_count = audio_segments.lines().count();
- let video_segment_count = video_segments.lines().count();
-
- if
- audio_segment_count >= (expected_segments as usize) &&
- video_segment_count >= (expected_segments as usize)
- {
- tracing::info!("All segments generated");
- break;
- }
-
- tokio::time::sleep(Duration::from_millis(300)).await;
- }
- }
-
- if let Some(ref ffmpeg_stdin) = self.ffmpeg_stdin {
- let mut stdin_guard = ffmpeg_stdin.lock().await;
- if let Some(mut stdin) = stdin_guard.take() {
- if let Err(e) = stdin.write_all(b"q\n").await {
- tracing::error!("Failed to send 'q' to video FFmpeg process: {}", e);
- }
- let _ = stdin.shutdown().await.map_err(|e| e.to_string());
- }
- }
-
- self.should_stop.store(true, Ordering::SeqCst);
-
- if let Some(sender) = self.audio_channel_sender.take() {
- drop(sender);
- }
-
- if let Some(sender) = self.video_channel_sender.take() {
- drop(sender);
- }
-
- if let Some(ref mut stream) = self.audio_stream {
- stream.pause().map_err(|_| "Failed to pause stream")?;
- tracing::info!("Audio recording paused.");
- } else {
- return Err("Original recording was not started".to_string());
- }
-
- if let Some(process) = &mut self.ffmpeg_process {
- let _ = process.kill().await.map_err(|e| e.to_string());
- }
-
- tracing::info!("Audio recording stopped.");
- Ok(())
- }
-
- async fn start_ffmpeg_process(&self, cmd: Command) -> Result<(Child, ChildStdin), Error> {
- let mut video_process = start_recording_process(cmd).await.map_err(|e| {
- tracing::error!("Failed to start video recording process: {}", e);
- std::io::Error::new(std::io::ErrorKind::Other, e.to_string())
- })?;
-
- let video_stdin = video_process.stdin.take().ok_or_else(|| {
- tracing::error!("Failed to take video stdin");
- std::io::Error::new(std::io::ErrorKind::Other, "Failed to take video stdin")
- })?;
-
- Ok((video_process, video_stdin))
- }
-}
-
-#[tauri::command]
-#[specta::specta]
-#[tracing::instrument]
-pub fn enumerate_audio_devices() -> Vec<String> {
- let host = cpal::default_host();
- let default_device = host.default_input_device().expect("No default input device available");
- let default_device_name = default_device.name().expect("Failed to get default device name");
-
- let devices = host.devices().expect("Failed to get devices");
- let mut input_device_names: Vec<String> = devices
- .filter_map(|device| {
- let supported_input_configs = device.supported_input_configs();
- if supported_input_configs.is_ok() && supported_input_configs.unwrap().count() > 0 {
- device.name().ok()
- } else {
- None
- }
- })
- .collect();
-
- input_device_names.retain(|name| name != &default_device_name);
- input_device_names.insert(0, default_device_name);
-
- input_device_names
-}
-
-use tokio::io::{ AsyncBufReadExt, BufReader };
-
-#[tracing::instrument]
-async fn start_recording_process(
- mut cmd: Command
-) -> Result<tokio::process::Child, std::io::Error> {
- let mut process = cmd.stdin(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
-
- if let Some(process_stderr) = process.stderr.take() {
- tokio::spawn(async move {
- let mut process_reader = BufReader::new(process_stderr).lines();
- while let Ok(Some(line)) = process_reader.next_line().await {
- // TODO: Collect this into one event. Custom implementation of Into<Stdio>?
- tracing::error!("FFmpeg process STDERR: {}", line);
- }
- });
- }
-
- Ok(process)
-}
-
-#[tracing::instrument]
-async fn wait_for_start_times(
- audio_start_time: &Mutex<Option<Instant>>,
- video_start_time: &Mutex<Option<Instant>>
-) -> (Instant, Instant) {
- loop {
- let audio_start_locked = audio_start_time.lock().await;
- let video_start_locked = video_start_time.lock().await;
-
- if audio_start_locked.is_some() && video_start_locked.is_some() {
- let audio_start = *audio_start_locked.as_ref().unwrap();
- let video_start = *video_start_locked.as_ref().unwrap();
- return (audio_start, video_start);
- }
- drop(audio_start_locked);
- drop(video_start_locked);
- tokio::time::sleep(Duration::from_millis(50)).await;
- }
-}
-
-pub enum TimeOffsetTarget {
- Audio,
- Video,
-}
-
-#[tracing::instrument]
-async fn create_time_offset_args(
- audio_start_time: &Mutex<Option<Instant>>,
- video_start_time: &Mutex<Option<Instant>>
-) -> Option<(TimeOffsetTarget, Vec<String>)> {
- let (audio_start, video_start) = wait_for_start_times(audio_start_time, video_start_time).await;
- let duration_difference = if audio_start > video_start {
- audio_start.duration_since(video_start)
- } else {
- video_start.duration_since(audio_start)
- };
-
- tracing::debug!("Duration difference: {:?}", duration_difference);
- tracing::debug!("Audio start: {:?}", audio_start);
- tracing::debug!("Video start: {:?}", video_start);
-
- // Convert the duration difference to a float representing seconds
- let offset_seconds =
- (duration_difference.as_secs() as f64) + (duration_difference.subsec_nanos() as f64) * 1e-9;
-
- // Depending on which started first, adjust the relevant FFmpeg command
- if audio_start > video_start {
- // Offset the video start time
- tracing::info!("Applying -itsoffset {:.3} to video", offset_seconds);
-
- Some((
- TimeOffsetTarget::Video,
- vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],
- ))
- } else if video_start > audio_start {
- // Offset the audio start time
- tracing::info!("Applying -itsoffset {:.3} to audio", offset_seconds);
-
- Some((
- TimeOffsetTarget::Audio,
- vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],
- ))
- } else {
- None
- }
-}
diff --git a/apps/desktop/src-tauri/src/media/audio.rs b/apps/desktop/src-tauri/src/media/audio.rs
new file mode 100644
index 000000000..7c41751e2
--- /dev/null
+++ b/apps/desktop/src-tauri/src/media/audio.rs
@@ -0,0 +1,239 @@
+use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
+use cpal::{Device, SampleFormat, SizedSample, Stream, SupportedStreamConfig};
+use indexmap::IndexMap;
+use num_traits::ToBytes;
+use std::{future::Future, path::PathBuf};
+use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc};
+
+use super::{Instant, SharedFlag, SharedInstant};
+use crate::utils;
+
+type SampleReceiver = mpsc::Receiver<Vec<u8>>;
+
+pub struct AudioCapturer {
+ device: Device,
+ pub device_name: String,
+ config: SupportedStreamConfig,
+ should_stop: SharedFlag,
+ sample_receiver: Option<SampleReceiver>,
+ stream: Option<Stream>,
+}
+
+impl AudioCapturer {
+ pub fn init(custom_device: Option<&str>, should_stop: SharedFlag) -> Option<Self> {
+ tracing::debug!("Custom device: {:?}", custom_device);
+
+ if custom_device == Some("None") {
+ return None;
+ }
+
+ let mut devices = get_input_devices();
+
+ let maybe_device = match custom_device {
+ None => {
+ let maybe_name = devices.first().map(|(name, _)| name.clone());
+ maybe_name.and_then(|device_name| devices.swap_remove_entry(&device_name))
+ }
+ Some(device_name) => devices.swap_remove_entry(device_name),
+ };
+
+ maybe_device.map(|(name, (device, config))| {
+ tracing::info!("Using audio device: {}", name);
+
+ Self {
+ config,
+ device,
+ device_name: name,
+ should_stop,
+ sample_receiver: None,
+ stream: None,
+ }
+ })
+ }
+
+ pub fn log_info(&self) {
+ tracing::info!("Sample rate: {}", self.sample_rate());
+ tracing::info!("Channels: {}", self.channels());
+ tracing::info!("Sample format: {}", self.sample_format());
+ }
+
+ pub fn start(&mut self, start_time: SharedInstant) -> Result<(), String> {
+ tracing::trace!("Building input stream...");
+
+ let (receiver, stream) = (match self.config.sample_format() {
+ SampleFormat::I8 => self.build_stream::<i8>(start_time),
+ SampleFormat::I16 => self.build_stream::<i16>(start_time),
+ SampleFormat::I32 => self.build_stream::<i32>(start_time),
+ SampleFormat::U8 => self.build_stream::<u8>(start_time),
+ SampleFormat::U16 => self.build_stream::<u16>(start_time),
+ SampleFormat::U32 => self.build_stream::<u32>(start_time),
+ SampleFormat::F32 => self.build_stream::<f32>(start_time),
+ SampleFormat::F64 => self.build_stream::<f64>(start_time),
+ _ => unreachable!(),
+ })?;
+
+ stream
+ .play()
+ .map_err(|_| "Failed to start audio recording")?;
+ tracing::info!("Audio recording started.");
+
+ self.stream = Some(stream);
+ self.sample_receiver = Some(receiver);
+ Ok(())
+ }
+
+ pub fn collect_samples(&mut self, destination: PathBuf) -> impl Future<Output = ()> + 'static {
+ tracing::trace!("Starting audio channel senders...");
+ let mut receiver = self
+ .sample_receiver
+ .take()
+ .expect("Audio sample collection already started!");
+ let should_stop = self.should_stop.clone();
+
+ async move {
+ let mut pipe = File::create(destination).await.unwrap();
+
+ while let Some(bytes) = receiver.recv().await {
+ if should_stop.get() {
+ break;
+ }
+ pipe.write_all(&bytes)
+ .await
+ .expect("Failed to write audio data to FFmpeg stdin");
+ }
+ }
+ }
+
+ pub fn stop(&mut self) -> Result<(), String> {
+ if let Some(ref mut stream) = self.stream {
+ stream.pause().map_err(|_| "Failed to pause stream")?;
+ tracing::info!("Audio recording paused.");
+ Ok(())
+ } else {
+ return Err("Original recording was not started".to_string());
+ }
+ }
+
+ // TODO: Where to add these...?
+ pub fn ffmpeg_filters(&self) -> Vec<&str> {
+ let mut audio_filters = Vec::new();
+
+ if self.channels() > 2 {
+ audio_filters.push("pan=stereo|FL=FL+0.5*FC|FR=FR+0.5*FC");
+ }
+
+ audio_filters.push("loudnorm");
+ audio_filters
+ }
+
+ pub fn sample_rate(&self) -> u32 {
+ self.config.sample_rate().0
+ }
+
+ pub fn channels(&self) -> u16 {
+ self.config.channels()
+ }
+
+ // Returns ffmpeg sample format ID and sample size in bytes
+ pub fn sample_format(&self) -> &str {
+ match self.config.sample_format() {
+ SampleFormat::I8 => "s8",
+ SampleFormat::I16 => "s16le",
+ SampleFormat::I32 => "s32le",
+ SampleFormat::U8 => "u8",
+ SampleFormat::U16 => "u16le",
+ SampleFormat::U32 => "u32le",
+ SampleFormat::F32 => "f32le",
+ SampleFormat::F64 => "f64le",
+ _ => unreachable!(),
+ }
+ }
+
+ fn build_stream<T>(&self, start_time: SharedInstant) -> Result<(SampleReceiver, Stream), String>
+ where
+ T: SizedSample + ToBytes<Bytes: AsRef<[u8]>>,
+ {
+ let (sender, receiver) = mpsc::channel(2048);
+
+ self.device
+ .build_input_stream(
+ &self.config.clone().into(),
+ move |data: &[T], _| {
+ let mut first_frame_time_guard = start_time.try_lock();
+
+ let sample_size = std::mem::size_of::<T>();
+ let mut bytes = vec![0; data.len() * sample_size];
+ for (dest, source) in bytes.chunks_exact_mut(sample_size).zip(data.iter()) {
+ dest.copy_from_slice(source.to_le_bytes().as_ref());
+ }
+
+ if sender.try_send(bytes).is_err() {
+ tracing::warn!("Audio channel send error. Dropping data.");
+ }
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
+ tracing::trace!("Audio start time captured");
+ }
+ }
+ },
+ |err| {
+ tracing::error!("An error occurred on the audio stream: {}", err);
+ },
+ None,
+ )
+ .map(|stream| (receiver, stream))
+ .map_err(|_| "Failed to build audio input stream".into())
+ }
+}
+
+pub fn get_input_devices() -> IndexMap<String, (Device, SupportedStreamConfig)> {
+ let host = cpal::default_host();
+ let mut device_map = IndexMap::new();
+
+ let get_usable_device = |device: Device| {
+ device
+ .supported_input_configs()
+ .map_err(utils::log_debug_error)
+ .ok()
+ .and_then(|mut configs| {
+ configs.find(|c| match c.sample_format() {
+ SampleFormat::I8
+ | SampleFormat::I16
+ | SampleFormat::I32
+ | SampleFormat::U8
+ | SampleFormat::U16
+ | SampleFormat::U32
+ | SampleFormat::F32
+ | SampleFormat::F64 => true,
+ _ => false,
+ })
+ })
+ .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
+}
diff --git a/apps/desktop/src-tauri/src/media/mod.rs b/apps/desktop/src-tauri/src/media/mod.rs
new file mode 100644
index 000000000..21c6d2dda
--- /dev/null
+++ b/apps/desktop/src-tauri/src/media/mod.rs
@@ -0,0 +1,403 @@
+use std::{
+ path::{Path, PathBuf},
+ process::Stdio,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
+ time::{Duration, Instant},
+};
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+use tokio::process::{Child, ChildStdin, Command};
+use tokio::sync::Mutex;
+
+use crate::{
+ recording::RecordingOptions,
+ utils::{create_named_pipe, ffmpeg_path_as_str},
+};
+
+mod audio;
+mod video;
+
+use audio::AudioCapturer;
+use video::VideoCapturer;
+
+type SharedInstant = Arc<Mutex<Option<Instant>>>;
+
+struct SharedFlag(Arc<AtomicBool>);
+
+impl Default for SharedFlag {
+ fn default() -> Self {
+ Self::new(false)
+ }
+}
+
+impl SharedFlag {
+ fn new(value: bool) -> Self {
+ Self(Arc::new(AtomicBool::new(value)))
+ }
+
+ fn get(&self) -> bool {
+ self.0.load(Ordering::SeqCst)
+ }
+
+ fn set(&self, value: bool) {
+ self.0.store(value, Ordering::SeqCst);
+ }
+
+ fn clone(&self) -> Self {
+ Self(Arc::clone(&self.0))
+ }
+}
+
+#[derive(Default)]
+pub struct MediaRecorder {
+ pub options: Option<RecordingOptions>,
+ audio_capturer: Option<AudioCapturer>,
+ audio_enabled: bool,
+ // video_capturer: Option<VideoCapturer>,
+ should_stop: SharedFlag,
+ ffmpeg_process: Option<Child>,
+ ffmpeg_stdin: Option<Arc<Mutex<Option<ChildStdin>>>>,
+ device_name: Option<String>,
+ start_time: Option<Instant>,
+ audio_file_path: Option<PathBuf>,
+ video_file_path: Option<PathBuf>,
+}
+
+impl MediaRecorder {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ #[tracing::instrument(skip(self))]
+ pub async fn start_media_recording(
+ &mut self,
+ options: RecordingOptions,
+ screenshot_dir: &Path,
+ audio_chunks_dir: &Path,
+ video_chunks_dir: &Path,
+ custom_device: Option<&str>,
+ max_screen_width: usize,
+ max_screen_height: usize,
+ ) -> Result<(), String> {
+ let options_clone = options.clone();
+ self.options = Some(options);
+
+ // let adjusted_width = max_screen_width & !2;
+ // let adjusted_height = max_screen_height & !2;
+
+ let ffmpeg_binary_path_str = ffmpeg_path_as_str().unwrap().to_owned();
+
+ let audio_start_time: SharedInstant = Arc::new(Mutex::new(None));
+ let video_start_time: SharedInstant = Arc::new(Mutex::new(None));
+
+ self.audio_capturer = AudioCapturer::init(custom_device, self.should_stop.clone());
+
+ let mut video_capturer = VideoCapturer::new(
+ max_screen_width,
+ max_screen_height,
+ self.should_stop.clone(),
+ );
+ let adjusted_width = video_capturer.frame_width;
+ let adjusted_height = video_capturer.frame_height;
+
+ if let Some(ref mut audio_capturer) = self.audio_capturer {
+ audio_capturer.log_info();
+
+ match audio_capturer.start(audio_start_time.clone()) {
+ Ok(_) => self.audio_enabled = true,
+ Err(error) => tracing::error!(error),
+ }
+ }
+
+ video_capturer.start(video_start_time.clone(), screenshot_dir, options_clone);
+
+ tracing::info!("Starting audio recording and processing...");
+ let audio_chunk_pattern = audio_chunks_dir.join("audio_recording_%03d.aac");
+ let video_chunk_pattern = video_chunks_dir.join("video_recording_%03d.ts");
+ let audio_segment_list_filename = audio_chunks_dir.join("segment_list.txt");
+ let video_segment_list_filename = video_chunks_dir.join("segment_list.txt");
+
+ let video_pipe_path = video_chunks_dir.join("pipe.pipe");
+
+ std::fs::remove_file(&video_pipe_path).ok();
+ create_named_pipe(&video_pipe_path).map_err(|e| e.to_string())?;
+
+ let audio_pipe_path = audio_chunks_dir.join("pipe.pipe");
+
+ std::fs::remove_file(&audio_pipe_path).ok();
+ create_named_pipe(&audio_pipe_path).map_err(|e| e.to_string())?;
+
+ let time_offset = if self.audio_enabled {
+ tracing::trace!("Adjusting FFmpeg commands based on start times...");
+ create_time_offset_args(&audio_start_time, &video_start_time).await
+ } else {
+ None
+ };
+
+ let size = format!("{}x{}", adjusted_width, adjusted_height);
+
+ let mut ffmpeg_command = Command::new(ffmpeg_binary_path_str);
+
+ if let Some((TimeOffsetTarget::Video, args)) = &time_offset {
+ ffmpeg_command.args(args);
+ }
+
+ ffmpeg_command
+ // video in
+ .args(["-f", "rawvideo", "-pix_fmt", "bgra"])
+ .args(["-s", &size, "-r", "30"])
+ .args(["-thread_queue_size", "4096", "-i"])
+ .arg(&video_pipe_path)
+ // video out
+ .args(["-vf", "fps=30,scale=in_range=full:out_range=limited"])
+ .args(["-c:v", "libx264", "-preset", "ultrafast"])
+ .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
+ .args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
+ .args(["-f", "segment", "-movflags", "frag_keyframe+empty_moov"])
+ .args(["-reset_timestamps", "1", "-an"])
+ .args(["-segment_time", "3"])
+ .args(["-segment_format", "ts"])
+ .args(["-segment_time_delta", "0.01", "-segment_list"])
+ .args([&video_segment_list_filename, &video_chunk_pattern]);
+
+ if self.audio_enabled {
+ if let Some((TimeOffsetTarget::Audio, args)) = &time_offset {
+ ffmpeg_command.args(args);
+ }
+
+ let capturer = self.audio_capturer.as_ref().unwrap();
+ let sample_format = capturer.sample_format();
+ let sample_rate_str = capturer.sample_rate().to_string();
+ let channels_str = capturer.channels().to_string();
+
+ ffmpeg_command
+ // audio in
+ .args(["-f", sample_format, "-ar", &sample_rate_str])
+ .args(["-ac", &channels_str, "-thread_queue_size", "4096", "-i"])
+ .arg(&audio_pipe_path)
+ // out
+ .args([
+ "-af",
+ "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
+ ])
+ .args(["-codec:a", "aac", "-b:a", "128k"])
+ .args(["-async", "1", "-f", "segment"])
+ .args(["-segment_time", "3", "-segment_time_delta", "0.01"])
+ .args(["-reset_timestamps", "1", "-vn", "-segment_list"])
+ .args([&audio_segment_list_filename, &audio_chunk_pattern]);
+ }
+
+ tracing::trace!("Starting FFmpeg process...");
+
+ tracing::trace!("Starting FFmpeg process...");
+
+ let (ffmpeg_child, ffmpeg_stdin) = self
+ .start_ffmpeg_process(ffmpeg_command)
+ .await
+ .map_err(|e| e.to_string())?;
+ tracing::trace!("Ffmpeg process started");
+
+ if let Some(ffmpeg_stdin_mutex) = &self.ffmpeg_stdin {
+ let mut stdin_lock = ffmpeg_stdin_mutex.lock().await;
+ *stdin_lock = Some(ffmpeg_stdin);
+ drop(stdin_lock);
+ tracing::trace!("Ffmpeg stdin set");
+ }
+
+ if self.audio_enabled {
+ let capturer = self.audio_capturer.as_mut().unwrap();
+ tokio::spawn(capturer.collect_samples(audio_pipe_path));
+ }
+
+ tokio::spawn(video_capturer.collect_frames(video_pipe_path));
+
+ self.start_time = Some(Instant::now());
+ self.audio_file_path = Some(audio_chunks_dir.to_path_buf());
+ self.video_file_path = Some(video_chunks_dir.to_path_buf());
+ self.ffmpeg_process = Some(ffmpeg_child);
+ self.device_name = self.audio_capturer.as_ref().map(|c| c.device_name.clone());
+
+ tracing::info!("Media recording successfully started");
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self))]
+ pub async fn stop_media_recording(&mut self) -> Result<(), String> {
+ if let Some(start_time) = self.start_time {
+ let segment_duration = Duration::from_secs(3);
+ let recording_duration = start_time.elapsed();
+ let expected_segments = recording_duration.as_secs() / segment_duration.as_secs();
+ let expected_audio_segments = match self.audio_enabled {
+ true => expected_segments,
+ false => 0,
+ };
+ let audio_file_path = self
+ .audio_file_path
+ .as_ref()
+ .ok_or("Audio file path not set")?;
+ let video_file_path = self
+ .video_file_path
+ .as_ref()
+ .ok_or("Video file path not set")?;
+ let audio_segment_list_filename = audio_file_path.join("segment_list.txt");
+ let video_segment_list_filename = video_file_path.join("segment_list.txt");
+
+ loop {
+ let audio_segments =
+ std::fs::read_to_string(&audio_segment_list_filename).unwrap_or_default();
+ let video_segments =
+ std::fs::read_to_string(&video_segment_list_filename).unwrap_or_default();
+
+ let audio_segment_count = audio_segments.lines().count();
+ let video_segment_count = video_segments.lines().count();
+
+ if audio_segment_count >= (expected_audio_segments as usize)
+ && video_segment_count >= (expected_segments as usize)
+ {
+ tracing::info!("All segments generated");
+ break;
+ }
+
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ }
+ }
+
+ if let Some(ref ffmpeg_stdin) = self.ffmpeg_stdin {
+ let mut stdin_guard = ffmpeg_stdin.lock().await;
+ if let Some(mut stdin) = stdin_guard.take() {
+ if let Err(e) = stdin.write_all(b"q\n").await {
+ tracing::error!("Failed to send 'q' to video FFmpeg process: {}", e);
+ }
+ let _ = stdin.shutdown().await.map_err(|e| e.to_string());
+ }
+ }
+
+ self.should_stop.set(true);
+
+ if let Some(ref mut audio_capturer) = self.audio_capturer {
+ audio_capturer.stop()?;
+ }
+
+ if let Some(process) = &mut self.ffmpeg_process {
+ let _ = process.kill().await.map_err(|e| e.to_string());
+ }
+
+ tracing::info!("Audio recording stopped.");
+ Ok(())
+ }
+
+ async fn start_ffmpeg_process(
+ &self,
+ cmd: Command,
+ ) -> Result<(Child, ChildStdin), std::io::Error> {
+ let mut video_process = start_recording_process(cmd).await.map_err(|e| {
+ tracing::error!("Failed to start video recording process: {}", e);
+ std::io::Error::new(std::io::ErrorKind::Other, e.to_string())
+ })?;
+
+ let video_stdin = video_process.stdin.take().ok_or_else(|| {
+ tracing::error!("Failed to take video stdin");
+ std::io::Error::new(std::io::ErrorKind::Other, "Failed to take video stdin")
+ })?;
+
+ Ok((video_process, video_stdin))
+ }
+}
+
+#[tauri::command]
+#[specta::specta]
+#[tracing::instrument]
+pub fn enumerate_audio_devices() -> Vec<String> {
+ let devices = audio::get_input_devices();
+
+ devices.keys().cloned().collect()
+}
+
+#[tracing::instrument]
+async fn start_recording_process(
+ mut cmd: Command,
+) -> Result<tokio::process::Child, std::io::Error> {
+ let mut process = cmd.stdin(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
+
+ if let Some(process_stderr) = process.stderr.take() {
+ tokio::spawn(async move {
+ let mut process_reader = BufReader::new(process_stderr).lines();
+ while let Ok(Some(line)) = process_reader.next_line().await {
+ // TODO: Collect this into one event. Custom implementation of Into<Stdio>?
+ tracing::error!("FFmpeg process STDERR: {}", line);
+ }
+ });
+ }
+
+ Ok(process)
+}
+
+#[tracing::instrument]
+async fn wait_for_start_times(
+ audio_start_time: &Mutex<Option<Instant>>,
+ video_start_time: &Mutex<Option<Instant>>,
+) -> (Instant, Instant) {
+ loop {
+ let audio_start_locked = audio_start_time.lock().await;
+ let video_start_locked = video_start_time.lock().await;
+
+ if audio_start_locked.is_some() && video_start_locked.is_some() {
+ let audio_start = *audio_start_locked.as_ref().unwrap();
+ let video_start = *video_start_locked.as_ref().unwrap();
+ return (audio_start, video_start);
+ }
+ drop(audio_start_locked);
+ drop(video_start_locked);
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
+pub enum TimeOffsetTarget {
+ Audio,
+ Video,
+}
+
+#[tracing::instrument]
+async fn create_time_offset_args(
+ audio_start_time: &Mutex<Option<Instant>>,
+ video_start_time: &Mutex<Option<Instant>>,
+) -> Option<(TimeOffsetTarget, Vec<String>)> {
+ let (audio_start, video_start) = wait_for_start_times(audio_start_time, video_start_time).await;
+ let duration_difference = if audio_start > video_start {
+ audio_start.duration_since(video_start)
+ } else {
+ video_start.duration_since(audio_start)
+ };
+
+ tracing::debug!("Duration difference: {:?}", duration_difference);
+ tracing::debug!("Audio start: {:?}", audio_start);
+ tracing::debug!("Video start: {:?}", video_start);
+
+ // Convert the duration difference to a float representing seconds
+ let offset_seconds =
+ (duration_difference.as_secs() as f64) + (duration_difference.subsec_nanos() as f64) * 1e-9;
+
+ // Depending on which started first, adjust the relevant FFmpeg command
+ if audio_start > video_start {
+ // Offset the video start time
+ tracing::info!("Applying -itsoffset {:.3} to video", offset_seconds);
+
+ Some((
+ TimeOffsetTarget::Video,
+ vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],
+ ))
+ } else if video_start > audio_start {
+ // Offset the audio start time
+ tracing::info!("Applying -itsoffset {:.3} to audio", offset_seconds);
+
+ Some((
+ TimeOffsetTarget::Audio,
+ vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],
+ ))
+ } else {
+ None
+ }
+}
diff --git a/apps/desktop/src-tauri/src/media/video.rs b/apps/desktop/src-tauri/src/media/video.rs
new file mode 100644
index 000000000..441959f97
--- /dev/null
+++ b/apps/desktop/src-tauri/src/media/video.rs
@@ -0,0 +1,186 @@
+use image::codecs::jpeg::JpegEncoder;
+use image::{ImageBuffer, Rgba};
+use scap::{
+ capturer::{Capturer, Options, Resolution},
+ frame::{Frame, FrameType},
+};
+use std::{
+ future::Future,
+ path::{Path, PathBuf},
+ time::Duration,
+};
+use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc};
+
+use super::{Instant, RecordingOptions, SharedFlag, SharedInstant};
+use crate::app::config;
+use crate::upload::{upload_file, FileType};
+
+pub struct VideoCapturer {
+ capturer: Option<Capturer>,
+ should_stop: SharedFlag,
+ pub frame_width: u32,
+ pub frame_height: u32,
+ frame_receiver: Option<mpsc::Receiver<Vec<u8>>>,
+}
+
+impl VideoCapturer {
+ pub fn new(_width: usize, _height: usize, should_stop: SharedFlag) -> VideoCapturer {
+ let mut capturer = Capturer::new(Options {
+ fps: 30,
+ target: None,
+ show_cursor: true,
+ show_highlight: true,
+ excluded_targets: None,
+ output_type: FrameType::BGRAFrame,
+ output_resolution: Resolution::Captured,
+ crop_area: None,
+ });
+
+ let [frame_width, frame_height] = capturer.get_output_frame_size();
+
+ Self {
+ capturer: Some(capturer),
+ should_stop,
+ frame_receiver: None,
+ frame_width,
+ frame_height,
+ }
+ }
+
+ pub fn start(
+ &mut self,
+ start_time: SharedInstant,
+ screenshot_dir: impl AsRef<Path>,
+ recording_options: RecordingOptions,
+ ) {
+ let mut capturer = self
+ .capturer
+ .take()
+ .expect("Video capturing thread has already been started!");
+ let (sender, receiver) = mpsc::channel(2048);
+
+ self.frame_receiver = Some(receiver);
+ let screenshot_file_path = screenshot_dir.as_ref().join("screen-capture.jpg");
+ let should_stop = self.should_stop.clone();
+
+ std::thread::spawn(move || {
+ tracing::trace!("Starting video recording capture thread...");
+
+ let capture_start_time = Instant::now();
+ let mut screenshot_captured: bool = false;
+ let take_screenshot_delay = Duration::from_secs(3);
+
+ capturer.start_capture();
+
+ while !should_stop.get() {
+ let screenshot_path = screenshot_file_path.clone();
+ let options_clone = recording_options.clone();
+
+ match capturer.get_next_frame() {
+ Ok(Frame::BGRA(frame)) => {
+ // TODO: Check if stride needs adjusting. Implement that in scap instead of here?
+ let now = Instant::now();
+
+ if now - capture_start_time >= take_screenshot_delay && !screenshot_captured
+ {
+ screenshot_captured = true;
+ let mut frame_data_clone = frame.data.clone();
+
+ std::thread::spawn(move || {
+ for chunk in frame_data_clone.chunks_mut(4) {
+ chunk.swap(0, 2);
+ }
+
+ let image: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_raw(
+ frame.width.try_into().unwrap(),
+ frame.height.try_into().unwrap(),
+ frame_data_clone,
+ )
+ .expect("Failed to create image buffer");
+
+ let mut output_file = std::fs::File::create(&screenshot_path)
+ .expect("Failed to create output file");
+ let mut encoder =
+ JpegEncoder::new_with_quality(&mut output_file, 70);
+
+ if let Err(e) = encoder.encode_image(&image) {
+ tracing::warn!("Failed to save screenshot: {}", e);
+ } else {
+ tracing::info!(
+ "Screenshot captured and saved to {:?}",
+ screenshot_path
+ );
+ }
+
+ if !config::is_local_mode() {
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ rt.block_on(async move {
+ let upload_task = tokio::spawn(upload_file(
+ Some(options_clone),
+ screenshot_path.clone(),
+ FileType::Screenshot,
+ ));
+ match upload_task.await {
+ Ok(result) => match result {
+ Ok(_) => tracing::info!(
+ "Screenshot successfully uploaded"
+ ),
+ Err(e) => {
+ tracing::warn!("Failed to upload file: {}", e)
+ }
+ },
+ Err(e) => {
+ tracing::error!("Failed to join task: {}", e)
+ }
+ }
+ });
+ }
+ });
+ }
+
+ if sender.try_send(frame.data).is_err() {
+ tracing::warn!("Video channel send error. Dropping data.");
+ }
+
+ let mut first_frame_time_guard = start_time.try_lock();
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
+ tracing::trace!("Video start time captured");
+ }
+ }
+ }
+ Ok(_) => unreachable!(),
+ Err(error) => {
+ tracing::error!("Capture error: {}", error);
+ break;
+ }
+ }
+ }
+ });
+ }
+
+ pub fn collect_frames(&mut self, destination: PathBuf) -> impl Future<Output = ()> + 'static {
+ tracing::trace!("Starting video channel senders...");
+ let mut receiver = self
+ .frame_receiver
+ .take()
+ .expect("Video frame collection already started!");
+ let should_stop = self.should_stop.clone();
+
+ async move {
+ let mut pipe = File::create(destination).await.unwrap();
+
+ while let Some(bytes) = receiver.recv().await {
+ if should_stop.get() {
+ break;
+ }
+ pipe.write_all(&bytes)
+ .await
+ .expect("Failed to write video data to FFmpeg stdin");
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 5e3c8605c..0cfa5a281 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -10,7 +10,6 @@ use std::sync::{
};
use tauri::State;
use tokio::sync::Mutex;
-use tokio::task::JoinHandle;
use tokio::time::Duration;
use crate::app::config;
diff --git a/apps/desktop/src-tauri/src/utils.rs b/apps/desktop/src-tauri/src/utils.rs
index d1061131b..df0a4139e 100644
--- a/apps/desktop/src-tauri/src/utils.rs
+++ b/apps/desktop/src-tauri/src/utils.rs
@@ -41,3 +41,7 @@ pub fn create_named_pipe(path: &Path) -> Result<(), nix::Error> {
unistd::mkfifo(path, stat::Mode::S_IRWXU)?;
Ok(())
}
+
+pub fn log_debug_error(error: impl std::fmt::Display) {
+ tracing::debug!("Error: {error}")
+}
diff --git a/apps/src/utils/commands.ts b/apps/src/utils/commands.ts
new file mode 100644
index 000000000..8ef1f19a6
--- /dev/null
+++ b/apps/src/utils/commands.ts
@@ -0,0 +1,57 @@
+/* eslint-disable */
+// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.
+
+declare global {
+ interface Window {
+ __TAURI_INVOKE__<T>(cmd: string, args?: Record<string, unknown>): Promise<T>;
+ }
+}
+
+// Function avoids 'window not defined' in SSR
+const invoke = () => window.__TAURI_INVOKE__;
+
+export function startDualRecording(options: RecordingOptions) {
+ return invoke()<null>("start_dual_recording", { options })
+}
+
+export function stopAllRecordings() {
+ return invoke()<null>("stop_all_recordings")
+}
+
+export function enumerateAudioDevices() {
+ return invoke()<string[]>("enumerate_audio_devices")
+}
+
+export function startServer() {
+ return invoke()<number>("start_server")
+}
+
+export function openScreenCapturePreferences() {
+ return invoke()<null>("open_screen_capture_preferences")
+}
+
+export function openMicPreferences() {
+ return invoke()<null>("open_mic_preferences")
+}
+
+export function openCameraPreferences() {
+ return invoke()<null>("open_camera_preferences")
+}
+
+export function hasScreenCaptureAccess() {
+ return invoke()<boolean>("has_screen_capture_access")
+}
+
+export function resetScreenPermissions() {
+ return invoke()<null>("reset_screen_permissions")
+}
+
+export function resetMicrophonePermissions() {
+ return invoke()<null>("reset_microphone_permissions")
+}
+
+export function resetCameraPermissions() {
+ return invoke()<null>("reset_camera_permissions")
+}
+
+export type RecordingOptions = { user_id: string; video_id: string; screen_index: string; video_index: string; audio_name: string; aws_region: string; aws_bucket: string }