Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Working recorder
Richie McIlroya3e51802f730
diff --git a/apps/desktop/src-tauri/.gitignore b/apps/desktop/src-tauri/.gitignoreindex f4dfb82b2..055c11391 100644--- a/apps/desktop/src-tauri/.gitignore+++ b/apps/desktop/src-tauri/.gitignore@@ -1,4 +1,4 @@# Generated by Cargo# will have compiled files and executables/target/-+/recordings/*\ No newline at end of filediff --git a/apps/desktop/src-tauri/.taurignore b/apps/desktop/src-tauri/.taurignoreindex d14744a2b..9c5bb8e26 100644--- a/apps/desktop/src-tauri/.taurignore+++ b/apps/desktop/src-tauri/.taurignore@@ -1,2 +1,4 @@+/recordings+/recordings/*/frames/frames/*\ No newline at end of filediff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lockindex 77374b020..6b0cf8fba 100644--- a/apps/desktop/src-tauri/Cargo.lock+++ b/apps/desktop/src-tauri/Cargo.lock@@ -2,20 +2,6 @@# It is not intended for manual editing.version = 3-[[package]]-name = "Cap"-version = "0.0.0"-dependencies = [- "image",- "scrap",- "serde",- "serde_json",- "tauri",- "tauri-build",- "tauri-plugin-context-menu",- "tauri-plugin-positioner",-]-[[package]]name = "addr2line"version = "0.21.0"@@ -429,6 +415,22 @@ dependencies = ["system-deps 6.1.2",]+[[package]]+name = "cap"+version = "0.0.0"+dependencies = [+ "ffmpeg-sidecar",+ "image",+ "scrap",+ "serde",+ "serde_json",+ "tauri",+ "tauri-build",+ "tauri-plugin-context-menu",+ "tauri-plugin-positioner",+ "which",+]+[[package]]name = "cargo_toml"version = "0.15.3"@@ -979,6 +981,12 @@ dependencies = ["simd-adler32",]+[[package]]+name = "ffmpeg-sidecar"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5b56b7872b0cbc828e83043a82268b111e3648dab25f29079fce448648e572a"+[[package]]name = "field-offset"version = "0.3.6"@@ -1530,6 +1538,15 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "home"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb"+dependencies = [+ "windows-sys 0.48.0",+]+[[package]]name = "html5ever"version = "0.25.2"@@ -4519,6 +4536,18 @@ version = "0.1.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9193164d4de03a926d909d3bc7c30543cecb35400c02114792c2cae20d5e2dbb"+[[package]]+name = "which"+version = "4.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7"+dependencies = [+ "either",+ "home",+ "once_cell",+ "rustix 0.38.20",+]+[[package]]name = "winapi"version = "0.2.8"diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 99d99614f..c649624d4 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -1,7 +1,7 @@[package]-name = "Cap"+name = "cap"version = "0.0.0"-description = "A Tauri App"+description = "Beautiful, shareable screen recordings. Open-source and privacy-friendly."authors = ["you"]license = ""repository = ""@@ -20,6 +20,8 @@ tauri-plugin-context-menu = "0.5.0"tauri-plugin-positioner = { version = "1.0", features = ["system-tray"] }scrap = "0.5.0"image = "0.24.7"+ffmpeg-sidecar = "0.5.1"+which = "4.2.2"[features]# this feature is used for production builds or when `devPath` points to the filesystemdiff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex c274335ed..67ca0c223 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -1,81 +1,96 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]-extern crate scrap;--use scrap::{Capturer, Display};-use std::io::ErrorKind::WouldBlock;-use std::thread;-use std::time::Duration;-use std::path::Path;-use std::fs;-use tauri::Manager;-use image::{ImageBuffer, RgbaImage, Pixel, Rgba};--// Define a command that can be invoked from the frontend+use std::sync::{Arc, Mutex};+use tauri::{Manager, Window};++use ffmpeg_sidecar::{+ command::ffmpeg_is_installed,+ download::{check_latest_version, download_ffmpeg_package, ffmpeg_download_url, unpack_ffmpeg},+ error::Result as FfmpegResult,+ paths::sidecar_dir,+ version::ffmpeg_version,+};++mod recorder;+use recorder::ScreenRecorder;+#[tauri::command]-fn take_screenshot() -> Result<(), String> {- let frames_dir = Path::new("frames");- if let Err(e) = fs::create_dir_all(&frames_dir) {- return Err(format!("Failed to create frames directory: {}", e));- }+fn start_video_recording(window: Window, recorder: tauri::State<'_, Arc<Mutex<ScreenRecorder>>>) {+ let window = window.clone();+ // Clone the Arc before moving it into the thread, which will then have a 'static lifetime.+ let recorder = recorder.inner().clone();+ std::thread::spawn(move || {+ let recorder = recorder.lock().expect("Failed to lock recorder.");+ if let Err(e) = recorder.start_recording() {+ window.emit("recording-error", &e.to_string()).expect("Failed to send recording-error event.");+ }+ });+}+++#[tauri::command]+fn stop_video_recording(recorder: tauri::State<'_, Arc<Mutex<ScreenRecorder>>>) {+ let recorder = recorder.lock().expect("Failed to lock recorder."); // Removed 'mut' keyword+ recorder.stop_recording();+}- let one_frame = Duration::from_nanos(16666667); // Approx. 1/60 second+fn main() {+ std::panic::set_hook(Box::new(|info| {+ eprintln!("Thread panicked: {:?}", info);+ }));- let display = Display::primary().map_err(|e| format!("Couldn't find primary display: {}", e))?;- let mut capturer = Capturer::new(display).map_err(|e| format!("Couldn't begin capture: {}", e))?;- let (w, h) = (capturer.width(), capturer.height());+ if which::which("ffmpeg").is_err() {+ if let Err(e) = handle_ffmpeg_installation() {+ eprintln!("Failed to handle FFmpeg installation: {}", e);+ }+ }- // Log width and height- println!("Width: {}, Height: {}", w, h);+ fn handle_ffmpeg_installation() -> FfmpegResult<()> {+ if ffmpeg_is_installed() {+ println!("FFmpeg is already installed! π");+ return Ok(());+ }- // Attempt to capture a frame, retrying if needed- let buffer = loop {- match capturer.frame() {- Ok(buffer) => break buffer,- Err(error) if error.kind() == WouldBlock => {- thread::sleep(one_frame);- continue;- },- Err(e) => return Err(format!("Error capturing frame: {}", e)),+ match check_latest_version() {+ Ok(version) => println!("Latest available version: {}", version),+ Err(_) => println!("Skipping version check on this platform."),}- };- println!("Captured! Processing...");+ let download_url = ffmpeg_download_url()?;+ let destination = sidecar_dir()?;- // Convert BGRA to RGBA- let mut rgba_buffer = Vec::with_capacity(buffer.len());- for chunk in buffer.chunks_exact(4) {- let bgra = [chunk[0], chunk[1], chunk[2], chunk[3]];- let rgba = Rgba::from_channels(bgra[2], bgra[1], bgra[0], bgra[3]);- rgba_buffer.extend_from_slice(&rgba.0);- }+ println!("Downloading from: {:?}", download_url);+ let archive_path = download_ffmpeg_package(download_url, &destination)?;+ println!("Downloaded package: {:?}", archive_path);- // Attempt to create an RgbaImage from the converted buffer.- let image: RgbaImage = ImageBuffer::from_vec(w as u32, h as u32, rgba_buffer)- .ok_or_else(|| "Creating the image buffer failed".to_string())?;-- let scaled_width = (w as f32 * 0.5) as u32; // Reducing width to 50%- let scaled_height = (h as f32 * 0.5) as u32; // Reducing height to 50%- let resized_image = image::imageops::resize(- &image,- scaled_width,- scaled_height,- image::imageops::FilterType::Lanczos3, // High-quality filter- );-- // Save the image- let image_path = frames_dir.join("screenshot.png");- resized_image.save(&image_path)- .map_err(|e| format!("Failed to save screenshot: {}", e))?;-- println!("Image saved as `screenshot.png`.");- Ok(())-}+ println!("Extracting...");+ unpack_ffmpeg(&archive_path, &destination)?;++ let version = ffmpeg_version()?;+ println!("FFmpeg version: {}", version);++ println!("Done! π");+ Ok(())+ }-fn main() {tauri::Builder::default()- .plugin(tauri_plugin_context_menu::init()) // Ensure you have this plugin in your dependencies- .invoke_handler(tauri::generate_handler![take_screenshot])+ .setup(|app| {+ // Fetch the full path to the FFmpeg binary+ let ffmpeg_binary_path = sidecar_dir()?.join(if cfg!(target_os = "windows") { "ffmpeg.exe" } else { "ffmpeg" });++ // Create an instance of ScreenRecorder with the ffmpeg_binary_path+ let recorder = ScreenRecorder::new(+ ffmpeg_binary_path,+ );++ let shared_recorder = Arc::new(Mutex::new(recorder));+ app.manage(shared_recorder);+ Ok(())+ })+ .invoke_handler(tauri::generate_handler![+ start_video_recording,+ stop_video_recording+ ]).run(tauri::generate_context!())- .expect("Failed to run Tauri application");+ .expect("Error while running tauri application");}\ No newline at end of filediff --git a/apps/desktop/src-tauri/src/recorder.rs b/apps/desktop/src-tauri/src/recorder.rsnew file mode 100644index 000000000..fe10d8eb4--- /dev/null+++ b/apps/desktop/src-tauri/src/recorder.rs@@ -0,0 +1,219 @@+use std::io::{ErrorKind::WouldBlock, Write};+use std::process::{Command, Stdio};+use std::sync::{Arc, Mutex};+use std::thread;+use std::time::{Duration, Instant};+use std::path::{PathBuf, Path};+use std::fs;+use std::sync::atomic::{AtomicBool, Ordering};+use std::fs::File;+use scrap::{Capturer, Display};+use image::{ImageBuffer, RgbaImage, Pixel, Rgba};++#[derive(Clone, PartialEq)]+pub enum RecordingState {+ Idle,+ Recording,+ Stopping,+}++pub struct ScreenRecorder {+ state: Arc<Mutex<RecordingState>>,+ ffmpeg_handle: Mutex<Option<thread::JoinHandle<Result<(), String>>>>,+ ffmpeg_path: PathBuf,+ should_stop: Arc<AtomicBool>,+}++const BYTES_PER_PIXEL: usize = 4;++fn save_frame_to_file(frame: &[u8], output_file_path: PathBuf) -> Result<(), std::io::Error> {+ let mut output_file = File::create(output_file_path)?;+ output_file.write_all(frame)?;+ Ok(())+}++impl ScreenRecorder {++ pub fn new(ffmpeg_path: PathBuf) -> Self {+ Self {+ state: Arc::new(Mutex::new(RecordingState::Idle)),+ ffmpeg_handle: Mutex::new(None),+ ffmpeg_path,+ should_stop: Arc::new(AtomicBool::new(false)),+ }+ }++ pub fn start_recording(&self) -> Result<(), String> {+ let state = self.state.clone();+ 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());++ let 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 = 60;+ let frame_duration = Duration::from_secs_f64(1.0 / framerate as f64);+ let mut last_frame_time = Instant::now();+ let one_frame_duration = Duration::from_secs_f64(1.0 / framerate as f64);++ println!("Display size: {}x{}", w, h);++ let 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());+ }+ *state_guard = RecordingState::Recording;+ drop(state_guard); // Drop the lock as soon as it's no longer needed.++ let recordings_dir = Path::new("recordings");+ fs::create_dir_all(&recordings_dir).map_err(|e| format!("Failed to create recordings directory: {}", e))?;++ let output_path = recordings_dir.join("recording.mp4");+ 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", // Input format+ "-pix_fmt", "bgra", // Input pixel format+ "-video_size", &format!("{}x{}", w, adjusted_height), // Input video size+ "-framerate", &framerate.to_string(), // Input frame rate+ "-i", "-", // Input from stdin (use `pipe:0` if `-` does not work)+ "-c:v", "libx264", // Video codec+ "-preset", "veryfast", // Encoding preset+ "-crf", "18", // Constant Rate Factor for quality+ "-pix_fmt", "yuv420p", // Output pixel format+ "-y", // Overwrite output file without asking+ "-movflags", "+faststart", // Enable fast start+ output_path_str, // Output file path+ ])+ .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 || {+ // Set up the capturer for the primary display.+ let mut capturer = Capturer::new(display).expect("Failed to start capture");+ let mut ffmpeg_stdin_guard = ffmpeg_stdin;++ // Create a new buffer for the frame with the exact size required, excluding any padding.+ let frame_size = w * h * BYTES_PER_PIXEL;++ // Capture frames in a loop.+ loop {+ let start_frame_time = Instant::now();+ if should_stop_clone.load(Ordering::SeqCst) {+ *state.lock().unwrap() = RecordingState::Stopping;+ break;+ }+ let buffer = match capturer.frame() {+ Ok(buffer) => buffer,+ Err(error) if error.kind() == WouldBlock => {+ thread::sleep(Duration::from_millis(1));+ continue;+ },+ Err(e) => return Err(format!("Error capturing frame: {}", e)),+ };++ // argb_to_i420(w as usize, adjusted_height as usize, &buffer[..capture_size], &mut yuv_buffer);++ let stride = buffer[..capture_size].len() / adjusted_height;++ // Write each row of the buffer to FFmpeg, excluding stride if there is any.+ // Here we're assuming there's no stride, so we write the entire row.+ 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);+ *state.lock().unwrap() = RecordingState::Stopping;+ break;+ }+ }++ // Flush FFmpeg's stdin to ensure all data is sent.+ 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);+ }+ };+++ // Handle closing FFmpeg's stdin and waiting for the encoding process to finish.+ drop(ffmpeg_stdin_guard);+ let output_status = command.wait_with_output();+ match output_status {+ 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)+ }+ },+ Err(e) => {+ let error_message = format!("Failed to wait for FFmpeg child: {}", e);+ eprintln!("{}", &error_message);+ Err(error_message)+ },+ }+ });+++ *self.ffmpeg_handle.lock().unwrap() = Some(ffmpeg_handle);++ Ok(())+ }+++ pub fn stop_recording(&self) {+ println!("Stop recording requested.");++ // Mark the flag to stop recording+ self.should_stop.store(true, Ordering::SeqCst);++ let mut ffmpeg_handle_lock = match self.ffmpeg_handle.lock() {+ Ok(guard) => guard,+ Err(_) => {+ eprintln!("Failed to lock ffmpeg_handle mutex.");+ return;+ }+ };++ if let Some(ffmpeg_handle) = ffmpeg_handle_lock.take() {+ drop(ffmpeg_handle_lock);+ match ffmpeg_handle.join() {+ Ok(result) => match result {+ Ok(_) => println!("Recording stopped successfully."),+ Err(e) => eprintln!("Recording thread encountered an error: {}", e),+ },+ Err(_) => eprintln!("Failed to join recording thread."),+ };+ } else {+ println!("Recording was not in progress or is already stopping.");+ }++ // Lastly, reset the should_stop flag for potential next recording.+ self.should_stop.store(false, Ordering::SeqCst);+ }+}\ No newline at end of filediff --git a/apps/desktop/src/components/FloatingOptions.tsx b/apps/desktop/src/components/FloatingOptions.tsxindex 392485545..af6358174 100644--- a/apps/desktop/src/components/FloatingOptions.tsx+++ b/apps/desktop/src/components/FloatingOptions.tsx@@ -157,12 +157,13 @@ export const FloatingOptions = () => {render={({ status, startRecording, stopRecording }) => {const handleStartAllRecordings = async () => {startRecording(); // Starts webcam recording- await invoke("take_screenshot");+ await invoke("start_video_recording");};// Similarly, for stopping all recordings- const handleStopAllRecordings = () => {+ const handleStopAllRecordings = async () => {stopRecording(); // Stops webcam recording+ await invoke("stop_video_recording");// stopDisplayRecording(); // Stops display recording};