Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Save webcam recording

Richie McIlroy58a50039e760
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index c649624d4..ac7246514 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -13,7 +13,7 @@ edition = "2021"
tauri-build = { version = "1.5.0", features = [] }
[dependencies]
-tauri = { version = "1.5.0", features = [ "window-set-ignore-cursor-events", "macos-private-api", "window-unminimize", "window-minimize", "window-close", "window-show", "window-start-dragging", "window-hide", "window-unmaximize", "window-maximize", "window-set-always-on-top", "shell-open"] }
+tauri = { version = "1.5.0", features = [ "fs-write-file", "fs-remove-file", "fs-read-file", "fs-rename-file", "fs-exists", "fs-remove-dir", "fs-read-dir", "fs-copy-file", "fs-create-dir", "window-set-ignore-cursor-events", "macos-private-api", "window-unminimize", "window-minimize", "window-close", "window-show", "window-start-dragging", "window-hide", "window-unmaximize", "window-maximize", "window-set-always-on-top", "shell-open"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tauri-plugin-context-menu = "0.5.0"
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 67ca0c223..95562fee1 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -15,9 +15,8 @@ mod recorder;
use recorder::ScreenRecorder;
#[tauri::command]
-fn start_video_recording(window: Window, recorder: tauri::State<'_, Arc<Mutex<ScreenRecorder>>>) {
+fn start_screen_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.");
@@ -29,9 +28,11 @@ fn start_video_recording(window: Window, recorder: tauri::State<'_, Arc<Mutex<Sc
#[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();
+fn stop_screen_recording(recorder: tauri::State<'_, Arc<Mutex<ScreenRecorder>>>) {
+ let recorder = recorder.lock().expect("Failed to lock recorder.");
+ if let Err(e) = recorder.stop_recording() {
+ eprintln!("Failed to stop recording: {}", e);
+ }
}
fn main() {
@@ -88,9 +89,10 @@ fn main() {
Ok(())
})
.invoke_handler(tauri::generate_handler![
- start_video_recording,
- stop_video_recording
+ start_screen_recording,
+ stop_screen_recording
])
+ .plugin(tauri_plugin_context_menu::init())
.run(tauri::generate_context!())
.expect("Error while running tauri application");
}
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/recorder.rs b/apps/desktop/src-tauri/src/recorder.rs
index fe10d8eb4..6b7b57ba9 100644
--- a/apps/desktop/src-tauri/src/recorder.rs
+++ b/apps/desktop/src-tauri/src/recorder.rs
@@ -6,9 +6,7 @@ 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 {
@@ -26,12 +24,6 @@ pub struct ScreenRecorder {
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 {
@@ -55,10 +47,8 @@ impl ScreenRecorder {
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 framerate = 30;
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);
@@ -67,12 +57,16 @@ impl ScreenRecorder {
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.
+ drop(state_guard);
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");
+ // Delete the existing recording file if it exists
+ if output_path.exists() {
+ fs::remove_file(&output_path).map_err(|e| format!("Failed to delete existing recording file: {}", e))?;
+ }
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);
@@ -80,18 +74,18 @@ impl ScreenRecorder {
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
+ "-f", "rawvideo",
+ "-pix_fmt", "bgra",
+ "-video_size", &format!("{}x{}", w, adjusted_height),
+ "-framerate", &framerate.to_string(),
+ "-i", "-",
+ "-c:v", "libx264",
+ "-preset", "veryfast",
+ "-crf", "18",
+ "-pix_fmt", "yuv420p",
+ "-y",
+ "-movflags", "+faststart",
+ output_path_str,
])
.stdin(Stdio::piped())
.spawn()
@@ -103,14 +97,9 @@ impl ScreenRecorder {
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) {
@@ -126,12 +115,9 @@ impl ScreenRecorder {
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;
@@ -142,7 +128,6 @@ impl ScreenRecorder {
}
}
- // 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;
@@ -153,8 +138,6 @@ impl ScreenRecorder {
}
};
-
- // 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 {
@@ -186,34 +169,44 @@ impl ScreenRecorder {
}
- pub fn stop_recording(&self) {
+ pub fn stop_recording(&self) -> Result<(), String> {
println!("Stop recording requested.");
-
+
+ // Check if recording is in progress or stopping
+ {
+ let state_guard = self.state.lock().map_err(|_| "Failed to acquire state lock".to_string())?;
+ if *state_guard == RecordingState::Idle {
+ println!("Recording is not in progress.");
+ return Ok(());
+ }
+ }
+
// 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;
+ // Wait for the recording thread to finish
+ {
+ let mut handle = self.ffmpeg_handle.lock().map_err(|_| "Failed to acquire ffmpeg_handle lock".to_string())?;
+ if let Some(ffmpeg_handle) = handle.take() {
+ // Join the ffmpeg thread
+ 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."),
+ }
}
- };
-
- 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.");
}
+ // Reset the state to `Idle`
+ let mut state_guard = self.state.lock().map_err(|_| "Failed to acquire state lock".to_string())?;
+ *state_guard = RecordingState::Idle;
+
// Lastly, reset the should_stop flag for potential next recording.
self.should_stop.store(false, Ordering::SeqCst);
+
+ Ok(())
}
+
}
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index 8d5abad29..3cb937ce8 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -29,6 +29,19 @@
"startDragging": true,
"setAlwaysOnTop": true,
"setIgnoreCursorEvents": true
+ },
+ "fs": {
+ "scope": ["**"],
+ "all": false,
+ "readFile": true,
+ "writeFile": true,
+ "readDir": true,
+ "copyFile": true,
+ "createDir": true,
+ "removeDir": true,
+ "removeFile": true,
+ "renameFile": true,
+ "exists": true
}
},
diff --git a/apps/desktop/src/components/FloatingOptions.tsx b/apps/desktop/src/components/FloatingOptions.tsx
index af6358174..f8cf95afb 100644
--- a/apps/desktop/src/components/FloatingOptions.tsx
+++ b/apps/desktop/src/components/FloatingOptions.tsx
@@ -1,13 +1,8 @@
-import { useEffect, useState } from "react";
-import {
- ReactMediaRecorder,
- // useDisplayRecorder,
-} from "@/utils/recording/client";
+import { useEffect } from "react";
+import { ReactMediaRecorder } from "@/utils/recording/client";
import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";
import { Video } from "@/components/icons/Video";
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 { Logo } from "@/components/icons/Logo";
@@ -15,100 +10,16 @@ import { emit } from "@tauri-apps/api/event";
import { showMenu } from "tauri-plugin-context-menu";
import { invoke } from "@tauri-apps/api/tauri";
-// type DisplayType = {
-// label: string;
-// track: MediaStreamTrack;
-// type: string;
-// } | null;
-
export const FloatingOptions = () => {
- const [foundDevices, setFoundDevices] = useState<MediaDeviceInfo[]>([]);
- const { selectedVideoDevice, selectedAudioDevice } = useMediaDevices();
+ const { devices, selectedVideoDevice, selectedAudioDevice, getDevices } =
+ useMediaDevices();
useEffect(() => {
- const fetchAndEmitDevices = async () => {
- try {
- const stream = await navigator.mediaDevices.getUserMedia({
- audio: true,
- video: true,
- });
-
- stream.getTracks().forEach((track) => track.stop());
-
- const devices = await navigator.mediaDevices.enumerateDevices();
- const filteredDevices = devices.filter(
- (device) =>
- device.kind === "audioinput" || device.kind === "videoinput"
- );
-
- setFoundDevices(filteredDevices);
-
- if (selectedVideoDevice === null) {
- const videoDevice = filteredDevices.find(
- (device) => device.kind === "videoinput"
- );
-
- if (videoDevice) {
- console.log("emitting video");
-
- await emit("change-device", {
- type: "video",
- device: videoDevice,
- });
- }
- }
-
- if (selectedAudioDevice === null) {
- const audioDevice = filteredDevices.find(
- (device) => device.kind === "audioinput"
- );
-
- if (audioDevice) {
- console.log("emitting audio");
-
- await emit("change-device", {
- type: "audio",
- device: audioDevice,
- });
- }
- }
- } catch (error) {
- console.error("Couldn't fetch devices", error);
- }
- };
-
- fetchAndEmitDevices();
- }, []);
-
- // // Helper function to handle "Screen" or "Window" selection
- // const selectScreenOrWindow = async (sourceType: string) => {
- // try {
- // // Use the getDisplayMedia API for screen capture options
- // const stream = (await navigator.mediaDevices.getDisplayMedia({
- // video: {
- // displaySurface: "monitor",
- // },
- // audio: false,
- // })) as MediaStream;
-
- // if (stream.getVideoTracks().length === 0) {
- // return;
- // }
- // // Now you should have access to the id, label and other properties of the chosen screen or window
- // const track = stream.getVideoTracks()[0];
- // const label = track ? track.label : "No Label";
-
- // // After selection, save it in the state
- // setSelectedDisplay({ label, track, type: sourceType });
-
- // // stream.getTracks().forEach((t) => t.stop()); // Stop the stream if you don't need it running
- // } catch (error) {
- // console.error("Failed to select screen or window:", error);
- // }
- // };
+ getDevices();
+ }, [getDevices]);
const handleContextClick = async (option: string) => {
- const filteredDevices = foundDevices
+ const filteredDevices = devices
.filter((device) =>
option === "video"
? device.kind === "videoinput"
@@ -156,15 +67,13 @@ export const FloatingOptions = () => {
}
render={({ status, startRecording, stopRecording }) => {
const handleStartAllRecordings = async () => {
- startRecording(); // Starts webcam recording
- await invoke("start_video_recording");
+ startRecording();
+ await invoke("start_screen_recording");
};
- // Similarly, for stopping all recordings
const handleStopAllRecordings = async () => {
- stopRecording(); // Stops webcam recording
- await invoke("stop_video_recording");
- // stopDisplayRecording(); // Stops display recording
+ stopRecording();
+ await invoke("stop_screen_recording");
};
return (
@@ -181,39 +90,8 @@ export const FloatingOptions = () => {
<div>
<Logo className="w-24 h-auto" />
</div>
- {/* <div>
- <button>
- <Settings className="w-5 h-5 text-black" />
- </button>
- </div> */}
</div>
<div className="space-y-4 w-full">
- {/* <div>
- <label className="text-sm font-medium">
- Display Settings
- </label>
-
- <div className="flex items-center space-x-1">
- <ActionButton
- handler={() => handleContextClick("screen")}
- icon={<Screen className="w-5 h-5" />}
- label={
- selectedDisplay?.type === "screen"
- ? selectedDisplay.label
- : "Screen"
- }
- />
- <ActionButton
- handler={() => handleContextClick("window")}
- icon={<Window className="w-5 h-5" />}
- label={
- selectedDisplay?.type === "window"
- ? selectedDisplay.label
- : "Window"
- }
- />
- </div>
- </div> */}
<div>
<label className="text-sm font-medium">Webcam Settings</label>
<div className="space-y-1">
diff --git a/apps/desktop/src/components/windows/Camera.tsx b/apps/desktop/src/components/windows/Camera.tsx
index ef47e8190..1e70a8a07 100644
--- a/apps/desktop/src/components/windows/Camera.tsx
+++ b/apps/desktop/src/components/windows/Camera.tsx
@@ -9,24 +9,16 @@ export const Camera = () => {
const { selectedVideoDevice } = useMediaDevices();
setWindowPosition("bottom_right");
- console.log("selected video2:");
- console.log(selectedVideoDevice);
-
return (
<div className="w-full h-full">
<ReactMediaRecorder
- audio={true}
video={
selectedVideoDevice
? { deviceId: selectedVideoDevice.deviceId }
: true
}
render={({ previewStream }) => {
- console.log("previewStream:");
- console.log(previewStream);
if (videoRef.current) {
- console.log("video ref:");
- console.log(videoRef.current.srcObject);
videoRef.current.srcObject = previewStream || null;
}
diff --git a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
index ca902c232..329841c89 100644
--- a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
+++ b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
@@ -1,4 +1,10 @@
-import { useState, createContext, useContext, useEffect } from "react";
+import {
+ useState,
+ createContext,
+ useContext,
+ useEffect,
+ useCallback,
+} from "react";
import { listen } from "@tauri-apps/api/event";
import { DeviceChangePayload } from "@/utils/types/shared";
@@ -12,6 +18,8 @@ interface MediaDeviceContextData {
setSelectedAudioDevice: React.Dispatch<
React.SetStateAction<MediaDeviceInfo | null>
>;
+ devices: MediaDeviceInfo[];
+ getDevices: () => Promise<void>;
}
export const MediaDeviceContext = createContext<
@@ -25,41 +33,32 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
useState<MediaDeviceInfo | null>(null);
const [selectedAudioDevice, setSelectedAudioDevice] =
useState<MediaDeviceInfo | null>(null);
+ const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
+
+ const getDevices = useCallback(async () => {
+ const fetchedDevices = await navigator.mediaDevices.enumerateDevices();
+ setDevices(fetchedDevices);
+
+ // Automatically select the first available devices if not already selected
+ if (!selectedVideoDevice) {
+ const videoInput = fetchedDevices.find(
+ (device) => device.kind === "videoinput"
+ );
+ setSelectedVideoDevice(videoInput || null);
+ }
+ if (!selectedAudioDevice) {
+ const audioInput = fetchedDevices.find(
+ (device) => device.kind === "audioinput"
+ );
+ setSelectedAudioDevice(audioInput || null);
+ }
+ }, [selectedVideoDevice, selectedAudioDevice]);
- // useEffect(() => {
- // const passVideoDeviceState = async () => {
- // try {
- // if (selectedVideoDevice === null) return;
- // await emit("change-device", {
- // type: "video",
- // device: selectedVideoDevice,
- // });
- // } catch (error) {
- // console.error("Error emitting event:", error);
- // }
- // };
-
- // passVideoDeviceState();
- // }, [selectedVideoDevice]);
-
- // useEffect(() => {
- // const passAudioDeviceState = async () => {
- // try {
- // if (selectedAudioDevice === null) return;
- // await emit("change-device", {
- // type: "audio",
- // device: selectedAudioDevice,
- // });
- // } catch (error) {
- // console.error("Error emitting event:", error);
- // }
- // };
-
- // passAudioDeviceState();
- // }, [selectedAudioDevice]);
+ useEffect(() => {
+ getDevices();
+ }, [getDevices]);
useEffect(() => {
- // Initialize the event listener
let unlistenFn: any;
const setupListener = async () => {
@@ -93,13 +92,12 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
setupListener();
- // Cleanup function to unlisten when the component unmounts
return () => {
if (unlistenFn) {
unlistenFn();
}
};
- }, []);
+ }, [selectedVideoDevice, selectedAudioDevice]);
return (
<MediaDeviceContext.Provider
@@ -108,6 +106,8 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
setSelectedVideoDevice,
selectedAudioDevice,
setSelectedAudioDevice,
+ devices,
+ getDevices,
}}
>
{children}
diff --git a/apps/desktop/src/utils/recording/client.ts b/apps/desktop/src/utils/recording/client.ts
index 44a692d24..017ebd82c 100644
--- a/apps/desktop/src/utils/recording/client.ts
+++ b/apps/desktop/src/utils/recording/client.ts
@@ -7,6 +7,8 @@ import { ReactElement, useCallback, useEffect, useRef, useState } from "react";
import { connect } from "extendable-media-recorder-wav-encoder";
import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";
import { useDidMountEffect } from "@/utils/hooks/useDidMount";
+import { writeBinaryFile, createDir } from "@tauri-apps/api/fs";
+import { appDataDir } from "@tauri-apps/api/path";
export type ReactMediaRecorderRenderProps = {
error: string;
@@ -156,7 +158,9 @@ export function useReactMediaRecorder({
}, [audio, video, screen]);
useEffect(() => {
- getMediaStream();
+ if (selectedVideoDevice || selectedAudioDevice || !customMediaStream) {
+ getMediaStream();
+ }
}, [selectedVideoDevice, selectedAudioDevice]);
useEffect(() => {
@@ -264,17 +268,39 @@ export function useReactMediaRecorder({
onStart();
};
- const onRecordingStop = () => {
+ const onRecordingStop = async () => {
+ console.log("onRecordingStop started");
const [chunk] = mediaChunks.current;
const blobProperty: BlobPropertyBag = Object.assign(
{ type: chunk.type },
- blobPropertyBag || (video ? { type: "video/mp4" } : { type: "audio/wav" })
+ blobPropertyBag || { type: "video/mp4" }
);
const blob = new Blob(mediaChunks.current, blobProperty);
- const url = URL.createObjectURL(blob);
- setStatus("stopped");
- setMediaBlobUrl(url);
- onStop(url, blob);
+ const buffer = await blob.arrayBuffer();
+ const data = new Uint8Array(buffer);
+
+ try {
+ // Get the app's data directory path
+ const dir = await appDataDir();
+ const filePath = `${dir}/recording.mp4`.replace(/\/\//g, "/");
+
+ console.log("Saving recording to:", filePath);
+
+ // Ensure the directory exists
+ await createDir(dir, { recursive: true });
+
+ // Write the file
+ await writeBinaryFile(filePath, data);
+ console.log("Recording saved successfully to:", filePath);
+
+ // Generate a Blob URL for preview or download
+ const url = URL.createObjectURL(blob);
+ setStatus("stopped");
+ setMediaBlobUrl(url);
+ onStop(url, blob);
+ } catch (error) {
+ console.error("Failed to save recording:", error);
+ }
};
const muteAudio = (mute: boolean) => {
@@ -340,112 +366,5 @@ export function useReactMediaRecorder({
};
}
-export const useDisplayRecorder = (
- screenStream: MediaStream | null,
- onStop?: (blobUrl: string, blob: Blob) => void
-) => {
- const mediaRecorder = useRef<MediaRecorder | null>(null);
- const mediaChunks = useRef<Blob[]>([]);
- const [status, setStatus] = useState<"idle" | "recording" | "stopped">(
- "idle"
- );
- const [screenBlobUrl, setScreenBlobUrl] = useState<string | undefined>(
- undefined
- );
- const [error, setError] = useState<string>("");
- const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9")
- ? "video/webm; codecs=vp9"
- : "video/mp4";
-
- const startRecording = useCallback(() => {
- if (status !== "idle" || !screenStream) return;
-
- try {
- mediaRecorder.current = new MediaRecorder(screenStream, {
- mimeType: mime,
- });
-
- mediaRecorder.current.ondataavailable = (event) => {
- console.log("new event: ", event);
- if (event.data.size > 0) {
- mediaChunks.current.push(event.data);
- }
- };
-
- mediaRecorder.current.onstart = () => {
- console.log("recording started");
- };
-
- mediaRecorder.current.onstop = () => {
- const blob = new Blob(mediaChunks.current, { type: mime });
- const url = URL.createObjectURL(blob);
- setScreenBlobUrl(url);
- setStatus("stopped");
- if (onStop) onStop(url, blob);
- };
-
- mediaRecorder.current.onerror = (event: any) => {
- console.log("recording error2: ", event);
- setError("Error during recording: " + event.error.name);
- setStatus("idle");
- };
-
- mediaRecorder.current.start();
- setStatus("recording");
- } catch (err) {
- console.log("recording error: ", err);
- setError("Failed to start recording: " + (err as Error).message);
- setStatus("idle");
- }
- }, [screenStream, status, onStop]);
-
- const stopRecording = useCallback(() => {
- if (status === "recording" && mediaRecorder.current) {
- mediaRecorder.current.stop();
- }
- }, [status]);
-
- const clearBlobUrl = useCallback(() => {
- if (screenBlobUrl) {
- URL.revokeObjectURL(screenBlobUrl);
- setScreenBlobUrl(undefined);
- }
- }, [screenBlobUrl]);
-
- // Make sure to clean up media resources when the component using this hook gets unmounted
- useEffect(() => {
- return () => {
- clearBlobUrl();
- if (mediaRecorder.current && mediaRecorder.current.state !== "inactive") {
- mediaRecorder.current.stop();
- }
- if (
- !mediaRecorder.current ||
- mediaRecorder.current.state === "inactive"
- ) {
- screenStream?.getTracks().forEach((track) => track.stop());
- }
- mediaChunks.current = [];
- mediaRecorder.current = null;
- };
- }, [clearBlobUrl, screenStream]);
-
- console.log("status", status);
- console.log("error", error);
- console.log("screenBlobUrl", screenBlobUrl);
- console.log("mediaChunks", mediaChunks.current);
- console.log(screenStream?.getTracks());
- console.log(mediaRecorder.current);
-
- return {
- startRecording,
- stopRecording,
- clearBlobUrl,
- screenBlobUrl,
- status,
- error,
- };
-};
-
export const ReactMediaRecorder = (props: ReactMediaRecorderProps) =>
props.render(useReactMediaRecorder(props));