Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

cleanup

Brendan Allan2deae8e004f9
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 007608cac..da239710d 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -35,10 +35,9 @@ use ffmpeg_sidecar::{
use winit::monitor::{MonitorHandle, VideoMode};
-
-fn main() {
+fn main() {
let _ = fix_path_env::fix();
-
+
std::panic::set_hook(Box::new(|info| {
eprintln!("Thread panicked: {:?}", info);
}));
@@ -73,7 +72,7 @@ fn main() {
handle_ffmpeg_installation().expect("Failed to install FFmpeg");
- #[command]
+ #[tauri::command]
async fn start_server(window: Window) -> Result<u16, String> {
start(move |url| {
let _ = window.emit("redirect_uri", url);
@@ -147,10 +146,14 @@ fn main() {
}));
let event_loop = winit::event_loop::EventLoop::new().expect("Failed to create event loop");
- let monitor: MonitorHandle = event_loop.primary_monitor().expect("No primary monitor found");
+ let monitor: MonitorHandle = event_loop
+ .primary_monitor()
+ .expect("No primary monitor found");
let video_modes: Vec<VideoMode> = monitor.video_modes().collect();
- let max_mode = video_modes.iter().max_by_key(|mode| mode.size().width * mode.size().height);
+ let max_mode = video_modes
+ .iter()
+ .max_by_key(|mode| mode.size().width * mode.size().height);
let (max_width, max_height) = if let Some(max_mode) = max_mode {
println!("Maximum resolution: {:?}", max_mode.size());
@@ -162,10 +165,10 @@ fn main() {
#[derive(serde::Deserialize, PartialEq)]
enum DeviceKind {
- #[serde(alias="videoinput")]
+ #[serde(alias = "videoinput")]
Video,
- #[serde(alias="audioinput")]
- Audio
+ #[serde(alias = "audioinput")]
+ Audio,
}
#[derive(serde::Deserialize)]
@@ -173,7 +176,7 @@ fn main() {
struct MediaDevice {
id: String,
kind: DeviceKind,
- label: String
+ label: String,
}
fn create_tray_menu(submenus: Option<Vec<SystemTraySubmenu>>) -> SystemTrayMenu {
@@ -191,7 +194,10 @@ fn main() {
.add_item(CustomMenuItem::new("quit".to_string(), "Quit").accelerator("CmdOrControl+Q"))
}
- let tray = SystemTray::new().with_menu(create_tray_menu(None)).with_menu_on_left_click(false).with_title("Cap");
+ let tray = SystemTray::new()
+ .with_menu(create_tray_menu(None))
+ .with_menu_on_left_click(false)
+ .with_title("Cap");
tauri::Builder::default()
.plugin(tauri_plugin_oauth::init())
@@ -199,14 +205,14 @@ fn main() {
.setup(move |app| {
let handle = app.handle();
- if let Some(options_window) = app.get_window("main") {
+ if let Some(options_window) = app.get_window("main") {
let _ = options_window.move_window(Position::Center);
#[cfg(target_os = "macos")]
apply_vibrancy(&options_window, NSVisualEffectMaterial::MediumLight, None, Some(16.0)).expect("Unsupported platform! 'apply_vibrancy' is only supported on macOS");
#[cfg(target_os = "windows")]
apply_blur(&options_window, Some((255, 255, 255, 255))).expect("Unsupported platform! 'apply_blur' is only supported on Windows");
-
+
set_shadow(&options_window, true).expect("Unsupported platform!");
}
@@ -250,7 +256,7 @@ fn main() {
}
}
});
-
+
let tray_handle = app.tray_handle();
app.listen_global("media-devices-set", move|event| {
#[derive(serde::Deserialize)]
@@ -266,7 +272,7 @@ fn main() {
let id_prefix = if kind == DeviceKind::Video {
"video"
} else {
- "audio"
+ "audio"
};
let mut none_item = CustomMenuItem::new(format!("in_{}_none", id_prefix), "None");
if selected_device.is_none() {
@@ -278,13 +284,13 @@ fn main() {
.filter(|device| device.kind == kind)
.fold(initial, |tray_items, device| {
let mut menu_item = CustomMenuItem::new(format!("in_{}_{}", id_prefix, device.id), &device.label);
-
+
if let Some(selected) = selected_device {
if selected.label == device.label {
menu_item = menu_item.selected();
}
}
-
+
tray_items.add_item(menu_item)
})
}
@@ -349,7 +355,7 @@ fn main() {
let kind = if item_id.contains("video") { "videoinput" } else { "audioinput" };
app.emit_all("tray-set-device-id", SetDevicePayload {
- device_type: kind.to_string(),
+ device_type: kind.to_string(),
id: if device_id == "none" { None } else { Some(device_id) }
}).expect("Failed to emit tray set media device event to windows");
}
diff --git a/apps/desktop/src-tauri/src/media.rs b/apps/desktop/src-tauri/src/media.rs
index af1371df9..e837bd56f 100644
--- a/apps/desktop/src-tauri/src/media.rs
+++ b/apps/desktop/src-tauri/src/media.rs
@@ -479,36 +479,51 @@ impl MediaRecorder {
std::fs::remove_file(&audio_pipe_path).ok();
create_named_pipe(&audio_pipe_path).map_err(|e| e.to_string())?;
+ let time_offset = if needs_audio {
+ println!("Adjusting FFmpeg commands based on start times...");
+ create_time_offset_args(&audio_start_time, &video_start_time).await
+ } else {
+ None
+ };
+
let size = format!("{}x{}", adjusted_width, adjusted_height);
- let mut ffmpeg_command = vec![
+ let mut ffmpeg_command = flatten_str_args([
["-f", "rawvideo"],
["-pix_fmt", "bgra"],
["-s", &size],
["-r", "30"],
["-thread_queue_size", "4096"],
["-i", &video_pipe_path],
- ];
+ ]);
- if needs_audio {
- ffmpeg_command.extend([
- // in
- ["-f", sample_format],
- ["-ar", &sample_rate_str],
- ["-ac", &channels_str],
- ["-thread_queue_size", "4096"],
- ["-i", &audio_pipe_path],
- // out
- [
- "-af",
- "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
- ],
- ["-c:a", "aac"],
- ["-b:a", "128k"],
- ["-async", "1"],
- ]);
+ let mut audio_args = flatten_str_args([
+ // in
+ ["-f", sample_format],
+ ["-ar", &sample_rate_str],
+ ["-ac", &channels_str],
+ ["-thread_queue_size", "4096"],
+ ["-i", &audio_pipe_path],
+ // out
+ [
+ "-af",
+ "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
+ ],
+ ["-c:a", "aac"],
+ ["-b:a", "128k"],
+ ["-async", "1"],
+ ]);
+
+ match time_offset {
+ Some((TimeOffsetTarget::Video, args)) => ffmpeg_command.splice(0..0, args.clone()),
+ Some((TimeOffsetTarget::Audio, args)) => audio_args.splice(0..0, args.clone()),
+ None => {}
};
- ffmpeg_command.extend([
+ if needs_audio {
+ ffmpeg_command.extend(audio_args);
+ }
+
+ ffmpeg_command.extend(flatten_str_args([
["-vf", "fps=30,scale=in_range=full:out_range=limited"],
["-c:v", "libx264"],
["-preset", "ultrafast"],
@@ -523,24 +538,9 @@ impl MediaRecorder {
["-segment_format", "ts"],
["-movflags", "frag_keyframe+empty_moov"],
["-reset_timestamps", "1"],
- ]);
+ ]));
- let mut ffmpeg_command = ffmpeg_command
- .into_iter()
- .flatten()
- .map(|s| s.to_string())
- .chain([output_chunk_pattern])
- .collect();
-
- if needs_audio {
- println!("Adjusting FFmpeg commands based on start times...");
- adjust_ffmpeg_commands_based_on_start_times(
- Arc::clone(&audio_start_time),
- Arc::clone(&video_start_time),
- &mut ffmpeg_command,
- )
- .await;
- }
+ ffmpeg_command.push(output_chunk_pattern);
println!("Starting FFmpeg process...");
@@ -550,8 +550,8 @@ impl MediaRecorder {
.map_err(|e| e.to_string())?;
println!("Ffmpeg process started");
- if let Some(ffmpeg_stdin) = &self.ffmpeg_stdin {
- let mut stdin_lock = ffmpeg_stdin.lock().await;
+ if let Some(ffmpeg_stdin_mutex) = &self.ffmpeg_stdin {
+ let mut stdin_lock = ffmpeg_stdin_mutex.lock().await;
*stdin_lock = Some(ffmpeg_stdin);
drop(stdin_lock);
println!("Ffmpeg stdin set");
@@ -749,8 +749,8 @@ async fn start_recording_process(
}
async fn wait_for_start_times(
- audio_start_time: Arc<Mutex<Option<Instant>>>,
- video_start_time: Arc<Mutex<Option<Instant>>>,
+ audio_start_time: &Mutex<Option<Instant>>,
+ video_start_time: &Mutex<Option<Instant>>,
) -> (Instant, Instant) {
loop {
let audio_start_locked = audio_start_time.lock().await;
@@ -767,11 +767,15 @@ async fn wait_for_start_times(
}
}
-async fn adjust_ffmpeg_commands_based_on_start_times(
- audio_start_time: Arc<Mutex<Option<Instant>>>,
- video_start_time: Arc<Mutex<Option<Instant>>>,
- ffmpeg_video_command: &mut Vec<String>,
-) {
+pub enum TimeOffsetTarget {
+ Audio,
+ Video,
+}
+
+async fn create_time_offset_args(
+ audio_start_time: &Mutex<Option<Instant>>,
+ video_start_time: &Mutex<Option<Instant>>,
+) -> Option<(TimeOffsetTarget, Vec<String>)> {
let (audio_start, video_start) = wait_for_start_times(audio_start_time, video_start_time).await;
let duration_difference = if audio_start > video_start {
audio_start.duration_since(video_start)
@@ -790,17 +794,25 @@ async fn adjust_ffmpeg_commands_based_on_start_times(
// Depending on which started first, adjust the relevant FFmpeg command
if audio_start > video_start {
// Offset the video start time
- ffmpeg_video_command.splice(
- 0..0,
- vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],
- );
println!("Applying -itsoffset {:.3} to video", offset_seconds);
+
+ Some((
+ TimeOffsetTarget::Video,
+ vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],
+ ))
} else if video_start > audio_start {
// Offset the audio start time
- // ffmpeg_audio_command.splice(
- // 0..0,
- // vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],
- // );
println!("Applying -itsoffset {:.3} to audio", offset_seconds);
+
+ Some((
+ TimeOffsetTarget::Audio,
+ vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],
+ ))
+ } else {
+ None
}
}
+
+fn flatten_str_args<'a>(args: impl IntoIterator<Item = [&'a str; 2]>) -> Vec<String> {
+ args.into_iter().flatten().map(|s| s.to_string()).collect()
+}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 2cd3b7885..37fd38a00 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -123,14 +123,13 @@ pub async fn start_dual_recording(
}
#[tauri::command]
-#[specta::specta]
pub async fn stop_all_recordings(
state: State<'_, Arc<Mutex<RecordingState>>>,
) -> Result<(), String> {
let mut guard = state.lock().await;
-
+
println!("Stopping media recording...");
-
+
guard.shutdown_flag.store(true, Ordering::SeqCst);
if let Some(mut media_process) = guard.media_process.take() {
@@ -152,7 +151,7 @@ pub async fn stop_all_recordings(
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
-
+
println!("All recordings and uploads stopped.");
Ok(())
@@ -227,7 +226,7 @@ async fn start_upload_loop(
if !upload_tasks.is_empty() {
let _ = join_all(upload_tasks).await;
}
-
+
tokio::time::sleep(Duration::from_millis(50)).await;
}
uploading_finished.store(true, Ordering::SeqCst);