Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Add local mode var + new contribution instructions guide
Richie McIlroyeeea1f6bd7a0
diff --git a/.env.example b/.env.exampleindex 03e9a8909..e1e37adce 100644--- a/.env.example+++ b/.env.example@@ -18,6 +18,12 @@NEXT_PUBLIC_ENVIRONMENT=developmentNEXT_PUBLIC_URL=http://localhost:3000+# IMPORTANT FOR LOCAL DEV:+# This determines whether or not the app will run in "local mode".+# when in local mode, auth will not be required in the desktop app+# and videos will not be uploaded to AWS S3.+NEXT_PUBLIC_LOCAL_MODE=false+# -- database ****************DB_MYSQL_MIGRATION_URL="mysql://root:@localhost:3306/planetscale"DB_PLANETSCALE_HOST=localhost:3900diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 92b763acf..9d68adf38 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -22,12 +22,26 @@ There are many ways to contribute to Cap. You can:### How do I get started with development on my local machine?-This is a very top level guide right now, but the basics are:+This is a very top level guide right now, but if you want to develop for both the web app and desktop app, you will need to make sure the below steps are followed. Alternatively, if you are only looking to run the desktop app locally, you can follow the `How do I run the desktop app locally without needing to use auth?` steps.1. Clone the repository2. Install dependencies with `pnpm install`3. Clone .env.example and rename it to .env4. Add your own API keys to the .env file-5. Run the app with `pnpm dev`+5. At the root of the directory, run the app with `pnpm dev`6. Make sure both the the desktop app, and web app can be built without any errors. For the desktop app, use `pnpm tauri:build`. For the web app, use `pnpm build`7. Submit a PR with your changes++### How do I run the desktop app locally without needing to use auth? ###++You can run cap in "local mode", which means that no auth is required for the desktop app, and no video segments are uploaded. Similar to the above steps, this is how you can run the Cap desktop app in local mode with the least amount of .env vars.++1. Clone the repository+2. Install dependencies with `pnpm install`+3. Clone .env.example and rename it to .env+4. Make sure you have `NEXT_PUBLIC_ENVIRONMENT=development`, `NEXT_PUBLIC_URL=http://localhost:3000` and `NEXT_PUBLIC_LOCAL_MODE=true`. These should be the only .env vars that you require to get the desktop app up and running.+5. At the root of the directory, run the app with `pnpm dev`++### How do I view the screen recording segments locally? ###++The video segments are stored in your app data directory, under the folder `so.cap.desktop`. You should see a directory called `chunks`, which will contain both `video` and `audio` directories. You can find the relevant segments in either of those.\ No newline at end of filediff --git a/apps/desktop/src-tauri/src/capture/src/common/quartz.rs b/apps/desktop/src-tauri/src/capture/src/common/quartz.rsindex e4478eec7..42c0dccf4 100644--- a/apps/desktop/src-tauri/src/capture/src/common/quartz.rs+++ b/apps/desktop/src-tauri/src/capture/src/common/quartz.rs@@ -85,8 +85,8 @@ impl Display {self.0.height()}- pub fn stride(&self) -> usize {- self.0.stride()+ pub fn bytes_per_row(&self) -> usize {+ self.0.bytes_per_row()}pub fn bits_per_pixel(&self) -> usize {diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/display.rs b/apps/desktop/src-tauri/src/capture/src/quartz/display.rsindex 4e904256b..b8046c1c8 100644--- a/apps/desktop/src-tauri/src/capture/src/quartz/display.rs+++ b/apps/desktop/src-tauri/src/capture/src/quartz/display.rs@@ -46,7 +46,7 @@ impl Display {}}- pub fn stride(self) -> usize {+ pub fn bytes_per_row(self) -> usize {unsafe {CGDisplayBytesPerRow(self.0) as usize}diff --git a/apps/desktop/src-tauri/src/media.rs b/apps/desktop/src-tauri/src/media.rsindex 80790468f..f5331a465 100644--- a/apps/desktop/src-tauri/src/media.rs+++ b/apps/desktop/src-tauri/src/media.rs@@ -65,12 +65,13 @@ impl MediaRecorder {let mut w = max_screen_width;let mut h = max_screen_height;- let adjusted_width = w & !1;- let adjusted_height = h & !1;+ let adjusted_width = w & !2;+ let adjusted_height = h & !2;let capture_size = adjusted_width * adjusted_height * 4;let (audio_tx, audio_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(2048);let (video_tx, video_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(2048);- let calculated_stride = (adjusted_width * 4) as usize;+ let bytes_per_pixel = display.bits_per_pixel() / 8;+ let calculated_stride = (bytes_per_pixel * adjusted_width) as usize;println!("Display width: {}", w);println!("Display height: {}", h);@@ -280,6 +281,11 @@ impl MediaRecorder {std::thread::spawn(move || {println!("Starting video recording capture thread...");+ let is_local_mode = match dotenv_codegen::dotenv!("NEXT_PUBLIC_LOCAL_MODE") {+ "true" => true,+ _ => false,+ };+let mut capturer = Capturer::new(Display::primary().expect("Failed to find primary display"), w.try_into().unwrap(), h.try_into().unwrap()).expect("Failed to start capture");let fps = FRAME_RATE;@@ -296,61 +302,64 @@ impl MediaRecorder {if now >= time_next {- if now - start_time >= capture_frame_at && !screenshot_captured {- if let Ok(frame) = capturer.frame() {- screenshot_captured = true;- let screenshot_file_path_owned_cloned = screenshot_file_path_owned.clone();- let w_cloned = adjusted_width.clone();- let h_cloned = adjusted_height.clone();-- let frame_clone = frame.to_vec();- std::thread::spawn(move || {- let mut frame_data = Vec::with_capacity(capture_size.try_into().unwrap());- println!("Frame length: {}", frame_clone.len());- let rt = tokio::runtime::Runtime::new().unwrap();-- for row in 0..adjusted_height {- let start: usize = row as usize * calculated_stride as usize;- let end: usize = start + calculated_stride as usize;- let mut row_data = frame_clone[start..end].to_vec();- for chunk in row_data.chunks_mut(4) {- chunk.swap(0, 2);- }- frame_data.extend_from_slice(&row_data);- }-- let path = Path::new(&screenshot_file_path_owned_cloned);- let image: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_raw(- w_cloned.try_into().unwrap(),- h_cloned.try_into().unwrap(),- frame_data- ).expect("Failed to create image buffer");-- let mut output_file = std::fs::File::create(&path).expect("Failed to create output file");- let mut encoder = JpegEncoder::new_with_quality(&mut output_file, 20);-- if let Err(e) = encoder.encode_image(&image) {- eprintln!("Failed to save screenshot: {}", e);- } else {- let screenshot_file_path_owned_cloned_copy = screenshot_file_path_owned_cloned.clone();- rt.block_on(async {- let upload_task = tokio::spawn(upload_file(Some(options_clone), screenshot_file_path_owned_cloned_copy.clone(), "screenshot".to_string()));- match upload_task.await {- Ok(result) => {- match result {- Ok(_) => println!("Screenshot captured and saved to {:?}", path),- Err(e) => eprintln!("Failed to upload file: {}", e),- }- },- Err(e) => eprintln!("Failed to join task: {}", e),+ if !is_local_mode {+ if now - start_time >= capture_frame_at && !screenshot_captured {+ if let Ok(frame) = capturer.frame() {+ screenshot_captured = true;+ let screenshot_file_path_owned_cloned = screenshot_file_path_owned.clone();+ let w_cloned = adjusted_width.clone();+ let h_cloned = adjusted_height.clone();++ let frame_clone = frame.to_vec();+ std::thread::spawn(move || {+ let mut frame_data = Vec::with_capacity(capture_size.try_into().unwrap());+ println!("Frame length: {}", frame_clone.len());+ let rt = tokio::runtime::Runtime::new().unwrap();++ for row in 0..adjusted_height {+ let start: usize = row as usize * calculated_stride as usize;+ let end: usize = start + calculated_stride as usize;+ let mut row_data = frame_clone[start..end].to_vec();+ for chunk in row_data.chunks_mut(4) {+ chunk.swap(0, 2);}- });- println!("Screenshot captured and saved to {:?}", path);- }- });+ frame_data.extend_from_slice(&row_data);+ }++ let path = Path::new(&screenshot_file_path_owned_cloned);+ let image: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_raw(+ w_cloned.try_into().unwrap(),+ h_cloned.try_into().unwrap(),+ frame_data+ ).expect("Failed to create image buffer");++ let mut output_file = std::fs::File::create(&path).expect("Failed to create output file");+ let mut encoder = JpegEncoder::new_with_quality(&mut output_file, 20);++ if let Err(e) = encoder.encode_image(&image) {+ eprintln!("Failed to save screenshot: {}", e);+ } else {+ let screenshot_file_path_owned_cloned_copy = screenshot_file_path_owned_cloned.clone();+ rt.block_on(async {+ let upload_task = tokio::spawn(upload_file(Some(options_clone), screenshot_file_path_owned_cloned_copy.clone(), "screenshot".to_string()));+ match upload_task.await {+ Ok(result) => {+ match result {+ Ok(_) => println!("Screenshot captured and saved to {:?}", path),+ Err(e) => eprintln!("Failed to upload file: {}", e),+ }+ },+ Err(e) => eprintln!("Failed to join task: {}", e),+ }+ });+ println!("Screenshot captured and saved to {:?}", path);+ }+ });+ }}}+let mut frame_data = Vec::with_capacity(capture_size.try_into().unwrap());match capturer.frame() {diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 6d40bd0da..b91024104 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -81,22 +81,30 @@ pub async fn start_dual_recording(state_guard.video_uploading_finished = Arc::new(AtomicBool::new(false));state_guard.audio_uploading_finished = Arc::new(AtomicBool::new(false));-// let screen_upload = start_upload_loop(video_chunks_dir.clone(), options.clone(), "video".to_string(), shutdown_flag.clone(), state_guard.video_uploading_finished.clone());-// let audio_upload = start_upload_loop(audio_chunks_dir, options.clone(), "audio".to_string(), shutdown_flag.clone(), state_guard.audio_uploading_finished.clone());+ let is_local_mode = match dotenv_codegen::dotenv!("NEXT_PUBLIC_LOCAL_MODE") {+ "true" => true,+ _ => false,+ };- drop(state_guard);+ if !is_local_mode {+ let screen_upload = start_upload_loop(video_chunks_dir.clone(), options.clone(), "video".to_string(), shutdown_flag.clone(), state_guard.video_uploading_finished.clone());+ let audio_upload = start_upload_loop(audio_chunks_dir, options.clone(), "audio".to_string(), shutdown_flag.clone(), state_guard.audio_uploading_finished.clone());- println!("Starting upload loops...");+ drop(state_guard);+ println!("Starting upload loops...");-// match tokio::try_join!(screen_upload, audio_upload) {-// Ok(_) => {-// println!("Both upload loops completed successfully.");-// },-// Err(e) => {-// eprintln!("An error occurred: {}", e);-// },-// }+ match tokio::try_join!(screen_upload, audio_upload) {+ Ok(_) => {+ println!("Both upload loops completed successfully.");+ },+ Err(e) => {+ eprintln!("An error occurred: {}", e);+ },+ }+ } else {+ println!("Skipping upload loops due to NEXT_PUBLIC_LOCAL_MODE being set to 'true'.");+ }Ok(())}@@ -114,10 +122,17 @@ pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -media_process.stop_media_recording().await.expect("Failed to stop media recording");}- while !guard.video_uploading_finished.load(Ordering::SeqCst)- || !guard.audio_uploading_finished.load(Ordering::SeqCst) {- println!("Waiting for uploads to finish...");- tokio::time::sleep(Duration::from_millis(50)).await;+ let is_local_mode = match dotenv_codegen::dotenv!("NEXT_PUBLIC_LOCAL_MODE") {+ "true" => true,+ _ => false,+ };++ if !is_local_mode {+ while !guard.video_uploading_finished.load(Ordering::SeqCst)+ || !guard.audio_uploading_finished.load(Ordering::SeqCst) {+ println!("Waiting for uploads to finish...");+ tokio::time::sleep(Duration::from_millis(50)).await;+ }}println!("All recordings and uploads stopped.");diff --git a/apps/desktop/src/app/page.tsx b/apps/desktop/src/app/page.tsxindex f49fe9562..2d9f9bd2c 100644--- a/apps/desktop/src/app/page.tsx+++ b/apps/desktop/src/app/page.tsx@@ -97,6 +97,15 @@ export default function CameraPage() {}}, [isSignedIn, cameraWindowOpen, permissions.confirmed]);+ if(process.env.NEXT_PUBLIC_LOCAL_MODE === "true"){+ return(+ <>+ <WindowActions />+ <Recorder />+ </>+ )+ }+if (loading && !permissionsLoaded) {return (<div className="w-full h-full flex items-center justify-center">diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsxindex 7c857ea4a..bf0c494ec 100644--- a/apps/desktop/src/components/windows/inner/Recorder.tsx+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx@@ -15,6 +15,8 @@ import { getLatestVideoId, saveLatestVideoId } from "@/utils/database/utils";import { openLinkInBrowser } from "@/utils/helpers";import toast, { Toaster } from "react-hot-toast";import { authFetch } from "@/utils/auth/helpers";+import { appDataDir, join } from "@tauri-apps/api/path";+import { open } from "@tauri-apps/api/shell";declare global {interface Window {@@ -170,8 +172,17 @@ export const Recorder = () => {const handleStartAllRecordings = async () => {try {setStartingRecording(true);- const videoData = await prepareVideoData();- console.log("Video data:", videoData);+ const videoData =+ process.env.NEXT_PUBLIC_LOCAL_MODE &&+ process.env.NEXT_PUBLIC_LOCAL_MODE === "true"+ ? {+ id: "test",+ user_id: "test",+ aws_region: "test",+ aws_bucket: "test",+ }+ : await prepareVideoData();+ console.log("Video data :", videoData);if (videoData) {await startDualRecording(videoData);} else {@@ -208,7 +219,12 @@ export const Recorder = () => {? `${process.env.NEXT_PUBLIC_URL}/s/${await getLatestVideoId()}`: `https://cap.link/${await getLatestVideoId()}`;- await openLinkInBrowser(url);+ if (+ !process.env.NEXT_PUBLIC_LOCAL_MODE ||+ process.env.NEXT_PUBLIC_LOCAL_MODE !== "true"+ ) {+ await openLinkInBrowser(url);+ }setIsRecording(false);setHasStartedRecording(false);