Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

wip: Recording improvements

Richie McIlroy8e7ce41cfcb9
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock
index 759d8f045..af82645cb 100644
--- a/apps/desktop/src-tauri/Cargo.lock
+++ b/apps/desktop/src-tauri/Cargo.lock
@@ -623,6 +623,7 @@ dependencies = [
"futures",
"image",
"jpeg-encoder",
+ "nix 0.20.0",
"regex",
"reqwest",
"sentry",
@@ -636,6 +637,7 @@ dependencies = [
"tauri-plugin-positioner",
"tokio",
"tokio-util",
+ "urlencoding",
"which",
"window-shadows",
"window-vibrancy",
@@ -2924,6 +2926,18 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54"
+[[package]]
+name = "nix"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa9b4819da1bc61c0ea48b63b7bc8604064dd43013e7cc325df098d49cd7c18a"
+dependencies = [
+ "bitflags 1.3.2",
+ "cc",
+ "cfg-if",
+ "libc",
+]
+
[[package]]
name = "nix"
version = "0.24.3"
@@ -5456,6 +5470,12 @@ dependencies = [
"serde",
]
+[[package]]
+name = "urlencoding"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
+
[[package]]
name = "utf-8"
version = "0.7.6"
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 00dfff9b6..42066bc09 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -41,6 +41,8 @@ sentry = "0.32.2"
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }
winit = "0.29.15"
jpeg-encoder = "0.6.0"
+nix = "0.20.0"
+urlencoding = "2.1.2"
[features]
# this feature is used for production builds or when `devPath` points to the filesystem
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 91bb5c6da..cb65acccb 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -187,7 +187,7 @@ fn main() {
tray_menu
.add_item(CustomMenuItem::new("show-window".to_string(), "Show Cap"))
- .add_item(CustomMenuItem::new("quit".to_string(), "Quit").accelerator("CmdOrControl+Q"))
+ // .add_item(CustomMenuItem::new("quit".to_string(), "Quit").accelerator("CmdOrControl+Q"))
}
let tray = SystemTray::new().with_menu(create_tray_menu(None)).with_menu_on_left_click(false).with_title("Cap");
@@ -212,7 +212,6 @@ fn main() {
let data_directory = handle.path_resolver().app_data_dir().unwrap_or_else(|| PathBuf::new());
let recording_state = RecordingState {
media_process: None,
- upload_handles: Mutex::new(vec![]),
recording_options: None,
shutdown_flag: Arc::new(AtomicBool::new(false)),
video_uploading_finished: Arc::new(AtomicBool::new(false)),
@@ -225,16 +224,31 @@ fn main() {
app.manage(Arc::new(Mutex::new(recording_state)));
let tray_handle = app.tray_handle();
- app.listen_global("toggle-recording", move|event| {
- let is_recording: bool = serde_json::from_str(event.payload().expect("Error while openning event payload")).expect("Error while deserializing recording state from event payload");
-
- let icon_bytes = if is_recording {
- include_bytes!("../icons/tray-stop-icon.png").to_vec()
- } else {
- include_bytes!("../icons/tray-default-icon.png").to_vec()
- };
-
- tray_handle.set_icon(tauri::Icon::Raw(icon_bytes)).expect("Error while setting tray icon");
+ app.listen_global("toggle-recording", move |event| {
+ let tray_handle = tray_handle.clone();
+ match event.payload() {
+ Some(payload) => {
+ match serde_json::from_str::<bool>(payload) {
+ Ok(is_recording) => {
+ let icon_bytes = if is_recording {
+ include_bytes!("../icons/tray-stop-icon.png").to_vec()
+ } else {
+ include_bytes!("../icons/tray-default-icon.png").to_vec()
+ };
+
+ if let Err(e) = tray_handle.set_icon(tauri::Icon::Raw(icon_bytes)) {
+ eprintln!("Error while setting tray icon: {}", e);
+ }
+ }
+ Err(e) => {
+ eprintln!("Error while deserializing recording state from event payload: {}", e);
+ }
+ }
+ }
+ None => {
+ eprintln!("Error while opening event payload");
+ }
+ }
});
let tray_handle = app.tray_handle();
@@ -308,11 +322,13 @@ fn main() {
"show-window" => {
let window = app.get_window("main").expect("Error while trying to get the main window.");
window.show().expect("Error while trying to show main window");
- window.set_focus().expect("Error while trying to set focus on main window");
- }
- "quit" => {
- app.exit(0);
+ if !window.is_focused().unwrap_or(false) {
+ window.set_focus().expect("Error while trying to set focus on main window");
+ }
}
+ // "quit" => {
+ // app.exit(0);
+ // }
item_id => {
if !item_id.starts_with("in") {
return;
diff --git a/apps/desktop/src-tauri/src/media.rs b/apps/desktop/src-tauri/src/media.rs
index c00f7cb63..206e669a3 100644
--- a/apps/desktop/src-tauri/src/media.rs
+++ b/apps/desktop/src-tauri/src/media.rs
@@ -14,7 +14,7 @@ use tokio::process::{Command, Child, ChildStdin};
use tokio::sync::{mpsc, Mutex};
use crate::recording::RecordingOptions;
-use crate::utils::{ffmpeg_path_as_str};
+use crate::utils::{ffmpeg_path_as_str, create_named_pipe, remove_named_pipe};
use crate::upload::upload_file;
use capture::{Capturer, Display};
@@ -22,10 +22,8 @@ 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_channel_sender: Option<mpsc::Sender<Vec<u8>>>,
@@ -40,10 +38,8 @@ 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_channel_sender: None,
@@ -72,6 +68,11 @@ impl MediaRecorder {
let (video_tx, video_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(2048);
let calculated_stride = (adjusted_width * 4) as usize;
+ let audio_pipe = format!("{}/audio_pipe", audio_file_path);
+ let video_pipe = format!("{}/video_pipe", video_file_path);
+ create_named_pipe(&audio_pipe).map_err(|e| e.to_string())?;
+ create_named_pipe(&video_pipe).map_err(|e| e.to_string())?;
+
println!("Display width: {}", w);
println!("Display height: {}", h);
println!("Adjusted width: {}", adjusted_width);
@@ -86,8 +87,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();
@@ -147,8 +147,7 @@ impl MediaRecorder {
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 ffmpeg_stdin = self.ffmpeg_stdin.clone();
let err_fn = move |err| {
eprintln!("an error occurred on stream: {}", err);
@@ -389,7 +388,6 @@ impl MediaRecorder {
time_next += spf;
}
- // Sleep until the next frame time
let now = Instant::now();
if time_next > now {
std::thread::sleep(time_next - now);
@@ -404,42 +402,17 @@ 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_output_chunk_pattern = format!("{}/video_recording_%03d.mp4", video_file_path_owned);
let video_segment_list_filename = format!("{}/segment_list.txt", video_file_path_owned);
-
- 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 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![
+ let video_size = format!("{}x{}", adjusted_width, adjusted_height);
+ let video_options = vec![
"-f", "rawvideo",
"-pix_fmt", "bgra",
- "-s", &format!("{}x{}", adjusted_width, adjusted_height),
+ "-s", &video_size,
"-r", "30",
"-thread_queue_size", "4096",
- "-i", "pipe:0",
+ "-i", &video_pipe,
"-vf", "fps=30,scale=in_range=full:out_range=limited",
"-c:v", "libx264",
"-preset", "ultrafast",
@@ -454,80 +427,85 @@ impl MediaRecorder {
"-segment_format", "mpegts",
"-reset_timestamps", "1",
&video_output_chunk_pattern,
- ].into_iter().map(|s| s.to_string()).collect();
+ ];
- if custom_device != Some("None") {
- 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;
+ let mut ffmpeg_command: Vec<String> = video_options.into_iter().map(|s| s.to_string()).collect();
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");
- }
-
- 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");
-
- 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 audio_options = vec![
+ "-f", sample_format,
+ "-ar", &sample_rate_str,
+ "-ac", &channels_str,
+ "-thread_queue_size", "4096",
+ "-i", &audio_pipe,
+ "-af", "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
+ "-c:a", "aac",
+ "-b:a", "128k",
+ "-f", "segment",
+ "-segment_time", "3",
+ "-segment_time_delta", "0.01",
+ "-segment_list", &audio_segment_list_filename,
+ "-reset_timestamps", "1",
+ &audio_output_chunk_pattern,
+ ];
+
+ ffmpeg_command.splice(0..0, audio_options.into_iter().map(|s| s.to_string()));
}
- if let Some(ffmpeg_video_stdin) = &self.ffmpeg_video_stdin {
- let mut video_stdin_lock = ffmpeg_video_stdin.lock().await;
- *video_stdin_lock = Some(video_stdin);
- drop(video_stdin_lock);
- println!("Video stdin set");
- }
+ // if custom_device != Some("None") {
+ // 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),
+ // &ffmpeg_command,
+ // &mut ffmpeg_command,
+ // ).await;
+ // }
if custom_device != Some("None") {
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");
+ let mut audio_pipe_writer = tokio::fs::OpenOptions::new()
+ .write(true)
+ .open(audio_pipe)
+ .await
+ .expect("Failed to open audio pipe for writing");
+
+ while let Some(bytes) = audio_channel_receiver.lock().await.as_mut().unwrap().recv().await {
+ if let Err(e) = audio_pipe_writer.write_all(&bytes).await {
+ if e.kind() == std::io::ErrorKind::BrokenPipe {
+ eprintln!("Audio pipe broken. FFmpeg process might have been terminated.");
+ break;
+ } else {
+ panic!("Failed to write audio data to pipe: {}", e);
}
- drop(audio_stdin_guard);
}
}
});
}
- 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");
+ let mut video_pipe_writer = tokio::fs::OpenOptions::new()
+ .write(true)
+ .open(video_pipe)
+ .await
+ .expect("Failed to open video pipe for writing");
+
+ while let Some(bytes) = video_channel_receiver.lock().await.as_mut().unwrap().recv().await {
+ if let Err(e) = video_pipe_writer.write_all(&bytes).await {
+ if e.kind() == std::io::ErrorKind::BrokenPipe {
+ eprintln!("Video pipe broken. FFmpeg process might have been terminated.");
+ break;
+ } else {
+ panic!("Failed to write video data to pipe: {}", e);
}
- drop(video_stdin_guard);
}
}
});
-
- if custom_device != Some("None") {
- self.ffmpeg_audio_process = audio_child;
- }
- self.ffmpeg_video_process = Some(video_child);
+ let (ffmpeg_process, ffmpeg_stdin) = self.start_ffmpeg_process(&ffmpeg_binary_path_str, &ffmpeg_command).await.map_err(|e| e.to_string())?;
+ self.ffmpeg_process = Some(ffmpeg_process);
+ self.ffmpeg_stdin = Some(Arc::new(Mutex::new(Some(ffmpeg_stdin))));
self.device_name = Some(device.name().expect("Failed to get device name"));
println!("End of the start_audio_recording function");
@@ -547,83 +525,63 @@ impl MediaRecorder {
}
pub async fn stop_media_recording(&mut self) -> Result<(), String> {
- 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() {
- let _ = audio_stdin.shutdown().await.map_err(|e| e.to_string());
- }
- }
-
- if let Some(ref ffmpeg_video_stdin) = self.ffmpeg_video_stdin {
- let mut video_stdin_guard = ffmpeg_video_stdin.lock().await;
- if let Some(mut video_stdin) = video_stdin_guard.take() {
- let _ = video_stdin.shutdown().await.map_err(|e| e.to_string());
+ if let Some(ref ffmpeg_stdin) = self.ffmpeg_stdin {
+ let mut stdin_guard = ffmpeg_stdin.lock().await;
+ if let Some(stdin) = stdin_guard.as_mut() {
+ if let Err(e) = stdin.write_all(b"q\n").await {
+ eprintln!("Failed to send graceful shutdown command to FFmpeg: {}", e);
+ } else {
+ println!("Sent graceful shutdown command to FFmpeg");
+ }
}
}
-
self.should_stop.store(true, Ordering::SeqCst);
+ println!("Stopping media recording...");
- if let Some(sender) = self.audio_channel_sender.take() {
- drop(sender);
+ if self.device_name.as_deref() != Some("None") {
+ if let Some(sender) = self.audio_channel_sender.take() {
+ drop(sender);
+ println!("Audio recording stopped.");
+ }
}
if let Some(sender) = self.video_channel_sender.take() {
drop(sender);
+ println!("Video recording stopped.");
}
- if let Some(ref mut stream) = self.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 self.device_name.as_deref() != Some("None") {
+ if let Some(ref mut stream) = self.stream {
+ stream.pause().map_err(|_| "Failed to pause stream")?;
+ println!("Audio recording paused.");
+ }
}
- 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());
+ let exit_status = process.wait().await.map_err(|e| e.to_string())?;
+ println!("FFmpeg process exited with status: {}", exit_status);
}
- println!("Audio recording stopped.");
Ok(())
}
- async fn start_audio_ffmpeg_processes(
+ async fn start_ffmpeg_process(
&self,
ffmpeg_binary_path: &str,
- audio_ffmpeg_command: &[String],
+ ffmpeg_command: &[String],
) -> Result<(Child, ChildStdin), Error> {
- let mut audio_process = start_recording_process(ffmpeg_binary_path, audio_ffmpeg_command).await.map_err(|e| {
+ let mut process = start_recording_process(ffmpeg_binary_path, 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(|| {
+ let stdin = 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(
- &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 video_stdin = video_process.stdin.take().ok_or_else(|| {
- eprintln!("Failed to take video stdin");
- std::io::Error::new(std::io::ErrorKind::Other, "Failed to take video stdin")
- })?;
-
- Ok((video_process, video_stdin))
+ Ok((process, stdin))
}
}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index b91024104..10d78eb3d 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -4,19 +4,16 @@ 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 tauri::State;
-use futures::future::join_all;
-use crate::upload::upload_file;
+use crate::upload::{upload_file, create_m3u8_master_playlist};
use crate::media::MediaRecorder;
pub struct RecordingState {
pub media_process: Option<MediaRecorder>,
- pub upload_handles: Mutex<Vec<JoinHandle<Result<(), String>>>>,
pub recording_options: Option<RecordingOptions>,
pub shutdown_flag: Arc<AtomicBool>,
pub video_uploading_finished: Arc<AtomicBool>,
@@ -44,81 +41,79 @@ pub struct RecordingOptions {
#[tauri::command]
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));
-
- let data_dir = state_guard.data_dir.as_ref()
- .ok_or("Data directory is not set in the recording state".to_string())?.clone();
-
- println!("data_dir: {:?}", data_dir);
-
- 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");
-
- clean_and_create_dir(&audio_chunks_dir)?;
- clean_and_create_dir(&video_chunks_dir)?;
- clean_and_create_dir(&screenshot_dir)?;
-
- let audio_name = if options.audio_name.is_empty() {
- None
- } else {
- Some(options.audio_name.clone())
- };
-
- 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())?;
-
- state_guard.media_process = Some(media_recording_result);
- state_guard.upload_handles = Mutex::new(vec![]);
- 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 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());
-
- drop(state_guard);
-
- 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'.");
- }
+ println!("Starting screen recording...");
+
+ let mut state_guard = state.lock().await;
+ let shutdown_flag = Arc::new(AtomicBool::new(false));
+ 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");
+
+ clean_and_create_dir(&audio_chunks_dir)?;
+ clean_and_create_dir(&video_chunks_dir)?;
+ clean_and_create_dir(&screenshot_dir)?;
+
+ let audio_option = if options.audio_name.is_empty() || options.audio_name == "None" {
+ None
+ } else {
+ Some(options.audio_name.clone())
+ };
+
+ let media_recorder = prepare_media_recording(
+ &options, &audio_chunks_dir, &video_chunks_dir, &screenshot_dir,
+ audio_option.clone(), state_guard.max_screen_width, state_guard.max_screen_height).await?;
+
+ state_guard.media_process = Some(media_recorder);
+ 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(if audio_option.is_some() { AtomicBool::new(false) } else { AtomicBool::new(true) });
+
+ drop(state_guard); // Dropping here after all necessary state updated
+
+ let is_local_mode = dotenv_codegen::dotenv!("NEXT_PUBLIC_LOCAL_MODE") == "true";
- Ok(())
+ if !is_local_mode {
+ let screen_upload = start_upload_loop(video_chunks_dir.clone(), options.clone(), "video".to_string(), shutdown_flag.clone(), state.lock().await.video_uploading_finished.clone());
+ let audio_upload = start_upload_loop(audio_chunks_dir, options.clone(), "audio".to_string(), shutdown_flag.clone(), state.lock().await.audio_uploading_finished.clone());
+
+ println!("Starting upload loops...");
+ match tokio::try_join!(screen_upload, audio_upload) {
+ Ok(_) => {
+ println!("Both upload loops completed successfully.");
+ },
+ Err(e) => {
+ return Err(format!("An error occurred in upload loops: {}", e));
+ },
+ }
+ } else {
+ println!("Skipping upload loops due to NEXT_PUBLIC_LOCAL_MODE being set to 'true'.");
+ }
+
+ Ok(())
}
#[tauri::command]
pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -> Result<(), String> {
- let mut guard = state.lock().await;
-
- println!("Stopping media recording...");
+ println!("Stopping all recordings...");
- guard.shutdown_flag.store(true, Ordering::SeqCst);
+ let shutdown_flag = {
+ let guard = state.lock().await;
+ guard.shutdown_flag.clone()
+ };
+
+ shutdown_flag.store(true, Ordering::SeqCst);
+
+ let mut guard = state.lock().await;
+ println!("1: Stopping media recording...");
if let Some(mut media_process) = guard.media_process.take() {
- println!("Stopping media recording...");
+ println!("2: Stopping media recording...");
media_process.stop_media_recording().await.expect("Failed to stop media recording");
}
@@ -128,13 +123,21 @@ 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) {
- println!("Waiting for uploads to finish...");
+ println!("Waiting for uploads to finish...");
+
+ let timeout = Duration::from_secs(10);
+ let start_time = std::time::Instant::now();
+
+ while !guard.video_uploading_finished.load(Ordering::SeqCst) || !guard.audio_uploading_finished.load(Ordering::SeqCst) {
+ if start_time.elapsed() > timeout {
+ return Err("Timeout waiting for uploads to finish".to_string());
+ }
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
-
+
+ drop(guard);
+
println!("All recordings and uploads stopped.");
Ok(())
@@ -170,17 +173,8 @@ async fn start_upload_loop(
uploading_finished: Arc<AtomicBool>,
) -> Result<(), String> {
let mut watched_segments: HashSet<String> = HashSet::new();
- let mut is_final_loop = false;
-
- loop {
- let mut upload_tasks = vec![];
- if shutdown_flag.load(Ordering::SeqCst) {
- if is_final_loop {
- break;
- }
- is_final_loop = true;
- }
+ while !shutdown_flag.load(Ordering::SeqCst) || !watched_segments.is_superset(&load_segment_list(&chunks_dir.join("segment_list.txt")).map_err(|e| e.to_string())?) {
let current_segments = load_segment_list(&chunks_dir.join("segment_list.txt"))
.map_err(|e| e.to_string())?
.difference(&watched_segments)
@@ -193,21 +187,30 @@ async fn start_upload_loop(
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 handle = 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(|_| ())
- }));
+ });
}
watched_segments.insert(segment_filename.clone());
}
- if !upload_tasks.is_empty() {
- let _ = join_all(upload_tasks).await;
- }
-
tokio::time::sleep(Duration::from_millis(50)).await;
}
+
+ if video_type == "video" {
+ let options_clone = options.clone();
+ let video_id = options_clone.video_id.clone();
+ let video_file_path = chunks_dir.join(watched_segments.iter().next().unwrap_or(&"".to_string())).to_str().unwrap_or_default().to_owned();
+ let audio_file_path = video_file_path.replace("video", "audio").replace(".mp4", ".aac");
+ let output_path = Path::new(&video_file_path).parent().unwrap().to_str().unwrap();
+
+ if let Err(e) = create_m3u8_master_playlist(&video_file_path, &audio_file_path, output_path, &video_id).await {
+ eprintln!("Error creating m3u8 master playlist: {}", e);
+ }
+ }
+
uploading_finished.store(true, Ordering::SeqCst);
Ok(())
}
@@ -230,8 +233,8 @@ 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,
+ screenshot_dir: &Path,
audio_name: Option<String>,
max_screen_width: usize,
max_screen_height: usize,
@@ -240,6 +243,6 @@ async fn prepare_media_recording(
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?;
+ media_recorder.start_media_recording(options.clone(), audio_file_path, video_file_path, screenshot_dir_path, audio_name.as_ref().map(String::as_str), max_screen_width, max_screen_height).await?;
Ok(media_recorder)
}
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rs
index 994129fba..14492b77c 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -1,6 +1,8 @@
use serde_json::Value as JsonValue;
use std::path::{Path};
use std::process::Command;
+use std::fs::File;
+use std::io::{BufRead, BufReader};
use reqwest;
use crate::recording::RecordingOptions;
@@ -30,6 +32,7 @@ pub async fn upload_file(
println!("Video duration: {} seconds", video_duration_str);
println!("Bandwidth: {} kbps", bandwidth_str);
println!("Resolution: {}", resolution);
+
(video_duration_str, bandwidth_str, resolution, video_codec, "".to_string())
}
_ => return Err("Invalid file type".to_string()),
@@ -94,6 +97,8 @@ pub async fn upload_file(
"audio/aac"
} else if file_path.to_lowercase().ends_with(".webm") {
"audio/webm"
+ } else if file_path.to_lowercase().ends_with(".mp4") {
+ "video/mp4"
} else {
"video/mp2t"
};
@@ -133,14 +138,14 @@ pub async fn upload_file(
}
}
- // Clean up the uploaded file
- println!("Removing file after upload: {}", file_path);
- let remove_result = tokio::fs::remove_file(&file_path).await;
- match &remove_result {
- Ok(_) => println!("File removed successfully"),
- Err(e) => println!("Failed to remove file after upload: {}", e),
- }
- remove_result.map_err(|e| format!("Failed to remove file after upload: {}", e))?;
+ // // Clean up the uploaded file
+ // println!("Removing file after upload: {}", file_path);
+ // let remove_result = tokio::fs::remove_file(&file_path).await;
+ // match &remove_result {
+ // Ok(_) => println!("File removed successfully"),
+ // Err(e) => println!("Failed to remove file after upload: {}", e),
+ // }
+ // remove_result.map_err(|e| format!("Failed to remove file after upload: {}", e))?;
Ok(file_key)
} else {
@@ -265,4 +270,66 @@ async fn get_video_metadata(file_path: &str) -> Result<(f64, u64, String, String
let video_codec = video_codec_str.to_string();
Ok((total_seconds, bandwidth, resolution, video_codec))
+}
+
+pub async fn create_m3u8_master_playlist(
+ video_file_path: &str,
+ audio_file_path: &str,
+ output_path: &str,
+ video_id: &str,
+) -> Result<String, String> {
+ let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;
+
+ let output = Command::new(&ffmpeg_binary_path_str)
+ .args(&[
+ "-i", video_file_path,
+ "-i", audio_file_path,
+ "-c:v", "copy",
+ "-c:a", "copy",
+ "-hls_time", "10",
+ "-hls_list_size", "0",
+ "-master_pl_name", "master.m3u8",
+ "-hls_flags", "independent_segments",
+ format!("{}/master.m3u8", output_path).as_str(),
+ ])
+ .output()
+ .map_err(|e| format!("Failed to execute FFmpeg for creating master playlist: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!("FFmpeg playlist command failed: {}", stderr));
+ }
+
+ let master_playlist_path = format!("{}/master.m3u8", output_path);
+ let file = File::open(&master_playlist_path)
+ .map_err(|e| format!("Failed to open master playlist file: {}", e))?;
+ let reader = BufReader::new(file);
+
+ let mut stream_inf_line = String::new();
+ for line in reader.lines() {
+ let line = line.map_err(|e| format!("Failed to read master playlist file: {}", e))?;
+ if line.starts_with("#EXT-X-STREAM-INF:") {
+ stream_inf_line = line.replace("#EXT-X-STREAM-INF:", "");
+ break;
+ }
+ }
+
+ let server_url_base: &'static str = dotenv_codegen::dotenv!("NEXT_PUBLIC_URL");
+ let api_url = format!("{}/api/desktop/video/metadata/create?videoId={}&xStreamInfo={}", server_url_base, video_id, urlencoding::encode(&stream_inf_line));
+
+ let client = reqwest::Client::new();
+ let response = client.get(&api_url)
+ .send()
+ .await
+ .map_err(|e| format!("Failed to send request to update xStreamInfo: {}", e))?;
+
+ if response.status().is_success() {
+ println!("Updated xStreamInfo successfully");
+ } else {
+ let status = response.status();
+ let error_body = response.text().await.unwrap_or_else(|_| "<no response body>".to_string());
+ return Err(format!("Failed to update xStreamInfo. Status: {}. Body: {}", status, error_body));
+ }
+
+ Ok(stream_inf_line)
}
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/utils.rs b/apps/desktop/src-tauri/src/utils.rs
index 5a9fad2d9..135b276da 100644
--- a/apps/desktop/src-tauri/src/utils.rs
+++ b/apps/desktop/src-tauri/src/utils.rs
@@ -103,4 +103,16 @@ pub fn ffmpeg_path_as_str() -> Result<String, String> {
} else {
Ok("ffmpeg".to_string())
}
+}
+
+pub fn create_named_pipe(path: &str) -> Result<(), nix::Error> {
+ use nix::sys::stat;
+ use nix::unistd;
+ 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(())
}
\ No newline at end of file
diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsx
index 418321210..dc0eb1719 100644
--- a/apps/desktop/src/components/windows/inner/Recorder.tsx
+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx
@@ -95,6 +95,7 @@ export const Recorder = () => {
});
};
+ console.log("selectedAudioDevice: ", selectedAudioDevice);
// const handleOverlayFinished = () => {
// setIsRecording(true);
// setStartingRecording(false);
@@ -187,20 +188,25 @@ export const Recorder = () => {
}
});
});
- emit("toggle-recording", true);
- await invoke("start_dual_recording", {
- options: {
- user_id: videoData.user_id,
- video_id: videoData.id,
- audio_name: selectedAudioDevice?.label,
- aws_region: videoData.aws_region,
- aws_bucket: videoData.aws_bucket,
- screen_index: "Capture screen 0",
- video_index: String(selectedVideoDevice?.index),
- },
- }).catch((error) => {
- console.error("Error invoking start_screen_recording:", error);
- });
+ await emit("toggle-recording", true);
+ try {
+ await invoke("start_dual_recording", {
+ options: {
+ user_id: videoData.user_id,
+ video_id: videoData.id,
+ audio_name: selectedAudioDevice?.label ?? "None",
+ aws_region: videoData.aws_region,
+ aws_bucket: videoData.aws_bucket,
+ screen_index: "Capture screen 0",
+ video_index: String(selectedVideoDevice?.index),
+ },
+ }).catch((error) => {
+ console.error("Error invoking start_screen_recording:", error);
+ });
+ } catch (error) {
+ console.error("Error starting screen recording:", error);
+ setStartingRecording(false);
+ }
};
const handleStartAllRecordings = async () => {
@@ -235,17 +241,25 @@ export const Recorder = () => {
}
setStoppingRecording(true);
- tauriWindow.then(({ WebviewWindow }) => {
- const main = WebviewWindow.getByLabel("main");
- if (main) {
- main.unminimize();
- }
- });
+ // try {
+ // tauriWindow.then(({ WebviewWindow }) => {
+ // const main = WebviewWindow.getByLabel("main");
+ // if (main && main.isMinimized()) {
+ // main.unminimize();
+ // }
+ // });
+ // } catch (error) {
+ // console.error("Error unminimizing main window:", error);
+ // }
try {
console.log("Stopping recordings...");
- await invoke("stop_all_recordings");
+ try {
+ await invoke("stop_all_recordings");
+ } catch (error) {
+ console.error("Error stopping recording:", error);
+ }
if (window.fathom !== undefined) {
window.fathom.trackEvent("stop_recording");
@@ -274,7 +288,7 @@ export const Recorder = () => {
setHasStartedRecording(false);
setStoppingRecording(false);
setCanStopRecording(false);
- emit("toggle-recording", false);
+ await emit("toggle-recording", false);
} catch (error) {
console.error("Error stopping recording:", error);
}
diff --git a/apps/web/app/api/desktop/video/metadata/create/route.ts b/apps/web/app/api/desktop/video/metadata/create/route.ts
index 34af8e5f2..4fea6d9f1 100644
--- a/apps/web/app/api/desktop/video/metadata/create/route.ts
+++ b/apps/web/app/api/desktop/video/metadata/create/route.ts
@@ -9,10 +9,9 @@ export async function GET(request: NextRequest) {
try {
const url = new URL(request.url);
const videoId = url.searchParams.get("videoId");
- const startTime = url.searchParams.get("startTime");
- const logType = url.searchParams.get("logType");
+ const xStreamInfo = url.searchParams.get("xStreamInfo");
- if (!videoId || !startTime || !logType) {
+ if (!videoId || !xStreamInfo) {
return new Response(
JSON.stringify({ error: "Missing required fields" }),
{
@@ -24,21 +23,10 @@ export async function GET(request: NextRequest) {
);
}
- if (logType === "video") {
- console.log("...Updating video start time...");
- await db
- .update(videos)
- .set({ videoStartTime: startTime.toString() })
- .where(eq(videos.id, videoId));
- }
-
- if (logType === "audio") {
- console.log("...Updating audio start time...");
- await db
- .update(videos)
- .set({ audioStartTime: startTime.toString() })
- .where(eq(videos.id, videoId));
- }
+ await db
+ .update(videos)
+ .set({ xStreamInfo: xStreamInfo })
+ .where(eq(videos.id, videoId));
return new Response(JSON.stringify({ success: true }), {
status: 200,
@@ -47,7 +35,7 @@ export async function GET(request: NextRequest) {
},
});
} catch (error) {
- console.error("Error updating video or audio start time", error);
+ console.error("Error updating xStreamInfo", error);
return new Response(JSON.stringify({ error: "Internal server error" }), {
status: 500,
headers: {
diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.ts
index 1fe1fc9f4..dae50b068 100644
--- a/apps/web/app/api/playlist/route.ts
+++ b/apps/web/app/api/playlist/route.ts
@@ -181,8 +181,6 @@ export async function GET(request: NextRequest) {
const generatedPlaylist = await generateMasterPlaylist(
videoMetadata?.Metadata?.resolution ?? "",
- videoMetadata?.Metadata?.videocodec ?? "",
- audioMetadata?.Metadata?.audiocodec ?? "",
process.env.NEXT_PUBLIC_URL +
"/api/playlist?userId=" +
userId +
@@ -194,7 +192,8 @@ export async function GET(request: NextRequest) {
userId +
"&videoId=" +
videoId +
- "&videoType=audio"
+ "&videoType=audio",
+ video.xStreamInfo ?? ""
);
return new Response(generatedPlaylist, {
diff --git a/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
index f87c21177..cf0de0fd2 100644
--- a/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
@@ -26,7 +26,9 @@ export const VideoPlayer = memo(
media: HTMLMediaElement,
hlsInstance: React.MutableRefObject<Hls | null>
) => {
- const hls = new Hls();
+ const hls = new Hls({
+ maxBufferLength: 30,
+ });
hls.on(Hls.Events.ERROR, (event, data) => {
console.error("HLS error:", data);
if (data.fatal) {
diff --git a/apps/web/utils/video/ffmpeg/helpers.ts b/apps/web/utils/video/ffmpeg/helpers.ts
index 6a61f7fda..6971c4aea 100644
--- a/apps/web/utils/video/ffmpeg/helpers.ts
+++ b/apps/web/utils/video/ffmpeg/helpers.ts
@@ -100,16 +100,18 @@ export async function generateM3U8Playlist(
export async function generateMasterPlaylist(
resolution: string,
- videoCodec: string,
- audioCodec: string,
videoPlaylistUrl: string,
- audioPlaylistUrl: string
+ audioPlaylistUrl: string,
+ xStreamInfo: string
) {
+ const streamInfo = xStreamInfo
+ ? xStreamInfo + ',AUDIO="audio"'
+ : `RESOLUTION=${resolution},AUDIO="audio"`;
const masterPlaylist = `#EXTM3U
#EXT-X-VERSION:4
#EXT-X-INDEPENDENT-SEGMENTS
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="Audio",DEFAULT=YES,AUTOSELECT=YES,LANGUAGE="en",URI="${audioPlaylistUrl}"
-#EXT-X-STREAM-INF:RESOLUTION=${resolution},CODECS="avc1.42001e,mp4a.40.2",AUDIO="audio"
+#EXT-X-STREAM-INF:${streamInfo}
${videoPlaylistUrl}
`;
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 9308a7930..7b00aa2a3 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -147,6 +147,7 @@ export const videos = mysqlTable(
public: boolean("public").notNull().default(true),
videoStartTime: varchar("videoStartTime", { length: 255 }),
audioStartTime: varchar("audioStartTime", { length: 255 }),
+ xStreamInfo: text("xStreamInfo"),
createdAt: timestamp("createdAt").notNull().defaultNow(),
updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),
},
diff --git a/packages/ui/style/tailwind.config.js b/packages/ui/style/tailwind.config.js
index 7702f6a02..edc11d209 100644
--- a/packages/ui/style/tailwind.config.js
+++ b/packages/ui/style/tailwind.config.js
@@ -15,7 +15,7 @@ module.exports = function (app, options) {
light: "300",
normal: "400",
medium: "500",
- semibold: "600",
+ semibold: "500",
bold: "600",
extrabold: "600",
"extra-bold": "600",