Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fixes: Multiple video/audio sync fixes

Richie McIlroy2bca990dc401
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock
index 9a8b8d473..a7dcfc39b 100644
--- a/apps/desktop/src-tauri/Cargo.lock
+++ b/apps/desktop/src-tauri/Cargo.lock
@@ -450,6 +450,8 @@ dependencies = [
name = "cap"
version = "0.0.0"
dependencies = [
+ "chrono",
+ "dotenv_codegen",
"ffmpeg-sidecar",
"futures",
"reqwest",
@@ -537,8 +539,10 @@ checksum = "9f13690e35a5e4ace198e7beea2895d29f3a9cc55015fcebe6336bd2010af9eb"
dependencies = [
"android-tzdata",
"iana-time-zone",
+ "js-sys",
"num-traits",
"serde",
+ "wasm-bindgen",
"windows-targets 0.52.0",
]
@@ -915,6 +919,35 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"
+[[package]]
+name = "dotenv"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f"
+
+[[package]]
+name = "dotenv_codegen"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56966279c10e4f8ee8c22123a15ed74e7c8150b658b26c619c53f4a56eb4a8aa"
+dependencies = [
+ "dotenv_codegen_implementation",
+ "proc-macro-hack",
+]
+
+[[package]]
+name = "dotenv_codegen_implementation"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53e737a3522cd45f6adc19b644ce43ef53e1e9045f2d2de425c1f468abd4cf33"
+dependencies = [
+ "dotenv",
+ "proc-macro-hack",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "dtoa"
version = "1.0.9"
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index d5c038789..5e3cf672b 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -28,6 +28,8 @@ tauri-plugin-oauth = { git = "https://github.com/FabianLars/tauri-plugin-oauth",
tauri-plugin-deep-link = { git = "https://github.com/FabianLars/tauri-plugin-deep-link", branch = "main" }
window-vibrancy = "0.4.3"
window-shadows = "0.2.2"
+chrono = "0.4.33"
+dotenv_codegen = "0.15.0"
[features]
# this feature is used for production builds or when `devPath` points to the filesystem
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 47da29cce..27b08b328 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -9,6 +9,9 @@ use tokio::sync::{Semaphore, Mutex};
use tokio::task::JoinHandle;
use tokio::time::{timeout, Duration};
use serde::{Serialize, Deserialize};
+use std::env;
+use chrono::Utc;
+use reqwest::Client;
use tauri::State;
use crate::utils::ffmpeg_path_as_str;
@@ -54,11 +57,9 @@ pub async fn start_dual_recording(
println!("data_dir: {:?}", data_dir);
let screen_chunks_dir = data_dir.join("chunks/screen");
- let video_chunks_dir = data_dir.join("chunks/video");
let audio_chunks_dir = data_dir.join("chunks/audio");
clean_and_create_dir(&screen_chunks_dir)?;
- clean_and_create_dir(&video_chunks_dir)?;
clean_and_create_dir(&audio_chunks_dir)?;
let ffmpeg_screen_args_future = construct_recording_args(&options, &screen_chunks_dir, "screen", &options.screen_index);
@@ -122,6 +123,12 @@ 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()));
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ let server_url_base: &'static str = dotenv_codegen::dotenv!("NEXT_PUBLIC_URL");
+ if let Err(e) = send_metadata_api(&options.video_id, &server_url_base).await {
+ eprintln!("Failed to send metadata API request: {}", e);
+ }
+
let ffmpeg_binary_path_clone = ffmpeg_binary_path_str.clone();
let ffmpeg_screen_screenshot_args_clone = ffmpeg_screen_screenshot_args.clone();
@@ -147,12 +154,10 @@ pub async fn start_dual_recording(
println!("Starting upload loops...");
- let audio_chunks_dir_arc = Some(Arc::new(audio_chunks_dir));
-
- let screen_upload = start_upload_loop(state.clone(), screen_chunks_dir, None, options.clone(), "screen".to_string(), shutdown_flag.clone());
- let video_upload = start_upload_loop(state.clone(), video_chunks_dir, audio_chunks_dir_arc, options.clone(), "video".to_string(), shutdown_flag.clone());
+ let screen_upload = start_upload_loop(state.clone(), screen_chunks_dir, options.clone(), "screen".to_string(), shutdown_flag.clone());
+ let audio_upload = start_upload_loop(state.clone(), audio_chunks_dir, options.clone(), "audio".to_string(), shutdown_flag.clone());
- match tokio::try_join!(screen_upload, video_upload) {
+ match tokio::try_join!(screen_upload, audio_upload) {
Ok(_) => {
println!("Both upload loops completed successfully.");
},
@@ -254,135 +259,78 @@ async fn construct_recording_args(
ensure_segment_list_exists(PathBuf::from(&segment_list_filename))
.map_err(|e| format!("Failed to ensure segment list file exists: {}", e))?;
- let fps = if video_type == "screen" { "60" } else { &options.framerate };
+ let fps = if video_type == "screen" { "30" } else { &options.framerate };
let preset = "ultrafast".to_string();
let crf = "28".to_string();
- let pix_fmt = "nv12".to_string();
+ let pix_fmt = "yuv420p".to_string();
let codec = "libx264".to_string();
let gop = "30".to_string();
let segment_time = "3".to_string();
let segment_list_type = "flat".to_string();
- let input_string = format!("{}:none", input_index);
match std::env::consts::OS {
"macos" => {
- if video_type == "screen" {
- Ok(vec![
- "-f".to_string(), "avfoundation".to_string(),
- "-framerate".to_string(), fps.to_string(),
- "-i".to_string(), input_string.to_string(),
- "-c:v".to_string(), codec,
- "-preset".to_string(), preset,
- "-pix_fmt".to_string(), pix_fmt,
- "-g".to_string(), gop,
- "-r".to_string(), fps.to_string(),
- "-f".to_string(), "segment".to_string(),
- "-segment_time".to_string(), segment_time,
- "-segment_format".to_string(), "mpegts".to_string(),
- "-segment_list".to_string(), segment_list_filename,
- "-segment_list_type".to_string(), segment_list_type,
- "-reset_timestamps".to_string(), "1".to_string(),
- output_filename_pattern,
- ])
- } else {
- Ok(vec![
- "-f".to_string(), "avfoundation".to_string(),
- "-video_size".to_string(), options.resolution.to_string(),
- "-framerate".to_string(), fps.to_string(),
- "-i".to_string(), input_string.to_string(),
- "-c:v".to_string(), codec,
- "-preset".to_string(), preset,
- "-pix_fmt".to_string(), pix_fmt,
- "-g".to_string(), gop,
- "-r".to_string(), fps.to_string(),
- "-f".to_string(), "segment".to_string(),
- "-segment_time".to_string(), segment_time,
- "-segment_format".to_string(), "mpegts".to_string(),
- "-segment_list".to_string(), segment_list_filename,
- "-segment_list_type".to_string(), segment_list_type,
- "-reset_timestamps".to_string(), "1".to_string(),
- output_filename_pattern,
- ])
- }
+ Ok(vec![
+ "-f".to_string(), "avfoundation".to_string(),
+ "-framerate".to_string(), fps.to_string(),
+ "-capture_cursor".to_string(), "1".to_string(),
+ "-thread_queue_size".to_string(), "512".to_string(),
+ "-i".to_string(), format!("{}", input_index),
+ "-c:v".to_string(), codec,
+ "-preset".to_string(), preset,
+ "-pix_fmt".to_string(), pix_fmt,
+ "-g".to_string(), gop,
+ "-r".to_string(), fps.to_string(),
+ "-an".to_string(),
+ "-f".to_string(), "segment".to_string(),
+ "-segment_time".to_string(), segment_time,
+ "-segment_format".to_string(), "mpegts".to_string(),
+ "-segment_list".to_string(), segment_list_filename,
+ "-segment_list_type".to_string(), segment_list_type,
+ "-reset_timestamps".to_string(), "1".to_string(),
+ output_filename_pattern,
+ ])
},
"linux" => {
- if video_type == "screen" {
- Ok(vec![
- "-f".to_string(), "x11grab".to_string(),
- "-i".to_string(), format!("{}+0,0", input_index),
- "-draw_mouse".to_string(), "1".to_string(),
- "-pix_fmt".to_string(), pix_fmt,
- "-c:v".to_string(), codec,
- "-crf".to_string(), crf,
- "-preset".to_string(), preset,
- "-g".to_string(), gop,
- "-r".to_string(), fps.to_string(),
- "-f".to_string(), "segment".to_string(),
- "-segment_time".to_string(), segment_time,
- "-segment_format".to_string(), "mpegts".to_string(),
- "-segment_list".to_string(), segment_list_filename,
- "-segment_list_type".to_string(), segment_list_type,
- "-reset_timestamps".to_string(), "1".to_string(),
- output_filename_pattern,
- ])
- } else {
- Ok(vec![
- "-f".to_string(), "x11grab".to_string(),
- "-i".to_string(), format!("{}+0,0", input_index),
- "-pix_fmt".to_string(), pix_fmt,
- "-c:v".to_string(), codec,
- "-crf".to_string(), crf,
- "-preset".to_string(), preset,
- "-g".to_string(), gop,
- "-r".to_string(), fps.to_string(),
- "-f".to_string(), "segment".to_string(),
- "-segment_time".to_string(), segment_time,
- "-segment_format".to_string(), "mpegts".to_string(),
- "-segment_list".to_string(), segment_list_filename,
- "-segment_list_type".to_string(), segment_list_type,
- "-reset_timestamps".to_string(), "1".to_string(),
- output_filename_pattern,
- ])
- }
+ Ok(vec![
+ "-f".to_string(), "x11grab".to_string(),
+ "-i".to_string(), format!("{}+0,0", input_index),
+ "-draw_mouse".to_string(), "1".to_string(),
+ "-pix_fmt".to_string(), pix_fmt,
+ "-c:v".to_string(), codec,
+ "-crf".to_string(), crf,
+ "-preset".to_string(), preset,
+ "-g".to_string(), gop,
+ "-r".to_string(), fps.to_string(),
+ "-an".to_string(),
+ "-f".to_string(), "segment".to_string(),
+ "-segment_time".to_string(), segment_time,
+ "-segment_format".to_string(), "mpegts".to_string(),
+ "-segment_list".to_string(), segment_list_filename,
+ "-segment_list_type".to_string(), segment_list_type,
+ "-reset_timestamps".to_string(), "1".to_string(),
+ output_filename_pattern,
+ ])
},
"windows" => {
- if video_type == "screen" {
- Ok(vec![
- "-f".to_string(), "gdigrab".to_string(),
- "-i".to_string(), "desktop".to_string(),
- "-pixel_format".to_string(), pix_fmt,
- "-c:v".to_string(), codec,
- "-crf".to_string(), crf,
- "-preset".to_string(), preset,
- "-g".to_string(), gop,
- "-r".to_string(), fps.to_string(),
- "-f".to_string(), "segment".to_string(),
- "-segment_time".to_string(), segment_time,
- "-segment_format".to_string(), "mpegts".to_string(),
- "-segment_list".to_string(), segment_list_filename,
- "-segment_list_type".to_string(), segment_list_type,
- "-reset_timestamps".to_string(), "1".to_string(),
- output_filename_pattern,
- ])
- } else {
- Ok(vec![
- "-f".to_string(), "dshow".to_string(),
- "-i".to_string(), format!("video={}", input_index),
- "-pixel_format".to_string(), pix_fmt,
- "-c:v".to_string(), codec,
- "-crf".to_string(), crf,
- "-preset".to_string(), preset,
- "-g".to_string(), gop,
- "-r".to_string(), fps.to_string(),
- "-f".to_string(), "segment".to_string(),
- "-segment_time".to_string(), segment_time,
- "-segment_format".to_string(), "mpegts".to_string(),
- "-segment_list".to_string(), segment_list_filename,
- "-segment_list_type".to_string(), segment_list_type,
- "-reset_timestamps".to_string(), "1".to_string(),
- output_filename_pattern,
- ])
- }
+ Ok(vec![
+ "-f".to_string(), "gdigrab".to_string(),
+ "-i".to_string(), "desktop".to_string(),
+ "-pixel_format".to_string(), pix_fmt,
+ "-c:v".to_string(), codec,
+ "-crf".to_string(), crf,
+ "-preset".to_string(), preset,
+ "-g".to_string(), gop,
+ "-r".to_string(), fps.to_string(),
+ "-an".to_string(), // This is the argument to skip audio recording.
+ "-f".to_string(), "segment".to_string(),
+ "-segment_time".to_string(), segment_time,
+ "-segment_format".to_string(), "mpegts".to_string(),
+ "-segment_list".to_string(), segment_list_filename,
+ "-segment_list_type".to_string(), segment_list_type,
+ "-reset_timestamps".to_string(), "1".to_string(),
+ output_filename_pattern,
+ ])
},
_ => Err("Unsupported OS".to_string()),
}
@@ -391,7 +339,6 @@ async fn construct_recording_args(
async fn start_upload_loop(
state: State<'_, Arc<Mutex<RecordingState>>>,
chunks_dir: PathBuf,
- audio_chunks_dir: Option<Arc<PathBuf>>,
options: RecordingOptions,
video_type: String,
shutdown_flag: Arc<AtomicBool>,
@@ -419,26 +366,6 @@ async fn start_upload_loop(
let options_clone = options.clone();
let video_type_clone = video_type.clone();
- if let Some(audio_dir) = &audio_chunks_dir {
- let audio_dir_path: &Path = audio_dir.as_ref();
- let audio_segment_filename = segment_filename.replace(".ts", ".aac");
- let audio_segment_path = audio_dir_path.join(&audio_segment_filename);
- if audio_segment_path.exists() {
- let audio_path_str = audio_segment_path.to_str().unwrap_or_default().to_owned();
- let audio_options_clone = options_clone.clone();
- let audio_video_type_clone = video_type_clone.clone();
-
- // Schedule audio upload
- tokio::spawn(async move {
- println!("Uploading audio for {}: {}", audio_video_type_clone, audio_path_str);
- match upload_file(Some(audio_options_clone), audio_path_str, "audio".to_string()).await {
- Ok(_) => println!("Audio segment uploaded successfully."),
- Err(e) => eprintln!("Failed to upload audio segment: {}", e),
- }
- });
- }
- }
-
let handle = tokio::spawn(async move {
println!("Uploading video for {}: {}", video_type_clone, filepath_str);
@@ -525,7 +452,7 @@ async fn upload_remaining_chunks(
let tasks: Vec<_> = entries.filter_map(|entry| entry.ok())
.filter_map(|entry| {
let path = entry.path();
- if path.is_file() && (path.extension().map_or(false, |e| e == "ts" || e == "webm")) && !shutdown_flag.load(Ordering::SeqCst) {
+ if path.is_file() && (path.extension().map_or(false, |e| e == "ts" || e == "aac")) && !shutdown_flag.load(Ordering::SeqCst) {
let video_type = video_type.to_string();
let semaphore_clone = semaphore.clone();
let actual_options_clone = actual_options.clone();
@@ -645,4 +572,32 @@ async fn upload_jpeg_files(
}
Ok(())
+}
+
+async fn send_metadata_api(video_id: &str, server_url_base: &str) -> Result<(), String> {
+ let client = Client::new();
+ let video_start_time = Utc::now().timestamp_millis();
+ println!("Sending metadata API request for video {}: {}", video_id, video_start_time);
+
+ // Constructing the query parameters
+ let params = [
+ ("videoId", video_id),
+ ("videoStartTime", &video_start_time.to_string()),
+ ];
+ let server_url = format!("{}/api/desktop/video/metadata/create", server_url_base);
+
+ match client.get(&server_url)
+ .query(&params)
+ .send()
+ .await {
+ Ok(response) => {
+ if response.status().is_success() {
+ let _response_body = response.text().await.map_err(|e| e.to_string())?;
+ Ok(())
+ } else {
+ Err(format!("API call failed with status {:?}", response.status()))
+ }
+ },
+ Err(err) => Err(err.to_string()),
+ }
}
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rs
index 15f5fa88c..35b683978 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -1,6 +1,7 @@
use serde_json::Value as JsonValue;
use std::path::{Path};
use std::process::Command;
+use std::env;
use reqwest;
use crate::recording::RecordingOptions;
@@ -26,7 +27,8 @@ pub async fn upload_file(
let file_key = format!("{}/{}/{}/{}", options.user_id, options.video_id, file_type, file_name);
- let server_url = format!("http://localhost:3000/api/upload/signed");
+ let server_url_base: &'static str = dotenv_codegen::dotenv!("NEXT_PUBLIC_URL");
+ let server_url = format!("{}/api/upload/signed", server_url_base);
// Create the request body for the Next.js handler
let body = serde_json::json!({
@@ -70,6 +72,8 @@ pub async fn upload_file(
let mime_type = if file_path.to_lowercase().ends_with(".aac") {
"audio/aac"
+ } else if file_path.to_lowercase().ends_with(".webm") {
+ "audio/webm"
} else {
"video/mp2t"
};
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index caf4fad8d..1c0811be2 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -90,14 +90,14 @@
"title": "Cap",
"label": "camera",
"url": "/camera",
- "width": 200,
- "height": 200,
+ "width": 250,
+ "height": 250,
"maximized": false,
"resizable": false,
"fullscreen": false,
"transparent": true,
"decorations": false,
- "alwaysOnTop": false,
+ "alwaysOnTop": true,
"center": false,
"x": 0,
"y": 0
diff --git a/apps/desktop/src/app/camera/page.tsx b/apps/desktop/src/app/camera/page.tsx
index 79c99cdaf..f44d2f4b8 100644
--- a/apps/desktop/src/app/camera/page.tsx
+++ b/apps/desktop/src/app/camera/page.tsx
@@ -1,8 +1,10 @@
"use client";
import { Camera } from "@/components/windows/Camera";
+import { setWindowPosition } from "@/utils/helpers";
export default function CameraPage() {
+ setWindowPosition("bottom_right");
return (
<div id="app" data-tauri-drag-region style={{ borderRadius: "50%" }}>
<Camera />
diff --git a/apps/desktop/src/components/windows/Camera.tsx b/apps/desktop/src/components/windows/Camera.tsx
index c66a51a44..c0ba26a76 100644
--- a/apps/desktop/src/components/windows/Camera.tsx
+++ b/apps/desktop/src/components/windows/Camera.tsx
@@ -1,102 +1,91 @@
-import { useEffect, useRef, useState } from "react";
+// @refresh reset
+
+import React, { useEffect, useRef, useMemo, useState } from "react";
import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";
export const Camera = () => {
const videoRef = useRef<HTMLVideoElement>(null);
- const { selectedVideoDevice } = useMediaDevices();
+ const { sharedStream } = useMediaDevices();
const [isLoading, setIsLoading] = useState(true);
- useEffect(() => {
- let activeStream: MediaStream | null = null;
-
- async function setupCamera() {
- if (!videoRef.current || !selectedVideoDevice) {
- setIsLoading(false);
- return;
- }
-
- setIsLoading(true);
- try {
- const devices = await navigator.mediaDevices.enumerateDevices();
- const videoDevices = devices.filter(
- (device) => device.kind === "videoinput"
- );
- const deviceId = videoDevices[selectedVideoDevice.index].deviceId;
+ const attemptPlayback = () => {
+ const videoElement = videoRef.current;
+ if (videoElement && !videoElement.srcObject) {
+ console.log("Assigning stream to video element.");
+ videoElement.srcObject = sharedStream;
+ setIsLoading(false);
+ }
- const stream = await navigator.mediaDevices.getUserMedia({
- video: {
- deviceId: deviceId,
- frameRate: { ideal: 30 },
- width: { ideal: 1920 },
- height: { ideal: 1080 },
- },
+ if (videoElement && videoElement.paused) {
+ console.log("Attempting to play video.");
+ videoElement
+ .play()
+ .then(() => {
+ console.log("Video playback started successfully.");
+ })
+ .catch((error) => {
+ console.log(`Error attempting to play video: ${error.message}`);
});
+ }
+ };
- // Ensure videoRef.current is still not null
- if (!videoRef.current) return;
+ useEffect(() => {
+ if (sharedStream) {
+ attemptPlayback();
+ const handleTrackAdded = () => attemptPlayback();
+ const handleTrackRemoved = () => attemptPlayback();
- videoRef.current.srcObject = stream;
- videoRef.current.onplaying = () => setIsLoading(false);
- await videoRef.current.play();
+ sharedStream.addEventListener("addtrack", handleTrackAdded);
+ sharedStream.addEventListener("removetrack", handleTrackRemoved);
- // Save stream for cleanup
- activeStream = stream;
- } catch (err) {
- console.error(err);
- setIsLoading(false);
- }
+ return () => {
+ sharedStream.removeEventListener("addtrack", handleTrackAdded);
+ sharedStream.removeEventListener("removetrack", handleTrackRemoved);
+ };
}
-
- setupCamera();
-
- return () => {
- if (activeStream) {
- activeStream.getTracks().forEach((track) => track.stop());
- activeStream = null;
- }
- setIsLoading(false);
- };
- }, [selectedVideoDevice]);
+ }, [sharedStream]);
return (
<div
data-tauri-drag-region
- className="w-[200px] h-[200px] bg-gray-200 rounded-full m-0 p-0 relative overflow-hidden flex items-center justify-center"
+ className="w-[250px] h-[250px] bg-gray-200 rounded-full m-0 p-0 relative overflow-hidden flex items-center justify-center"
>
- {isLoading ? (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- stroke="#fff"
- viewBox="0 0 38 38"
- className="w-24 h-24"
- >
- <g
- fill="none"
- fillRule="evenodd"
- strokeWidth="2"
- transform="translate(1 1)"
+ {isLoading && (
+ <div className="w-full h-full absolute top-0 left-0 bg-gray-200 z-10 flex items-center justify-center">
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ stroke="#fff"
+ viewBox="0 0 38 38"
+ className="w-24 h-24"
>
- <circle cx="18" cy="18" r="18" strokeOpacity="0.4"></circle>
- <path d="M36 18c0-9.94-8.06-18-18-18">
- <animateTransform
- attributeName="transform"
- dur="1s"
- from="0 18 18"
- repeatCount="indefinite"
- to="360 18 18"
- type="rotate"
- ></animateTransform>
- </path>
- </g>
- </svg>
- ) : (
- <video
- ref={videoRef}
- autoPlay
- muted
- className="absolute top-0 left-0 w-full h-full object-cover pointer-events-none"
- />
+ <g
+ fill="none"
+ fillRule="evenodd"
+ strokeWidth="2"
+ transform="translate(1 1)"
+ >
+ <circle cx="18" cy="18" r="18" strokeOpacity="0.4"></circle>
+ <path d="M36 18c0-9.94-8.06-18-18-18">
+ <animateTransform
+ attributeName="transform"
+ dur="1s"
+ from="0 18 18"
+ repeatCount="indefinite"
+ to="360 18 18"
+ type="rotate"
+ ></animateTransform>
+ </path>
+ </g>
+ </svg>
+ </div>
)}
+ <video
+ ref={videoRef}
+ autoPlay
+ playsInline
+ muted
+ className="absolute top-0 left-0 w-full h-full object-cover pointer-events-none"
+ />
</div>
);
};
diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsx
index c045c49f9..d3a8c6e4d 100644
--- a/apps/desktop/src/components/windows/inner/Recorder.tsx
+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx
@@ -9,11 +9,10 @@ import { Window } from "@/components/icons/Window";
import { ActionButton } from "@/components/recording/ActionButton";
import { Button } from "@cap/ui";
import { Logo } from "@/components/icons/Logo";
-import { emit, listen } from "@tauri-apps/api/event";
+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 callbackTemplate from "./callbackTemplate";
import { useMediaRecorder } from "@/utils/recording/useMediaRecorder";
import { getSelectedVideoProperties } from "@/utils/recording/utils";
@@ -30,6 +29,9 @@ export const Recorder = () => {
selectedDisplayType,
isRecording,
setIsRecording,
+ startingRecording,
+ setStartingRecording,
+ sharedStream,
} = useMediaDevices();
const [countdownActive, setCountdownActive] = useState(false);
const [stoppingRecording, setStoppingRecording] = useState(false);
@@ -75,6 +77,7 @@ export const Recorder = () => {
// appWindow.hide();
// WebviewWindow.getByLabel("camera")?.hide();
setIsRecording(true);
+ setStartingRecording(false);
setCountdownActive(false);
};
@@ -83,6 +86,7 @@ export const Recorder = () => {
`${process.env.NEXT_PUBLIC_URL}/api/desktop/video/create`,
{
credentials: "include",
+ cache: "no-store",
}
);
@@ -111,7 +115,6 @@ export const Recorder = () => {
aws_region: string;
aws_bucket: string;
}) => {
- // Extracted from the useEffect hook; this starts the video recording
console.log("Starting dual recording...");
const mediaSettings = await getSelectedVideoProperties();
if (mediaSettings?.resolution && mediaSettings?.framerate) {
@@ -136,15 +139,13 @@ export const Recorder = () => {
const handleStartAllRecordings = async () => {
try {
const videoData = await prepareVideoData();
- if (videoData) {
- setIsRecording(true);
- const stream = await navigator.mediaDevices.getUserMedia({
- audio: { deviceId: selectedAudioDevice?.deviceId },
- video: { deviceId: selectedVideoDevice?.deviceId },
- });
+ console.log("Video data:", videoData);
+ console.log("Shared stream:", sharedStream);
+ if (videoData && sharedStream) {
+ setStartingRecording(true);
setCountdownActive(true);
await Promise.all([
- startMediaRecording(stream),
+ startMediaRecording(sharedStream),
startDualRecording(videoData),
]);
} else {
@@ -161,14 +162,32 @@ export const Recorder = () => {
try {
console.log("Stopping recordings...");
-
- await new Promise((resolve) => setTimeout(resolve, 3500));
+ const videoId = await getLatestVideoId();
+ const queryParams = new URLSearchParams({
+ videoId,
+ }).toString();
+ const res = await fetch(
+ `${process.env.NEXT_PUBLIC_URL}/api/desktop/video/metadata/retrieve?${queryParams}`,
+ {
+ credentials: "include",
+ cache: "no-store",
+ }
+ );
+
+ const data = await res.json();
+
+ console.log("Video metadata retrieve:", data);
await stopMediaRecording();
+ if (data?.difference) {
+ console.log("Waiting for difference...");
+ await new Promise((resolve) => setTimeout(resolve, data.difference));
+ }
+
await invoke("stop_all_recordings");
- console.log("Recordings stopped...");
+ console.log("All recordings stopped...");
console.log("Opening window...");
@@ -277,9 +296,11 @@ export const Recorder = () => {
handleStartAllRecordings();
}
}}
- spinner={stoppingRecording}
+ spinner={startingRecording || stoppingRecording}
>
- {isRecording
+ {startingRecording
+ ? "Starting..."
+ : isRecording
? stoppingRecording
? currentStoppingMessage
: "Stop Recording"
diff --git a/apps/desktop/src/utils/helpers.ts b/apps/desktop/src/utils/helpers.ts
index cfe2dfc6c..f295c24f0 100644
--- a/apps/desktop/src/utils/helpers.ts
+++ b/apps/desktop/src/utils/helpers.ts
@@ -22,8 +22,8 @@ export const setWindowPosition = (
case "bottom_right":
appWindow.setPosition(
new LogicalPosition(
- windowWidth - appWidth - 125,
- windowHeight - appHeight - 25
+ windowWidth - appWidth - 75,
+ windowHeight - appHeight
)
);
return;
@@ -93,7 +93,6 @@ export const getVideoSettings = async (
export const requestMediaDevicesPermission = async () => {
try {
- // Request permission by trying to access the user's media devices
await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
console.log("Permissions to access media devices have been granted.");
} catch (error) {
diff --git a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
index 6b3420053..c9fdc8499 100644
--- a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
+++ b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
@@ -6,11 +6,12 @@ import {
useContext,
useEffect,
useCallback,
+ useRef,
} from "react";
import { listen } from "@tauri-apps/api/event";
import { getLocalDevices, enumerateAndStoreDevices } from "./utils";
-interface Devices {
+export interface Devices {
index: number;
label: string;
kind: "videoinput" | "audioinput";
@@ -30,6 +31,12 @@ export interface MediaDeviceContextData {
getDevices: () => Promise<void>;
isRecording: boolean;
setIsRecording: React.Dispatch<React.SetStateAction<boolean>>;
+ startingRecording: boolean;
+ setStartingRecording: React.Dispatch<React.SetStateAction<boolean>>;
+ sharedStream: MediaStream | null;
+ startSharedStream: () => Promise<void>;
+ stopSharedStream: () => void;
+ updateTrigger: number;
}
export const MediaDeviceContext = createContext<
@@ -48,6 +55,49 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
>("screen");
const [devices, setDevices] = useState<Devices[]>([]);
const [isRecording, setIsRecording] = useState(false);
+ const [startingRecording, setStartingRecording] = useState(false);
+ const sharedStream = useRef<MediaStream | null>(null);
+ const [updateTrigger, setUpdateTrigger] = useState(0);
+
+ const updateSharedStream = useCallback((newStream: MediaStream | null) => {
+ sharedStream.current = newStream;
+ setUpdateTrigger((prev) => prev + 1);
+ }, []);
+
+ const startSharedStream = useCallback(async () => {
+ if (selectedVideoDevice || selectedAudioDevice) {
+ const constraints = {
+ video: selectedVideoDevice
+ ? {
+ deviceId: selectedVideoDevice.deviceId,
+ frameRate: { ideal: 30 },
+ width: { ideal: 1920 },
+ height: { ideal: 1080 },
+ }
+ : false,
+ audio: selectedAudioDevice
+ ? { deviceId: selectedAudioDevice.deviceId }
+ : false,
+ };
+
+ try {
+ console.log("starting shared stream");
+ const stream = await navigator.mediaDevices.getUserMedia(constraints);
+ sharedStream.current = stream;
+ updateSharedStream(stream);
+ } catch (error) {
+ console.error("Failed to start shared media stream:", error);
+ }
+ }
+ }, [selectedVideoDevice, selectedAudioDevice]);
+
+ const stopSharedStream = useCallback(() => {
+ if (sharedStream) {
+ console.log("stopping shared stream");
+ sharedStream.current?.getTracks().forEach((track) => track.stop());
+ sharedStream.current = null;
+ }
+ }, [sharedStream]);
const getDevices = useCallback(async () => {
console.log("getDevices called");
@@ -95,6 +145,27 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
getDevices();
}, []);
+ useEffect(() => {
+ // Function to start the shared stream only if not already started
+ const ensureStreamStarted = async () => {
+ if (!sharedStream.current) {
+ console.log("No active shared stream. Attempting to start.");
+ await startSharedStream();
+ } else {
+ console.log("Shared stream already active. Skipping reinitialization.");
+ }
+ };
+
+ ensureStreamStarted();
+ }, [startSharedStream]);
+
+ useEffect(() => {
+ return () => {
+ // Component cleanup
+ stopSharedStream();
+ };
+ }, [stopSharedStream]);
+
useEffect(() => {
let unlistenFn: any;
@@ -151,6 +222,12 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
getDevices,
isRecording,
setIsRecording,
+ startingRecording,
+ setStartingRecording,
+ sharedStream: sharedStream.current,
+ startSharedStream,
+ stopSharedStream,
+ updateTrigger,
}}
>
{children}
diff --git a/apps/desktop/src/utils/recording/useAudioRecorder.ts b/apps/desktop/src/utils/recording/useAudioRecorder.ts
index 4ea2c7883..4a639b025 100644
--- a/apps/desktop/src/utils/recording/useAudioRecorder.ts
+++ b/apps/desktop/src/utils/recording/useAudioRecorder.ts
@@ -1,106 +1,178 @@
-import { useState, useRef } from "react";
-import { dataDir, 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";
+import { useRef, useEffect, useCallback } from "react";
+import { appDataDir, join } from "@tauri-apps/api/path";
+import {
+ writeBinaryFile,
+ writeTextFile,
+ readTextFile,
+ createDir,
+} from "@tauri-apps/api/fs";
+import { getLatestVideoId } from "../database/utils";
export const useAudioRecorder = () => {
- const [isRecordingAudio, setIsRecordingAudio] = useState(false);
+ const isRecordingAudio = useRef(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 queue = useRef<Blob[]>([]);
+ const processingQueue = useRef(false);
+ const segmentCounter = useRef(0);
+ const firstRecordingStarted = useRef(false);
+
+ const getAudioSegmentsDir = async () => {
+ const dir = await appDataDir();
+ return join(dir, "chunks", "audio");
+ };
+
+ const appendToAudioSegmentListFile = async (fileName: string) => {
+ const dir = await getAudioSegmentsDir();
+ const segmentListPath = await join(dir, "segment_list.txt");
+ let fileContent;
+ try {
+ fileContent = await readTextFile(segmentListPath);
+ } catch (error) {
+ fileContent = "";
}
+ const newContent = `${fileContent}${fileName}\n`;
+ await writeTextFile({ path: segmentListPath, contents: newContent });
+ };
- const { audioDevices } = await getLocalDevices();
- const audioDeviceInfo = audioDevices.find(
- (device) =>
- device.kind === "audioinput" &&
- device.label === selectedAudioDevice.label
- );
+ const saveAudioSegment = async (data: Uint8Array, fileName: string) => {
+ const dir = await getAudioSegmentsDir();
+ await createDir(dir, { recursive: true });
+ const filePath = await join(dir, fileName);
+ await writeBinaryFile({ path: filePath, contents: data });
+ await appendToAudioSegmentListFile(fileName);
+ };
- if (!audioDeviceInfo) {
- throw new Error("Cannot find audio device info");
+ const processQueue = useCallback(async () => {
+ if (!processingQueue.current && queue.current.length > 0) {
+ processingQueue.current = true;
+ while (queue.current.length > 0) {
+ try {
+ const chunk = queue.current.shift();
+ if (!chunk) continue;
+ const buffer = new Uint8Array(await chunk.arrayBuffer());
+ const segmentNumber = segmentCounter.current++;
+ const fileName = `audio_segment_${segmentNumber
+ .toString()
+ .padStart(3, "0")}.webm`;
+ await saveAudioSegment(buffer, fileName);
+ } catch (error) {
+ console.error("Failed to process audio chunk:", error);
+ }
+ }
+ processingQueue.current = false;
}
+ }, []);
+
+ const sendMetadataAPI = useCallback(async () => {
+ if (!firstRecordingStarted.current) {
+ firstRecordingStarted.current = true;
+ try {
+ const videoId = getLatestVideoId();
+ const response = await fetch("/api/desktop/video/metadata/create", {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ videoId: videoId,
+ audioStartTime: Date.now(),
+ }),
+ });
+ if (!response.ok) {
+ throw new Error(`API call failed with status ${response.status}`);
+ }
+ const jsonResponse = await response.json();
+ console.log("Metadata updated successfully:", jsonResponse);
+ } catch (error) {
+ console.error("Error updating video and audio start time:", error);
+ }
+ }
+ }, []);
- const audioStream = await navigator.mediaDevices.getUserMedia({
- audio: { deviceId: audioDeviceInfo.deviceId },
- });
-
- mediaRecorder.current = new MediaRecorder(audioStream);
+ const startAudioRecording = useCallback(
+ async (mediaStream: MediaStream) => {
+ if (!mediaStream) {
+ console.error("Media stream is null.");
+ return;
+ }
- if (mediaRecorder.current === null) {
- console.error("mediaRecorder is null.");
- return;
- }
+ console.log("mediaStream:", mediaStream);
- mediaRecorder.current.start();
- setIsRecordingAudio(true);
+ const audioTracks = mediaStream.getAudioTracks();
+ if (audioTracks.length === 0) {
+ console.error("No audio track found in the media stream.");
+ return;
+ }
- mediaRecorder.current.ondataavailable = (event) => {
- audioChunks.current.push(event.data);
- };
+ const audioStream = new MediaStream(audioTracks);
- mediaRecorder.current.onerror = (event: any) => {
- console.error("Recording error:", event.error);
- setIsRecordingAudio(false);
- };
- };
+ mediaRecorder.current = new MediaRecorder(audioStream, {
+ mimeType: "audio/webm",
+ });
+ if (!mediaRecorder.current) {
+ console.error("mediaRecorder is null.");
+ return;
+ }
+ mediaRecorder.current.start();
+ isRecordingAudio.current = true;
+
+ mediaRecorder.current.ondataavailable = (event) => {
+ if (event.data.size > 0) {
+ queue.current.push(event.data);
+ processQueue();
+ }
+ };
+
+ await sendMetadataAPI();
+
+ const requestDataInterval = setInterval(() => {
+ if (mediaRecorder.current && isRecordingAudio.current === true) {
+ mediaRecorder.current.stop();
+ mediaRecorder.current.onstop = () => {
+ if (isRecordingAudio.current) {
+ mediaRecorder.current?.start();
+ }
+ };
+ } else {
+ clearInterval(requestDataInterval);
+ }
+ }, 3000);
+
+ return () => {
+ clearInterval(requestDataInterval);
+ if (mediaRecorder.current) {
+ mediaRecorder.current.stop();
+ isRecordingAudio.current = false;
+ }
+ };
+ },
+ [processQueue, sendMetadataAPI]
+ );
+
+ const stopAudioRecording = useCallback(async () => {
+ if (mediaRecorder.current) {
+ mediaRecorder.current.stop();
+ console.log("Audio recording stopped.");
+ }
+ isRecordingAudio.current = false;
+ while (processingQueue.current || queue.current.length > 0) {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ firstRecordingStarted.current = false;
+ console.log("Queue processed and audio recording fully stopped.");
+ }, []);
- const stopAudioRecording = () => {
- return new Promise<string>((resolve, reject) => {
- if (mediaRecorder.current && isRecordingAudio) {
+ useEffect(() => {
+ return () => {
+ if (isRecordingAudio.current && mediaRecorder.current) {
mediaRecorder.current.stop();
-
- // Event handler for when recording stops
- mediaRecorder.current.onstop = async () => {
- try {
- const audioBlob = new Blob(audioChunks.current, {
- type: "audio/aac",
- });
- const buffer = await audioBlob.arrayBuffer();
- const dir = await dataDir();
- const filePath = await join(
- dir,
- `cap_audio_${new Date().toISOString()}.aac`
- );
-
- 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."));
+ isRecordingAudio.current = false;
}
- });
- };
+ };
+ }, []);
return {
- isRecordingAudio,
+ isRecordingAudio: isRecordingAudio.current,
startAudioRecording,
stopAudioRecording,
};
diff --git a/apps/desktop/src/utils/recording/useMediaRecorder.ts b/apps/desktop/src/utils/recording/useMediaRecorder.ts
index 7e2daa586..81739c7e4 100644
--- a/apps/desktop/src/utils/recording/useMediaRecorder.ts
+++ b/apps/desktop/src/utils/recording/useMediaRecorder.ts
@@ -8,6 +8,7 @@ import {
createDir,
} from "@tauri-apps/api/fs";
import { appDataDir, join } from "@tauri-apps/api/path";
+import { getLatestVideoId } from "../database/utils";
export const useMediaRecorder = () => {
const isRecording = useRef(false);
@@ -41,7 +42,7 @@ export const useMediaRecorder = () => {
};
const appendToSegmentListFile = async (fileName: string) => {
- const dir = await getVideoChunksDir();
+ const dir = await getAudioChunksDir();
const segmentListPath = await join(dir, "segment_list.txt");
let fileContent;
@@ -114,10 +115,6 @@ export const useMediaRecorder = () => {
3,
"0"
)}.mp4`;
- const outputFileName = `output-${String(chunkNumber).padStart(
- 3,
- "0"
- )}.ts`;
const audioOutputFileName = `output-${String(chunkNumber).padStart(
3,
"0"
@@ -135,21 +132,6 @@ export const useMediaRecorder = () => {
console.log("log-3");
- await ffmpeg.exec([
- "-i",
- inputFileName,
- "-an",
- "-c:v",
- "libx264",
- "-preset",
- "veryfast",
- "-tune",
- "zerolatency",
- "-f",
- "mpegts",
- outputFileName,
- ]);
-
await ffmpeg.exec([
"-i",
inputFileName,
@@ -163,16 +145,6 @@ export const useMediaRecorder = () => {
console.log("log-4");
- try {
- const savedVideo = (await ffmpeg.readFile(
- outputFileName
- )) as Uint8Array;
- await saveFile(savedVideo, outputFileName, false);
- console.log("log-5");
- } catch (error) {
- console.error("Failed to save file:", error);
- }
-
try {
const savedAudio = (await ffmpeg.readFile(
audioOutputFileName
@@ -181,46 +153,13 @@ export const useMediaRecorder = () => {
await createDir(audioDir, { recursive: true });
const audioPath = await join(audioDir, audioOutputFileName);
await writeBinaryFile(audioPath, savedAudio);
- console.log("Audio saved.");
+ await appendToSegmentListFile(audioOutputFileName);
+ console.log("Audio saved: ", audioOutputFileName);
} catch (error) {
console.error("Failed to save audio:", error);
}
- if (segmentCounter.current === 2) {
- const screenshotFileName = "video-capture.jpeg";
-
- console.log("Generating screenshot...");
-
- await ffmpeg.exec([
- "-i",
- outputFileName,
- "-ss",
- "0",
- "-frames:v",
- "1",
- "-q:v",
- "1",
- screenshotFileName,
- ]);
-
- try {
- const savedScreenshot = (await ffmpeg.readFile(
- screenshotFileName
- )) as Uint8Array;
- await saveFile(savedScreenshot, screenshotFileName, true);
- console.log("Screenshot saved.");
- } catch (error) {
- console.error("Failed to save screenshot:", error);
- }
-
- // Clean up by deleting the temporary screenshot file generated by FFmpeg
- await ffmpeg.deleteFile(screenshotFileName);
-
- console.log("Screenshot process completed.");
- }
-
await ffmpeg.deleteFile(inputFileName);
- await ffmpeg.deleteFile(outputFileName);
} catch (error) {
console.error("Failed to process chunk:", error);
}
@@ -230,39 +169,99 @@ export const useMediaRecorder = () => {
}
}, [queue]);
+ const sendMetadataAPI = async () => {
+ try {
+ const videoId = await getLatestVideoId();
+ const audioStartTime = Date.now();
+ const queryParams = new URLSearchParams({
+ videoId,
+ audioStartTime: audioStartTime.toString(),
+ }).toString();
+ const res = await fetch(
+ `${process.env.NEXT_PUBLIC_URL}/api/desktop/video/metadata/create?${queryParams}`,
+ {
+ method: "GET",
+ credentials: "include",
+ cache: "no-store",
+ }
+ );
+ if (res.status === 401) {
+ console.error("Unauthorized");
+ return;
+ }
+ const data = await res.json();
+ console.log("Metadata fetched successfully:", data);
+ } catch (error) {
+ console.error("Error fetching video and audio start time:", error);
+ }
+ };
+
const startMediaRecording = useCallback(
async (stream: MediaStream) => {
- // Reset queue and counters here to ensure a fresh start
- queue.current = []; // Clear the queue
- segmentCounter.current = 0;
- processingQueue.current = false;
- isRecording.current = true;
- console.log("Recording started");
+ if (!stream.active || !stream.getTracks().length) {
+ console.error("The provided stream is not active or has no tracks.");
+ return;
+ }
+
+ console.log("stream:");
+ console.log(stream);
- const options = { mimeType: "video/mp4;" };
- mediaRecorder.current = new MediaRecorder(stream, options);
+ console.log("stream.getTracks():");
+ console.log(stream.getTracks());
- mediaRecorder.current.ondataavailable = (event) => {
- console.log(`Blob size: ${event.data.size}`);
- if (event.data.size > 0) {
- queue.current.push(event.data);
- processQueue();
+ const initRecorder = () => {
+ if (
+ mediaRecorder.current &&
+ mediaRecorder.current.state !== "inactive"
+ ) {
+ mediaRecorder.current.stop();
+ }
+
+ if (isRecording.current === false) {
+ return;
}
+
+ const options = {
+ mimeType: "video/mp4",
+ audioBitsPerSecond: 128000,
+ videoBitsPerSecond: 0,
+ };
+ mediaRecorder.current = new MediaRecorder(stream, options);
+
+ mediaRecorder.current.ondataavailable = (event) => {
+ console.log(`Blob size: ${event.data.size}`);
+ if (event.data.size > 0) {
+ queue.current.push(event.data);
+ processQueue();
+ }
+ };
+
+ mediaRecorder.current.onerror = (event: any) => {
+ console.error("MediaRecorder error:", event.error);
+ };
+
+ mediaRecorder.current.start();
+ console.log("MediaRecorder started:", mediaRecorder.current);
};
- mediaRecorder.current.start();
+ isRecording.current = true;
+ initRecorder();
+ await sendMetadataAPI();
const requestDataInterval = setInterval(() => {
- if (mediaRecorder.current && isRecording.current) {
- console.log("Requesting data periodically");
+ if (mediaRecorder.current && isRecording.current === true) {
+ console.log("Stopping and restarting the recorder to gather chunks.");
mediaRecorder.current.stop();
- mediaRecorder.current.start();
+ mediaRecorder.current.onstop = () => {
+ initRecorder();
+ };
} else {
clearInterval(requestDataInterval);
}
}, 3000);
return () => {
+ clearInterval(requestDataInterval);
if (
mediaRecorder.current &&
mediaRecorder.current.state !== "inactive"
@@ -277,16 +276,18 @@ export const useMediaRecorder = () => {
);
const stopMediaRecording = useCallback(async () => {
+ if (mediaRecorder.current) {
+ mediaRecorder.current.stop();
+ console.log("Media recording stopped.");
+ }
+
isRecording.current = false;
while (processingQueue.current || queue.current.length > 0) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
- if (mediaRecorder.current && mediaRecorder.current.state !== "inactive") {
- mediaRecorder.current.stop();
- console.log("Media recording stopped and queue processed.");
- }
+ console.log("Queue processed and recording fully stopped.");
}, []);
return {
diff --git a/apps/web/app/api/desktop/video/metadata/create/route.ts b/apps/web/app/api/desktop/video/metadata/create/route.ts
new file mode 100644
index 000000000..7c8e3810b
--- /dev/null
+++ b/apps/web/app/api/desktop/video/metadata/create/route.ts
@@ -0,0 +1,58 @@
+import { type NextRequest } from "next/server";
+import { db } from "@cap/database";
+import { videos } from "@cap/database/schema";
+import { eq } from "drizzle-orm";
+
+export const dynamic = "force-dynamic";
+
+export async function GET(request: NextRequest) {
+ try {
+ const url = new URL(request.url);
+ const videoId = url.searchParams.get("videoId");
+ const videoStartTime = url.searchParams.get("videoStartTime");
+ const audioStartTime = url.searchParams.get("audioStartTime");
+
+ if (!videoId || (!videoStartTime && !audioStartTime)) {
+ return new Response(
+ JSON.stringify({ error: "Missing required fields" }),
+ {
+ status: 400,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+
+ if (videoStartTime) {
+ console.log("...Updating video start time...");
+ await db
+ .update(videos)
+ .set({ videoStartTime: Number(videoStartTime) })
+ .where(eq(videos.id, videoId));
+ }
+
+ if (audioStartTime) {
+ console.log("...Updating audio start time...");
+ await db
+ .update(videos)
+ .set({ audioStartTime: Number(audioStartTime) })
+ .where(eq(videos.id, videoId));
+ }
+
+ return new Response(JSON.stringify({ success: true }), {
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ } catch (error) {
+ console.error("Error updating video or audio start time", error);
+ return new Response(JSON.stringify({ error: "Internal server error" }), {
+ status: 500,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+}
diff --git a/apps/web/app/api/desktop/video/metadata/retrieve/route.ts b/apps/web/app/api/desktop/video/metadata/retrieve/route.ts
new file mode 100644
index 000000000..b39205fe8
--- /dev/null
+++ b/apps/web/app/api/desktop/video/metadata/retrieve/route.ts
@@ -0,0 +1,65 @@
+import { type NextRequest } from "next/server";
+import { db } from "@cap/database";
+import { videos } from "@cap/database/schema";
+import { eq } from "drizzle-orm";
+import { difference } from "next/dist/build/utils";
+
+export const dynamic = "force-dynamic";
+
+export async function GET(request: NextRequest) {
+ try {
+ const url = new URL(request.url);
+ const videoId = url.searchParams.get("videoId");
+
+ if (!videoId) {
+ return new Response(
+ JSON.stringify({ error: "Missing required fields" }),
+ {
+ status: 400,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+
+ const query = await db.select().from(videos).where(eq(videos.id, videoId));
+
+ if (query.length === 0) {
+ return new Response(JSON.stringify({ error: "Video not found" }), {
+ status: 404,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ const video = query[0];
+ const videoStartTime = video.videoStartTime
+ ? new Date(video.videoStartTime).getTime()
+ : 0;
+ const audioStartTime = video.audioStartTime
+ ? new Date(video.audioStartTime).getTime()
+ : 0;
+
+ const timeDifference = videoStartTime - audioStartTime;
+
+ return new Response(
+ JSON.stringify({ success: true, difference: timeDifference }),
+ {
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ } catch (error) {
+ console.error("Error updating video or audio start time", error);
+ return new Response(JSON.stringify({ error: "Internal server error" }), {
+ status: 500,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+}
diff --git a/apps/web/app/api/upload/signed/route.ts b/apps/web/app/api/upload/signed/route.ts
index c0f484328..7ab99bf8d 100644
--- a/apps/web/app/api/upload/signed/route.ts
+++ b/apps/web/app/api/upload/signed/route.ts
@@ -15,10 +15,6 @@ export async function POST(request: NextRequest) {
const { userId, fileKey, duration, awsBucket, awsRegion } =
await request.json();
- console.log("Duration start...");
- console.log(duration);
- console.log("...Duration end...");
-
if (!userId || !duration || !fileKey || !awsBucket || !awsRegion) {
console.error("Missing required fields in /api/upload/signed/route.ts");
@@ -33,7 +29,11 @@ export async function POST(request: NextRequest) {
);
}
- const contentType = fileKey.endsWith(".aac") ? "audio/aac" : "video/mp2t";
+ const contentType = fileKey.endsWith(".aac")
+ ? "audio/aac"
+ : fileKey.endsWith(".webm")
+ ? "audio/webm"
+ : "video/mp2t";
const Fields = {
"Content-Type": contentType,
diff --git a/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx b/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx
index 52042cccf..109620ec1 100644
--- a/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx
+++ b/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx
@@ -27,6 +27,6 @@ export const AudioPlayer = forwardRef<HTMLAudioElement, AudioPlayerProps>(
}
}, [src, ref]);
- return <audio ref={ref} controls={false} style={{ display: "none" }} />;
+ return <audio ref={ref} controls={true} style={{ display: "none" }} />;
}
);
diff --git a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
index e6f30ff37..b3c377385 100644
--- a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
@@ -14,7 +14,6 @@ const formatTime = (time: number) => {
};
export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
- const video1Ref = useRef<HTMLVideoElement>(null);
const video2Ref = useRef<HTMLVideoElement>(null);
const audioPlayerRef = useRef<HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = useState(false);
@@ -22,66 +21,138 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
const [isLoading, setIsLoading] = useState(true);
const [longestDuration, setLongestDuration] = useState(0);
const [seeking, setSeeking] = useState(false);
+ const [videoMetadataLoaded, setVideoMetadataLoaded] = useState(false);
+ const [audioMetadataLoaded, setAudioMetadataLoaded] = useState(false);
useEffect(() => {
- const handleLoadedMetadata = () => {
- const duration1 = video1Ref.current?.duration || 0;
- const duration2 = video2Ref.current?.duration || 0;
- setLongestDuration(Math.max(duration1, duration2));
- setIsLoading(!(duration1 > 0 && duration2 > 0));
+ const adjustForStartTimes = () => {
+ if (!video2Ref.current || !audioPlayerRef.current) return;
+ console.log("Adjusting start times");
+
+ const videoStartTime = data.videoStartTime
+ ? new Date(data.videoStartTime).getTime()
+ : 0;
+ const audioStartTime = data.audioStartTime
+ ? new Date(data.audioStartTime).getTime()
+ : 0;
+
+ const timeDifference = videoStartTime - audioStartTime;
+
+ console.log("Time difference", timeDifference);
+
+ if (timeDifference > 0) {
+ audioPlayerRef.current.currentTime = timeDifference / 1000;
+ video2Ref.current.currentTime = 0; // Ensure video starts from the beginning
+ } else if (timeDifference < 0) {
+ video2Ref.current.currentTime = Math.abs(timeDifference / 1000);
+ audioPlayerRef.current.currentTime = 0; // Ensure audio starts from the beginning
+ }
+
+ const videoLength = video2Ref.current.duration;
+ const audioLength = audioPlayerRef.current.duration;
+
+ const lengthDifference = Math.abs(videoLength - audioLength);
+
+ if (lengthDifference > 0) {
+ console.log("Length difference detected");
+
+ if (videoLength > audioLength) {
+ video2Ref.current.currentTime =
+ video2Ref.current.currentTime - lengthDifference;
+ } else {
+ audioPlayerRef.current.currentTime =
+ audioPlayerRef.current.currentTime - lengthDifference;
+ }
+ }
+
+ console.log("refs:");
+ console.log(video2Ref.current.currentTime);
+ console.log(audioPlayerRef.current.currentTime);
+
+ console.log("Start times adjusted");
+ setIsLoading(false);
+ };
+
+ if (videoMetadataLoaded && audioMetadataLoaded) {
+ adjustForStartTimes();
+ }
+ }, [
+ videoMetadataLoaded,
+ audioMetadataLoaded,
+ data.videoStartTime,
+ data.audioStartTime,
+ ]);
+
+ useEffect(() => {
+ const onVideoLoadedMetadata = () => {
+ setVideoMetadataLoaded(true);
+ if (video2Ref.current) {
+ setLongestDuration(video2Ref.current.duration);
+ }
};
+ const onAudioLoadedMetadata = () => {
+ setAudioMetadataLoaded(true);
+ if (audioPlayerRef.current) {
+ setLongestDuration(
+ Math.max(longestDuration, audioPlayerRef.current.duration)
+ );
+ }
+ };
+
+ const videoElement = video2Ref.current;
+ const audioElement = audioPlayerRef.current;
- video1Ref.current?.addEventListener("loadedmetadata", handleLoadedMetadata);
- video2Ref.current?.addEventListener("loadedmetadata", handleLoadedMetadata);
+ videoElement?.addEventListener("loadedmetadata", onVideoLoadedMetadata);
+ audioElement?.addEventListener("loadedmetadata", onAudioLoadedMetadata);
return () => {
- video1Ref.current?.removeEventListener(
+ videoElement?.removeEventListener(
"loadedmetadata",
- handleLoadedMetadata
+ onVideoLoadedMetadata
);
- video2Ref.current?.removeEventListener(
+ audioElement?.removeEventListener(
"loadedmetadata",
- handleLoadedMetadata
+ onAudioLoadedMetadata
);
};
}, []);
useEffect(() => {
const handleTimeUpdate = () => {
- if (video1Ref.current && video2Ref.current && !seeking) {
+ if (video2Ref.current && !seeking) {
const currentTime = Math.min(
- video1Ref.current.currentTime,
- video2Ref.current.currentTime
+ video2Ref.current.currentTime,
+ audioPlayerRef.current?.currentTime || Infinity
);
setCurrentTime(currentTime);
}
};
- video1Ref.current?.addEventListener("timeupdate", handleTimeUpdate);
- video2Ref.current?.addEventListener("timeupdate", handleTimeUpdate);
+ const videoElement = video2Ref.current;
+ const audioElement = audioPlayerRef.current;
+
+ videoElement?.addEventListener("timeupdate", handleTimeUpdate);
+ audioElement?.addEventListener("timeupdate", handleTimeUpdate);
return () => {
- video1Ref.current?.removeEventListener("timeupdate", handleTimeUpdate);
- video2Ref.current?.removeEventListener("timeupdate", handleTimeUpdate);
+ videoElement?.removeEventListener("timeupdate", handleTimeUpdate);
+ audioElement?.removeEventListener("timeupdate", handleTimeUpdate);
};
}, [seeking]);
const handlePlayPauseClick = () => {
setIsPlaying(!isPlaying);
if (!isPlaying) {
- video1Ref.current?.play();
video2Ref.current?.play();
audioPlayerRef.current?.play();
} else {
- video1Ref.current?.pause();
video2Ref.current?.pause();
audioPlayerRef.current?.pause();
}
};
const handleMuteClick = () => {
- const muted = !video1Ref.current?.muted;
- if (video1Ref.current) video1Ref.current.muted = muted;
+ const muted = !video2Ref.current?.muted;
if (video2Ref.current) video2Ref.current.muted = muted;
};
@@ -110,14 +181,12 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
// Pause both videos before adjusting the time.
if (isPlaying) {
- video1Ref.current?.pause();
video2Ref.current?.pause();
}
applyTimeToVideos(seekTo);
if (isPlaying) {
- video1Ref.current?.play();
video2Ref.current?.play();
}
};
@@ -137,7 +206,6 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
};
const applyTimeToVideos = (time: number) => {
- if (video1Ref.current) video1Ref.current.currentTime = time;
if (video2Ref.current) video2Ref.current.currentTime = time;
setCurrentTime(time);
};
@@ -147,19 +215,15 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
useEffect(() => {
if (isPlaying) {
- video1Ref.current?.play();
video2Ref.current?.play();
} else {
- video1Ref.current?.pause();
video2Ref.current?.pause();
}
}, [isPlaying]);
useEffect(() => {
const syncPlay = () => {
- if (video1Ref.current && video2Ref.current && !isLoading) {
- const playPromise1 = video1Ref.current.play();
- playPromise1.catch((e) => console.log("Play failed for video 1", e));
+ if (video2Ref.current && !isLoading) {
const playPromise2 = video2Ref.current.play();
playPromise2.catch((e) => console.log("Play failed for video 2", e));
}
@@ -170,43 +234,43 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
}
}, [isPlaying, isLoading]);
- useEffect(() => {
- const video = video1Ref.current;
- const audio = audioPlayerRef.current;
+ // useEffect(() => {
+ // const video = video2Ref.current;
+ // const audio = audioPlayerRef.current;
- // Function to synchronize audio playback with video
- const synchronizePlayback = () => {
- if (!video || !audio) return;
+ // // Function to synchronize audio playback with video
+ // const synchronizePlayback = () => {
+ // if (!video || !audio) return;
- // Calculate the time drift between audio and video
- const drift = Math.abs(video.currentTime - audio.currentTime);
+ // // Calculate the time drift between audio and video
+ // const drift = Math.abs(video.currentTime - audio.currentTime);
- // Adjust audio currentTime if drift exceeds a small tolerance (e.g., 0.1 seconds)
- if (drift > 0.1) {
- audio.currentTime = video.currentTime;
- }
- };
+ // // Adjust audio currentTime if drift exceeds a small tolerance (e.g., 0.1 seconds)
+ // if (drift > 0.1) {
+ // audio.currentTime = video.currentTime;
+ // }
+ // };
- // Sync audio on video seek
- const handleSeek = () => {
- synchronizePlayback(); // Adjust audio to match video currentTime
- if (isPlaying) {
- audio?.play().catch((e) => console.error("Audio playback failed:", e)); // Ensure audio resumes if it was playing
- }
- };
+ // // Sync audio on video seek
+ // const handleSeek = () => {
+ // synchronizePlayback(); // Adjust audio to match video currentTime
+ // if (isPlaying) {
+ // audio?.play().catch((e) => console.error("Audio playback failed:", e)); // Ensure audio resumes if it was playing
+ // }
+ // };
- // Add event listeners
- video?.addEventListener("seeked", handleSeek);
- video?.addEventListener("timeupdate", synchronizePlayback);
+ // // Add event listeners
+ // video?.addEventListener("seeked", handleSeek);
+ // video?.addEventListener("timeupdate", synchronizePlayback);
- // Cleanup event listeners
- return () => {
- if (video) {
- video.removeEventListener("seeked", handleSeek);
- video.removeEventListener("timeupdate", synchronizePlayback);
- }
- };
- }, [isPlaying]); // Dependency on isPlaying ensures updates when playback state changes
+ // // Cleanup event listeners
+ // return () => {
+ // if (video) {
+ // video.removeEventListener("seeked", handleSeek);
+ // video.removeEventListener("timeupdate", synchronizePlayback);
+ // }
+ // };
+ // }, [isPlaying]);
return (
<div
@@ -241,12 +305,6 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
ref={audioPlayerRef}
src={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=audio`}
/>
- <div className="w-[200px] h-[200px] absolute bottom-4 right-12 overflow-hidden rounded-full z-10 shadow-lg">
- <VideoPlayer
- ref={video1Ref}
- src={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=video`}
- />
- </div>
<div
className="relative block w-full h-full rounded-lg bg-black"
style={{ paddingBottom: "min(806px, 56.25%)" }}
@@ -312,7 +370,7 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
type="button"
onClick={() => handleMuteClick()}
>
- {video1Ref?.current?.muted && video2Ref?.current?.muted ? (
+ {video2Ref?.current?.muted ? (
<VolumeX className="w-auto h-6" />
) : (
<Volume2 className="w-auto h-6" />
diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjs
index b02a3f5d1..1df7462e6 100644
--- a/apps/web/next.config.mjs
+++ b/apps/web/next.config.mjs
@@ -85,7 +85,11 @@ const nextConfig = {
},
{
key: "Access-Control-Allow-Methods",
- value: "GET",
+ value: "GET, POST, PUT, DELETE, OPTIONS",
+ },
+ {
+ key: "Access-Control-Allow-Headers",
+ value: "*",
},
{
key: "Access-Control-Allow-Credentials",
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index f010fda53..963b21a35 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -10,6 +10,7 @@ import {
boolean,
uniqueIndex,
varchar,
+ bigint,
} from "drizzle-orm/mysql-core";
import { relations } from "drizzle-orm/relations";
import { nanoIdLength } from "./helpers";
@@ -141,8 +142,9 @@ export const videos = mysqlTable(
awsRegion: varchar("awsRegion", { length: 255 }),
awsBucket: varchar("awsBucket", { length: 255 }),
metadata: json("metadata"),
- converted: boolean("converted").notNull().default(false),
public: boolean("public").notNull().default(true),
+ videoStartTime: bigint("videoStartTime", { mode: "number" }),
+ audioStartTime: bigint("audioStartTime", { mode: "number" }),
createdAt: timestamp("createdAt").notNull().defaultNow(),
updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),
},