Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

wip: Switch to mux.com

Richie McIlroy4d2d63866f22
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 543a65182..c65684b2a 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -11,6 +11,7 @@
"@cap/database": "workspace:*",
"@cap/ui": "workspace:*",
"@cap/utils": "workspace:*",
+ "@mux/mux-node": "^8.5.1",
"@sentry/nextjs": "^7.105.0",
"@tauri-apps/api": "^1.5.3",
"@tensorflow-models/body-pix": "^2.2.1",
diff --git a/apps/desktop/src-tauri/src/media.rs b/apps/desktop/src-tauri/src/media.rs
index 206e669a3..a898ee860 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, create_named_pipe, remove_named_pipe};
+use crate::utils::{ffmpeg_path_as_str};
use crate::upload::upload_file;
use capture::{Capturer, Display};
@@ -22,8 +22,10 @@ const FRAME_RATE: u64 = 30;
pub struct MediaRecorder {
pub options: Option<RecordingOptions>,
- ffmpeg_process: Option<tokio::process::Child>,
- ffmpeg_stdin: Option<Arc<Mutex<Option<tokio::process::ChildStdin>>>>,
+ 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>>>>,
device_name: Option<String>,
stream: Option<cpal::Stream>,
audio_channel_sender: Option<mpsc::Sender<Vec<u8>>>,
@@ -38,8 +40,10 @@ impl MediaRecorder {
pub fn new() -> Self {
MediaRecorder {
options: None,
- ffmpeg_process: None,
- ffmpeg_stdin: None,
+ ffmpeg_audio_process: None,
+ ffmpeg_video_process: None,
+ ffmpeg_audio_stdin: None,
+ ffmpeg_video_stdin: None,
device_name: None,
stream: None,
audio_channel_sender: None,
@@ -68,11 +72,6 @@ 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);
@@ -87,7 +86,8 @@ 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_stdin = Some(Arc::new(Mutex::new(None)));
+ self.ffmpeg_audio_stdin = Some(Arc::new(Mutex::new(None)));
+ self.ffmpeg_video_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,7 +147,8 @@ impl MediaRecorder {
let sample_rate_str = sample_rate.to_string();
let channels_str = channels.to_string();
- let ffmpeg_stdin = self.ffmpeg_stdin.clone();
+ 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);
@@ -388,6 +389,7 @@ 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);
@@ -402,17 +404,42 @@ 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.mp4", video_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 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 video_size = format!("{}x{}", adjusted_width, adjusted_height);
- let video_options = vec![
+ let mut ffmpeg_video_command: Vec<String> = vec![
"-f", "rawvideo",
"-pix_fmt", "bgra",
- "-s", &video_size,
+ "-s", &format!("{}x{}", adjusted_width, adjusted_height),
"-r", "30",
"-thread_queue_size", "4096",
- "-i", &video_pipe,
+ "-i", "pipe:0",
"-vf", "fps=30,scale=in_range=full:out_range=limited",
"-c:v", "libx264",
"-preset", "ultrafast",
@@ -425,87 +452,83 @@ impl MediaRecorder {
"-segment_time_delta", "0.01",
"-segment_list", &video_segment_list_filename,
"-segment_format", "mpegts",
+ "-movflags", "frag_keyframe+empty_moov",
"-reset_timestamps", "1",
&video_output_chunk_pattern,
- ];
+ ].into_iter().map(|s| s.to_string()).collect();
- let mut ffmpeg_command: Vec<String> = video_options.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;
if custom_device != Some("None") {
- 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()));
+ 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");
}
- // 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 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!("Starting audio channel senders...");
tokio::spawn(async move {
- 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);
+ 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);
}
}
});
}
+ println!("Starting video channel senders...");
tokio::spawn(async move {
- 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);
+ 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);
}
}
});
+
+ if custom_device != Some("None") {
+ self.ffmpeg_audio_process = audio_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.ffmpeg_video_process = Some(video_child);
self.device_name = Some(device.name().expect("Failed to get device name"));
println!("End of the start_audio_recording function");
@@ -525,63 +548,83 @@ impl MediaRecorder {
}
pub async fn stop_media_recording(&mut self) -> Result<(), 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");
- }
+ 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());
}
}
- self.should_stop.store(true, Ordering::SeqCst);
- println!("Stopping media recording...");
- 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(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());
}
}
+ self.should_stop.store(true, Ordering::SeqCst);
+
+ if let Some(sender) = self.audio_channel_sender.take() {
+ drop(sender);
+ }
+
if let Some(sender) = self.video_channel_sender.take() {
drop(sender);
- println!("Video recording stopped.");
}
- 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(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 let Some(process) = &mut self.ffmpeg_process {
+ if let Some(process) = &mut self.ffmpeg_video_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_ffmpeg_process(
+ async fn start_audio_ffmpeg_processes(
&self,
ffmpeg_binary_path: &str,
- ffmpeg_command: &[String],
+ audio_ffmpeg_command: &[String],
) -> Result<(Child, ChildStdin), Error> {
- let mut process = start_recording_process(ffmpeg_binary_path, ffmpeg_command).await.map_err(|e| {
+ 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 stdin = process.stdin.take().ok_or_else(|| {
+ 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((process, 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))
}
}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 10d78eb3d..f7d5bf16d 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -4,11 +4,13 @@ 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, create_m3u8_master_playlist};
+use crate::upload::{upload_file};
use crate::media::MediaRecorder;
@@ -41,79 +43,80 @@ 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();
- 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";
-
- 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'.");
- }
+ 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.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'.");
+ }
- Ok(())
+ Ok(())
}
#[tauri::command]
pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -> Result<(), String> {
- println!("Stopping all recordings...");
-
- 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...");
+
+ println!("Stopping media recording...");
+
+ guard.shutdown_flag.store(true, Ordering::SeqCst);
if let Some(mut media_process) = guard.media_process.take() {
- println!("2: Stopping media recording...");
+ println!("Stopping media recording...");
media_process.stop_media_recording().await.expect("Failed to stop media recording");
}
@@ -123,21 +126,13 @@ pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -
};
if !is_local_mode {
- 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());
- }
+ while !guard.video_uploading_finished.load(Ordering::SeqCst)
+ || !guard.audio_uploading_finished.load(Ordering::SeqCst) {
+ println!("Waiting for uploads to finish...");
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
-
- drop(guard);
-
+
println!("All recordings and uploads stopped.");
Ok(())
@@ -173,8 +168,17 @@ 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)
@@ -187,30 +191,33 @@ async fn start_upload_loop(
let options_clone = options.clone();
let video_type_clone = video_type.clone();
let segment_path_clone = segment_path.clone();
- let handle = tokio::spawn(async move {
+ 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(|_| ())
- });
+ }));
}
watched_segments.insert(segment_filename.clone());
}
- tokio::time::sleep(Duration::from_millis(50)).await;
- }
+ if !upload_tasks.is_empty() {
+ let _ = join_all(upload_tasks).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 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(".ts", ".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);
- }
- }
+ // 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);
+ // }
+ // }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
uploading_finished.store(true, Ordering::SeqCst);
Ok(())
}
@@ -233,8 +240,8 @@ fn load_segment_list(segment_list_path: &Path) -> io::Result<HashSet<String>> {
async fn prepare_media_recording(
options: &RecordingOptions,
audio_chunks_dir: &Path,
- video_chunks_dir: &Path,
screenshot_dir: &Path,
+ video_chunks_dir: &Path,
audio_name: Option<String>,
max_screen_width: usize,
max_screen_height: usize,
@@ -243,6 +250,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, video_file_path, screenshot_dir_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, screenshot_dir_path, video_file_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 14492b77c..2b76781bb 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -17,26 +17,26 @@ pub async fn upload_file(
if let Some(ref options) = options {
println!("Uploading video...");
- let (video_duration_str, bandwidth_str, resolution, video_codec, audio_codec) = match file_type.as_str() {
- "screenshot" => ("".to_string(), "".to_string(), "".to_string(), "".to_string(), "".to_string()),
- "audio" => {
- let (video_duration, audio_codec) = get_audio_metadata(&file_path).await?;
- let video_duration_str = format!("{:.1}", video_duration);
- println!("Audio duration: {} seconds", video_duration_str);
- (video_duration_str, "".to_string(), "".to_string(), "".to_string(), audio_codec)
- },
- "video" => {
- let (video_duration, bandwidth, resolution, video_codec) = get_video_metadata(&file_path).await?;
- let video_duration_str = format!("{:.1}", video_duration);
- let bandwidth_str = format!("{}", bandwidth);
- 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()),
- };
+ // let (video_duration_str, bandwidth_str, resolution, video_codec, audio_codec) = match file_type.as_str() {
+ // "screenshot" => ("".to_string(), "".to_string(), "".to_string(), "".to_string(), "".to_string()),
+ // "audio" => {
+ // let (video_duration, audio_codec) = get_audio_metadata(&file_path).await?;
+ // let video_duration_str = format!("{:.1}", video_duration);
+ // println!("Audio duration: {} seconds", video_duration_str);
+ // (video_duration_str, "".to_string(), "".to_string(), "".to_string(), audio_codec)
+ // },
+ // "video" => {
+ // let (video_duration, bandwidth, resolution, video_codec) = get_video_metadata(&file_path).await?;
+ // let video_duration_str = format!("{:.1}", video_duration);
+ // let bandwidth_str = format!("{}", bandwidth);
+ // 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()),
+ // };
let file_name = Path::new(&file_path)
.file_name()
@@ -45,21 +45,21 @@ pub async fn upload_file(
.to_string();
let file_key = format!("{}/{}/{}/{}", options.user_id, options.video_id, file_type, 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 server_url = format!("{}/api/upload/mux", server_url_base);
// Create the request body for the Next.js handler
let body = serde_json::json!({
"userId": options.user_id,
- "duration": video_duration_str,
- "bandwidth": bandwidth_str,
- "resolution": resolution,
- "videoCodec": video_codec,
- "audioCodec": audio_codec,
+ "videoId": options.video_id,
+ // "duration": video_duration_str,
+ // "bandwidth": bandwidth_str,
+ // "resolution": resolution,
+ // "videoCodec": video_codec,
+ // "audioCodec": audio_codec,
"fileKey": file_key,
- "awsBucket": options.aws_bucket,
- "awsRegion": options.aws_region,
+ // "awsBucket": options.aws_bucket,
+ // "awsRegion": options.aws_region,
});
let client = reqwest::Client::new();
@@ -75,68 +75,68 @@ pub async fn upload_file(
println!("Server response: {}", server_response);
- // Deserialize the server response
- let presigned_post_data: JsonValue = serde_json::from_str(&server_response)
- .map_err(|e| format!("Failed to deserialize server response: {}", e))?;
+ // // Deserialize the server response
+ // let 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()
- .ok_or("Fields object is missing or not an object")?;
+ // // Construct the multipart form for the file upload
+ // 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();
+ // let mut form = reqwest::multipart::Form::new();
- for (key, value) in fields.iter() {
- 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());
- }
+ // for (key, value) in fields.iter() {
+ // 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);
+ // 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") {
- "audio/webm"
- } else if file_path.to_lowercase().ends_with(".mp4") {
- "video/mp4"
- } else {
- "video/mp2t"
- };
-
- 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)
- .map_err(|e| format!("Error setting MIME type: {}", e))?;
-
- form = form.part("file", file_part);
-
- 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;
-
- match response {
- Ok(response) if response.status().is_success() => {
- println!("File uploaded successfully");
- }
- Ok(response) => {
- // The response was received without a network error, but the status code isn't a success.
- let status = response.status(); // Get the status before consuming the response
- 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) => {
- // The send operation failed before we got any response at all (e.g., a network error).
- return Err(format!("Failed to send upload file request: {}", e));
- }
- }
+ // let mime_type = if file_path.to_lowercase().ends_with(".aac") {
+ // "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"
+ // };
+
+ // 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)
+ // .map_err(|e| format!("Error setting MIME type: {}", e))?;
+
+ // form = form.part("file", file_part);
+
+ // 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;
+
+ // match response {
+ // Ok(response) if response.status().is_success() => {
+ // println!("File uploaded successfully");
+ // }
+ // Ok(response) => {
+ // // The response was received without a network error, but the status code isn't a success.
+ // let status = response.status(); // Get the status before consuming the response
+ // 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) => {
+ // // The send operation failed before we got any response at all (e.g., a network error).
+ // return Err(format!("Failed to send upload file request: {}", e));
+ // }
+ // }
// // Clean up the uploaded file
// println!("Removing file after upload: {}", file_path);
@@ -147,189 +147,189 @@ pub async fn upload_file(
// }
// remove_result.map_err(|e| format!("Failed to remove file after upload: {}", e))?;
- Ok(file_key)
+ Ok(file_path)
} else {
return Err("No recording options provided".to_string());
}
}
-async fn get_audio_metadata(file_path: &str) -> Result<(f64, String), String> {
- let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;
+// async fn get_audio_metadata(file_path: &str) -> Result<(f64, String), String> {
+// let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;
- let output = Command::new(&ffmpeg_binary_path_str)
- .args(&[
- "-i", file_path,
- "-f", "null",
- "-"])
- .output()
- .map_err(|e| format!("Failed to execute FFmpeg for getting metadata: {}", e))?;
+// let output = Command::new(&ffmpeg_binary_path_str)
+// .args(&[
+// "-i", file_path,
+// "-f", "null",
+// "-"])
+// .output()
+// .map_err(|e| format!("Failed to execute FFmpeg for getting metadata: {}", e))?;
- // Extract the metadata from FFmpeg's stderr
- let stderr = String::from_utf8_lossy(&output.stderr);
+// // Extract the metadata from FFmpeg's stderr
+// let stderr = String::from_utf8_lossy(&output.stderr);
- // Extract duration
- let duration_line = stderr.split('\n')
- .find(|line| line.contains("Duration"))
- .ok_or("Duration line not found in FFmpeg output")?;
+// // Extract duration
+// let duration_line = stderr.split('\n')
+// .find(|line| line.contains("Duration"))
+// .ok_or("Duration line not found in FFmpeg output")?;
- let duration_str = duration_line.split("Duration:").nth(1).unwrap()
- .split(',').next().unwrap()
- .trim();
+// let duration_str = duration_line.split("Duration:").nth(1).unwrap()
+// .split(',').next().unwrap()
+// .trim();
- let duration_parts: Vec<&str> = duration_str.split(':').collect();
- if duration_parts.len() != 3 {
- return Err("Invalid duration format".to_string());
- }
+// let duration_parts: Vec<&str> = duration_str.split(':').collect();
+// if duration_parts.len() != 3 {
+// return Err("Invalid duration format".to_string());
+// }
- let hours: f64 = duration_parts[0].parse().map_err(|_| "Failed to parse hours")?;
- let minutes: f64 = duration_parts[1].parse().map_err(|_| "Failed to parse minutes")?;
- let seconds: f64 = duration_parts[2].parse().map_err(|_| "Failed to parse seconds")?;
+// let hours: f64 = duration_parts[0].parse().map_err(|_| "Failed to parse hours")?;
+// let minutes: f64 = duration_parts[1].parse().map_err(|_| "Failed to parse minutes")?;
+// let seconds: f64 = duration_parts[2].parse().map_err(|_| "Failed to parse seconds")?;
- let total_seconds = hours * 3600.0 + minutes * 60.0 + seconds;
+// let total_seconds = hours * 3600.0 + minutes * 60.0 + seconds;
- // Extract audio codec
- let audio_codec_line = stderr.split('\n')
- .find(|line| line.contains("Audio:"))
- .ok_or("Audio line not found in FFmpeg output")?;
+// // Extract audio codec
+// let audio_codec_line = stderr.split('\n')
+// .find(|line| line.contains("Audio:"))
+// .ok_or("Audio line not found in FFmpeg output")?;
- let audio_codec_str = audio_codec_line.split("Audio:").nth(1).unwrap()
- .split(',').next().unwrap()
- .trim();
+// let audio_codec_str = audio_codec_line.split("Audio:").nth(1).unwrap()
+// .split(',').next().unwrap()
+// .trim();
- let audio_codec = audio_codec_str.to_string();
+// let audio_codec = audio_codec_str.to_string();
- Ok((total_seconds, audio_codec))
-}
+// Ok((total_seconds, audio_codec))
+// }
-async fn get_video_metadata(file_path: &str) -> Result<(f64, u64, String, String), String> {
- let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;
+// async fn get_video_metadata(file_path: &str) -> Result<(f64, u64, String, String), String> {
+// let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;
- let output = Command::new(&ffmpeg_binary_path_str)
- .args(&[
- "-i", file_path,
- "-f", "null",
- "-"])
- .output()
- .map_err(|e| format!("Failed to execute FFmpeg for getting metadata: {}", e))?;
+// let output = Command::new(&ffmpeg_binary_path_str)
+// .args(&[
+// "-i", file_path,
+// "-f", "null",
+// "-"])
+// .output()
+// .map_err(|e| format!("Failed to execute FFmpeg for getting metadata: {}", e))?;
- // Extract the metadata from FFmpeg's stderr
- let stderr = String::from_utf8_lossy(&output.stderr);
-
- // Extract duration
- let duration_line = stderr.split('\n')
- .find(|line| line.contains("Duration"))
- .ok_or("Duration line not found in FFmpeg output")?;
-
- let duration_str = duration_line.split("Duration:").nth(1).unwrap()
- .split(',').next().unwrap()
- .trim();
-
- let duration_parts: Vec<&str> = duration_str.split(':').collect();
- if duration_parts.len() != 3 {
- return Err("Invalid duration format".to_string());
- }
-
- let hours: f64 = duration_parts[0].parse().map_err(|_| "Failed to parse hours")?;
- let minutes: f64 = duration_parts[1].parse().map_err(|_| "Failed to parse minutes")?;
- let seconds: f64 = duration_parts[2].parse().map_err(|_| "Failed to parse seconds")?;
-
- let total_seconds = hours * 3600.0 + minutes * 60.0 + seconds;
-
- let bitrate_line = stderr.split('\n')
- .find(|line| line.contains("bitrate"))
- .ok_or("Bitrate line not found in FFmpeg output")?;
-
- let bitrate_str = bitrate_line.split("bitrate:").nth(1)
- .and_then(|s| s.split(',').next())
- .and_then(|s| s.trim().split(' ').next())
- .ok_or("Failed to parse bitrate")?;
-
- let bitrate_kbps: u64 = bitrate_str.parse().map_err(|_| "Failed to parse bitrate")?;
- let bandwidth = bitrate_kbps * 1000;
-
- // Extract resolution
- let resolution_line = stderr.split('\n')
- .find(|line| line.contains("Video:"))
- .ok_or("Video line not found in FFmpeg output")?;
-
- let resolution_str = resolution_line.split(',').nth(2).unwrap()
- .trim()
- .split(' ').next().unwrap();
-
- let resolution = resolution_str.to_string();
-
- let video_codec_line = stderr.split('\n')
- .find(|line| line.contains("Video:"))
- .ok_or("Video line not found in FFmpeg output")?;
-
- let video_codec_str = video_codec_line.split("Video:").nth(1).unwrap()
- .split(',').next().unwrap()
- .trim();
-
- 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
+// // Extract the metadata from FFmpeg's stderr
+// let stderr = String::from_utf8_lossy(&output.stderr);
+
+// // Extract duration
+// let duration_line = stderr.split('\n')
+// .find(|line| line.contains("Duration"))
+// .ok_or("Duration line not found in FFmpeg output")?;
+
+// let duration_str = duration_line.split("Duration:").nth(1).unwrap()
+// .split(',').next().unwrap()
+// .trim();
+
+// let duration_parts: Vec<&str> = duration_str.split(':').collect();
+// if duration_parts.len() != 3 {
+// return Err("Invalid duration format".to_string());
+// }
+
+// let hours: f64 = duration_parts[0].parse().map_err(|_| "Failed to parse hours")?;
+// let minutes: f64 = duration_parts[1].parse().map_err(|_| "Failed to parse minutes")?;
+// let seconds: f64 = duration_parts[2].parse().map_err(|_| "Failed to parse seconds")?;
+
+// let total_seconds = hours * 3600.0 + minutes * 60.0 + seconds;
+
+// let bitrate_line = stderr.split('\n')
+// .find(|line| line.contains("bitrate"))
+// .ok_or("Bitrate line not found in FFmpeg output")?;
+
+// let bitrate_str = bitrate_line.split("bitrate:").nth(1)
+// .and_then(|s| s.split(',').next())
+// .and_then(|s| s.trim().split(' ').next())
+// .ok_or("Failed to parse bitrate")?;
+
+// let bitrate_kbps: u64 = bitrate_str.parse().map_err(|_| "Failed to parse bitrate")?;
+// let bandwidth = bitrate_kbps * 1000;
+
+// // Extract resolution
+// let resolution_line = stderr.split('\n')
+// .find(|line| line.contains("Video:"))
+// .ok_or("Video line not found in FFmpeg output")?;
+
+// let resolution_str = resolution_line.split(',').nth(2).unwrap()
+// .trim()
+// .split(' ').next().unwrap();
+
+// let resolution = resolution_str.to_string();
+
+// let video_codec_line = stderr.split('\n')
+// .find(|line| line.contains("Video:"))
+// .ok_or("Video line not found in FFmpeg output")?;
+
+// let video_codec_str = video_codec_line.split("Video:").nth(1).unwrap()
+// .split(',').next().unwrap()
+// .trim();
+
+// 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/web/app/api/upload/mux/route.ts b/apps/web/app/api/upload/mux/route.ts
new file mode 100644
index 000000000..3ed9b8318
--- /dev/null
+++ b/apps/web/app/api/upload/mux/route.ts
@@ -0,0 +1,70 @@
+import { NextRequest } from "next/server";
+import Mux from "@mux/mux-node";
+
+const mux = new Mux({
+ tokenId: process.env["MUX_TOKEN_ID"],
+ tokenSecret: process.env["MUX_TOKEN_SECRET"],
+});
+
+export async function POST(request: NextRequest) {
+ try {
+ const { userId, videoId, fileKey } = await request.json();
+
+ if (!userId || !fileKey || !videoId) {
+ console.error("Missing required fields in /api/upload/mux/route.ts");
+
+ return new Response(
+ JSON.stringify({ error: "Missing required fields" }),
+ {
+ status: 400,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+
+ let asset = await mux.Video.Assets.get(videoId).catch(async () => {
+ const newAsset = await mux.Video.Assets.create({
+ input: [],
+ playback_policy: "public",
+ passthrough: videoId,
+ });
+ return newAsset;
+ });
+
+ // Create a direct upload URL
+ const upload = await mux.Video.Uploads.create({
+ cors_origin: request.headers.get("origin") || "*",
+ new_asset_settings: { playback_policy: "public", passthrough: asset.id },
+ });
+
+ // Respond with the upload URL and ID
+ return new Response(
+ JSON.stringify({
+ videoId: videoId,
+ userId: userId,
+ uploadUrl: upload.url,
+ uploadId: upload.id,
+ assetId: asset.id,
+ }),
+ {
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ } catch (error) {
+ console.error("Error when uploading to Mux", error);
+ return new Response(
+ JSON.stringify({ error: "Error when uploading to Mux" }),
+ {
+ status: 500,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+}
diff --git a/apps/web/app/api/upload/signed/route.ts b/apps/web/app/api/upload/signed/route.ts
index 31103c34a..71ffac9fe 100644
--- a/apps/web/app/api/upload/signed/route.ts
+++ b/apps/web/app/api/upload/signed/route.ts
@@ -42,6 +42,8 @@ export async function POST(request: NextRequest) {
? "audio/aac"
: fileKey.endsWith(".webm")
? "audio/webm"
+ : fileKey.endsWith(".mp4")
+ ? "video/mp4"
: "video/mp2t";
const Fields = {
diff --git a/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
index cf0de0fd2..f87c21177 100644
--- a/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
@@ -26,9 +26,7 @@ export const VideoPlayer = memo(
media: HTMLMediaElement,
hlsInstance: React.MutableRefObject<Hls | null>
) => {
- const hls = new Hls({
- maxBufferLength: 30,
- });
+ const hls = new Hls();
hls.on(Hls.Events.ERROR, (event, data) => {
console.error("HLS error:", data);
if (data.fatal) {
diff --git a/apps/web/package.json b/apps/web/package.json
index b55b217cd..b15884514 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -19,6 +19,7 @@
"@ffmpeg/util": "^0.12.1",
"@headlessui/react": "^1.7.17",
"@hookform/resolvers": "^3.3.2",
+ "@mux/mux-node": "^8.5.1",
"@octokit/rest": "^20.0.2",
"@react-email/components": "^0.0.13",
"@react-email/render": "0.0.11",
diff --git a/apps/web/utils/video/ffmpeg/helpers.ts b/apps/web/utils/video/ffmpeg/helpers.ts
index 6971c4aea..50a043b7a 100644
--- a/apps/web/utils/video/ffmpeg/helpers.ts
+++ b/apps/web/utils/video/ffmpeg/helpers.ts
@@ -82,7 +82,8 @@ export async function generateM3U8Playlist(
}[]
) {
const baseM3U8Content = `#EXTM3U
-#EXT-X-TARGETDURATION:3
+#EXT-X-INDEPENDENT-SEGMENTS
+#EXT-X-TARGETDURATION:4
#EXT-X-VERSION:4
#EXT-X-MEDIA-SEQUENCE:0
`;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 769a1ef77..0d1929af4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -35,6 +35,9 @@ importers:
'@cap/utils':
specifier: workspace:*
version: link:../../packages/utils
+ '@mux/mux-node':
+ specifier: ^8.5.1
+ version: 8.5.1
'@sentry/nextjs':
specifier: ^7.105.0
@@ -138,6 +141,9 @@ importers:
'@hookform/resolvers':
specifier: ^3.3.2
version: 3.3.4([email protected])
+ '@mux/mux-node':
+ specifier: ^8.5.1
+ version: 8.5.1
'@octokit/rest':
specifier: ^20.0.2
version: 20.0.2
@@ -2277,6 +2283,24 @@ packages:
react: 18.2.0
dev: false
+ resolution: {integrity: sha512-QEuN+4tjcET3xid69KMf39EE8/v5OL6NhV8ZEBxoRh0ET+srOgFLcHBKPwG+ydyFWdPh7SDfW94TmorZJzcnoQ==}
+ dependencies:
+ '@types/node': 18.19.31
+ '@types/node-fetch': 2.6.11
+ '@types/qs': 6.9.15
+ abort-controller: 3.0.0
+ agentkeepalive: 4.5.0
+ form-data-encoder: 1.7.2
+ formdata-node: 4.4.1
+ jose: 4.15.4
+ node-fetch: 2.7.0
+ qs: 6.12.0
+ web-streams-polyfill: 3.3.3
+ transitivePeerDependencies:
+ - encoding
+ dev: false
+
resolution: {integrity: sha512-Py8zIo+02ht82brwwhTg36iogzFqGLPXlRGKQw5s+qP/kMNc4MAyDeEwBKDijk6zTIbegEgu8Qy7C1LboslQAw==}
dev: false
@@ -4769,6 +4793,12 @@ packages:
resolution: {integrity: sha512-eEn8RkzZFcT0gb8qyi0CcfSOQnLE+NbGLIIaxGGmjn/N35v/C3M8ohxcpSlNlCv+H8vPpMGmrGDdCkzr8xu2tQ==}
dev: false
+ resolution: {integrity: sha512-ArgCD39YpyyrtFKIqMDvjz79jto5fcI/SVUs2HwB+f0dAzq68yqOdyaSivLiLugSziTpNXLQrVb7RZFmdZzbhA==}
+ dependencies:
+ undici-types: 5.26.5
+ dev: false
+
resolution: {integrity: sha512-g557vgQjUUfN76MZAN/dt1z3dzcUsimuysco0KeluHgrPdJXkP/XdAURgyO2W9fZWHRtRBiVKzKn8vyOAwlG+w==}
dependencies:
@@ -4789,6 +4819,10 @@ packages:
resolution: {integrity: sha512-ga8y9v9uyeiLdpKddhxYQkxNDrfvuPrlFb0N1qnZZByvcElJaXthF1UhvCh9TLWJBEHeNtdnbysW7Y6Uq8CVng==}
+ resolution: {integrity: sha512-uXHQKES6DQKKCLh441Xv/dwxOq1TVS3JPUMlEqoEglvlhR6Mxnlew/Xq/LRVHpLyk7iK3zODe1qYHIMltO7XGg==}
+ dev: false
+
resolution: {integrity: sha512-TJxDm6OfAX2KJWJdMEVTwWke5Sc/E/RlnPGvGfS0W7+6ocy2xhDVQVh/KvC2Uf7kACs+gDytdusDSdWfWkaNzw==}
dependencies:
@@ -5048,6 +5082,13 @@ packages:
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
dev: false
+ resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}
+ engines: {node: '>=6.5'}
+ dependencies:
+ event-target-shim: 5.0.1
+ dev: false
+
resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}
peerDependencies:
@@ -5097,6 +5138,13 @@ packages:
- supports-color
dev: true
+ resolution: {integrity: sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==}
+ engines: {node: '>= 8.0.0'}
+ dependencies:
+ humanize-ms: 1.2.1
+ dev: false
+
resolution: {integrity: sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==}
engines: {node: '>=8'}
@@ -7140,6 +7188,11 @@ packages:
es5-ext: 0.10.62
dev: true
+ resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}
+ engines: {node: '>=6'}
+ dev: false
+
resolution: {integrity: sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==}
dev: false
@@ -7296,6 +7349,10 @@ packages:
cross-spawn: 7.0.3
signal-exit: 4.1.0
+ resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==}
+ dev: false
+
resolution: {integrity: sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==}
engines: {node: '>= 6'}
@@ -7305,6 +7362,14 @@ packages:
mime-types: 2.1.35
dev: false
+ resolution: {integrity: sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==}
+ engines: {node: '>= 12.20'}
+ dependencies:
+ node-domexception: 1.0.0
+ web-streams-polyfill: 4.0.0-beta.3
+ dev: false
+
resolution: {integrity: sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==}
@@ -7772,6 +7837,12 @@ packages:
resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==}
engines: {node: '>=10.17.0'}
+ resolution: {integrity: sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==}
+ dependencies:
+ ms: 2.1.3
+ dev: false
+
resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}
engines: {node: '>=0.10.0'}
@@ -9087,7 +9158,6 @@ packages:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
- dev: true
resolution: {integrity: sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==}
@@ -9250,6 +9320,11 @@ packages:
lower-case: 1.1.4
dev: true
+ resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}
+ engines: {node: '>=10.5.0'}
+ dev: false
+
resolution: {integrity: sha512-StxNAxh15zr77QvvkmveSQ8uCQ4+v5FkvNTj0OESmiHu+VRi/gXArXtkWMElOsOUNLtUEvI4yS+rdtOHZTwlQA==}
engines: {node: 4.x || >=6.0.0}
@@ -11576,6 +11651,16 @@ packages:
dependencies:
defaults: 1.0.4
+ resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
+ engines: {node: '>= 8'}
+ dev: false
+
+ resolution: {integrity: sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==}
+ engines: {node: '>= 14'}
+ dev: false
+
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
dev: false