Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Faster chunk uploading, improved record button

Richie McIlroya27be994fc3b
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index d6d390501..6435b4811 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1,7 +1,7 @@
use std::path::{Path, PathBuf};
use std::collections::HashSet;
-use std::io::{self, BufReader, BufRead, ErrorKind, AsyncWriteExt};
-use tokio::fs::{OpenOptions, read_to_string, File};
+use std::io::{self, BufReader, BufRead, ErrorKind};
+use std::fs::File;
use std::sync::Arc;
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -10,7 +10,6 @@ use tokio::task::JoinHandle;
use tokio::time::{timeout, Duration};
use serde::{Serialize, Deserialize};
use tauri::State;
-use serde_json::{Value, json};
use crate::utils::ffmpeg_path_as_str;
use crate::upload::upload_file;
@@ -36,12 +35,6 @@ pub struct RecordingOptions {
pub resolution: String,
}
-#[derive(Serialize, Deserialize, Debug)]
-struct MetadataRecord {
- start_time: String,
- end_time: Option<String>,
-}
-
#[tauri::command]
pub async fn start_dual_recording(
state: State<'_, Arc<Mutex<RecordingState>>>,
@@ -93,6 +86,11 @@ pub async fn start_dual_recording(
tokio::spawn(log_output(screen_stdout, "Screen stdout".to_string()));
tokio::spawn(log_output(screen_stderr, "Screen stderr".to_string()));
+ // let video_stdout = video_child.stdout.take().unwrap();
+ // let video_stderr = video_child.stderr.take().unwrap();
+ // tokio::spawn(log_output(video_stdout, "Video stdout".to_string()));
+ // tokio::spawn(log_output(video_stderr, "Video stderr".to_string()));
+
state_guard.screen_process = Some(screen_child);
// guard.video_process = Some(video_child);
state_guard.upload_handles = Mutex::new(vec![]);
@@ -115,14 +113,6 @@ pub async fn start_dual_recording(
},
}
- let start_time = chrono::Utc::now();
-
- // Add the start time to metadata.json
- append_metadata(&data_dir.join("metadata.json"), &MetadataRecord {
- start_time: start_time.to_rfc3339(),
- end_time: None,
- }).await?;
-
Ok(())
}
@@ -130,80 +120,35 @@ pub async fn start_dual_recording(
pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -> Result<(), String> {
println!("!!STOPPING screen recording...");
+ // Lock the state to access shared data.
let mut guard = state.lock().await;
+ // Immediately instruct ongoing operations to stop.
guard.shutdown_flag.store(true, Ordering::SeqCst);
-
- if let Some(child_process) = &mut guard.screen_process {
- if let Err(e) = child_process.kill().await {
- eprintln!("Failed to kill the child process: {}", e);
- } else {
- println!("Child process terminated successfully.");
- }
- }
- // if let Some(child_process) = &mut guard.video_process {
- // if let Err(e) = child_process.kill().await {
- // eprintln!("Failed to kill the child process: {}", e);
- // } else {
- // println!("Child process terminated successfully.");
- // }
- // }
-
- guard.screen_process = None;
- // guard.video_process = None;
-
- let data_dir = guard.data_dir.as_ref()
- .ok_or("Data directory is not set in the recording state".to_string())?;
-
- let chunks_dir_screen = data_dir.join("chunks/screen");
-
- let chunks_dir_video = data_dir.join("chunks/video");
- let recording_options = guard.recording_options.clone();
-
- drop(guard);
-
- // Create join handles for the final uploads
- let handle_screen = upload_remaining_chunks(&chunks_dir_screen, recording_options.clone(), "screen");
- let handle_video = upload_remaining_chunks(&chunks_dir_video, recording_options.clone(), "video");
-
- // Await the final upload tasks
- tokio::select! {
- // Await either completion or an error from the screen upload task
- result = handle_screen => {
- if let Err(e) = result {
- eprintln!("Error uploading remaining screen chunks: {}", e);
- }
- }
- // Await either completion or an error from the video upload task
- result = handle_video => {
- if let Err(e) = result {
- eprintln!("Error uploading remaining video chunks: {}", e);
- }
- }
+ // Immediately try to close running FFmpeg processes.
+ if let Some(child_process) = &mut guard.screen_process {
+ let _ = child_process.kill().await;
}
+ // Assuming there's a video_process similar to screen_process.
+ //if let Some(child_process) = &mut guard.video_process {
+ // let _ = child_process.kill().await;
+ //}
- let guard = state.lock().await;
- let mut upload_handles = guard.upload_handles.lock().await;
+ // Swap out the current upload_handles for an empty vector to take ownership.
+ let mut upload_handles_lock = guard.upload_handles.lock().await;
+ let upload_handles = std::mem::take(&mut *upload_handles_lock);
- // Drain the upload_handles to get ownership of the JoinHandles
- let handles: Vec<_> = upload_handles.drain(..).collect();
-
- // Explicitly drop the locks before awaiting the handles
- drop(upload_handles);
+ // Explicitly drop the locks so other async operations can proceed.
+ drop(upload_handles_lock);
drop(guard);
- // Await each of the JoinHandles to completion
- for handle in handles {
- let _ = handle.await.map_err(|e| e.to_string())?;
- }
-
- let end_time = chrono::Utc::now();
+ // Now using try_join_all with the owned join handles obtained from the state.
+ // This will wait for all the current upload handles to complete.
+ let _ = futures::future::try_join_all(upload_handles.into_iter()).await;
- // Update the metadata.json with the end time
- append_metadata_end_time(&data_dir.join("metadata.json"), &end_time.to_rfc3339()).await?;
+ println!("All recordings and uploads stopped.");
- // All checks and uploads are done, return Ok(())
Ok(())
}
@@ -276,7 +221,6 @@ async fn construct_recording_args(
"-pix_fmt".to_string(), pix_fmt,
"-g".to_string(), gop,
"-r".to_string(), fps.to_string(),
- "-draw_mouse".to_string(), "1".to_string(),
"-f".to_string(), "segment".to_string(),
"-segment_time".to_string(), segment_time,
"-segment_format".to_string(), "matroska".to_string(),
@@ -487,33 +431,43 @@ async fn upload_remaining_chunks(
chunks_dir: &PathBuf,
options: Option<RecordingOptions>,
video_type: &str,
+ shutdown_flag: Arc<AtomicBool>,
) -> Result<(), String> {
+ // Include shutdown_flag in parameters and check it inside loop to quickly react to stop signals.
+
if let Some(actual_options) = options {
let retry_interval = Duration::from_secs(2);
let upload_timeout = Duration::from_secs(15);
let file_stability_timeout = Duration::from_secs(1);
let file_stability_checks = 2;
- // Get directory entries
+ // Adjusted for immediate reaction to shutdown_flag.
+ if shutdown_flag.load(Ordering::SeqCst) {
+ return Ok(());
+ }
+
let entries = std::fs::read_dir(chunks_dir).map_err(|e| format!("Error reading directory: {}", e))?;
- // A semaphore to limit the number of concurrent uploads
- let semaphore = Arc::new(Semaphore::new(16));
+ let semaphore = Arc::new(Semaphore::new(16)); // Control concurrency to prevent resource exhaustion.
- // Create upload tasks for each file entry
let tasks: Vec<_> = entries.filter_map(|entry| entry.ok())
- .map(|entry| {
+ .filter_map(|entry| {
let path = entry.path();
- if path.is_file() && (path.extension().map_or(false, |e| e == "mkv" || e == "webm")) {
+ if path.is_file() && (path.extension().map_or(false, |e| e == "mkv" || e == "webm")) && !shutdown_flag.load(Ordering::SeqCst) {
let video_type = video_type.to_string();
let semaphore_clone = semaphore.clone();
let actual_options_clone = actual_options.clone();
+ let shutdown_flag_clone = shutdown_flag.clone();
- // Spawn a task to upload the file
Some(tokio::spawn(async move {
let _permit = semaphore_clone.acquire().await;
let filepath_str = path.to_str().unwrap_or_default().to_owned();
+ // Quick exit if shutdown signal is received.
+ if shutdown_flag_clone.load(Ordering::SeqCst) {
+ return;
+ }
+
// Check for file size stability
let mut last_size = 0;
let mut stable_count = 0;
@@ -572,47 +526,11 @@ async fn upload_remaining_chunks(
})
.collect();
- // Wait for all the tasks to finish
- for task in tasks {
- if let Some(handle) = task {
- if let Err(e) = handle.await {
- eprintln!("Failed to join task: {:?}", e);
- }
- }
- }
+ // Await all tasks concurrently.
+ let _ = futures::future::try_join_all(tasks).await;
Ok(())
} else {
Err("No recording options provided".to_string())
}
-}
-
-async fn append_metadata(file_path: &Path, record: &MetadataRecord) -> Result<(), String> {
- let mut data = match read_to_string(file_path).await {
- Ok(contents) => serde_json::from_str::<Vec<MetadataRecord>>(&contents).unwrap_or_default(),
- Err(_) => vec![],
- };
-
- data.push(record.clone());
-
- let new_data = serde_json::to_string(&data).map_err(|e| e.to_string())?;
- tokio::fs::write(file_path, new_data.as_bytes()).await.map_err(|e| e.to_string())?;
-
- Ok(())
-}
-
-async fn append_metadata_end_time(file_path: &Path, end_time: &str) -> Result<(), String> {
- let mut data = match read_to_string(file_path).await {
- Ok(contents) => serde_json::from_str::<Vec<MetadataRecord>>(&contents).unwrap_or_default(),
- Err(_) => vec![],
- };
-
- if let Some(last_record) = data.last_mut() {
- last_record.end_time = Some(end_time.to_string());
- }
-
- let new_data = serde_json::to_string(&data).map_err(|e| e.to_string())?;
- tokio::fs::write(file_path, new_data.as_bytes()).await.map_err(|e| e.to_string())?;
-
- Ok(())
}
\ No newline at end of file
diff --git a/apps/desktop/src/components/recording/ActionButton.tsx b/apps/desktop/src/components/recording/ActionButton.tsx
index 9aeb0fefd..f2a3e7de3 100644
--- a/apps/desktop/src/components/recording/ActionButton.tsx
+++ b/apps/desktop/src/components/recording/ActionButton.tsx
@@ -21,7 +21,7 @@ export const ActionButton = ({
active === true
? "bg-white hover:bg-gray-100"
: "bg-gray-100 hover:bg-white"
- } border-gray-300 w-full h-[50px] py-2 px-4 text-[15px] border-2 flex items-center justify-start rounded-[15px] flex-grow transition-all shadow-sm shadow-[0px 0px 180px rgba(255, 255, 255, 0.18)]`}
+ } border-gray-300 w-full h-[50px] py-2 px-4 text-[14px] border-2 flex items-center justify-start rounded-[15px] flex-grow transition-all shadow-sm shadow-[0px 0px 180px rgba(255, 255, 255, 0.18)]`}
>
<span>{icon}</span>
{label && (
diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsx
index c9e35fdf6..55d55a2e4 100644
--- a/apps/desktop/src/components/windows/inner/Recorder.tsx
+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx
@@ -7,7 +7,7 @@ import { Microphone } from "@/components/icons/Microphone";
import { Screen } from "@/components/icons/Screen";
import { Window } from "@/components/icons/Window";
import { ActionButton } from "@/components/recording/ActionButton";
-import { Button } from "@/components/Button";
+import { Button } from "@cap/ui";
import { Logo } from "@/components/icons/Logo";
import { emit, listen } from "@tauri-apps/api/event";
import { showMenu } from "tauri-plugin-context-menu";
@@ -247,7 +247,7 @@ export const Recorder = () => {
return (
<div
data-tauri-drag-region
- className="relative flex items-center justify-center overflow-hidden"
+ className="relative flex items-center justify-center"
>
{countdownActive && (
<Countdown
@@ -298,22 +298,23 @@ export const Recorder = () => {
/>
</div>
</div>
- {isRecording === true ? (
- <Button
- variant="primary"
- handler={handleStopAllRecordings}
- label={
- stoppingRecording ? currentStoppingMessage : "Stop Recording"
+ <Button
+ className="w-[97.6%] flex mx-auto"
+ onClick={() => {
+ if (isRecording) {
+ handleStopAllRecordings();
+ } else {
+ handleStartAllRecordings();
}
- spinner={stoppingRecording}
- />
- ) : (
- <Button
- variant="primary"
- handler={handleStartAllRecordings}
- label="Start Recording"
- />
- )}
+ }}
+ spinner={stoppingRecording}
+ >
+ {isRecording
+ ? stoppingRecording
+ ? currentStoppingMessage
+ : "Stop Recording"
+ : "Start Recording"}
+ </Button>
</div>
</div>
<Toaster />
diff --git a/packages/ui/src/components/Button.tsx b/packages/ui/src/components/Button.tsx
index ca1bcf422..303065bf0 100644
--- a/packages/ui/src/components/Button.tsx
+++ b/packages/ui/src/components/Button.tsx
@@ -10,13 +10,13 @@ const buttonVariants = cva(
variants: {
variant: {
default:
- "group relative isolate inline-flex items-center justify-center overflow-hidden text-sm transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md ring-1 before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay dark:ring-0 bg-primary ring-2 text-white ring-primary",
+ "group relative isolate font-medium inline-flex items-center justify-center overflow-hidden text-sm transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-full ring-1 before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-full before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-full after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay dark:ring-0 bg-primary ring-2 text-white ring-primary",
destructive: "bg-red-500 text-red-900 hover:bg-red-600",
outline: "border border-input bg-white text-primary hover:bg-gray-50",
secondary: "bg-secondary text-white hover:bg-secondary-1",
},
size: {
- default: "h-9 px-5 text-base",
+ default: "h-10 px-5 text-base",
sm: "h-8 rounded-lg px-3 text-sm",
lg: "h-10 px-5 text-lg",
icon: "h-10 w-10",
@@ -33,17 +33,47 @@ export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
+ spinner?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
- ({ className, variant, size, asChild = false, ...props }, ref) => {
+ (
+ { className, variant, size, asChild = false, spinner = false, ...props },
+ ref
+ ) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
className={classNames(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
- />
+ >
+ {props.children}
+ {spinner && (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ className="w-6 h-6 ml-2"
+ viewBox="0 0 24 24"
+ >
+ <style>
+ {"@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"}
+ </style>
+ <path
+ fill="#FFF"
+ d="M12 1a11 11 0 1 0 11 11A11 11 0 0 0 12 1Zm0 19a8 8 0 1 1 8-8 8 8 0 0 1-8 8Z"
+ opacity={0.25}
+ />
+ <path
+ fill="#FFF"
+ d="M10.14 1.16a11 11 0 0 0-9 8.92A1.59 1.59 0 0 0 2.46 12a1.52 1.52 0 0 0 1.65-1.3 8 8 0 0 1 6.66-6.61A1.42 1.42 0 0 0 12 2.69a1.57 1.57 0 0 0-1.86-1.53Z"
+ style={{
+ transformOrigin: "center",
+ animation: "spinner_AtaB .75s infinite linear",
+ }}
+ />
+ </svg>
+ )}
+ </Comp>
);
}
);