Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Nicer webcam preview, better loading state

Richie McIlroy61cebff2c7ff
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 81185e160..92b763acf 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -29,5 +29,5 @@ This is a very top level guide right now, but the basics are:
3. Clone .env.example and rename it to .env
4. Add your own API keys to the .env file
5. Run the app with `pnpm dev`
-6. Make sure the app can be built without any errors with `pnpm build`
+6. Make sure both the the desktop app, and web app can be built without any errors. For the desktop app, use `pnpm tauri:build`. For the web app, use `pnpm build`
7. Submit a PR with your changes
diff --git a/apps/desktop/src-tauri/src/audio.rs b/apps/desktop/src-tauri/src/audio.rs
index 52edaeb09..102d1c70d 100644
--- a/apps/desktop/src-tauri/src/audio.rs
+++ b/apps/desktop/src-tauri/src/audio.rs
@@ -1,8 +1,6 @@
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::SampleFormat;
-use std::io::{BufReader, BufRead};
use std::process::{Stdio, Command};
-use std::thread;
use std::io::Write;
use byteorder::{ByteOrder, LittleEndian};
use std::sync::{Arc, Mutex};
@@ -13,6 +11,7 @@ use crate::utils::ffmpeg_path_as_str;
pub struct AudioRecorder {
pub options: Option<RecordingOptions>,
ffmpeg_stdin: Arc<Mutex<Option<std::process::ChildStdin>>>,
+ device_name: Option<String>,
stream: Option<cpal::Stream>,
}
@@ -22,16 +21,44 @@ impl AudioRecorder {
AudioRecorder {
options: None,
ffmpeg_stdin: Arc::new(Mutex::new(None)),
+ device_name: None,
stream: None,
}
}
- pub fn setup_recording(&mut self, options: RecordingOptions, audio_file_path: &str) {
+ pub fn setup_recording(&mut self, options: RecordingOptions, audio_file_path: &str, custom_device: Option<&str>) -> Result<(), &'static str> {
self.options = Some(options);
let host = cpal::default_host();
- let device = host.default_input_device().expect("No input device available");
- let config = device.default_input_config().expect("Failed to get default input config");
+ let devices = host.devices().expect("Failed to get devices");
+
+ let mut input_devices = devices.filter_map(|device| {
+ let supported_input_configs = device.supported_input_configs();
+ if supported_input_configs.is_ok() && supported_input_configs.unwrap().count() > 0 {
+ Some(device)
+ } else {
+ None
+ }
+ });
+
+ let device = if let Some(custom_device_name) = custom_device {
+ input_devices
+ .find(|d| d.name().map(|name| name == custom_device_name).unwrap_or(false))
+ .unwrap_or_else(|| host.default_input_device().expect("No default input device available"))
+ } else {
+ host.default_input_device().expect("No default input device available")
+ };
+
+ println!("Using audio device: {}", device.name().expect("Failed to get device name"));
+
+ let config = device.supported_input_configs()
+ .expect("Failed to get supported input configs")
+ .find(|c| c.sample_format() == SampleFormat::F32 || c.sample_format() == SampleFormat::I16 || c.sample_format() == SampleFormat::I8 || c.sample_format() == SampleFormat::I32)
+ .unwrap_or_else(||
+ device.supported_input_configs().expect("Failed to get supported input configs").next().expect("No supported input config")
+ )
+ .with_max_sample_rate();
+
let sample_rate = config.sample_rate().0;
let channels = config.channels();
let sample_format = match config.sample_format() {
@@ -62,9 +89,7 @@ impl AudioRecorder {
audio_filters.push("pan=stereo|FL=FL+0.5*FC|FR=FR+0.5*FC");
}
- // Add loudnorm and acompressor to the filter chain
audio_filters.push("loudnorm");
- audio_filters.push("acompressor");
let audio_filters_str = audio_filters.join(",");
@@ -90,42 +115,7 @@ impl AudioRecorder {
.spawn()
.expect("ffmpeg command failed to start");
- thread::spawn(move || {
- let stdout = BufReader::new(child.stdout.take().expect("failed to get stdout"));
- for line in stdout.lines() {
- match line {
- Ok(line) => eprintln!("Audio stdout: {}", line),
- Err(e) => eprintln!("Error reading FFmpeg stdout: {}", e),
- }
- }
- });
-
- thread::spawn(move || {
- let stderr = BufReader::new(child.stderr.take().expect("failed to get stderr"));
- for line in stderr.lines() {
- match line {
- Ok(line) => eprintln!("Audio stderr: {}", line),
- Err(e) => eprintln!("Error reading FFmpeg stderr: {}", e),
- }
- }
- });
-
let stdin = child.stdin.take().expect("failed to get stdin");
- *self.ffmpeg_stdin.lock().unwrap() = Some(stdin);
-
- self.start_audio_recording().expect("Failed to start audio recording");
- }
-
- pub fn start_audio_recording(&mut self) -> Result<(), &'static str> {
- let host = cpal::default_host();
- let device = host.default_input_device().ok_or("Unable to find default input device")?;
- let config: cpal::SupportedStreamConfig = device
- .default_input_config()
- .expect("Failed to get default input config");
- println!("Default input config: {:?}", config);
- let sample_format = config.sample_format();
-
- println!("Starting audio recording with sample format: {:?}", sample_format);
let err_fn = move |err| {
eprintln!("an error occurred on stream: {}", err);
@@ -133,7 +123,7 @@ impl AudioRecorder {
let ffmpeg_stdin_arc_clone = Arc::clone(&self.ffmpeg_stdin);
- let stream_result: Result<cpal::Stream, cpal::BuildStreamError> = match sample_format {
+ let stream_result: Result<cpal::Stream, cpal::BuildStreamError> = match config.sample_format() {
SampleFormat::I8 => device.build_input_stream(
&config.into(),
move |data: &[i8], _: &_| {
@@ -193,9 +183,20 @@ impl AudioRecorder {
};
let stream = stream_result.map_err(|_| "Failed to build input stream")?;
- stream.play().map_err(|_| "Failed to play stream")?;
-
self.stream = Some(stream);
+ *self.ffmpeg_stdin.lock().unwrap() = Some(stdin);
+ self.device_name = Some(device.name().expect("Failed to get device name"));
+
+ Ok(())
+ }
+
+ pub fn start_audio_recording(&mut self) -> Result<(), &'static str> {
+ if let Some(ref mut stream) = self.stream {
+ stream.play().map_err(|_| "Failed to play stream")?;
+ println!("Started audio recording.");
+ } else {
+ println!("Audio recording was not started.");
+ }
Ok(())
}
@@ -221,3 +222,26 @@ impl AudioRecorder {
}
}
+#[tauri::command]
+pub fn enumerate_audio_devices() -> Vec<String> {
+ let host = cpal::default_host();
+ let default_device = host.default_input_device().expect("No default input device available");
+ let default_device_name = default_device.name().expect("Failed to get default device name");
+
+ let devices = host.devices().expect("Failed to get devices");
+ let mut input_device_names: Vec<String> = devices
+ .filter_map(|device| {
+ let supported_input_configs = device.supported_input_configs();
+ if supported_input_configs.is_ok() && supported_input_configs.unwrap().count() > 0 {
+ device.name().ok()
+ } else {
+ None
+ }
+ })
+ .collect();
+
+ input_device_names.retain(|name| name != &default_device_name);
+ input_device_names.insert(0, default_device_name);
+
+ input_device_names
+}
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index c8cd859de..bb705a0f4 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -18,6 +18,7 @@ mod audio;
use recording::{RecordingState, start_dual_recording, stop_all_recordings};
use upload::upload_file;
+use audio::{enumerate_audio_devices};
use ffmpeg_sidecar::{
command::ffmpeg_is_installed,
@@ -92,6 +93,8 @@ fn main() {
upload_handles: Mutex::new(vec![]),
recording_options: None,
shutdown_flag: Arc::new(AtomicBool::new(false)),
+ video_uploading_finished: Arc::new(AtomicBool::new(false)),
+ audio_uploading_finished: Arc::new(AtomicBool::new(false)),
data_dir: Some(data_directory),
};
@@ -102,6 +105,7 @@ fn main() {
.invoke_handler(tauri::generate_handler![
start_dual_recording,
stop_all_recordings,
+ enumerate_audio_devices,
upload_file
])
.plugin(tauri_plugin_context_menu::init())
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 65676a8d8..d95443a3a 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -8,8 +8,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync:: {Mutex};
use tokio::task::JoinHandle;
use tokio::time::{Duration};
-use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
-use tokio::io::{BufReader as TokioBufReader, AsyncRead};
+use tokio::io::{AsyncWriteExt};
use serde::{Serialize, Deserialize};
use chrono::Utc;
use reqwest::Client;
@@ -27,7 +26,9 @@ pub struct RecordingState {
pub upload_handles: Mutex<Vec<JoinHandle<Result<(), String>>>>,
pub recording_options: Option<RecordingOptions>,
pub shutdown_flag: Arc<AtomicBool>,
- pub data_dir: Option<PathBuf>,
+ pub video_uploading_finished: Arc<AtomicBool>,
+ pub audio_uploading_finished: Arc<AtomicBool>,
+ pub data_dir: Option<PathBuf>
}
unsafe impl Send for RecordingState {}
@@ -38,6 +39,7 @@ pub struct RecordingOptions {
pub video_id: String,
pub screen_index: String,
pub video_index: String,
+ pub audio_name: String,
pub aws_region: String,
pub aws_bucket: String,
pub framerate: String,
@@ -57,9 +59,8 @@ pub async fn start_dual_recording(
let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;
let data_dir = state_guard.data_dir.as_ref()
- .ok_or("Data directory is not set in the recording state".to_string())?;
+ .ok_or("Data directory is not set in the recording state".to_string())?.clone();
- //print the data_dir
println!("data_dir: {:?}", data_dir);
let screen_chunks_dir = data_dir.join("chunks/screen");
@@ -67,15 +68,26 @@ pub async fn start_dual_recording(
clean_and_create_dir(&screen_chunks_dir)?;
clean_and_create_dir(&audio_chunks_dir)?;
- let ffmpeg_screen_args_future = construct_recording_args(&options, &screen_chunks_dir, "screen", &options.screen_index);
+ state_guard.audio_process = Some(AudioRecorder::new());
+
+ let audio_name = if options.audio_name.is_empty() {
+ None
+ } else {
+ Some(options.audio_name.clone())
+ };
- // let ffmpeg_video_args_future = construct_recording_args(&options, &video_chunks_dir, "video", &options.video_index);
+ if let Some(ref mut audio_process) = state_guard.audio_process {
+ let audio_file_path = audio_chunks_dir.to_str().unwrap();
+ audio_process.setup_recording(options.clone(), audio_file_path, audio_name.as_deref()).map_err(|e| e.to_string())?;
+ }
+
+ let ffmpeg_screen_args_future = construct_recording_args(&options, &screen_chunks_dir, "screen", &options.screen_index);
let ffmpeg_screen_args = ffmpeg_screen_args_future.await.map_err(|e| e.to_string())?;
-
let screenshot_output_path = data_dir.join("screen-capture.jpg").to_str().unwrap().to_string();
let ffmpeg_screen_screenshot_args = match std::env::consts::OS {
"macos" => vec![
+ "-y".to_string(),
"-f".to_string(),
"avfoundation".to_string(),
"-i".to_string(),
@@ -85,6 +97,7 @@ pub async fn start_dual_recording(
screenshot_output_path.clone()
],
"windows" => vec![
+ "-y".to_string(),
"-f".to_string(),
"gdigrab".to_string(),
"-i".to_string(),
@@ -94,20 +107,23 @@ pub async fn start_dual_recording(
screenshot_output_path.clone()
],
"linux" => vec![
+ "-y".to_string(),
"-f".to_string(),
"x11grab".to_string(),
"-i".to_string(),
":0.0".to_string(),
"-vframes".to_string(),
"1".to_string(),
- screenshot_output_path
+ screenshot_output_path.clone()
],
_ => return Err("Unsupported OS".to_string()),
};
- // let ffmpeg_video_args = ffmpeg_video_args_future.await.map_err(|e| e.to_string())?;
println!("Screen args: {:?}", ffmpeg_screen_args);
- // println!("Video args: {:?}", ffmpeg_video_args);
+
+ if let Some(mut audio_process) = state_guard.audio_process.take() {
+ audio_process.start_audio_recording().expect("Failed to start audio recording");
+ }
let mut screen_child = tokio::process::Command::new(&ffmpeg_binary_path_str)
.args(&ffmpeg_screen_args)
@@ -116,71 +132,39 @@ pub async fn start_dual_recording(
.stderr(Stdio::piped())
.spawn()
.map_err(|e| e.to_string())?;
+
+ let screen_process_stdin = screen_child.stdin.take().ok_or("Failed to open stdin for screen recording process".to_string())?;
- // let mut video_child = tokio::process::Command::new(&ffmpeg_binary_path_str)
- // .args(&ffmpeg_video_args)
- // .stdout(Stdio::piped())
- // .stderr(Stdio::piped())
- // .spawn()
- // .map_err(|e| e.to_string())?;
-
- // In the part where you spawn the FFmpeg process and handle its output:
-
- let screen_stderr = screen_child.stderr.take().unwrap();
- let ffmpeg_start_trigger = "time=00:00:00.00".to_string();
-
- let server_url_base: String = dotenv_codegen::dotenv!("NEXT_PUBLIC_URL").into();
- let video_id_clone = options.video_id.clone();
-
- let started_callback = Arc::new(move || {
- let server_url_base = server_url_base.clone();
- let video_id_clone = video_id_clone.clone();
- tokio::spawn(async move {
- if let Err(e) = send_metadata_api(&video_id_clone, &server_url_base).await {
- eprintln!("Failed to send metadata API request: {}", e);
- }
- });
- });
-
- state_guard.audio_process = Some(AudioRecorder::new());
-
- if let Some(ref mut audio_process) = state_guard.audio_process {
- let audio_file_path = audio_chunks_dir.to_str().unwrap();
- audio_process.setup_recording(options.clone(), audio_file_path);
- }
-
- tokio::spawn(log_output(screen_stderr, "Screen stderr".to_string(), Some(ffmpeg_start_trigger), Some(started_callback)));
- let ffmpeg_binary_path_clone = ffmpeg_binary_path_str.clone();
- let ffmpeg_screen_screenshot_args_clone = ffmpeg_screen_screenshot_args.clone();
+ let options_clone = state_guard.recording_options.clone();
// Spawn the screenshot task without directly awaiting it
tokio::spawn(async move {
- if let Err(e) = take_screenshot(ffmpeg_binary_path_clone, ffmpeg_screen_screenshot_args_clone).await {
- eprintln!("Failed to take screenshot: {}", e);
+ if let Err(e) = take_screenshot(
+ ffmpeg_binary_path_str.clone(),
+ ffmpeg_screen_screenshot_args.clone(),
+ screenshot_output_path.clone(),
+ options_clone.clone(),
+ ).await {
+ eprintln!("Failed to take and upload screenshot: {}", e);
}
});
- let screen_process_stdin = screen_child.stdin.take().ok_or("Failed to open stdin for screen recording process".to_string())?;
-
- // let video_stdout = video_child.stdout.take().unwrap();
- // let video_stderr = video_child.stderr.take().unwrap();
- // tokio::spawn(log_output(video_stdout, "Video stdout".to_string()));
- // tokio::spawn(log_output(video_stderr, "Video stderr".to_string()));
-
state_guard.screen_process = Some(screen_child);
state_guard.screen_process_stdin = Some(screen_process_stdin);
- // guard.video_process = Some(video_child);
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 screen_upload = start_upload_loop(screen_chunks_dir, options.clone(), "screen".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...");
- let screen_upload = start_upload_loop(state.clone(), screen_chunks_dir, options.clone(), "screen".to_string(), shutdown_flag.clone());
- let audio_upload = start_upload_loop(state.clone(), audio_chunks_dir, options.clone(), "audio".to_string(), shutdown_flag.clone());
match tokio::try_join!(screen_upload, audio_upload) {
Ok(_) => {
@@ -198,13 +182,8 @@ pub async fn start_dual_recording(
pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -> Result<(), String> {
println!("!!STOPPING screen recording...");
- // Lock the state to access shared data.
let mut guard = state.lock().await;
-
- // Immediately instruct ongoing operations to stop.
- guard.shutdown_flag.store(true, Ordering::SeqCst);
-
- // Immediately try to close running FFmpeg processes.
+
if let Some(stdin) = guard.screen_process_stdin.take() {
if let Err(e) = graceful_stop_ffmpeg(stdin).await {
eprintln!("Failed to send quit command to FFmpeg: {}", e);
@@ -212,7 +191,7 @@ pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -
}
if let Some(audio_process) = &mut guard.audio_process {
- audio_process.stop_audio_recording().expect("Failed to stop audio recording");
+ audio_process.stop_audio_recording().expect("Failed to stop audio recording");
}
if let Some(mut child) = guard.screen_process.take() {
@@ -222,35 +201,14 @@ pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -
}
}
- // Assuming there's a video_process similar to screen_process.
- //if let Some(child_process) = &mut guard.video_process {
- // let _ = child_process.kill().await;
- //}
-
- // Swap out the current upload_handles for an empty vector to take ownership.
- let mut upload_handles_lock = guard.upload_handles.lock().await;
- let upload_handles = std::mem::take(&mut *upload_handles_lock);
-
- // Explicitly drop the locks so other async operations can proceed.
- drop(upload_handles_lock);
- drop(guard);
-
- // Now using try_join_all with the owned join handles obtained from the state.
- // This will wait for all the current upload handles to complete.
- let _ = futures::future::try_join_all(upload_handles.into_iter()).await;
-
- let state_guard = state.lock().await;
- let data_dir_option = state_guard.data_dir.clone();
- let options_clone = state_guard.recording_options.clone();
- let _shutdown_flag_clone = state_guard.shutdown_flag.clone();
- drop(state_guard);
+ guard.shutdown_flag.store(true, Ordering::SeqCst);
- if let Some(data_dir) = data_dir_option {
- if let Err(e) = upload_jpeg_files(&data_dir, options_clone).await {
- eprintln!("Error uploading JPEG files: {}", e);
- }
+ 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(100)).await;
}
-
+
println!("All recordings and uploads stopped.");
Ok(())
@@ -263,41 +221,14 @@ fn clean_and_create_dir(dir: &Path) -> Result<(), String> {
}
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
- // Ensure the segment list file exists within the given directory
- // This assumes a naming convention where the segment list file is named "segment_list.txt"
let segment_list_path = dir.join("segment_list.txt");
match File::open(&segment_list_path) {
- Ok(_) => Ok(()), // File already exists, return Ok(())
+ Ok(_) => Ok(()),
Err(ref e) if e.kind() == ErrorKind::NotFound => {
- // Create the file if it does not exist, but ignore the returned File object
File::create(&segment_list_path).map_err(|e| e.to_string())?;
- Ok(()) // Now the file is created, return Ok(())
+ Ok(())
},
- Err(e) => Err(e.to_string()), // Handle other possible file I/O errors
- }
-}
-
-async fn log_output<R>(
- reader: R,
- description: String,
- start_trigger: Option<String>,
- started_callback: Option<Arc<dyn Fn() + Send + Sync>>
-)
-where
- R: AsyncRead + Unpin + Send + 'static,
-{
- let mut buf_reader = TokioBufReader::new(reader).lines();
-
- while let Ok(Some(line)) = buf_reader.next_line().await {
- println!("{}: {}", description, line);
-
- if let Some(trigger) = &start_trigger {
- if line.contains(trigger) {
- if let Some(callback) = &started_callback {
- callback();
- }
- }
- }
+ Err(e) => Err(e.to_string()),
}
}
@@ -391,64 +322,65 @@ async fn construct_recording_args(
}
async fn start_upload_loop(
- state: State<'_, Arc<Mutex<RecordingState>>>,
chunks_dir: PathBuf,
options: RecordingOptions,
video_type: String,
shutdown_flag: Arc<AtomicBool>,
+ uploading_finished: Arc<AtomicBool>,
) -> Result<(), String> {
- println!("Starting upload loop for {}", video_type);
-
- let segment_list_path = chunks_dir.join("segment_list.txt");
-
let mut watched_segments: HashSet<String> = HashSet::new();
+ let mut ongoing_tasks: Vec<JoinHandle<Result<(), String>>> = vec![];
loop {
- if shutdown_flag.load(Ordering::SeqCst) {
- println!("Shutdown flag set, exiting upload loop for {}", video_type);
- break;
+ if shutdown_flag.load(Ordering::SeqCst) && ongoing_tasks.is_empty() {
+ break;
}
- match load_segment_list(&segment_list_path) {
- Ok(new_segments) => {
- for segment_filename in new_segments {
- let segment_path = chunks_dir.join(&segment_filename);
-
- // Check if the segment is new and schedule it for upload
- if segment_path.is_file() && watched_segments.insert(segment_filename.clone()) {
- let filepath_str = segment_path.to_str().unwrap_or_default().to_owned();
- let options_clone = options.clone();
- let video_type_clone = video_type.clone();
+ let current_segments = load_segment_list(&chunks_dir.join("segment_list.txt"))
+ .map_err(|e| e.to_string())?
+ .difference(&watched_segments)
+ .cloned()
+ .collect::<HashSet<String>>();
+
+ for segment_filename in &current_segments {
+ let segment_path = chunks_dir.join(segment_filename);
+ if segment_path.is_file() {
+ let options_clone = options.clone();
+ let video_type_clone = video_type.clone();
+ let filepath_str = segment_path.to_str().unwrap_or_default().to_owned();
+
+ // Spawn an upload task for each new segment
+ let upload_task = tokio::spawn(async move {
+ println!("Uploading video for {}: {}", video_type_clone, filepath_str);
+ upload_file(Some(options_clone), filepath_str, video_type_clone).await.map(|_| ())
+ });
+ ongoing_tasks.push(upload_task);
+ }
+ watched_segments.insert(segment_filename.clone());
+ }
- let handle = tokio::spawn(async move {
- println!("Uploading video for {}: {}", video_type_clone, filepath_str);
-
- match upload_file(Some(options_clone.clone()), filepath_str.clone(), video_type_clone.clone()).await {
- Ok(file_key) => {
- println!("Chunk uploaded: {}", file_key);
- },
- Err(e) => {
- eprintln!("Failed to upload chunk {}: {}", filepath_str, e);
- }
- }
-
- Ok(())
- });
-
- // Store the handle in the state for later awaits or cancels if required.
- let guard = state.lock().await;
- guard.upload_handles.lock().await.push(handle);
-
- drop(guard);
- }
- }
+ let mut i = 0;
+ while i != ongoing_tasks.len() {
+ let task = &mut ongoing_tasks[i];
+ tokio::select! {
+ _ = task => {
+ ongoing_tasks.remove(i);
+ },
+ _ = tokio::time::sleep(Duration::from_millis(100)) => {
+ i += 1;
+ },
}
- Err(e) => eprintln!("Failed to read segment list for {}: {}", video_type, e),
}
- tokio::time::sleep(Duration::from_secs(3)).await;
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+
+ for task in ongoing_tasks {
+ let _ = task.await;
}
+ uploading_finished.store(true, Ordering::SeqCst);
+
Ok(())
}
@@ -480,122 +412,16 @@ fn load_segment_list(segment_list_path: &Path) -> io::Result<HashSet<String>> {
Ok(segments)
}
-// Unused for now
-// async fn upload_remaining_chunks(
-// chunks_dir: &PathBuf,
-// options: Option<RecordingOptions>,
-// video_type: &str,
-// shutdown_flag: Arc<AtomicBool>,
-// ) -> Result<(), String> {
-// // Include shutdown_flag in parameters and check it inside loop to quickly react to stop signals.
-
-// if let Some(actual_options) = options {
-// let retry_interval = Duration::from_secs(2);
-// let upload_timeout = Duration::from_secs(15);
-// let file_stability_timeout = Duration::from_secs(1);
-// let file_stability_checks = 2;
-
-// // Adjusted for immediate reaction to shutdown_flag.
-// if shutdown_flag.load(Ordering::SeqCst) {
-// return Ok(());
-// }
-
-// let entries = std::fs::read_dir(chunks_dir).map_err(|e| format!("Error reading directory: {}", e))?;
-
-// let semaphore = Arc::new(Semaphore::new(16));
-
-// let tasks: Vec<_> = entries.filter_map(|entry| entry.ok())
-// .filter_map(|entry| {
-// let path = entry.path();
-// if path.is_file() && (path.extension().map_or(false, |e| e == "ts" || e == "aac")) && !shutdown_flag.load(Ordering::SeqCst) {
-// let video_type = video_type.to_string();
-// let semaphore_clone = semaphore.clone();
-// let actual_options_clone = actual_options.clone();
-// let shutdown_flag_clone = shutdown_flag.clone();
-
-// Some(tokio::spawn(async move {
-// let _permit = semaphore_clone.acquire().await;
-// let filepath_str = path.to_str().unwrap_or_default().to_owned();
-
-// // Quick exit if shutdown signal is received.
-// if shutdown_flag_clone.load(Ordering::SeqCst) {
-// return;
-// }
-
-// // Check for file size stability
-// let mut last_size = 0;
-// let mut stable_count = 0;
-// while stable_count < file_stability_checks {
-// if !path.exists() {
-// eprintln!("File does not exist: {}", path.display());
-// break; // Exit the loop if the file does not exist
-// }
-// match std::fs::metadata(&path) {
-// Ok(metadata) => {
-// let current_size = metadata.len();
-// if last_size == current_size {
-// stable_count += 1;
-// } else {
-// last_size = current_size;
-// stable_count = 0;
-// }
-// },
-// Err(e) => {
-// eprintln!("Failed to get file metadata: {}", e);
-// break; // Exit the loop if any other error occurs
-// }
-// }
-// tokio::time::sleep(file_stability_timeout).await;
-// }
-
-// println!("File size stable: {}", filepath_str);
-
-// // Proceed with upload after confirming file stability
-// let mut attempts = 0;
-// // Retry loop with timeout
-// while attempts < 3 {
-// attempts += 1;
-// match timeout(upload_timeout, upload_file(Some(actual_options_clone.clone()), filepath_str.clone(), video_type.clone())).await {
-// Ok(Ok(_)) => {
-// // Upload succeeded
-// println!("Successful upload on attempt {}", attempts);
-// break; // Break out of the loop on success
-// }
-// Ok(Err(e)) => {
-// // Upload failed but did not timeout
-// eprintln!("Failed to upload (attempt {}): {}", attempts, e);
-// }
-// Err(_) => {
-// // Upload attempt timed out
-// eprintln!("Upload attempt timed out (attempt {})", attempts);
-// }
-// }
-// // Wait for retry_interval before retrying
-// tokio::time::sleep(retry_interval).await;
-// }
-// }))
-// } else {
-// None
-// }
-// })
-// .collect();
-
-// // Await all tasks concurrently.
-// let _ = futures::future::try_join_all(tasks).await;
-
-// Ok(())
-// } else {
-// Err("No recording options provided".to_string())
-// }
-// }
-
async fn take_screenshot(
ffmpeg_binary_path_str: String,
ffmpeg_screen_screenshot_args: Vec<String>,
+ screenshot_path: String,
+ options: Option<RecordingOptions>,
) -> Result<(), String> {
println!("Waiting for 3 seconds before taking the screenshot...");
tokio::time::sleep(Duration::from_secs(3)).await;
+ // Start the FFmpeg process for taking a screenshot
let mut screen_screenshot_child = tokio::process::Command::new(&ffmpeg_binary_path_str)
.args(&ffmpeg_screen_screenshot_args)
.stdout(Stdio::piped())
@@ -603,10 +429,21 @@ async fn take_screenshot(
.spawn()
.map_err(|e| e.to_string())?;
- let screen_screenshot_stdout = screen_screenshot_child.stdout.take().unwrap();
- let screen_screenshot_stderr = screen_screenshot_child.stderr.take().unwrap();
- tokio::spawn(log_output(screen_screenshot_stdout, "Screen screenshot stdout".to_string(), None, None));
- tokio::spawn(log_output(screen_screenshot_stderr, "Screen screenshot stderr".to_string(), None, None));
+ match screen_screenshot_child.wait().await {
+ Ok(status) if status.success() => {
+ println!("Screenshot captured: {}", &screenshot_path);
+ if let Some(ref opts) = options {
+ match upload_file(Some(opts.clone()), screenshot_path.clone(), "screenshot".to_string()).await {
+ Ok(_) => println!("Screenshot uploaded successfully."),
+ Err(e) => eprintln!("Failed to upload screenshot: {}", e),
+ }
+ } else {
+ eprintln!("No recording options set, skipping upload.");
+ }
+ },
+ Ok(_) => eprintln!("Screenshot command completed, but may have failed."),
+ Err(e) => eprintln!("Failed to execute screenshot command: {}", e),
+ }
Ok(())
}
@@ -657,7 +494,6 @@ async fn send_metadata_api(video_id: &str, server_url_base: &str) -> Result<(),
}
async fn graceful_stop_ffmpeg(mut stdin: tokio::process::ChildStdin) -> Result<(), std::io::Error> {
- // Sending 'q' followed by newline tells FFmpeg to quit gracefully
stdin.write_all(b"q\n").await?;
Ok(())
}
\ No newline at end of file
diff --git a/apps/desktop/src/app/page.tsx b/apps/desktop/src/app/page.tsx
index 83ddeb35b..324c6a859 100644
--- a/apps/desktop/src/app/page.tsx
+++ b/apps/desktop/src/app/page.tsx
@@ -38,9 +38,18 @@ export default function CameraPage() {
if (monitor && monitor.size) {
const x = 100;
- const y = monitor.size.height - windowHeight - 100;
+ const y = monitor.size.height * 0.66;
const scalingFactor = monitor.scaleFactor;
+ console.log("x", x);
+ console.log("y", y);
+ console.log("scalingFactor", scalingFactor);
+ console.log("monitor", monitor);
+ console.log("monitor.size", monitor.size);
+ console.log("monitor.size.height", monitor.size.height);
+ console.log("windowHeight", windowHeight);
+ console.log("windowWidth", windowWidth);
+
const existingCameraWindow = WebviewWindow.getByLabel("camera");
if (existingCameraWindow) {
console.log("Camera window already open.");
diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsx
index 99617d2f0..a84d59718 100644
--- a/apps/desktop/src/components/windows/inner/Recorder.tsx
+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx
@@ -28,7 +28,7 @@ export const Recorder = () => {
startingRecording,
setStartingRecording,
} = useMediaDevices();
- const [countdownActive, setCountdownActive] = useState(false);
+ // const [countdownActive, setCountdownActive] = useState(false);
const [stoppingRecording, setStoppingRecording] = useState(false);
const [currentStoppingMessage, setCurrentStoppingMessage] =
useState("Stopping Recording");
@@ -70,11 +70,11 @@ export const Recorder = () => {
});
};
- const handleOverlayFinished = () => {
- setIsRecording(true);
- setStartingRecording(false);
- setCountdownActive(false);
- };
+ // const handleOverlayFinished = () => {
+ // setIsRecording(true);
+ // setStartingRecording(false);
+ // // setCountdownActive(false);
+ // };
const prepareVideoData = async () => {
const res = await fetch(
@@ -113,10 +113,14 @@ export const Recorder = () => {
console.log("Starting dual recording...");
const mediaSettings = await getSelectedVideoProperties();
if (mediaSettings?.resolution && mediaSettings?.framerate) {
+ console.log("Setting recording as active...");
+ setIsRecording(true);
+ setStartingRecording(false);
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",
@@ -137,14 +141,14 @@ export const Recorder = () => {
console.log("Video data:", videoData);
if (videoData) {
setStartingRecording(true);
- setCountdownActive(true);
+ // setCountdownActive(true);
await startDualRecording(videoData);
} else {
throw new Error("Failed to prepare video data.");
}
} catch (error) {
console.error("Error starting recordings:", error);
- setCountdownActive(false);
+ // setCountdownActive(false);
}
};
@@ -168,14 +172,14 @@ export const Recorder = () => {
await openLinkInBrowser(url);
setIsRecording(false);
- setCountdownActive(false);
+ // setCountdownActive(false);
setStoppingRecording(false);
} catch (error) {
- console.error("Error invoking upload_file:", error);
+ console.error("Error stopping recording:", error);
}
setIsRecording(false);
- setCountdownActive(false);
+ // setCountdownActive(false);
setStoppingRecording(false);
};
@@ -222,12 +226,12 @@ export const Recorder = () => {
return (
<>
- {countdownActive && (
+ {/* {countdownActive && (
<Countdown
countdownFrom={3}
onCountdownFinish={handleOverlayFinished}
/>
- )}
+ )} */}
<div
data-tauri-drag-region
className="pt-4 relative flex items-center justify-center"
diff --git a/apps/desktop/src/utils/helpers.ts b/apps/desktop/src/utils/helpers.ts
index af44241d8..840a2e604 100644
--- a/apps/desktop/src/utils/helpers.ts
+++ b/apps/desktop/src/utils/helpers.ts
@@ -4,17 +4,14 @@ export const openLinkInBrowser = async (url: string) => {
let open:
| ((path: string, openWith?: string) => Promise<void>)
| ((arg0: string) => any);
- import("@tauri-apps/api/shell").then((shell) => {
- open = shell.open;
- });
+ const shellImport = await import("@tauri-apps/api/shell");
+ open = shellImport.open;
if (typeof window === "undefined") {
return;
}
- if (!open) {
- await open(url);
- }
+ await open(url);
return;
};
diff --git a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
index 12d0cf774..464fceea3 100644
--- a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
+++ b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
@@ -62,7 +62,6 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
}, []);
const getDevices = useCallback(async () => {
- console.log("getDevices called");
await enumerateAndStoreDevices();
try {
diff --git a/apps/desktop/src/utils/recording/utils.ts b/apps/desktop/src/utils/recording/utils.ts
index 7db971b15..bd92609d6 100644
--- a/apps/desktop/src/utils/recording/utils.ts
+++ b/apps/desktop/src/utils/recording/utils.ts
@@ -1,22 +1,26 @@
"use client";
+import { invoke } from "@tauri-apps/api/tauri";
+
export const enumerateAndStoreDevices = async () => {
if (typeof navigator !== "undefined" && typeof window !== "undefined") {
await navigator.mediaDevices.getUserMedia({
video: true,
- audio: true,
});
- const devices = await navigator.mediaDevices.enumerateDevices();
-
- const videoDevices = devices.filter(
- (device) => device.kind === "videoinput"
- );
- const audioDevices = devices.filter(
- (device) => device.kind === "audioinput"
- );
+ const video = await navigator.mediaDevices.enumerateDevices();
+ const audio: string[] = await invoke("enumerate_audio_devices");
+ const videoDevices = video.filter((device) => device.kind === "videoinput");
+ const audioDevices = audio.map((device) => {
+ return {
+ deviceId: device,
+ groupId: "",
+ kind: "audioinput",
+ label: device,
+ };
+ });
- window.localStorage.setItem("videoDevices", JSON.stringify(videoDevices));
window.localStorage.setItem("audioDevices", JSON.stringify(audioDevices));
+ window.localStorage.setItem("videoDevices", JSON.stringify(videoDevices));
}
};
diff --git a/apps/web/app/api/thumbnail/route.ts b/apps/web/app/api/thumbnail/route.ts
index d2a44a453..21598670c 100644
--- a/apps/web/app/api/thumbnail/route.ts
+++ b/apps/web/app/api/thumbnail/route.ts
@@ -4,6 +4,15 @@ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
export const revalidate = 3500;
+type FileKey = {
+ type: "screen";
+ key: string;
+};
+
+type ResponseObject = {
+ screen: string | null;
+};
+
export async function GET(request: NextRequest) {
const { searchParams } = request.nextUrl;
const userId = searchParams.get("userId");
@@ -31,21 +40,15 @@ export async function GET(request: NextRequest) {
});
const bucket = process.env.CAP_AWS_BUCKET;
- const fileKeys = [
+ const fileKeys: FileKey[] = [
{
- type: "screen" as "screen" | "video",
+ type: "screen",
key: `${userId}/${videoId}/screenshot/screen-capture.jpg`,
},
- {
- type: "video" as "screen" | "video",
- key: `${userId}/${videoId}/screenshot/video-capture.jpeg`,
- },
];
- // Initialize a response object
- const responseObject: { screen: string | null; video: string | null } = {
+ const responseObject: ResponseObject = {
screen: null,
- video: null,
};
await Promise.all(
@@ -59,8 +62,6 @@ export async function GET(request: NextRequest) {
responseObject[type] = url;
} catch (error) {
console.error("Error generating URL for:", key, error);
-
- // Set the response object to null if an error occurred
responseObject[type] = null;
}
})
diff --git a/apps/web/components/VideoThumbnail.tsx b/apps/web/components/VideoThumbnail.tsx
index ab8f1e6ad..0cc1b6784 100644
--- a/apps/web/components/VideoThumbnail.tsx
+++ b/apps/web/components/VideoThumbnail.tsx
@@ -13,7 +13,7 @@ export const VideoThumbnail = ({
videoId,
alt,
}: VideoThumbnailProps) => {
- const [imageUrls, setImageUrls] = useState({ screen: "", video: "" });
+ const [imageUrls, setImageUrls] = useState({ screen: "" });
const [loading, setLoading] = useState(true);
// Fetch the pre-signed URLs on component mount
@@ -25,7 +25,7 @@ export const VideoThumbnail = ({
);
if (response.ok) {
const data = await response.json();
- setImageUrls({ screen: data.screen, video: data.video });
+ setImageUrls({ screen: data.screen });
} else {
console.error("Failed to fetch pre-signed URLs");
}
@@ -44,18 +44,6 @@ export const VideoThumbnail = ({
loading ? "bg-gray-200" : "bg-black"
}`}
>
- {imageUrls.video && (
- <div className="absolute bottom-2 right-2 w-[50px] h-[50px] z-10 rounded-full overflow-hidden">
- <Image
- src={imageUrls.video}
- alt="Video Thumbnail"
- layout="fill"
- objectFit="cover"
- className="w-full h-full"
- onLoadingComplete={() => setLoading(false)}
- />
- </div>
- )}
{imageUrls.screen && (
<Image
src={imageUrls.screen}