Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
end of recording timing fixes
PJ8fe07dfe16d4
diff --git a/Cargo.lock b/Cargo.lockindex 45e2f8a43..68984f6ea 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4357,7 +4357,7 @@ dependencies = [[[package]]name = "scap"version = "0.0.5"-source = "git+https://github.com/CapSoftware/scap?rev=1b7c70df754ee9c2c4e040266f45d16354367bd7#1b7c70df754ee9c2c4e040266f45d16354367bd7"+source = "git+https://github.com/CapSoftware/scap#69d2652c4cc3d44d3f7d3ef19a785044a878964a"dependencies = ["apple-sys-helmer-fork","cocoa 0.25.0",diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 306950153..43c461704 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -66,7 +66,7 @@ bytemuck = "1.14.3"num-traits = "0.2.19"indexmap = "2.2.6"regex = "1"-scap = { git = "https://github.com/CapSoftware/scap", rev = "1b7c70df754ee9c2c4e040266f45d16354367bd7" }+scap = { git = "https://github.com/CapSoftware/scap" }image = { version = "0.24.9", features = ["jpeg", "png", "webp"] }sentry = "0.32.2"fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }diff --git a/apps/desktop/src-tauri/src/app/commands.rs b/apps/desktop/src-tauri/src/app/commands.rsindex b57c0aba3..9304b6723 100644--- a/apps/desktop/src-tauri/src/app/commands.rs+++ b/apps/desktop/src-tauri/src/app/commands.rs@@ -6,7 +6,7 @@ macro_rules! generate_handler {#[cfg(debug_assertions)]tauri_specta::ts::export(specta::collect_types![$($command),*],- "../../src/utils/commands.ts"+ "../src/utils/commands.ts").unwrap();tauri::generate_handler![$($command),*]diff --git a/apps/desktop/src-tauri/src/media/audio.rs b/apps/desktop/src-tauri/src/media/audio.rsindex 7c41751e2..634178e9b 100644--- a/apps/desktop/src-tauri/src/media/audio.rs+++ b/apps/desktop/src-tauri/src/media/audio.rs@@ -3,6 +3,7 @@ use cpal::{Device, SampleFormat, SizedSample, Stream, SupportedStreamConfig};use indexmap::IndexMap;use num_traits::ToBytes;use std::{future::Future, path::PathBuf};+use tokio::sync::mpsc::error::TrySendError;use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc};use super::{Instant, SharedFlag, SharedInstant};@@ -94,12 +95,13 @@ impl AudioCapturer {let mut pipe = File::create(destination).await.unwrap();while let Some(bytes) = receiver.recv().await {- if should_stop.get() {- break;- }pipe.write_all(&bytes).await.expect("Failed to write audio data to FFmpeg stdin");++ if should_stop.get() {+ receiver.close();+ }}}}@@ -107,7 +109,7 @@ impl AudioCapturer {pub fn stop(&mut self) -> Result<(), String> {if let Some(ref mut stream) = self.stream {stream.pause().map_err(|_| "Failed to pause stream")?;- tracing::info!("Audio recording paused.");+ tracing::info!("Audio capturing stopped.");Ok(())} else {return Err("Original recording was not started".to_string());@@ -167,15 +169,22 @@ impl AudioCapturer {dest.copy_from_slice(source.to_le_bytes().as_ref());}- if sender.try_send(bytes).is_err() {- tracing::warn!("Audio channel send error. Dropping data.");- }-- if let Ok(ref mut start_time_option) = first_frame_time_guard {- if start_time_option.is_none() {- **start_time_option = Some(Instant::now());+ match sender.try_send(bytes) {+ Ok(_) => {+ if let Ok(ref mut start_time_option) = first_frame_time_guard {+ if start_time_option.is_none() {+ **start_time_option = Some(Instant::now());- tracing::trace!("Audio start time captured");+ tracing::trace!("Audio start time captured");+ }+ }+ }+ Err(TrySendError::Full(_)) => {+ // TODO: Consider panicking? This should *never* happen+ tracing::error!("Channel buffer is full!");+ }+ _ => {+ tracing::info!("Recording has been stopped. Dropping data.")}}},diff --git a/apps/desktop/src-tauri/src/media/mod.rs b/apps/desktop/src-tauri/src/media/mod.rsindex 21c6d2dda..f36a1f2f5 100644--- a/apps/desktop/src-tauri/src/media/mod.rs+++ b/apps/desktop/src-tauri/src/media/mod.rs@@ -10,6 +10,7 @@ use std::{use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};use tokio::process::{Child, ChildStdin, Command};use tokio::sync::Mutex;+use tokio::task::JoinHandle;use crate::{recording::RecordingOptions,@@ -63,6 +64,8 @@ pub struct MediaRecorder {start_time: Option<Instant>,audio_file_path: Option<PathBuf>,video_file_path: Option<PathBuf>,+ audio_pipe_task: Option<JoinHandle<()>>,+ video_pipe_task: Option<JoinHandle<()>>,}impl MediaRecorder {@@ -81,6 +84,10 @@ impl MediaRecorder {max_screen_width: usize,max_screen_height: usize,) -> Result<(), String> {+ if !scap::has_permission() {+ scap::request_permission();+ }+let options_clone = options.clone();self.options = Some(options);@@ -208,10 +215,10 @@ impl MediaRecorder {if self.audio_enabled {let capturer = self.audio_capturer.as_mut().unwrap();- tokio::spawn(capturer.collect_samples(audio_pipe_path));+ self.audio_pipe_task = Some(tokio::spawn(capturer.collect_samples(audio_pipe_path)));}- tokio::spawn(video_capturer.collect_frames(video_pipe_path));+ self.video_pipe_task = Some(tokio::spawn(video_capturer.collect_frames(video_pipe_path)));self.start_time = Some(Instant::now());self.audio_file_path = Some(audio_chunks_dir.to_path_buf());@@ -224,49 +231,32 @@ impl MediaRecorder {Ok(())}+ /// The order of operations in this function is important!! Letting the tasks+ /// that pipe collected audio/video into FFmpeg gracefully shut down first allows+ /// us to close the ffmpeg process (and kill the cpal stream) with impunity.#[tracing::instrument(skip(self))]pub async fn stop_media_recording(&mut self) -> Result<(), String> {- if let Some(start_time) = self.start_time {- let segment_duration = Duration::from_secs(3);- let recording_duration = start_time.elapsed();- let expected_segments = recording_duration.as_secs() / segment_duration.as_secs();- let expected_audio_segments = match self.audio_enabled {- true => expected_segments,- false => 0,- };- let audio_file_path = self- .audio_file_path- .as_ref()- .ok_or("Audio file path not set")?;- let video_file_path = self- .video_file_path- .as_ref()- .ok_or("Video file path not set")?;- let audio_segment_list_filename = audio_file_path.join("segment_list.txt");- let video_segment_list_filename = video_file_path.join("segment_list.txt");-- loop {- let audio_segments =- std::fs::read_to_string(&audio_segment_list_filename).unwrap_or_default();- let video_segments =- std::fs::read_to_string(&video_segment_list_filename).unwrap_or_default();-- let audio_segment_count = audio_segments.lines().count();- let video_segment_count = video_segments.lines().count();-- if audio_segment_count >= (expected_audio_segments as usize)- && video_segment_count >= (expected_segments as usize)- {- tracing::info!("All segments generated");- break;- }+ self.should_stop.set(true);++ if self.audio_enabled {+ if let Some(ref mut audio_task) = self.audio_pipe_task {+ audio_task.await.map_err(|error| error.to_string())?;+ tracing::info!("Audio recording stopped");+ }- tokio::time::sleep(Duration::from_millis(300)).await;+ if let Some(ref mut audio_capturer) = self.audio_capturer {+ audio_capturer.stop()?;}}+ if let Some(ref mut video_task) = self.video_pipe_task {+ video_task.await.map_err(|error| error.to_string())?;+ tracing::info!("Video capturing stopped");+ }+if let Some(ref ffmpeg_stdin) = self.ffmpeg_stdin {let mut stdin_guard = ffmpeg_stdin.lock().await;+ tracing::debug!("Shutting down recording");if let Some(mut stdin) = stdin_guard.take() {if let Err(e) = stdin.write_all(b"q\n").await {tracing::error!("Failed to send 'q' to video FFmpeg process: {}", e);@@ -275,17 +265,11 @@ impl MediaRecorder {}}- self.should_stop.set(true);-- if let Some(ref mut audio_capturer) = self.audio_capturer {- audio_capturer.stop()?;- }-if let Some(process) = &mut self.ffmpeg_process {let _ = process.kill().await.map_err(|e| e.to_string());}- tracing::info!("Audio recording stopped.");+ tracing::info!("All recording stopped.");Ok(())}diff --git a/apps/desktop/src-tauri/src/media/video.rs b/apps/desktop/src-tauri/src/media/video.rsindex 441959f97..a592ed843 100644--- a/apps/desktop/src-tauri/src/media/video.rs+++ b/apps/desktop/src-tauri/src/media/video.rs@@ -9,6 +9,7 @@ use std::{path::{Path, PathBuf},time::Duration,};+use tokio::sync::mpsc::error::TrySendError;use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc};use super::{Instant, RecordingOptions, SharedFlag, SharedInstant};@@ -26,7 +27,7 @@ pub struct VideoCapturer {impl VideoCapturer {pub fn new(_width: usize, _height: usize, should_stop: SharedFlag) -> VideoCapturer {let mut capturer = Capturer::new(Options {- fps: 30,+ fps: 60,target: None,show_cursor: true,show_highlight: true,@@ -72,7 +73,7 @@ impl VideoCapturer {capturer.start_capture();- while !should_stop.get() {+ loop {let screenshot_path = screenshot_file_path.clone();let options_clone = recording_options.clone();@@ -138,17 +139,25 @@ impl VideoCapturer {});}- if sender.try_send(frame.data).is_err() {- tracing::warn!("Video channel send error. Dropping data.");- }-- let mut first_frame_time_guard = start_time.try_lock();+ match sender.try_send(frame.data) {+ Ok(_) => {+ let mut first_frame_time_guard = start_time.try_lock();- if let Ok(ref mut start_time_option) = first_frame_time_guard {- if start_time_option.is_none() {- **start_time_option = Some(Instant::now());+ if let Ok(ref mut start_time_option) = first_frame_time_guard {+ if start_time_option.is_none() {+ **start_time_option = Some(Instant::now());- tracing::trace!("Video start time captured");+ tracing::trace!("Video start time captured");+ }+ }+ }+ Err(TrySendError::Full(_)) => {+ // TODO: Consider panicking? This should *never* happen+ tracing::error!("Channel buffer is full!");+ }+ _ => {+ tracing::info!("Recording has been stopped. Dropping data.");+ break;}}}@@ -174,12 +183,13 @@ impl VideoCapturer {let mut pipe = File::create(destination).await.unwrap();while let Some(bytes) = receiver.recv().await {- if should_stop.get() {- break;- }pipe.write_all(&bytes).await.expect("Failed to write video data to FFmpeg stdin");++ if should_stop.get() {+ receiver.close();+ }}}}diff --git a/apps/src/utils/commands.ts b/apps/src/utils/commands.tsdeleted file mode 100644index 8ef1f19a6..000000000--- a/apps/src/utils/commands.ts+++ /dev/null@@ -1,57 +0,0 @@-/* eslint-disable */-// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.--declare global {- interface Window {- __TAURI_INVOKE__<T>(cmd: string, args?: Record<string, unknown>): Promise<T>;- }-}--// Function avoids 'window not defined' in SSR-const invoke = () => window.__TAURI_INVOKE__;--export function startDualRecording(options: RecordingOptions) {- return invoke()<null>("start_dual_recording", { options })-}--export function stopAllRecordings() {- return invoke()<null>("stop_all_recordings")-}--export function enumerateAudioDevices() {- return invoke()<string[]>("enumerate_audio_devices")-}--export function startServer() {- return invoke()<number>("start_server")-}--export function openScreenCapturePreferences() {- return invoke()<null>("open_screen_capture_preferences")-}--export function openMicPreferences() {- return invoke()<null>("open_mic_preferences")-}--export function openCameraPreferences() {- return invoke()<null>("open_camera_preferences")-}--export function hasScreenCaptureAccess() {- return invoke()<boolean>("has_screen_capture_access")-}--export function resetScreenPermissions() {- return invoke()<null>("reset_screen_permissions")-}--export function resetMicrophonePermissions() {- return invoke()<null>("reset_microphone_permissions")-}--export function resetCameraPermissions() {- return invoke()<null>("reset_camera_permissions")-}--export type RecordingOptions = { user_id: string; video_id: string; screen_index: string; video_index: string; audio_name: string; aws_region: string; aws_bucket: string }