Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
wip: Upload audio from frontend, stop_all_recordings func.
Richie McIlroy61731fe55383
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex 590c4542d..dc6071bd0 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -11,7 +11,8 @@ mod upload;mod devices;mod utils;-use recording::{RecordingState, start_dual_recording};+use recording::{RecordingState, start_dual_recording, stop_all_recordings};+use upload::upload_file;use devices::list_devices;use ffmpeg_sidecar::{@@ -76,6 +77,8 @@ fn main() {}).invoke_handler(tauri::generate_handler![start_dual_recording,+ stop_all_recordings,+ upload_file,list_devices]).manage(Arc::new(Mutex::new(RecordingState { screen_process: None, video_process: None, tx: None })))diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 6570d7278..4dcada8cb 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -7,7 +7,7 @@ use serde::{Serialize, Deserialize};use tauri::State;use crate::utils::ffmpeg_path_as_str;-use crate::upload::upload_video;+use crate::upload::upload_file;#[warn(dead_code)]pub struct RecordingState {@@ -22,7 +22,6 @@ pub struct RecordingOptions {pub video_id: String,pub screen_index: String,pub video_index: String,- pub audio_index: String,pub aws_region: String,pub aws_bucket: String,pub framerate: String,@@ -51,10 +50,8 @@ pub async fn start_dual_recording(clean_and_create_dir(&screen_chunks_dir)?;clean_and_create_dir(&video_chunks_dir)?;- let ffmpeg_screen_args_future = construct_recording_args(&options, &screen_chunks_dir, "screen", &options.screen_index, &options.video_index);- let ffmpeg_video_args_future = construct_recording_args(&options, &video_chunks_dir, "video", &options.video_index, &options.audio_index);-- // Await the futures to get the arguments+ let ffmpeg_screen_args_future = construct_recording_args(&options, &screen_chunks_dir, "screen", &options.screen_index);+ let ffmpeg_video_args_future = construct_recording_args(&options, &video_chunks_dir, "video", &options.video_index);let ffmpeg_screen_args = ffmpeg_screen_args_future.await.map_err(|e| e.to_string())?;let ffmpeg_video_args = ffmpeg_video_args_future.await.map_err(|e| e.to_string())?;@@ -90,20 +87,44 @@ pub async fn start_dual_recording(let mut guard = state.lock().await;*guard = RecordingState {- screen_process: Some(screen_child),- video_process: Some(video_child),+ screen_process: None,+ video_process: None,tx: Some(tx),};drop(guard);tokio::join!(start_upload_loop(screen_chunks_dir, options.clone(), "screen".to_string()),- start_upload_loop(video_chunks_dir, options.clone(), "video".to_string())+ start_upload_loop(video_chunks_dir, options.clone(), "video".to_string()),);Ok(())}+#[tauri::command]+pub async fn stop_all_recordings(+ state: State<'_, Arc<Mutex<RecordingState>>>,+) -> Result<(), String> {+ let mut guard = state.lock().await;++ if let Some(screen_process) = guard.screen_process.take() {+ screen_process.kill().await.map_err(|e| format!("Failed to stop screen recording: {}", e))?;+ }++ if let Some(video_process) = guard.video_process.take() {+ video_process.kill().await.map_err(|e| format!("Failed to stop video recording: {}", e))?;+ }++ // This code sends a stop message to the channel which is being listened to in the upload loop.+ // This will allow you to terminate the loop gracefully, which is useful to ensure that all+ // currently processed files are finished uploading before the recording stops.+ if let Some(tx) = guard.tx.take() {+ let _ = tx.send(()).await;+ }++ Ok(())+}+fn clean_and_create_dir(dir: &Path) -> Result<(), String> {if dir.exists() {for entry in std::fs::read_dir(dir).map_err(|e| e.to_string())? {@@ -132,19 +153,16 @@ async fn construct_recording_args(chunks_dir: &Path,video_type: &str,input_index: &str,- audio_index: &str,) -> Result<Vec<String>, String> {let output_filename_pattern = format!("{}/recording_chunk_%03d.mkv", chunks_dir.display());let fps = if video_type == "screen" { "60" } else { &options.framerate };- let preset = "veryfast".to_string();- let crf = "20".to_string();- let pix_fmt = "yuyv422".to_string();+ let preset = "ultrafast".to_string();+ let crf = "23".to_string();+ let pix_fmt = "nv12".to_string();let codec = "libx264".to_string();- let gop = "60".to_string();+ let gop = "30".to_string();let segment_time = "10".to_string();-- //Set the correct input index. If screen, just use the index. If video, use the index and the audio index- let input_string = if video_type == "screen" { input_index.to_string() } else { format!("{}:{}", input_index, audio_index) };+ let input_string = format!("{}:none", input_index);match std::env::consts::OS {"macos" => {@@ -152,7 +170,7 @@ async fn construct_recording_args(Ok(vec!["-f".to_string(), "avfoundation".to_string(),"-framerate".to_string(), fps.to_string(),- "-i".to_string(), format!("{}:none", input_index),+ "-i".to_string(), input_string.to_string(),"-c:v".to_string(), codec,"-crf".to_string(), crf,"-preset".to_string(), preset,@@ -172,7 +190,6 @@ async fn construct_recording_args("-framerate".to_string(), fps.to_string(),"-i".to_string(), input_string.to_string(),"-c:v".to_string(), codec,- "-c:a".to_string(), "aac".to_string(),"-preset".to_string(), preset,"-pix_fmt".to_string(), pix_fmt,"-fps_mode".to_string(), "vfr".to_string(),@@ -225,7 +242,7 @@ async fn construct_recording_args(Ok(vec!["-f".to_string(), "gdigrab".to_string(),"-i".to_string(), "desktop".to_string(),- "-pix_fmt".to_string(), pix_fmt,+ "-pixel_format".to_string(), pix_fmt,"-c:v".to_string(), codec,"-crf".to_string(), crf,"-preset".to_string(), preset,@@ -241,7 +258,7 @@ async fn construct_recording_args(Ok(vec!["-f".to_string(), "dshow".to_string(),"-i".to_string(), format!("video={}", input_index),- "-pix_fmt".to_string(), pix_fmt,+ "-pixel_format".to_string(), pix_fmt,"-c:v".to_string(), codec,"-crf".to_string(), crf,"-preset".to_string(), preset,@@ -300,7 +317,7 @@ async fn start_upload_loop(chunks_dir: PathBuf, options: RecordingOptions, video// Log the file path, and the video type in one print, starting with "Uploading video from"println!("Uploading video for {}: {}", video_type, filepath_str);- match upload_video(+ match upload_file(options.clone(),filepath_str.clone(),video_type.clone(),diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 4df6b892e..f4884a35e 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -1,15 +1,14 @@use serde_json::Value as JsonValue;use std::path::{Path};-use futures::{TryStreamExt};-use tokio_util::codec::{BytesCodec, FramedRead};use reqwest;use crate::recording::RecordingOptions;-pub async fn upload_video(+#[tauri::command]+pub async fn upload_file(options: RecordingOptions,file_path: String,- video_type: String+ file_type: String) -> Result<String, String> {println!("Uploading video...");@@ -19,7 +18,7 @@ pub async fn upload_video(.ok_or("Invalid file path")?.to_string();- let file_key = format!("{}/{}/{}/{}", options.user_id, video_type, options.video_id, file_name);+ let file_key = format!("{}/{}/{}/{}", options.user_id, file_type, options.video_id, file_name);// Here we assume your server listens on localhost:3000 and the route is `api/upload/new`let server_url = format!("http://localhost:3000/api/upload/new");@@ -63,14 +62,8 @@ pub async fn upload_video(println!("Uploading file: {}", file_path);- let file = tokio::fs::File::open(&file_path).await.map_err(|e| format!("Failed to open file: {}", e))?;- let metadata = file.metadata().await.map_err(|e| format!("Failed to extract file metadata: {}", e))?;- let file_length = metadata.len();-- println!("Uploading file: {} with size: {}", file_path, file_length);-- let stream = FramedRead::new(file, BytesCodec::new()).map_ok(|bytes| bytes.freeze());- let file_part = reqwest::multipart::Part::stream(reqwest::Body::wrap_stream(stream))+ let file_bytes = tokio::fs::read(&file_path).await.map_err(|e| format!("Failed to read file: {}", e))?;+ let file_part = reqwest::multipart::Part::bytes(file_bytes).file_name(file_name.clone()).mime_str("application/octet-stream").map_err(|e| format!("Error setting MIME type: {}", e))?;diff --git a/apps/desktop/src/components/windows/Camera.tsx b/apps/desktop/src/components/windows/Camera.tsxindex 00af7b161..a0713de51 100644--- a/apps/desktop/src/components/windows/Camera.tsx+++ b/apps/desktop/src/components/windows/Camera.tsx@@ -19,31 +19,46 @@ export const Camera = () => {return videoDevices[selectedVideoDevice.index].deviceId;}).then((deviceId) =>- navigator.mediaDevices.getUserMedia({- video: {- deviceId: deviceId,- frameRate: { ideal: 30 },- width: { ideal: 1920 },- height: { ideal: 1080 },- },- })- )- .then((stream) => {- let video = videoRef.current;- if (video) {- video.srcObject = stream;- video.onplaying = () => {+ navigator.mediaDevices+ .getUserMedia({+ video: {+ deviceId: deviceId,+ frameRate: { ideal: 30 },+ width: { ideal: 1920 },+ height: { ideal: 1080 },+ },+ })+ //Save fps and widthXheight settings to local storage+ .then((stream) => {+ const videoTrack = stream.getVideoTracks()[0];+ const settings = videoTrack.getSettings();+ const videoProperties = {+ framerate: settings.frameRate ? String(settings.frameRate) : "",+ resolution: `${settings.width}x${settings.height}`,+ };+ localStorage.setItem(+ "videoDeviceProperties",+ JSON.stringify(videoProperties)+ );+ return stream;+ })+ .then((stream) => {+ let video = videoRef.current;+ if (video) {+ video.srcObject = stream;+ video.onplaying = () => {+ setIsLoading(false);+ };+ video.play().catch((error) => {+ console.error("Error attempting to play the video:", error);+ });+ }+ })+ .catch((err) => {+ console.error(err);setIsLoading(false);- };- video.play().catch((error) => {- console.error("Error attempting to play the video:", error);- });- }- })- .catch((err) => {- console.error(err);- setIsLoading(false);- });+ })+ );setIsLoading(false);}diff --git a/apps/desktop/src/components/windows/Options.tsx b/apps/desktop/src/components/windows/Options.tsxindex cdbef3b0a..a4b313895 100644--- a/apps/desktop/src/components/windows/Options.tsx+++ b/apps/desktop/src/components/windows/Options.tsx@@ -4,7 +4,6 @@ import { useAuth } from "@/utils/database/AuthContext";export const Options = () => {const { session, userRef } = useAuth();-const currentUser = userRef.current;if (currentUser) {diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsxindex 2a353732e..a86d3c643 100644--- a/apps/desktop/src/components/windows/inner/Recorder.tsx+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx@@ -9,11 +9,14 @@ import { emit } from "@tauri-apps/api/event";import { showMenu } from "tauri-plugin-context-menu";import { invoke } from "@tauri-apps/api/tauri";import { Countdown } from "./Countdown";-import { appWindow, WebviewWindow } from "@tauri-apps/api/window";+// import { appWindow, WebviewWindow } from "@tauri-apps/api/window";import { AuthSession } from "@supabase/supabase-js";import { supabase } from "@/utils/database/client";import type { Database } from "@cap/utils";-import { getVideoSettings } from "@/utils/helpers";+// import { getVideoSettings } from "@/utils/helpers";+import { useAudioRecorder } from "@/utils/recording/useAudioRecorder";+import { getSelectedVideoProperties } from "@/utils/recording/utils";+import { getLatestVideoId, saveLatestVideoId } from "@/utils/database/utils";export const Recorder = ({ session }: { session: AuthSession | null }) => {const {@@ -24,6 +27,7 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {setIsRecording,} = useMediaDevices();const [countdownActive, setCountdownActive] = useState(false);+ const { startAudioRecording, stopAudioRecording } = useAudioRecorder();const handleContextClick = async (option: string) => {const filteredDevices = devices@@ -60,8 +64,8 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {};const handleOverlayFinished = () => {- appWindow.minimize();- WebviewWindow.getByLabel("camera")?.minimize();+ // appWindow.minimize();+ // WebviewWindow.getByLabel("camera")?.minimize();setIsRecording(true);setCountdownActive(false);};@@ -71,15 +75,37 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {};const handleStopAllRecordings = async () => {- await invoke("stop_screen_recording");+ const recordedAudioFilePath = await stopAudioRecording();+ if (recordedAudioFilePath) {+ try {+ await invoke("upload_file", {+ options: {+ user_id: session?.user?.id,+ video_id: await getLatestVideoId(),+ screen_index: "",+ video_index: "",+ aws_region: import.meta.env.VITE_AWS_REGION,+ aws_bucket: import.meta.env.VITE_AWS_BUCKET,+ framerate: "",+ resolution: "",+ },+ filePath: recordedAudioFilePath,+ fileType: "audio",+ });+ } catch (error) {+ console.error("Error invoking upload_file:", error);+ }+ } else {+ console.error("Audio file path string is not available.");+ }setIsRecording(false);+ setCountdownActive(false);};useEffect(() => {const startRecording = async () => {if (isRecording) {- const mediaSettings = await getVideoSettings(selectedVideoDevice);-+ const mediaSettings = await getSelectedVideoProperties();const {data: videoData,error: videoError,@@ -96,16 +122,17 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {.select().single();- console.log("session:");- console.log(session?.user?.id);- console.log("import.meta.env.VITE_AWS_REGION:");- console.log(import.meta.env.VITE_AWS_REGION);- console.log("import.meta.env.VITE_AWS_BUCKET:");- console.log(import.meta.env.VITE_AWS_BUCKET);- console.log("videoData:");- console.log(videoData);- console.log("videoError:");- console.log(videoError);+ if (session?.user?.id === undefined) {+ console.error("session.user.id is undefined");+ setIsRecording(false);+ return;+ }++ if (videoError) {+ console.error("videoError:", videoError);+ setIsRecording(false);+ return;+ }if (videoData === null) {console.error("videoData is null");@@ -113,13 +140,18 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {return;}+ await saveLatestVideoId(videoData.id);+ await startAudioRecording(selectedAudioDevice);++ console.log("mediaSettings:", mediaSettings);+ console.log("videoData:", videoData);+if (- videoData &&videoData.id &&mediaSettings?.resolution &&mediaSettings?.framerate) {- invoke("start_dual_recording", {+ await invoke("start_dual_recording", {options: {user_id: session?.user?.id,video_id: videoData.id,@@ -127,7 +159,6 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {aws_bucket: videoData.aws_bucket,screen_index: "Capture screen 0",video_index: String(selectedVideoDevice?.index),- audio_index: String(selectedAudioDevice?.index),...mediaSettings,},}).catch((error) => {diff --git a/apps/desktop/src/utils/database/utils.ts b/apps/desktop/src/utils/database/utils.tsnew file mode 100644index 000000000..8d5ec0f20--- /dev/null+++ b/apps/desktop/src/utils/database/utils.ts@@ -0,0 +1,11 @@+export const saveLatestVideoId = async (videoId: string) => {+ try {+ window.localStorage.setItem("latestVideoId", videoId);+ } catch (error) {+ console.error(error);+ }+};++export const getLatestVideoId = async () => {+ return window.localStorage.getItem("latestVideoId") || "";+};diff --git a/apps/desktop/src/utils/helpers.ts b/apps/desktop/src/utils/helpers.tsindex 26c4f748a..1c3f66008 100644--- a/apps/desktop/src/utils/helpers.ts+++ b/apps/desktop/src/utils/helpers.ts@@ -65,16 +65,11 @@ export function concatenateTypedArrays(export const getVideoSettings = async (videoDevice: MediaDeviceContextData["selectedVideoDevice"]) => {- console.log("getVideoSettings Video Device:");- console.log(videoDevice);-if (!videoDevice) {return Promise.reject("Video device not selected");}try {- await requestMediaDevicesPermission();-const devices = await navigator.mediaDevices.enumerateDevices();const videoDevices = devices.filter((device) => device.kind === "videoinput"diff --git a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx b/apps/desktop/src/utils/recording/MediaDeviceContext.tsxindex b5b8e04e7..87cb40577 100644--- a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx+++ b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx@@ -7,6 +7,7 @@ import {} from "react";import { listen } from "@tauri-apps/api/event";import { invoke } from "@tauri-apps/api/tauri";+import { getLocalDevices, enumerateAndStoreDevices } from "./utils";interface Devices {index: number;@@ -46,13 +47,13 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({const getDevices = useCallback(async () => {console.log("getDevices called");+ await enumerateAndStoreDevices();try {const deviceList = (await invoke("list_devices")) as DeviceList;- const { video_devices, audio_devices } = deviceList;+ const { video_devices } = deviceList;- console.log("deviceList:");- console.log(deviceList);+ const { audioDevices } = await getLocalDevices();const formattedDevices = [...(video_devices.map((device, index) => ({@@ -60,12 +61,13 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({label: device,kind: "videoinput",})) as Devices[]),- ...(audio_devices.map((device, index) => ({+ ...(audioDevices.map((device: MediaDeviceInfo, index: number) => ({index: index,- label: device,+ label: device.label,kind: "audioinput",})) as Devices[]),];+setDevices(formattedDevices);// Automatically select the first available devices if not already selected@@ -112,8 +114,6 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({}if (payload.type === "audio") {- console.log("receiving audio payload:");- console.log(payload);if (selectedAudioDevice?.index !== payload.device.index) {setSelectedAudioDevice(payload.device);}diff --git a/apps/desktop/src/utils/recording/useAudioRecorder.ts b/apps/desktop/src/utils/recording/useAudioRecorder.tsnew file mode 100644index 000000000..3c77fbbe9--- /dev/null+++ b/apps/desktop/src/utils/recording/useAudioRecorder.ts@@ -0,0 +1,107 @@+import { useState, useRef } from "react";+import { appDataDir, join } from "@tauri-apps/api/path";+import { writeBinaryFile } from "@tauri-apps/api/fs";+import { MediaDeviceContextData } from "@/utils/recording/MediaDeviceContext";+import { getLocalDevices } from "@/utils/recording/utils";++export const useAudioRecorder = () => {+ const [isRecordingAudio, setIsRecordingAudio] = useState(false);+ const mediaRecorder = useRef<MediaRecorder | null>(null);+ const audioChunks = useRef<BlobPart[]>([]);++ const startAudioRecording = async (+ selectedAudioDevice: MediaDeviceContextData["selectedAudioDevice"]+ ) => {+ if (!selectedAudioDevice) {+ console.error("No audio device selected");+ throw new Error("No audio device selected");+ }++ const { audioDevices } = await getLocalDevices();+ const audioDeviceInfo = audioDevices.find(+ (device) =>+ device.kind === "audioinput" &&+ device.label === selectedAudioDevice.label+ );++ if (!audioDeviceInfo) {+ throw new Error("Cannot find audio device info");+ }++ const audioStream = await navigator.mediaDevices.getUserMedia({+ audio: { deviceId: audioDeviceInfo.deviceId },+ });++ mediaRecorder.current = new MediaRecorder(audioStream);++ if (mediaRecorder.current === null) {+ console.error("mediaRecorder is null.");+ return;+ }++ mediaRecorder.current.start();+ setIsRecordingAudio(true);++ mediaRecorder.current.ondataavailable = (event) => {+ audioChunks.current.push(event.data);+ };++ mediaRecorder.current.onerror = (event: any) => {+ console.error("Recording error:", event.error);+ setIsRecordingAudio(false);+ };+ };++ const stopAudioRecording = () => {+ return new Promise<string>((resolve, reject) => {+ if (mediaRecorder.current && isRecordingAudio) {+ mediaRecorder.current.stop();++ // Event handler for when recording stops+ mediaRecorder.current.onstop = async () => {+ try {+ const audioBlob = new Blob(audioChunks.current, {+ type: "audio/mp3",+ });+ const buffer = await audioBlob.arrayBuffer();+ const dir = await appDataDir();+ const filePath = await join(+ dir,+ `cap_audio_${new Date().toISOString()}.mp3`+ );++ await writeBinaryFile({+ path: filePath,+ contents: new Uint8Array(buffer),+ });+ audioChunks.current = []; // Clear audio chunks+ setIsRecordingAudio(false); // Update the recording state++ // Resolve the promise with the file path+ resolve(filePath);+ } catch (error) {+ console.error("Error writing audio file:", error);+ reject(error);+ }+ };++ // Event handler for errors+ mediaRecorder.current.onerror = (event: any) => {+ console.error("Recording error:", event.error);+ reject(event.error);+ };+ } else {+ console.error(+ "stopAudioRecording was called but the mediaRecorder is not recording"+ );+ reject(new Error("MediaRecorder is not recording."));+ }+ });+ };++ return {+ isRecordingAudio,+ startAudioRecording,+ stopAudioRecording,+ };+};diff --git a/apps/desktop/src/utils/recording/utils.ts b/apps/desktop/src/utils/recording/utils.tsnew file mode 100644index 000000000..16ff6edca--- /dev/null+++ b/apps/desktop/src/utils/recording/utils.ts@@ -0,0 +1,26 @@+export const enumerateAndStoreDevices = async () => {+ await navigator.mediaDevices.getUserMedia({ audio: true });+ const devices = await navigator.mediaDevices.enumerateDevices();++ const audioDevices = devices.filter((device) => device.kind === "audioinput");++ window.localStorage.setItem("audioDevices", JSON.stringify(audioDevices));+};++export const getLocalDevices = async () => {+ const audioDevices = JSON.parse(+ window.localStorage.getItem("audioDevices") || "[]"+ ) as MediaDeviceInfo[];++ console.log("audioDevices:", audioDevices);++ return { audioDevices };+};++export const getSelectedVideoProperties = async () => {+ const videoDeviceProperties = JSON.parse(+ window.localStorage.getItem("videoDeviceProperties") || "{}"+ );++ return videoDeviceProperties;+};