Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: add window overlay option, change recording to 30 fps
Richie McIlroye3d112545630
diff --git a/apps/desktop/src-tauri/src/media/video.rs b/apps/desktop/src-tauri/src/media/video.rsindex 37231f7a4..973da3378 100644--- a/apps/desktop/src-tauri/src/media/video.rs+++ b/apps/desktop/src-tauri/src/media/video.rs@@ -1,21 +1,13 @@use image::codecs::jpeg::JpegEncoder;-use image::{ImageBuffer, Rgba};-use scap::{- capturer::{Capturer, Options, Resolution},- frame::{Frame, FrameType},-};-use std::{- future::Future,- path::{Path, PathBuf},- sync::Arc,- time::Duration,-};+use image::{ ImageBuffer, Rgba };+use scap::{ capturer::{ Capturer, Options, Resolution }, frame::{ Frame, FrameType } };+use std::{ future::Future, path::{ Path, PathBuf }, sync::Arc, time::Duration };use tokio::sync::mpsc::error::TrySendError;-use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc};+use tokio::{ fs::File, io::AsyncWriteExt, sync::mpsc };-use super::{Instant, RecordingOptions, SharedFlag, SharedInstant};+use super::{ Instant, RecordingOptions, SharedFlag, SharedInstant };use crate::app::config;-use crate::upload::{upload_file, FileType};+use crate::upload::{ upload_file, FileType };pub struct VideoCapturer {capturer: Option<Capturer>,@@ -26,7 +18,7 @@ pub struct VideoCapturer {}impl VideoCapturer {- pub const FPS: u32 = 60;+ pub const FPS: u32 = 30;pub fn new(_width: usize, _height: usize, should_stop: SharedFlag) -> VideoCapturer {let mut capturer = Capturer::new(Options {@@ -55,10 +47,9 @@ impl VideoCapturer {&mut self,start_time: SharedInstant,screenshot_dir: impl AsRef<Path>,- recording_options: RecordingOptions,+ recording_options: RecordingOptions) {- let mut capturer = self- .capturer+ let mut capturer = self.capturer.take().expect("Video capturing thread has already been started!");let (sender, receiver) = mpsc::channel(2048);@@ -90,19 +81,22 @@ impl VideoCapturer {let width = frame.width;let height = frame.height;let frame_data = match frame.width == 0 && frame.height == 0 {- true => match last_frame.take() {- Some(data) => data,- None => {- tracing::error!(- "Somehow got an idle frame before any complete frame"- );- continue;+ true =>+ match last_frame.take() {+ Some(data) => data,+ None => {+ tracing::error!(+ "Somehow got an idle frame before any complete frame"+ );+ continue;+ }}- },false => Arc::new(frame.data),};- if now - capture_start_time >= take_screenshot_delay && !screenshot_captured+ if+ now - capture_start_time >= take_screenshot_delay &&+ !screenshot_captured{screenshot_captured = true;let mut frame_data_clone = (*frame_data).clone();@@ -115,14 +109,16 @@ impl VideoCapturer {let image: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_raw(width.try_into().unwrap(),height.try_into().unwrap(),- frame_data_clone,- )- .expect("Failed to create image buffer");+ frame_data_clone+ ).expect("Failed to create image buffer");- let mut output_file = std::fs::File::create(&screenshot_path)+ let mut output_file = std::fs::File+ ::create(&screenshot_path).expect("Failed to create output file");- let mut encoder =- JpegEncoder::new_with_quality(&mut output_file, 70);+ let mut encoder = JpegEncoder::new_with_quality(+ &mut output_file,+ 70+ );if let Err(e) = encoder.encode_image(&image) {tracing::warn!("Failed to save screenshot: {}", e);@@ -136,20 +132,27 @@ impl VideoCapturer {if !config::is_local_mode() {let rt = tokio::runtime::Runtime::new().unwrap();rt.block_on(async move {- let upload_task = tokio::spawn(upload_file(- Some(options_clone),- screenshot_path.clone(),- FileType::Screenshot,- ));+ let upload_task = tokio::spawn(+ upload_file(+ Some(options_clone),+ screenshot_path.clone(),+ FileType::Screenshot+ )+ );match upload_task.await {- Ok(result) => match result {- Ok(_) => tracing::info!(- "Screenshot successfully uploaded"- ),- Err(e) => {- tracing::warn!("Failed to upload file: {}", e)+ Ok(result) =>+ match result {+ Ok(_) =>+ tracing::info!(+ "Screenshot successfully uploaded"+ ),+ Err(e) => {+ tracing::warn!(+ "Failed to upload file: {}",+ e+ )+ }}- },Err(e) => {tracing::error!("Failed to join task: {}", e)}@@ -207,8 +210,7 @@ impl VideoCapturer {pub fn collect_frames(&mut self, destination: PathBuf) -> impl Future<Output = ()> + 'static {tracing::trace!("Starting video channel senders...");- let mut receiver = self- .frame_receiver+ let mut receiver = self.frame_receiver.take().expect("Video frame collection already started!");let should_stop = self.should_stop.clone();@@ -217,9 +219,7 @@ impl VideoCapturer {let mut pipe = File::create(destination).await.unwrap();while let Some(bytes) = receiver.recv().await {- pipe.write_all(&bytes)- .await- .expect("Failed to write video data to FFmpeg stdin");+ pipe.write_all(&bytes).await.expect("Failed to write video data to FFmpeg stdin");if should_stop.get() {receiver.close();diff --git a/apps/desktop/src/components/windows/Camera.tsx b/apps/desktop/src/components/windows/Camera.tsxindex 65a384f70..aae5a91f0 100644--- a/apps/desktop/src/components/windows/Camera.tsx+++ b/apps/desktop/src/components/windows/Camera.tsx@@ -22,10 +22,14 @@ export const Camera = () => {);const [overlaySize, setOverlaySize] = useState<"sm" | "lg">("sm");const [overlayShape, setOverlayShape] = useState<"round" | "square">(- localStorage.getItem("cameraOverlayShape") as "round" | "square" || "round"+ (localStorage.getItem("cameraOverlayShape") as "round" | "square") ||+ "round");- useEffect(() => localStorage.setItem("cameraOverlayShape", overlayShape), [overlayShape]);+ useEffect(+ () => localStorage.setItem("cameraOverlayShape", overlayShape),+ [overlayShape]+ );useEffect(() => {if (!videoRef.current || !selectedVideoDevice) return;@@ -126,7 +130,7 @@ export const Camera = () => {}}, []);- const getOverlayBorderRadius= () => {+ const getOverlayBorderRadius = () => {if (overlayShape === "round") return "9999px";if (overlaySize === "sm") return "3rem";else return "4rem";@@ -134,13 +138,16 @@ export const Camera = () => {const handleContextMenu = async () => {const { showMenu } = await import("tauri-plugin-context-menu");- const videoDevices = devices.filter((device) => device.kind === "videoinput");+ const videoDevices = devices.filter(+ (device) => device.kind === "videoinput"+ );const select = async (device: Device | null) => {- emit("change-device", { type: "videoinput", device: device })- .catch((error) => console.log("Failed to emit change-device event:", error));+ emit("change-device", { type: "videoinput", device: device }).catch(+ (error) => console.log("Failed to emit change-device event:", error)+ );};-+const menuItems = [{label: "Select Video:",@@ -154,6 +161,14 @@ export const Camera = () => {{is_separator: true,},+ {+ label: "Refresh Overlay",+ event: async () => {+ if (typeof window !== "undefined") {+ window.location.reload();+ }+ },+ },{label: "Close Overlay",checked: selectedVideoDevice === null,@@ -164,12 +179,10 @@ export const Camera = () => {await showMenu({items: [...menuItems],...(videoDevices.length === 0 && {- items: [- { label: "Nothing found." },- ],+ items: [{ label: "Nothing found." }],}),});- }+ };return (<div@@ -228,8 +241,12 @@ export const Camera = () => {className="h-full flex items-center justify-center p-2 hover:bg-gray-900"><div>- {overlaySize === "sm" && <Expand className="w-5 h-5 stroke-gray-200" />}- {overlaySize === "lg" && <Minimize className="w-5 h-5 stroke-gray-200" />}+ {overlaySize === "sm" && (+ <Expand className="w-5 h-5 stroke-gray-200" />+ )}+ {overlaySize === "lg" && (+ <Minimize className="w-5 h-5 stroke-gray-200" />+ )}</div></div><div@@ -238,8 +255,14 @@ export const Camera = () => {}}className="h-full flex items-center justify-center p-2 hover:bg-gray-900">- {overlayShape === "round" && <div><Squircle className="w-5 h-5 stroke-gray-200" /></div>}- {overlayShape === "square" && <span className="w-3 h-3 bg-gray-200 rounded-full"></span>}+ {overlayShape === "round" && (+ <div>+ <Squircle className="w-5 h-5 stroke-gray-200" />+ </div>+ )}+ {overlayShape === "square" && (+ <span className="w-3 h-3 bg-gray-200 rounded-full"></span>+ )}</div><divonClick={mirrorCamera}@@ -259,9 +282,11 @@ export const Camera = () => {autoPlayplaysInlinemuted- className={"absolute top-0 left-0 w-full h-full object-cover pointer-events-none"}+ className={+ "absolute top-0 left-0 w-full h-full object-cover pointer-events-none"+ }style={{ borderRadius: getOverlayBorderRadius() }}/></div>);-};\ No newline at end of file+};