Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Recording countdown. Better ffmpeg performance.
Richie McIlroya9f48fac150b
diff --git a/apps/desktop/src-tauri/src/recorder.rs b/apps/desktop/src-tauri/src/recorder.rsindex 6b7b57ba9..6fc9e3d34 100644--- a/apps/desktop/src-tauri/src/recorder.rs+++ b/apps/desktop/src-tauri/src/recorder.rs@@ -5,6 +5,7 @@ use std::thread;use std::time::{Duration, Instant};use std::path::{PathBuf, Path};use std::fs;+use std::fs::File;use std::sync::atomic::{AtomicBool, Ordering};use scrap::{Capturer, Display};@@ -40,18 +41,14 @@ impl ScreenRecorder {let should_stop = self.should_stop.clone();let ffmpeg_path = self.ffmpeg_path.clone();- println!("Starting recording from function");- println!("ffmpeg_path: {}", ffmpeg_path.to_str().unwrap());-+ // Ensure we have a primary display to capturelet display = Display::primary().map_err(|_| "Failed to find primary display".to_string())?;let (w, h) = (display.width(), display.height());let adjusted_height = h & !1;let capture_size = w * adjusted_height * BYTES_PER_PIXEL;let framerate = 30;- let frame_duration = Duration::from_secs_f64(1.0 / framerate as f64);-- println!("Display size: {}x{}", w, h);+ // Check current recording statelet mut state_guard = state.lock().map_err(|_| "Failed to acquire state lock".to_string())?;if *state_guard != RecordingState::Idle {return Err("Recording is already in progress".to_owned());@@ -59,110 +56,106 @@ impl ScreenRecorder {*state_guard = RecordingState::Recording;drop(state_guard);+ // Define paths for recordings and temp datalet recordings_dir = Path::new("recordings");fs::create_dir_all(&recordings_dir).map_err(|e| format!("Failed to create recordings directory: {}", e))?;+ let tmp_file_path = recordings_dir.join("temporary_capture.raw");+ let output_path = recordings_dir.join("recording.mp4").to_owned();- let output_path = recordings_dir.join("recording.mp4");- // Delete the existing recording file if it exists+ // Delete existing files if necessaryif output_path.exists() {fs::remove_file(&output_path).map_err(|e| format!("Failed to delete existing recording file: {}", e))?;}- let output_path_str = output_path.to_str().ok_or_else(|| "Failed to construct output file path string".to_string())?;-- println!("Output path: {}", output_path_str);- println!("Starting FFmpeg...");-- let mut command = Command::new(&self.ffmpeg_path)- .args(&[- "-f", "rawvideo",- "-pix_fmt", "bgra",- "-video_size", &format!("{}x{}", w, adjusted_height),- "-framerate", &framerate.to_string(),- "-i", "-",- "-c:v", "libx264",- "-preset", "veryfast",- "-crf", "18",- "-pix_fmt", "yuv420p",- "-y",- "-movflags", "+faststart",- output_path_str,- ])- .stdin(Stdio::piped())- .spawn()- .map_err(|e| format!("Failed to start FFmpeg: {}", e))?;-- let ffmpeg_stdin = command.stdin.take().ok_or_else(|| "Failed to take FFmpeg stdin".to_string())?;-- println!("FFmpeg started");-- let should_stop_clone = should_stop.clone();- let ffmpeg_handle = thread::spawn(move || {+ let output_path_str = output_path.to_str().ok_or_else(|| "Failed to construct output file path string".to_string())?.to_owned();++ // Spawn the recording thread+ let ffmpeg_handle = thread::spawn(move || {+ // Start the capture session and open the temporary filelet mut capturer = Capturer::new(display).expect("Failed to start capture");- let mut ffmpeg_stdin_guard = ffmpeg_stdin;+ let mut raw_file = File::create(&tmp_file_path)+ .map_err(|e| format!("Failed to create temporary raw file: {}", e))?;++ let frame_duration = Duration::from_secs_f64(1.0 / framerate as f64);loop {- let start_frame_time = Instant::now();- if should_stop_clone.load(Ordering::SeqCst) {- *state.lock().unwrap() = RecordingState::Stopping;+ // Start timing the frame capture+ let frame_start = Instant::now();++ // Stop the loop if the recording is set to be stopped+ if should_stop.load(Ordering::SeqCst) {break;- }+ }++ // Capture a frame, handling potential errorslet buffer = match capturer.frame() {Ok(buffer) => buffer,Err(error) if error.kind() == WouldBlock => {- thread::sleep(Duration::from_millis(1));+ // If capturing would block, wait a bit and retry+ thread::sleep(Duration::from_micros(100));continue;},Err(e) => return Err(format!("Error capturing frame: {}", e)),};-let stride = buffer[..capture_size].len() / adjusted_height;for row in 0..adjusted_height {let start = row * stride;let end = start + stride;- if let Err(e) = ffmpeg_stdin_guard.write_all(&buffer[start..end]) {- eprintln!("Failed to write to FFmpeg stdin: {:?}", e);+ if let Err(e) = raw_file.write_all(&buffer[start..end]) {+ eprintln!("Failed to write frame: {:?}", e);*state.lock().unwrap() = RecordingState::Stopping;break;}}- if let Err(e) = ffmpeg_stdin_guard.flush() {- eprintln!("Failed to flush FFmpeg stdin: {:?}", e);- *state.lock().unwrap() = RecordingState::Stopping;- }-- if let Some(time_to_sleep) = frame_duration.checked_sub(start_frame_time.elapsed()) {- thread::sleep(time_to_sleep);+ // Calculate the time to sleep to maintain the target framerate+ let elapsed_time = frame_start.elapsed();+ if let Some(remaining_sleep_duration) = frame_duration.checked_sub(elapsed_time) {+ thread::sleep(remaining_sleep_duration);}- };-- drop(ffmpeg_stdin_guard);- let output_status = command.wait_with_output();- match output_status {+ }+ // Close the temporary file to ensure all data is flushed+ drop(raw_file);++ // Start the encoding process using FFmpeg+ let status = Command::new(&ffmpeg_path)+ .args(&[+ "-f", "rawvideo",+ "-pix_fmt", "bgra",+ "-s", &format!("{}x{}", w, adjusted_height),+ "-r", &framerate.to_string(),+ "-i", tmp_file_path.to_str().unwrap(),+ "-c:v", "libx264",+ "-preset", "veryfast",+ "-crf", "15",+ "-pix_fmt", "yuv420p",+ "-y",+ "-movflags", "+faststart",+ &output_path_str,+ ])+ .output();++ // Handle the FFmpeg output+ match status {+ Ok(output) if output.status.success() => {+ // Encoding succeeded, remove the temporary file+ fs::remove_file(&tmp_file_path).map_err(|e| format!("Failed to remove temporary file: {}", e))?;+ Ok(())+ },Ok(output) => {- if !output.stderr.is_empty() {- eprintln!("FFmpeg stderr: {}", String::from_utf8_lossy(&output.stderr));- }- if output.status.success() {- println!("FFmpeg encoding completed successfully.");- Ok(())- } else {- let error_message = format!("FFmpeg exited with error, status: {:?}", output.status.code());- eprintln!("{}", &error_message);- Err(error_message)- }+ // Encoding failed - handle the error and FFmpeg's output accordingly+ let stderr = String::from_utf8_lossy(&output.stderr);+ Err(format!("FFmpeg failed with error: {}", stderr))},Err(e) => {- let error_message = format!("Failed to wait for FFmpeg child: {}", e);- eprintln!("{}", &error_message);- Err(error_message)- },+ // FFmpeg failed to start or some other error occurred while waiting for it to complete+ Err(format!("Failed to start encoding process: {}", e))+ }}});-+ // Save the handle to join later*self.ffmpeg_handle.lock().unwrap() = Some(ffmpeg_handle);Ok(())diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsxindex 391e20031..4ab0e59cc 100644--- a/apps/desktop/src/components/windows/inner/Recorder.tsx+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx@@ -113,7 +113,7 @@ export const Recorder = () => {>{countdownActive && (<Countdown- countdownFrom={3}+ countdownFrom={1}onCountdownFinish={handleOverlayFinished}/>)}