Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
combine video and audio into one ffmpeg process
Brendan Allane24b78355552
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex f199f5d6d..2eed91cbf 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -1,27 +1,29 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]-use std::collections::LinkedList;-use std::sync::{Arc};-use std::path::PathBuf;use cpal::Devices;use regex::Regex;+use std::collections::LinkedList;+use std::path::PathBuf;+use std::sync::atomic::AtomicBool;+use std::sync::Arc;+use std::vec;+use tauri::{+ CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTraySubmenu, Window,+};+use tauri_plugin_oauth::start;+use tauri_plugin_positioner::{Position, WindowExt};use tokio::sync::Mutex;-use std::sync::atomic::{AtomicBool};-use std::{vec};-use tauri::{CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTraySubmenu, Window};-use window_vibrancy::{apply_blur, apply_vibrancy, NSVisualEffectMaterial};use window_shadows::set_shadow;-use tauri_plugin_positioner::{WindowExt, Position};-use tauri_plugin_oauth::start;+use window_vibrancy::{apply_blur, apply_vibrancy, NSVisualEffectMaterial};+mod media;mod recording;mod upload;mod utils;-mod media;-use recording::{RecordingState, start_dual_recording, stop_all_recordings};-use media::{enumerate_audio_devices};-use utils::{has_screen_capture_access};+use media::enumerate_audio_devices;+use recording::{start_dual_recording, stop_all_recordings, RecordingState};+use utils::has_screen_capture_access;use ffmpeg_sidecar::{command::ffmpeg_is_installed,@@ -238,8 +240,7 @@ fn main() {media_process: None,recording_options: None,shutdown_flag: Arc::new(AtomicBool::new(false)),- video_uploading_finished: Arc::new(AtomicBool::new(false)),- audio_uploading_finished: Arc::new(AtomicBool::new(false)),+ uploading_finished: Arc::new(AtomicBool::new(false)),data_dir: Some(data_directory),max_screen_width: max_width as usize,max_screen_height: max_height as usize,diff --git a/apps/desktop/src-tauri/src/media.rs b/apps/desktop/src-tauri/src/media.rsindex 436eaa0c3..e7b8d02ac 100644--- a/apps/desktop/src-tauri/src/media.rs+++ b/apps/desktop/src-tauri/src/media.rs@@ -1,67 +1,72 @@+use byteorder::{ByteOrder, LittleEndian};use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};use cpal::SampleFormat;-use std::process::{Stdio};-use byteorder::{ByteOrder, LittleEndian};-use std::sync::{Arc, atomic::{AtomicBool, Ordering}};-use std::io::{ErrorKind::WouldBlock, Error};-use std::time::{Instant, Duration};-use std::path::Path;-use image::{ImageBuffer, Rgba, ImageFormat};use image::codecs::jpeg::JpegEncoder;--use tokio::io::{AsyncWriteExt};-use tokio::process::{Command, Child, ChildStdin};+use image::{ImageBuffer, ImageFormat, Rgba};+use std::io::{Error, ErrorKind::WouldBlock};+use std::path::Path;+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::recording::RecordingOptions;-use crate::utils::{ffmpeg_path_as_str};-use crate::upload::upload_file;+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_audio_process: Option<tokio::process::Child>,- ffmpeg_video_process: Option<tokio::process::Child>,- ffmpeg_audio_stdin: Option<Arc<Mutex<Option<tokio::process::ChildStdin>>>>,- ffmpeg_video_stdin: Option<Arc<Mutex<Option<tokio::process::ChildStdin>>>>,+ ffmpeg_process: Option<tokio::process::Child>,+ ffmpeg_stdin: Option<Arc<Mutex<Option<tokio::process::ChildStdin>>>>,device_name: Option<String>,- stream: Option<cpal::Stream>,+ 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<String>,- video_file_path: Option<String>,+ file_path: Option<String>,}impl MediaRecorder {-pub fn new() -> Self {MediaRecorder {options: None,- ffmpeg_audio_process: None,- ffmpeg_video_process: None,- ffmpeg_audio_stdin: None,- ffmpeg_video_stdin: None,+ ffmpeg_process: None,+ ffmpeg_stdin: None,device_name: None,- stream: 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,+ file_path: None,}}- pub async fn start_media_recording(&mut self, options: RecordingOptions, audio_file_path: &str, video_file_path: &str, screenshot_file_path: &str, custom_device: Option<&str>, max_screen_width: usize, max_screen_height: usize) -> Result<(), String> {+ pub async fn start_media_recording(+ &mut self,+ options: RecordingOptions,+ chunks_file_path: &str,+ screenshot_file_path: &str,+ custom_device: Option<&str>,+ max_screen_width: usize,+ max_screen_height: usize,+ ) -> Result<(), String> {self.options = Some(options.clone());println!("Custom device: {:?}", custom_device);@@ -93,8 +98,7 @@ impl MediaRecorder {self.audio_channel_receiver = Some(audio_rx);self.video_channel_sender = Some(video_tx);self.video_channel_receiver = Some(video_rx);- self.ffmpeg_audio_stdin = Some(Arc::new(Mutex::new(None)));- self.ffmpeg_video_stdin = Some(Arc::new(Mutex::new(None)));+ 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();@@ -115,20 +119,41 @@ impl MediaRecorder {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"))+ .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")+ host.default_input_device()+ .expect("No default input device available")};- println!("Using audio device: {}", device.name().expect("Failed to get device name"));+ println!(+ "Using audio device: {}",+ device.name().expect("Failed to get device name")+ );- let config = device.supported_input_configs()+ 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")- )+ .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;@@ -149,139 +174,139 @@ impl MediaRecorder {println!("FFmpeg binary path: {}", ffmpeg_binary_path_str);- let audio_file_path_owned = audio_file_path.to_owned();- let video_file_path_owned = video_file_path.to_owned();let sample_rate_str = sample_rate.to_string();let channels_str = channels.to_string();- let ffmpeg_audio_stdin = self.ffmpeg_audio_stdin.clone();- let ffmpeg_video_stdin = self.ffmpeg_video_stdin.clone();-let err_fn = move |err| {eprintln!("an error occurred on stream: {}", err);};- if custom_device != Some("None") {+ let needs_audio = custom_device != Some("None");++ if needs_audio {println!("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() {- eprintln!("Channel send error. Dropping data.");+ 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() {+ eprintln!("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());++ println!("Audio start time captured");+ }+ }}- }-- if let Ok(ref mut start_time_option) = first_frame_time_guard {- if start_time_option.is_none() {- **start_time_option = Some(Instant::now());-- println!("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() {- eprintln!("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());-- println!("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() {- eprintln!("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());-- println!("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() {- eprintln!("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());-- println!("Audio start time captured");- }- }- }- },- err_fn,- None,- ),- _sample_format => Err(cpal::BuildStreamError::DeviceNotAvailable),- };+ },+ 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() {+ eprintln!("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());++ println!("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() {+ eprintln!("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());++ println!("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() {+ eprintln!("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());++ println!("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.stream = Some(stream);+ self.audio_stream = Some(stream);self.trigger_play()?;}let video_start_time_clone = Arc::clone(&video_start_time);- let screenshot_file_path_owned = format!("{}/screen-capture.jpg", screenshot_file_path);+ let screenshot_file_path_owned = format!("{screenshot_file_path}/screen-capture.jpg");+let capture_frame_at = Duration::from_secs(3);std::thread::spawn(move || {@@ -292,7 +317,12 @@ impl MediaRecorder {_ => false,};- 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 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);@@ -309,10 +339,12 @@ impl MediaRecorder {if now >= time_next {match capturer.frame() {Ok(frame) => {- let mut frame_data = Vec::with_capacity(capture_size.try_into().unwrap());+ 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);+ 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 rowlet start = row * padded_stride;@@ -323,7 +355,8 @@ impl MediaRecorder {if now - start_time >= capture_frame_at && !screenshot_captured {screenshot_captured = true;- let screenshot_file_path_owned_cloned = screenshot_file_path_owned.clone();+ let screenshot_file_path_owned_cloned =+ screenshot_file_path_owned.clone();let mut frame_data_clone = frame_data.clone();std::thread::spawn(move || {@@ -332,31 +365,46 @@ impl MediaRecorder {}let path = Path::new(&screenshot_file_path_owned_cloned);- 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(&path).expect("Failed to create output file");- let mut encoder = JpegEncoder::new_with_quality(&mut output_file, 20);+ 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(&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) {eprintln!("Failed to save screenshot: {}", e);} else {if !is_local_mode {let rt = tokio::runtime::Runtime::new().unwrap();- let screenshot_file_path_owned_cloned_copy = screenshot_file_path_owned_cloned.clone();+ let screenshot_file_path_owned_cloned_copy =+ screenshot_file_path_owned_cloned.clone();rt.block_on(async {- let upload_task = tokio::spawn(upload_file(Some(options_clone), screenshot_file_path_owned_cloned_copy.clone(), "screenshot".to_string()));+ let upload_task = tokio::spawn(upload_file(+ Some(options_clone),+ screenshot_file_path_owned_cloned_copy.clone(),+ upload::FileType::Screenshot,+ ));match upload_task.await {- Ok(result) => {- match result {- Ok(_) => println!("Screenshot captured and saved to {:?}", path),- Err(e) => eprintln!("Failed to upload file: {}", e),- }+ Ok(result) => match result {+ Ok(_) => println!(+ "Screenshot captured and saved to {:?}",+ path+ ),+ Err(e) => eprintln!(+ "Failed to upload file: {}",+ e+ ),},- Err(e) => eprintln!("Failed to join task: {}", e),+ Err(e) => {+ eprintln!("Failed to join task: {}", e)+ }}});}@@ -382,15 +430,15 @@ impl MediaRecorder {}frame_count += 1;- },+ }Err(error) if error.kind() == WouldBlock => {std::thread::sleep(Duration::from_millis(1));continue;- },+ }Err(error) => {eprintln!("Capture error: {}", error);break;- },+ }}time_next += spf;@@ -409,10 +457,8 @@ impl MediaRecorder {});println!("Starting audio recording and processing...");- let audio_output_chunk_pattern = format!("{}/audio_recording_%03d.aac", audio_file_path_owned);- let audio_segment_list_filename = format!("{}/segment_list.txt", audio_file_path_owned);- let video_output_chunk_pattern = format!("{}/video_recording_%03d.ts", video_file_path_owned);- let video_segment_list_filename = format!("{}/segment_list.txt", video_file_path_owned);+ let video_output_chunk_pattern = format!("{chunks_file_path}/video_recording_%03d.ts");+ let video_segment_list_filename = format!("{chunks_file_path}/segment_list.txt");let mut audio_filters = Vec::new();@@ -422,123 +468,140 @@ impl MediaRecorder {audio_filters.push("loudnorm");- let mut ffmpeg_audio_command: Vec<String> = vec![- "-f", sample_format,- "-ar", &sample_rate_str,- "-ac", &channels_str,- "-thread_queue_size", "4096",- "-i", "pipe:0",- "-af", "aresample=async=1:min_hard_comp=0.100000:first_pts=0",- "-c:a", "aac",- "-b:a", "128k",- "-async", "1",- "-f", "segment",- "-segment_time", "3",- "-segment_time_delta", "0.01",- "-segment_list", &audio_segment_list_filename,- "-reset_timestamps", "1",- &audio_output_chunk_pattern,- ].into_iter().map(|s| s.to_string()).collect();-- let mut ffmpeg_video_command: Vec<String> = vec![- "-f", "rawvideo",- "-pix_fmt", "bgra",- "-s", &format!("{}x{}", adjusted_width, adjusted_height),- "-r", "30",- "-thread_queue_size", "4096",- "-i", "pipe:0",- "-vf", "fps=30,scale=in_range=full:out_range=limited",- "-c:v", "libx264",- "-preset", "ultrafast",- "-pix_fmt", "yuv420p",- "-tune", "zerolatency",- "-vsync", "1",- "-force_key_frames", "expr:gte(t,n_forced*3)",- "-f", "segment",- "-segment_time", "3",- "-segment_time_delta", "0.01",- "-segment_list", &video_segment_list_filename,- "-segment_format", "ts",- "-movflags", "frag_keyframe+empty_moov",- "-reset_timestamps", "1",- &video_output_chunk_pattern,- ].into_iter().map(|s| s.to_string()).collect();-- if custom_device != Some("None") {+ std::fs::create_dir_all(format!("{chunks_file_path}/pipes")).map_err(|e| e.to_string())?;++ let video_pipe_path = format!("{chunks_file_path}/pipes/video.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 = format!("{chunks_file_path}/pipes/audio.pipe");++ std::fs::remove_file(&audio_pipe_path).ok();+ create_named_pipe(&audio_pipe_path).map_err(|e| e.to_string())?;++ let size = format!("{}x{}", adjusted_width, adjusted_height);+ let mut ffmpeg_command = vec![+ ["-f", "rawvideo"],+ ["-pix_fmt", "bgra"],+ ["-s", &size],+ ["-r", "30"],+ ["-thread_queue_size", "4096"],+ ["-i", &video_pipe_path],+ ];++ if needs_audio {+ ffmpeg_command.extend([+ // in+ ["-f", sample_format],+ ["-ar", &sample_rate_str],+ ["-ac", &channels_str],+ ["-thread_queue_size", "4096"],+ ["-i", &audio_pipe_path],+ // out+ [+ "-af",+ "aresample=async=1:min_hard_comp=0.100000:first_pts=0",+ ],+ ["-c:a", "aac"],+ ["-b:a", "128k"],+ ["-async", "1"],+ ]);+ };++ ffmpeg_command.extend([+ ["-vf", "fps=30,scale=in_range=full:out_range=limited"],+ ["-c:v", "libx264"],+ ["-preset", "ultrafast"],+ ["-pix_fmt", "yuv420p"],+ ["-tune", "zerolatency"],+ ["-vsync", "1"],+ ["-force_key_frames", "expr:gte(t,n_forced*3)"],+ ["-f", "segment"],+ ["-segment_time", "3"],+ ["-segment_time_delta", "0.01"],+ ["-segment_list", &video_segment_list_filename],+ ["-segment_format", "ts"],+ ["-movflags", "frag_keyframe+empty_moov"],+ ["-reset_timestamps", "1"],+ ]);++ let mut ffmpeg_command = ffmpeg_command+ .into_iter()+ .flatten()+ .map(|s| s.to_string())+ .chain([video_output_chunk_pattern])+ .collect();++ if needs_audio {println!("Adjusting FFmpeg commands based on start times...");adjust_ffmpeg_commands_based_on_start_times(Arc::clone(&audio_start_time),Arc::clone(&video_start_time),- &mut ffmpeg_audio_command,- &mut ffmpeg_video_command,- ).await;- }-- println!("Starting FFmpeg audio and video processes...");-- let mut audio_stdin: Option<ChildStdin> = None;- let mut audio_child: Option<Child> = None;-- if custom_device != Some("None") {- let (child, stdin) = self.start_audio_ffmpeg_processes(&ffmpeg_binary_path_str, &ffmpeg_audio_command).await.map_err(|e| e.to_string())?;- audio_child = Some(child);- audio_stdin = Some(stdin);- println!("Audio process started");+ &mut ffmpeg_command,+ )+ .await;}- let (video_child, video_stdin) = self.start_video_ffmpeg_processes(&ffmpeg_binary_path_str, &ffmpeg_video_command).await.map_err(|e| e.to_string())?;- println!("Video process started");+ println!("Starting FFmpeg process...");- if let Some(ffmpeg_audio_stdin) = &self.ffmpeg_audio_stdin {- let mut audio_stdin_lock = ffmpeg_audio_stdin.lock().await;- *audio_stdin_lock = audio_stdin;- drop(audio_stdin_lock);- println!("Audio stdin set");- }+ let (ffmpeg_child, ffmpeg_stdin) = self+ .start_ffmpeg_process(&ffmpeg_binary_path_str, &ffmpeg_command)+ .await+ .map_err(|e| e.to_string())?;+ println!("Ffmpeg process started");- if let Some(ffmpeg_video_stdin) = &self.ffmpeg_video_stdin {+ if let Some(ffmpeg_video_stdin) = &self.ffmpeg_stdin {let mut video_stdin_lock = ffmpeg_video_stdin.lock().await;- *video_stdin_lock = Some(video_stdin);+ *video_stdin_lock = Some(ffmpeg_stdin);drop(video_stdin_lock);- println!("Video stdin set");+ println!("Ffmpeg stdin set");}- if custom_device != Some("None") {+ if needs_audio {println!("Starting audio channel senders...");+tokio::spawn(async move {- while let Some(bytes) = &audio_channel_receiver.lock().await.as_mut().unwrap().recv().await {- if let Some(audio_stdin_arc) = &ffmpeg_audio_stdin{- let mut audio_stdin_guard = audio_stdin_arc.lock().await;- if let Some(ref mut stdin) = *audio_stdin_guard {- stdin.write_all(&bytes).await.expect("Failed to write audio data to FFmpeg stdin");- }- drop(audio_stdin_guard);- }+ 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+ {+ audio_pipe+ .write_all(&bytes)+ .await+ .expect("Failed to write audio data to FFmpeg stdin");}});}println!("Starting video channel senders...");tokio::spawn(async move {- while let Some(bytes) = &video_channel_receiver.lock().await.as_mut().unwrap().recv().await {- if let Some(video_stdin_arc) = &ffmpeg_video_stdin {- let mut video_stdin_guard = video_stdin_arc.lock().await;- if let Some(ref mut stdin) = *video_stdin_guard {- stdin.write_all(&bytes).await.expect("Failed to write video data to FFmpeg stdin");- }- drop(video_stdin_guard);- }+ let mut video_pipe = File::create(video_pipe_path).await.unwrap();++ while let Some(bytes) = &video_channel_receiver+ .lock()+ .await+ .as_mut()+ .unwrap()+ .recv()+ .await+ {+ video_pipe+ .write_all(&bytes)+ .await+ .expect("Failed to write video data to FFmpeg stdin");}});- if custom_device != Some("None") {- self.ffmpeg_audio_process = audio_child;- }-self.start_time = Some(Instant::now());- self.audio_file_path = Some(audio_file_path_owned);- self.video_file_path = Some(video_file_path_owned);- self.ffmpeg_video_process = Some(video_child);+ self.file_path = Some(chunks_file_path.to_string());+ self.ffmpeg_process = Some(ffmpeg_child);self.device_name = Some(device.name().expect("Failed to get device name"));println!("End of the start_audio_recording function");@@ -546,8 +609,8 @@ impl MediaRecorder {Ok(())}- pub fn trigger_play (&mut self) -> Result<(), &'static str> {- if let Some(ref mut stream) = self.stream {+ 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")?;println!("Audio recording playing.");} else {@@ -562,19 +625,16 @@ impl MediaRecorder {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 = format!("{}/segment_list.txt", audio_file_path);+ let video_file_path = self.file_path.as_ref().ok_or("Video file path not set")?;let video_segment_list_filename = format!("{}/segment_list.txt", video_file_path);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 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 {+ if video_segment_count >= expected_segments as usize {println!("All segments generated");break;}@@ -583,17 +643,7 @@ impl MediaRecorder {}}- if let Some(ref ffmpeg_audio_stdin) = self.ffmpeg_audio_stdin {- let mut audio_stdin_guard = ffmpeg_audio_stdin.lock().await;- if let Some(mut audio_stdin) = audio_stdin_guard.take() {- if let Err(e) = audio_stdin.write_all(b"q\n").await {- eprintln!("Failed to send 'q' to audio FFmpeg process: {}", e);- }- let _ = audio_stdin.shutdown().await.map_err(|e| e.to_string());- }- }-- if let Some(ref ffmpeg_video_stdin) = self.ffmpeg_video_stdin {+ if let Some(ref ffmpeg_video_stdin) = self.ffmpeg_stdin {let mut video_stdin_guard = ffmpeg_video_stdin.lock().await;if let Some(mut video_stdin) = video_stdin_guard.take() {if let Err(e) = video_stdin.write_all(b"q\n").await {@@ -613,18 +663,14 @@ impl MediaRecorder {drop(sender);}- if let Some(ref mut stream) = self.stream {+ if let Some(ref mut stream) = self.audio_stream {stream.pause().map_err(|_| "Failed to pause stream")?;println!("Audio recording paused.");} else {return Err("Original recording was not started".to_string());}- if let Some(process) = &mut self.ffmpeg_audio_process {- let _ = process.kill().await.map_err(|e| e.to_string());- }-- if let Some(process) = &mut self.ffmpeg_video_process {+ if let Some(process) = &mut self.ffmpeg_process {let _ = process.kill().await.map_err(|e| e.to_string());}@@ -632,33 +678,17 @@ impl MediaRecorder {Ok(())}- async fn start_audio_ffmpeg_processes(- &self,- ffmpeg_binary_path: &str,- audio_ffmpeg_command: &[String],- ) -> Result<(Child, ChildStdin), Error> {- let mut audio_process = start_recording_process(ffmpeg_binary_path, audio_ffmpeg_command).await.map_err(|e| {- eprintln!("Failed to start audio recording process: {}", e);- std::io::Error::new(std::io::ErrorKind::Other, e.to_string())- })?;-- let audio_stdin = audio_process.stdin.take().ok_or_else(|| {- eprintln!("Failed to take audio stdin");- std::io::Error::new(std::io::ErrorKind::Other, "Failed to take audio stdin")- })?;-- Ok((audio_process, audio_stdin))- }-- async fn start_video_ffmpeg_processes(+ async fn start_ffmpeg_process(&self,ffmpeg_binary_path: &str,video_ffmpeg_command: &[String],) -> Result<(Child, ChildStdin), Error> {- let mut video_process = start_recording_process(ffmpeg_binary_path, video_ffmpeg_command).await.map_err(|e| {- eprintln!("Failed to start video recording process: {}", e);- std::io::Error::new(std::io::ErrorKind::Other, e.to_string())- })?;+ let mut video_process = start_recording_process(ffmpeg_binary_path, video_ffmpeg_command)+ .await+ .map_err(|e| {+ eprintln!("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(|| {eprintln!("Failed to take video stdin");@@ -667,15 +697,18 @@ impl MediaRecorder {Ok((video_process, video_stdin))}-}#[tauri::command]#[specta::specta]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 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@@ -695,7 +728,7 @@ pub fn enumerate_audio_devices() -> Vec<String> {input_device_names}-use tokio::io::{BufReader, AsyncBufReadExt};+use tokio::io::{AsyncBufReadExt, BufReader};async fn start_recording_process(ffmpeg_binary_path_str: &str,@@ -708,7 +741,7 @@ async fn start_recording_process(.spawn()?;if let Some(process_stderr) = process.stderr.take() {- tokio::spawn(async move {+ tokio::spawn(async move {let mut process_reader = BufReader::new(process_stderr).lines();while let Ok(Some(line)) = process_reader.next_line().await {eprintln!("FFmpeg process STDERR: {}", line);@@ -741,7 +774,7 @@ async fn wait_for_start_times(async fn adjust_ffmpeg_commands_based_on_start_times(audio_start_time: Arc<Mutex<Option<Instant>>>,video_start_time: Arc<Mutex<Option<Instant>>>,- ffmpeg_audio_command: &mut Vec<String>,+ // ffmpeg_audio_command: &mut Vec<String>,ffmpeg_video_command: &mut Vec<String>,) {let (audio_start, video_start) = wait_for_start_times(audio_start_time, video_start_time).await;@@ -756,22 +789,23 @@ async fn adjust_ffmpeg_commands_based_on_start_times(println!("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;+ 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 commandif audio_start > video_start {// Offset the video start time- ffmpeg_video_command.splice(0..0, vec![- "-itsoffset".to_string(), format!("{:.3}", offset_seconds)- ]);+ ffmpeg_video_command.splice(+ 0..0,+ vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],+ );println!("Applying -itsoffset {:.3} to video", offset_seconds);} else if video_start > audio_start {// Offset the audio start time- ffmpeg_audio_command.splice(0..0, vec![- "-itsoffset".to_string(), format!("{:.3}", offset_seconds)- ]);+ // ffmpeg_audio_command.splice(+ // 0..0,+ // vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],+ // );println!("Applying -itsoffset {:.3} to audio", offset_seconds);}-}diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex d7bc2492b..67f3b401b 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -1,28 +1,30 @@-use std::path::{Path, PathBuf};+use futures::future::join_all;+use serde::{Deserialize, Serialize};use std::collections::HashSet;-use std::io::{self, BufReader, BufRead, ErrorKind};use std::fs::File;-use std::sync::{Arc, atomic::{AtomicBool, Ordering}};-use tokio::sync:: {Mutex};-use tokio::task::JoinHandle;-use tokio::time::{Duration};-use serde::{Serialize, Deserialize};+use std::io::{self, BufRead, BufReader, ErrorKind};+use std::path::{Path, PathBuf};+use std::sync::{+ atomic::{AtomicBool, Ordering},+ Arc,+};use tauri::State;-use futures::future::join_all;+use tokio::sync::Mutex;+use tokio::task::JoinHandle;+use tokio::time::Duration;-use crate::upload::{upload_file};+use crate::upload::{self, upload_file};use crate::media::MediaRecorder;pub struct RecordingState {- pub media_process: Option<MediaRecorder>,- pub recording_options: Option<RecordingOptions>,- pub shutdown_flag: Arc<AtomicBool>,- pub video_uploading_finished: Arc<AtomicBool>,- pub audio_uploading_finished: Arc<AtomicBool>,- pub data_dir: Option<PathBuf>,- pub max_screen_width: usize,- pub max_screen_height: usize,+ pub media_process: Option<MediaRecorder>,+ pub recording_options: Option<RecordingOptions>,+ pub shutdown_flag: Arc<AtomicBool>,+ pub uploading_finished: Arc<AtomicBool>,+ pub data_dir: Option<PathBuf>,+ pub max_screen_width: usize,+ pub max_screen_height: usize,}unsafe impl Send for RecordingState {}@@ -32,85 +34,100 @@ unsafe impl Sync for MediaRecorder {}#[derive(Debug, Serialize, Deserialize, Clone, specta::Type)]pub struct RecordingOptions {- pub user_id: String,- pub video_id: String,- pub screen_index: String,- pub video_index: String,- pub audio_name: String,- pub aws_region: String,- pub aws_bucket: String,+ pub user_id: String,+ pub video_id: String,+ pub screen_index: String,+ pub video_index: String,+ pub audio_name: String,+ pub aws_region: String,+ pub aws_bucket: String,}#[tauri::command]#[specta::specta]pub async fn start_dual_recording(- state: State<'_, Arc<Mutex<RecordingState>>>,- options: RecordingOptions,+ state: State<'_, Arc<Mutex<RecordingState>>>,+ options: RecordingOptions,) -> Result<(), String> {- println!("Starting screen recording...");- let mut state_guard = state.lock().await;-- let shutdown_flag = Arc::new(AtomicBool::new(false));+ println!("Starting screen recording...");+ let mut state_guard = state.lock().await;- let data_dir = state_guard.data_dir.as_ref()- .ok_or("Data directory is not set in the recording state".to_string())?.clone();+ let shutdown_flag = Arc::new(AtomicBool::new(false));- println!("data_dir: {:?}", data_dir);+ let data_dir = state_guard+ .data_dir+ .as_ref()+ .ok_or("Data directory is not set in the recording state".to_string())?+ .clone();- let audio_chunks_dir = data_dir.join("chunks/audio");- let video_chunks_dir = data_dir.join("chunks/video");- let screenshot_dir = data_dir.join("screenshots");+ println!("data_dir: {:?}", data_dir);- clean_and_create_dir(&audio_chunks_dir)?;- clean_and_create_dir(&video_chunks_dir)?;- clean_and_create_dir(&screenshot_dir)?;+ let screenshot_dir = data_dir.join("screenshots");+ let chunks_dir = data_dir.join("chunks");- let audio_name = if options.audio_name.is_empty() {- None- } else {- Some(options.audio_name.clone())- };+ clean_and_create_dir(&chunks_dir)?;+ clean_and_create_dir(&screenshot_dir)?;- let media_recording_preparation = prepare_media_recording(&options, &audio_chunks_dir, &video_chunks_dir, &screenshot_dir, audio_name, state_guard.max_screen_width, state_guard.max_screen_height);- let media_recording_result = media_recording_preparation.await.map_err(|e| e.to_string())?;+ let audio_name = if options.audio_name.is_empty() {+ None+ } else {+ Some(options.audio_name.clone())+ };- state_guard.media_process = Some(media_recording_result);- state_guard.recording_options = Some(options.clone());- state_guard.shutdown_flag = shutdown_flag.clone();- state_guard.video_uploading_finished = Arc::new(AtomicBool::new(false));- state_guard.audio_uploading_finished = Arc::new(AtomicBool::new(false));+ let media_recording_preparation = prepare_media_recording(+ &options,+ &chunks_dir,+ &screenshot_dir,+ audio_name,+ state_guard.max_screen_width,+ state_guard.max_screen_height,+ );+ let media_recording_result = media_recording_preparation+ .await+ .map_err(|e| e.to_string())?;++ state_guard.media_process = Some(media_recording_result);+ state_guard.recording_options = Some(options.clone());+ state_guard.shutdown_flag = shutdown_flag.clone();+ state_guard.uploading_finished = Arc::new(AtomicBool::new(false));- let is_local_mode = match dotenv_codegen::dotenv!("NEXT_PUBLIC_LOCAL_MODE") {- "true" => true,- _ => false,- };+ let is_local_mode = match dotenv_codegen::dotenv!("NEXT_PUBLIC_LOCAL_MODE") {+ "true" => true,+ _ => false,+ };- if !is_local_mode {- let screen_upload = start_upload_loop(video_chunks_dir.clone(), options.clone(), "video".to_string(), shutdown_flag.clone(), state_guard.video_uploading_finished.clone());- let audio_upload = start_upload_loop(audio_chunks_dir, options.clone(), "audio".to_string(), shutdown_flag.clone(), state_guard.audio_uploading_finished.clone());+ if !is_local_mode {+ let upload = start_upload_loop(+ chunks_dir.clone(),+ options.clone(),+ shutdown_flag.clone(),+ state_guard.uploading_finished.clone(),+ );- drop(state_guard);+ drop(state_guard);- println!("Starting upload loops...");+ println!("Starting upload loops...");- match tokio::try_join!(screen_upload, audio_upload) {- Ok(_) => {- println!("Both upload loops completed successfully.");- },- Err(e) => {- eprintln!("An error occurred: {}", e);- },- }- } else {- println!("Skipping upload loops due to NEXT_PUBLIC_LOCAL_MODE being set to 'true'.");- }+ match upload.await {+ Ok(_) => {+ println!("Both upload loops completed successfully.");+ }+ Err(e) => {+ eprintln!("An error occurred: {}", e);+ }+ }+ } else {+ println!("Skipping upload loops due to NEXT_PUBLIC_LOCAL_MODE being set to 'true'.");+ }- Ok(())+ Ok(())}#[tauri::command]#[specta::specta]-pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -> Result<(), String> {+pub async fn stop_all_recordings(+ state: State<'_, Arc<Mutex<RecordingState>>>,+) -> Result<(), String> {let mut guard = state.lock().await;println!("Stopping media recording...");@@ -119,7 +136,10 @@ pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -if let Some(mut media_process) = guard.media_process.take() {println!("Stopping media recording...");- media_process.stop_media_recording().await.expect("Failed to stop media recording");+ media_process+ .stop_media_recording()+ .await+ .expect("Failed to stop media recording");}let is_local_mode = match dotenv_codegen::dotenv!("NEXT_PUBLIC_LOCAL_MODE") {@@ -128,8 +148,7 @@ pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -};if !is_local_mode {- while !guard.video_uploading_finished.load(Ordering::SeqCst)- || !guard.audio_uploading_finished.load(Ordering::SeqCst) {+ while !guard.uploading_finished.load(Ordering::SeqCst) {println!("Waiting for uploads to finish...");tokio::time::sleep(Duration::from_millis(50)).await;}@@ -148,24 +167,23 @@ fn clean_and_create_dir(dir: &Path) -> Result<(), String> {std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;if !dir.to_string_lossy().contains("screenshots") {- let segment_list_path = dir.join("segment_list.txt");- match File::open(&segment_list_path) {- Ok(_) => Ok(()),- Err(ref e) if e.kind() == ErrorKind::NotFound => {- File::create(&segment_list_path).map_err(|e| e.to_string())?;- Ok(())- },- Err(e) => Err(e.to_string()),- }+ let segment_list_path = dir.join("segment_list.txt");+ match File::open(&segment_list_path) {+ Ok(_) => Ok(()),+ Err(ref e) if e.kind() == ErrorKind::NotFound => {+ File::create(&segment_list_path).map_err(|e| e.to_string())?;+ Ok(())+ }+ Err(e) => Err(e.to_string()),+ }} else {- Ok(())+ Ok(())}}async fn start_upload_loop(chunks_dir: PathBuf,options: RecordingOptions,- video_type: String,shutdown_flag: Arc<AtomicBool>,uploading_finished: Arc<AtomicBool>,) -> Result<(), String> {@@ -191,12 +209,17 @@ async fn start_upload_loop(let segment_path = chunks_dir.join(segment_filename);if segment_path.is_file() {let options_clone = options.clone();- let video_type_clone = video_type.clone();let segment_path_clone = segment_path.clone();upload_tasks.push(tokio::spawn(async move {let filepath_str = segment_path_clone.to_str().unwrap_or_default().to_owned();- println!("Uploading video for {}: {}", video_type_clone, filepath_str);- upload_file(Some(options_clone), filepath_str, video_type_clone).await.map(|_| ())+ println!("Uploading video: {}", filepath_str);+ upload_file(+ Some(options_clone),+ filepath_str,+ upload::FileType::VideoWithAudio,+ )+ .await+ .map(|_| ())}));}watched_segments.insert(segment_filename.clone());@@ -228,18 +251,25 @@ fn load_segment_list(segment_list_path: &Path) -> io::Result<HashSet<String>> {}async fn prepare_media_recording(- options: &RecordingOptions,- audio_chunks_dir: &Path,- screenshot_dir: &Path,- video_chunks_dir: &Path,- audio_name: Option<String>,- max_screen_width: usize,- max_screen_height: usize,+ options: &RecordingOptions,+ screenshot_dir: &Path,+ video_chunks_dir: &Path,+ audio_name: Option<String>,+ max_screen_width: usize,+ max_screen_height: usize,) -> Result<MediaRecorder, String> {- let mut media_recorder = MediaRecorder::new();- let audio_file_path = audio_chunks_dir.to_str().unwrap();- let video_file_path = video_chunks_dir.to_str().unwrap();- let screenshot_dir_path = screenshot_dir.to_str().unwrap();- media_recorder.start_media_recording(options.clone(), audio_file_path, screenshot_dir_path, video_file_path, audio_name.as_ref().map(String::as_str), max_screen_width, max_screen_height).await?;- Ok(media_recorder)+ let mut media_recorder = MediaRecorder::new();+ let video_file_path = video_chunks_dir.to_str().unwrap();+ let screenshot_dir_path = screenshot_dir.to_str().unwrap();+ media_recorder+ .start_media_recording(+ options.clone(),+ screenshot_dir_path,+ video_file_path,+ audio_name.as_ref().map(String::as_str),+ max_screen_width,+ max_screen_height,+ )+ .await?;+ Ok(media_recorder)}diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 55cf324d0..d41543cc4 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -1,25 +1,37 @@+use regex::Regex;use reqwest;-use std::fs::File;-use std::io::Read;+use serde_json::Value as JsonValue;use std::path::Path;use std::process::{Command, Output};use std::str;-use std::fs;-use regex::Regex;-use serde_json::Value as JsonValue;use crate::recording::RecordingOptions;-use crate::utils::{ffmpeg_path_as_str};+use crate::utils::ffmpeg_path_as_str;++pub enum FileType {+ VideoWithAudio,+ Screenshot,+}++impl std::fmt::Display for FileType {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ match self {+ FileType::VideoWithAudio => write!(f, "video-with-audio"),+ FileType::Screenshot => write!(f, "screenshot"),+ }+ }+}pub async fn upload_file(options: Option<RecordingOptions>,file_path: String,- file_type: String,+ file_type: FileType,) -> Result<String, String> {if let Some(ref options) = options {println!("Uploading video...");- let duration = get_video_duration(&file_path).map_err(|e| format!("Failed to get video duration: {}", e))?;+ let duration = get_video_duration(&file_path)+ .map_err(|e| format!("Failed to get video duration: {}", e))?;let duration_str = duration.to_string();let file_name = Path::new(&file_path)@@ -28,40 +40,48 @@ pub async fn upload_file(.ok_or("Invalid file path")?.to_string();- let file_key = format!("{}/{}/{}/{}", options.user_id, options.video_id, file_type, file_name);+ let file_key = format!(+ "{}/{}/{}/{}",+ options.user_id,+ options.video_id,+ file_type.to_string(),+ file_name+ );let server_url_base: &'static str = dotenv_codegen::dotenv!("NEXT_PUBLIC_URL");let server_url = format!("{}/api/upload/signed", server_url_base);-- let body: serde_json::Value;-- if file_type == "video" {- let (codec_name, width, height, frame_rate, bit_rate) = log_video_info(&file_path).map_err(|e| format!("Failed to log video info: {}", e))?;-- body = serde_json::json!({- "userId": options.user_id,- "fileKey": file_key,- "awsBucket": options.aws_bucket,- "awsRegion": options.aws_region,- "duration": duration_str,- "resolution": format!("{}x{}", width, height),- "framerate": frame_rate,- "bandwidth": bit_rate,- "videoCodec": codec_name,- });- } else {- body = serde_json::json!({- "userId": options.user_id,- "fileKey": file_key,- "awsBucket": options.aws_bucket,- "awsRegion": options.aws_region,- "duration": duration_str,- });- }+ let body = match file_type {+ FileType::VideoWithAudio => {+ let (codec_name, width, height, frame_rate, bit_rate) = log_video_info(&file_path)+ .map_err(|e| format!("Failed to log video info: {}", e))?;++ serde_json::json!({+ "userId": options.user_id,+ "fileKey": file_key,+ "awsBucket": options.aws_bucket,+ "awsRegion": options.aws_region,+ "duration": duration_str,+ "resolution": format!("{}x{}", width, height),+ "framerate": frame_rate,+ "bandwidth": bit_rate,+ "videoCodec": codec_name,+ })+ }+ FileType::Screenshot => {+ serde_json::json!({+ "userId": options.user_id,+ "fileKey": file_key,+ "awsBucket": options.aws_bucket,+ "awsRegion": options.aws_region,+ "duration": duration_str,+ })+ }+ };let client = reqwest::Client::new();- let server_response = client.post(server_url)+ let server_response = client+ .post(server_url).json(&body).send().await@@ -72,25 +92,26 @@ pub async fn upload_file(println!("Server response: {}", server_response);-// Deserialize the server responselet presigned_post_data: JsonValue = serde_json::from_str(&server_response).map_err(|e| format!("Failed to deserialize server response: {}", e))?;// Construct the multipart form for the file upload- let fields = presigned_post_data["presignedPostData"]["fields"].as_object()+ let fields = presigned_post_data["presignedPostData"]["fields"]+ .as_object().ok_or("Fields object is missing or not an object")?;-+let mut form = reqwest::multipart::Form::new();-+for (key, value) in fields.iter() {- let value_str = value.as_str()+ let value_str = value+ .as_str().ok_or(format!("Value for key '{}' is not a string", key))?;form = form.text(key.to_string(), value_str.to_owned());}println!("Uploading file: {}", file_path);-+let mime_type = if file_path.to_lowercase().ends_with(".aac") {"audio/aac"} else if file_path.to_lowercase().ends_with(".webm") {@@ -101,7 +122,9 @@ pub async fn upload_file("video/mp2t"};- let file_bytes = tokio::fs::read(&file_path).await.map_err(|e| format!("Failed to read file: {}", e))?;+ let file_bytes = tokio::fs::read(&file_path)+ .await+ .map_err(|e| format!("Failed to read file: {}", e))?;let file_part = reqwest::multipart::Part::bytes(file_bytes).file_name(file_name.clone()).mime_str(mime_type)@@ -109,15 +132,13 @@ pub async fn upload_file(form = form.part("file", file_part);- let post_url = presigned_post_data["presignedPostData"]["url"].as_str()+ let post_url = presigned_post_data["presignedPostData"]["url"]+ .as_str().ok_or("URL is missing or not a string")?;println!("Uploading file to: {}", post_url);- let response = client.post(post_url)- .multipart(form)- .send()- .await;+ let response = client.post(post_url).multipart(form).send().await;match response {Ok(response) if response.status().is_success() => {@@ -125,9 +146,18 @@ pub async fn upload_file(}Ok(response) => {let status = response.status();- let error_body = response.text().await.unwrap_or_else(|_| "<no response body>".to_string());- eprintln!("Failed to upload file. Status: {}. Body: {}", status, error_body);- return Err(format!("Failed to upload file. Status: {}. Body: {}", status, error_body));+ let error_body = response+ .text()+ .await+ .unwrap_or_else(|_| "<no response body>".to_string());+ eprintln!(+ "Failed to upload file. Status: {}. Body: {}",+ status, error_body+ );+ return Err(format!(+ "Failed to upload file. Status: {}. Body: {}",+ status, error_body+ ));}Err(e) => {return Err(format!("Failed to send upload file request: {}", e));@@ -193,13 +223,14 @@ fn log_video_info(file_path: &str) -> Result<(String, String, String, String, Stlet codec_name = info_parts[0].to_string();let width: String = info_parts[1].to_string();let height: String = info_parts[2].to_string();-+// Parse frame rate as a fraction and convert to floatlet frame_rate_parts: Vec<&str> = info_parts[3].split('/').collect();- let frame_rate: f64 = frame_rate_parts[0].parse::<f64>().unwrap() / frame_rate_parts[1].parse::<f64>().unwrap();+ let frame_rate: f64 =+ frame_rate_parts[0].parse::<f64>().unwrap() / frame_rate_parts[1].parse::<f64>().unwrap();let frame_rate: String = frame_rate.to_string();-+let bit_rate: String = info_parts[4].to_string();Ok((codec_name, width, height, frame_rate, bit_rate))-}\ No newline at end of file+}diff --git a/apps/desktop/src-tauri/src/utils.rs b/apps/desktop/src-tauri/src/utils.rsindex 34b4213f5..00a770716 100644--- a/apps/desktop/src-tauri/src/utils.rs+++ b/apps/desktop/src-tauri/src/utils.rs@@ -110,8 +110,3 @@ pub fn create_named_pipe(path: &str) -> Result<(), nix::Error> {unistd::mkfifo(path, stat::Mode::S_IRWXU)?;Ok(())}--pub fn remove_named_pipe(path: &str) -> Result<(), std::io::Error> {- std::fs::remove_file(path)?;- Ok(())-}diff --git a/apps/web/app/api/upload/mux/create/route.ts b/apps/web/app/api/upload/mux/create/route.tsindex bea163b5d..6122648db 100644--- a/apps/web/app/api/upload/mux/create/route.ts+++ b/apps/web/app/api/upload/mux/create/route.ts@@ -97,8 +97,7 @@ export async function GET(request: NextRequest) {}const bucket = process.env.CAP_AWS_BUCKET || "";- const videoPrefix = `${userId}/${videoId}/video/`;- const audioPrefix = `${userId}/${videoId}/audio/`;+ const videoPrefix = `${userId}/${videoId}/video-with-audio/`;try {const s3Client = new S3Client({@@ -114,13 +113,7 @@ export async function GET(request: NextRequest) {Prefix: videoPrefix,});- const audioSegmentCommand = new ListObjectsV2Command({- Bucket: bucket,- Prefix: audioPrefix,- });-const videoSegments = await s3Client.send(videoSegmentCommand);- const audioSegments = await s3Client.send(audioSegmentCommand);const videoSegmentKeys = (videoSegments.Contents || []).map((object) => `s3://${bucket}/${object.Key}`@@ -148,10 +141,6 @@ export async function GET(request: NextRequest) {);}- const audioSegmentKeys = (audioSegments.Contents || []).map(- (object) => `s3://${bucket}/${object.Key}`- );-const mediaConvertClient = new MediaConvertClient({region: process.env.CAP_AWS_REGION || "",credentials: {@@ -165,18 +154,14 @@ export async function GET(request: NextRequest) {const createJobCommand = new CreateJobCommand({Role: process.env.CAP_AWS_MEDIACONVERT_ROLE_ARN || "",Settings: {- Inputs: videoSegmentKeys.map((videoSegmentKey, index) => {- const audioSegmentKey = audioSegmentKeys[index];+ Inputs: videoSegmentKeys.map((videoSegmentKey) => {return {FileInput: videoSegmentKey,- ...(audioSegmentKey && {- AudioSelectors: {- "Audio Selector 1": {- DefaultSelection: "DEFAULT",- ExternalAudioFileInput: audioSegmentKey,- },+ AudioSelectors: {+ "Audio Selector 1": {+ DefaultSelection: "DEFAULT",},- }),+ },VideoSelector: {},TimecodeSource: "ZEROBASED",};@@ -218,21 +203,19 @@ export async function GET(request: NextRequest) {},},},- ...(audioSegmentKeys.length > 0 && {- AudioDescriptions: [- {- AudioSourceName: "Audio Selector 1",- CodecSettings: {- Codec: "AAC",- AacSettings: {- Bitrate: 128000,- CodingMode: "CODING_MODE_2_0",- SampleRate: 48000,- },+ AudioDescriptions: [+ {+ AudioSourceName: "Audio Selector 1",+ CodecSettings: {+ Codec: "AAC",+ AacSettings: {+ Bitrate: 128000,+ CodingMode: "CODING_MODE_2_0",+ SampleRate: 48000,},},- ],- }),+ },+ ],},],},