Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: App is now buildable 🎉 + audio sync fixes

Richie McIlroy8c8746964e6a
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 6036c7421..e9f08d6fb 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -11,8 +11,6 @@
"@cap/database": "workspace:*",
"@cap/ui": "workspace:*",
"@cap/utils": "workspace:*",
- "@ffmpeg/ffmpeg": "^0.12.10",
- "@ffmpeg/util": "^0.12.1",
"@tauri-apps/api": "^1.5.0",
"autoprefixer": "^10.4.16",
"cookies-next": "^4.1.0",
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock
index e2c50cd91..2e1fd8336 100644
--- a/apps/desktop/src-tauri/Cargo.lock
+++ b/apps/desktop/src-tauri/Cargo.lock
@@ -445,9 +445,9 @@ checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec"
[[package]]
name = "bytemuck"
-version = "1.14.1"
+version = "1.14.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed2490600f404f2b94c167e31d3ed1d5f3c225a0f3b80230053b3e0b7b962bd9"
+checksum = "a2ef034f05691a48569bd920a96c81b9d91bbad1ab5ac7c4616c1f6ef36cb79f"
[[package]]
name = "byteorder"
@@ -492,14 +492,13 @@ dependencies = [
name = "cap"
version = "0.0.0"
dependencies = [
+ "bytemuck",
"byteorder",
"chrono",
"cpal",
"dotenv_codegen",
"ffmpeg-sidecar",
"futures",
- "hound",
- "num-traits",
"reqwest",
"serde",
"serde_json",
@@ -1880,12 +1879,6 @@ dependencies = [
"windows-sys 0.52.0",
]
-[[package]]
-name = "hound"
-version = "3.5.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f"
-
[[package]]
name = "html5ever"
version = "0.26.0"
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 589649c2a..8d8b0a1b9 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -20,7 +20,6 @@ tauri-plugin-context-menu = "0.7.0"
tauri-plugin-positioner = { version = "1.0.4", features = ["system-tray"] }
ffmpeg-sidecar = "0.5.1"
cpal = "0.15.2"
-hound = "3.5.1"
which = "4.2.2"
tokio = { version = "1.35.1", features = ["full"] }
tokio-util = { version = "0.7.10", features = ["io"] }
@@ -32,8 +31,8 @@ window-vibrancy = "0.4.3"
window-shadows = "0.2.2"
chrono = "0.4.33"
dotenv_codegen = "0.15.0"
-num-traits = "0.2"
byteorder = "1.4.3"
+bytemuck = "1.14.3"
[features]
# this feature is used for production builds or when `devPath` points to the filesystem
diff --git a/apps/desktop/src-tauri/src/audio.rs b/apps/desktop/src-tauri/src/audio.rs
index 0f34a20dc..52edaeb09 100644
--- a/apps/desktop/src-tauri/src/audio.rs
+++ b/apps/desktop/src-tauri/src/audio.rs
@@ -13,6 +13,7 @@ use crate::utils::ffmpeg_path_as_str;
pub struct AudioRecorder {
pub options: Option<RecordingOptions>,
ffmpeg_stdin: Arc<Mutex<Option<std::process::ChildStdin>>>,
+ stream: Option<cpal::Stream>,
}
impl AudioRecorder {
@@ -21,6 +22,7 @@ impl AudioRecorder {
AudioRecorder {
options: None,
ffmpeg_stdin: Arc::new(Mutex::new(None)),
+ stream: None,
}
}
@@ -33,11 +35,10 @@ impl AudioRecorder {
let sample_rate = config.sample_rate().0;
let channels = config.channels();
let sample_format = match config.sample_format() {
- SampleFormat::F32 => "f32le",
- SampleFormat::I16 => "s16le",
SampleFormat::I8 => "s8",
- SampleFormat::U16 => "u16le",
- SampleFormat::U8 => "u8",
+ SampleFormat::I16 => "s16le",
+ SampleFormat::I32 => "s32le",
+ SampleFormat::F32 => "f32le",
_ => panic!("Unsupported sample format."),
};
@@ -54,6 +55,18 @@ impl AudioRecorder {
println!("Starting audio recording and processing...");
let output_chunk_pattern = format!("{}/audio_recording_%03d.aac", audio_file_path_owned);
let segment_list_filename = format!("{}/segment_list.txt", audio_file_path_owned);
+
+ let mut audio_filters = Vec::new();
+
+ if channels > 2 {
+ audio_filters.push("pan=stereo|FL=FL+0.5*FC|FR=FR+0.5*FC");
+ }
+
+ // Add loudnorm and acompressor to the filter chain
+ audio_filters.push("loudnorm");
+ audio_filters.push("acompressor");
+
+ let audio_filters_str = audio_filters.join(",");
let ffmpeg_command = vec![
"-f", sample_format,
@@ -62,11 +75,13 @@ impl AudioRecorder {
"-i", "-",
"-c:a", "aac",
"-b:a", "128k",
+ "-af", &audio_filters_str,
"-f", "segment",
"-segment_time", "3",
"-segment_list", &segment_list_filename,
&output_chunk_pattern,
];
+
let mut child = Command::new(&ffmpeg_binary_path_str)
.args(&ffmpeg_command)
.stdin(Stdio::piped())
@@ -118,78 +133,81 @@ impl AudioRecorder {
let ffmpeg_stdin_arc_clone = Arc::clone(&self.ffmpeg_stdin);
- let stream: cpal::Stream = match config.sample_format() {
- SampleFormat::F32 => {
- device.build_input_stream(&config.into(), move |data: &[f32], _: &_| {
- println!("Received {} samples", data.len());
- let mut ffmpeg_stdin_lock = ffmpeg_stdin_arc_clone.lock().unwrap();
- if let Some(ref mut stdin) = *ffmpeg_stdin_lock {
- let bytes = data.iter().flat_map(|&sample| sample.to_ne_bytes()).collect::<Vec<u8>>();
- let _ = stdin.write_all(&bytes);
- let _ = stdin.flush();
- }
- }, err_fn, None).map_err(|_| "Failed to build input stream for F32 format")?
- },
- SampleFormat::I16 => {
- device.build_input_stream(&config.into(), move |data: &[i16], _: &_| {
- println!("Received {} samples", data.len());
- let mut ffmpeg_stdin_lock = ffmpeg_stdin_arc_clone.lock().unwrap();
- if let Some(ref mut stdin) = *ffmpeg_stdin_lock {
- let bytes = data.iter().flat_map(|&sample| {
- let mut buf = [0; 2];
- LittleEndian::write_i16(&mut buf, sample);
- buf.to_vec()
- }).collect::<Vec<u8>>();
- let _ = stdin.write_all(&bytes);
- let _ = stdin.flush();
- }
- }, err_fn, None).map_err(|_| "Failed to build input stream for U16 format")?
- },
- SampleFormat::I8 => {
- device.build_input_stream(&config.into(), move |data: &[i8], _: &_| {
- println!("Received {} samples", data.len());
- let mut ffmpeg_stdin_lock = ffmpeg_stdin_arc_clone.lock().unwrap();
- if let Some(ref mut stdin) = *ffmpeg_stdin_lock {
- let bytes = data.iter().map(|&sample| sample as u8).collect::<Vec<u8>>();
- let _ = stdin.write_all(&bytes);
- let _ = stdin.flush();
- }
- }, err_fn, None).map_err(|_| "Failed to build input stream for I8 format")?
- },
- SampleFormat::U16 => {
- device.build_input_stream(&config.into(), move |data: &[u16], _: &_| {
- println!("Received {} samples", data.len());
- let mut ffmpeg_stdin_lock = ffmpeg_stdin_arc_clone.lock().unwrap();
- if let Some(ref mut stdin) = *ffmpeg_stdin_lock {
- let bytes = data.iter().flat_map(|&sample| {
- let mut buf = [0; 2];
- LittleEndian::write_u16(&mut buf, sample);
- buf.to_vec()
- }).collect::<Vec<u8>>();
- let _ = stdin.write_all(&bytes);
- let _ = stdin.flush();
- }
- }, err_fn, None).map_err(|_| "Failed to build input stream for U16 format")?
- },
- SampleFormat::U8 => {
- device.build_input_stream(&config.into(), move |data: &[u8], _: &_| {
- println!("Received {} samples", data.len());
- let mut ffmpeg_stdin_lock = ffmpeg_stdin_arc_clone.lock().unwrap();
- if let Some(ref mut stdin) = *ffmpeg_stdin_lock {
- let _ = stdin.write_all(data);
- let _ = stdin.flush();
- }
- }, err_fn, None).map_err(|_| "Failed to build input stream for U8 format")?
- },
- _ => return Err("Unsupported sample format"),
+ let stream_result: Result<cpal::Stream, cpal::BuildStreamError> = match sample_format {
+ SampleFormat::I8 => device.build_input_stream(
+ &config.into(),
+ move |data: &[i8], _: &_| {
+ let mut ffmpeg_stdin_lock = ffmpeg_stdin_arc_clone.lock().unwrap();
+ if let Some(ref mut stdin) = *ffmpeg_stdin_lock {
+ let bytes = data.iter().map(|&sample| sample as u8).collect::<Vec<u8>>();
+ let _ = stdin.write_all(&bytes);
+ let _ = stdin.flush();
+ }
+ },
+ err_fn,
+ None,
+ ),
+ SampleFormat::I16 => device.build_input_stream(
+ &config.into(),
+ move |data: &[i16], _: &_| {
+ let mut ffmpeg_stdin_lock = ffmpeg_stdin_arc_clone.lock().unwrap();
+ if let Some(ref mut stdin) = *ffmpeg_stdin_lock {
+ let mut bytes = vec![0; data.len() * 2];
+ LittleEndian::write_i16_into(data, &mut bytes);
+ let _ = stdin.write_all(&bytes);
+ let _ = stdin.flush();
+ }
+ },
+ err_fn,
+ None,
+ ),
+ SampleFormat::I32 => device.build_input_stream(
+ &config.into(),
+ move |data: &[i32], _: &_| {
+ let mut ffmpeg_stdin_lock = ffmpeg_stdin_arc_clone.lock().unwrap();
+ if let Some(ref mut stdin) = *ffmpeg_stdin_lock {
+ let mut bytes = vec![0; data.len() * 4];
+ LittleEndian::write_i32_into(data, &mut bytes);
+ let _ = stdin.write_all(&bytes);
+ let _ = stdin.flush();
+ }
+ },
+ err_fn,
+ None,
+ ),
+ SampleFormat::F32 => device.build_input_stream(
+ &config.into(),
+ move |data: &[f32], _: &_| {
+ let mut ffmpeg_stdin_lock = ffmpeg_stdin_arc_clone.lock().unwrap();
+ if let Some(ref mut stdin) = *ffmpeg_stdin_lock {
+ let bytes = bytemuck::cast_slice::<f32, u8>(data);
+ if let Err(e) = stdin.write_all(bytes) {
+ eprintln!("Failed to write data to FFmpeg stdin: {}", e);
+ }
+ }
+ },
+ err_fn,
+ None,
+ ),
+ _sample_format => Err(cpal::BuildStreamError::DeviceNotAvailable),
};
- stream.play().unwrap();
+ let stream = stream_result.map_err(|_| "Failed to build input stream")?;
+ stream.play().map_err(|_| "Failed to play stream")?;
+
+ self.stream = Some(stream);
Ok(())
}
pub fn stop_audio_recording(&mut self) -> Result<(), &'static str> {
+ if let Some(ref mut stream) = self.stream {
+ stream.pause().map_err(|_| "Failed to pause stream")?;
+ println!("Stopped audio recording.");
+ } else {
+ return Err("Recording was not started");
+ }
+
let mut ffmpeg_stdin_opt = self.ffmpeg_stdin.lock().map_err(|_| "Failed to acquire lock on ffmpeg stdin")?;
if ffmpeg_stdin_opt.is_some() {
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 4b243552a..c8cd859de 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -71,11 +71,6 @@ fn main() {
.plugin(tauri_plugin_positioner::init())
.setup(move |app| {
let handle = app.handle();
-
- if let Some(camera_window) = app.get_window("camera") {
- let _ = camera_window.move_window(Position::BottomRight);
- set_shadow(&camera_window, true).expect("Unsupported platform!");
- }
if let Some(options_window) = app.get_window("main") {
let _ = options_window.move_window(Position::Center);
@@ -91,6 +86,7 @@ fn main() {
let data_directory = handle.path_resolver().app_data_dir().unwrap_or_else(|| PathBuf::new());
let recording_state = RecordingState {
screen_process: None,
+ screen_process_stdin: None,
video_process: None,
audio_process: None,
upload_handles: Mutex::new(vec![]),
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 40d5c75c5..65676a8d8 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -5,10 +5,10 @@ use std::fs::File;
use std::sync::Arc;
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, Ordering};
-use tokio::sync::{Semaphore, Mutex};
+use tokio::sync:: {Mutex};
use tokio::task::JoinHandle;
-use tokio::time::{timeout, Duration};
-use tokio::io::AsyncBufReadExt;
+use tokio::time::{Duration};
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
use tokio::io::{BufReader as TokioBufReader, AsyncRead};
use serde::{Serialize, Deserialize};
use chrono::Utc;
@@ -21,6 +21,7 @@ use crate::audio::AudioRecorder;
pub struct RecordingState {
pub screen_process: Option<tokio::process::Child>,
+ pub screen_process_stdin: Option<tokio::process::ChildStdin>,
pub video_process: Option<tokio::process::Child>,
pub audio_process: Option<AudioRecorder>,
pub upload_handles: Mutex<Vec<JoinHandle<Result<(), String>>>>,
@@ -51,23 +52,6 @@ pub async fn start_dual_recording(
println!("Starting screen recording...");
let mut state_guard = state.lock().await;
- let data_dir = state_guard.data_dir.clone().ok_or("Data directory is not set")?;
-
- state_guard.audio_process = Some(AudioRecorder::new());
-
- if let Some(ref mut audio_process) = state_guard.audio_process {
- let audio_chunks_dir = data_dir.join("chunks/audio");
- clean_and_create_dir(&audio_chunks_dir)?;
-
- // Convert the path to a string for the setup_recording function.
- let audio_file_path = audio_chunks_dir.to_str().unwrap();
-
- // Prepare RecordingOptions for the audio recorder.
- // Ensure your RecordingOptions is available and configured correctly for use here.
- // This assumes `options` is of type RecordingOptions and it's already populated with necessary values.
- audio_process.setup_recording(options.clone(), audio_file_path);
- }
-
let shutdown_flag = Arc::new(AtomicBool::new(false));
let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;
@@ -79,8 +63,9 @@ pub async fn start_dual_recording(
println!("data_dir: {:?}", data_dir);
let screen_chunks_dir = data_dir.join("chunks/screen");
-
+ let audio_chunks_dir = data_dir.join("chunks/audio");
clean_and_create_dir(&screen_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);
@@ -126,6 +111,7 @@ pub async fn start_dual_recording(
let mut screen_child = tokio::process::Command::new(&ffmpeg_binary_path_str)
.args(&ffmpeg_screen_args)
+ .stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
@@ -156,6 +142,13 @@ pub async fn start_dual_recording(
});
});
+ state_guard.audio_process = Some(AudioRecorder::new());
+
+ if let Some(ref mut audio_process) = state_guard.audio_process {
+ let audio_file_path = audio_chunks_dir.to_str().unwrap();
+ audio_process.setup_recording(options.clone(), audio_file_path);
+ }
+
tokio::spawn(log_output(screen_stderr, "Screen stderr".to_string(), Some(ffmpeg_start_trigger), Some(started_callback)));
let ffmpeg_binary_path_clone = ffmpeg_binary_path_str.clone();
@@ -168,12 +161,15 @@ pub async fn start_dual_recording(
}
});
+ let screen_process_stdin = screen_child.stdin.take().ok_or("Failed to open stdin for screen recording process".to_string())?;
+
// let video_stdout = video_child.stdout.take().unwrap();
// let video_stderr = video_child.stderr.take().unwrap();
// tokio::spawn(log_output(video_stdout, "Video stdout".to_string()));
// tokio::spawn(log_output(video_stderr, "Video stderr".to_string()));
state_guard.screen_process = Some(screen_child);
+ state_guard.screen_process_stdin = Some(screen_process_stdin);
// guard.video_process = Some(video_child);
state_guard.upload_handles = Mutex::new(vec![]);
state_guard.recording_options = Some(options.clone());
@@ -183,16 +179,17 @@ pub async fn start_dual_recording(
println!("Starting upload loops...");
- // let screen_upload = start_upload_loop(state.clone(), screen_chunks_dir, options.clone(), "screen".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) {
- // Ok(_) => {
- // println!("Both upload loops completed successfully.");
- // },
- // Err(e) => {
- // eprintln!("An error occurred: {}", e);
- // },
- // }
+ match tokio::try_join!(screen_upload, audio_upload) {
+ Ok(_) => {
+ println!("Both upload loops completed successfully.");
+ },
+ Err(e) => {
+ eprintln!("An error occurred: {}", e);
+ },
+ }
Ok(())
}
@@ -208,13 +205,23 @@ pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -
guard.shutdown_flag.store(true, Ordering::SeqCst);
// Immediately try to close running FFmpeg processes.
- if let Some(child_process) = &mut guard.screen_process {
- let _ = child_process.kill().await;
+ if let Some(stdin) = guard.screen_process_stdin.take() {
+ if let Err(e) = graceful_stop_ffmpeg(stdin).await {
+ eprintln!("Failed to send quit command to FFmpeg: {}", e);
+ }
}
if let Some(audio_process) = &mut guard.audio_process {
- audio_process.stop_audio_recording();
+ audio_process.stop_audio_recording().expect("Failed to stop audio recording");
+ }
+
+ if let Some(mut child) = guard.screen_process.take() {
+ match child.wait().await {
+ Ok(status) => println!("FFmpeg process exited with status: {}", status),
+ Err(e) => eprintln!("Failed to wait for FFmpeg process to exit: {}", e),
+ }
}
+
// Assuming there's a video_process similar to screen_process.
//if let Some(child_process) = &mut guard.video_process {
// let _ = child_process.kill().await;
@@ -271,7 +278,7 @@ fn clean_and_create_dir(dir: &Path) -> Result<(), String> {
}
async fn log_output<R>(
- mut reader: R,
+ reader: R,
description: String,
start_trigger: Option<String>,
started_callback: Option<Arc<dyn Fn() + Send + Sync>>
@@ -473,113 +480,114 @@ fn load_segment_list(segment_list_path: &Path) -> io::Result<HashSet<String>> {
Ok(segments)
}
-async fn upload_remaining_chunks(
- chunks_dir: &PathBuf,
- options: Option<RecordingOptions>,
- video_type: &str,
- shutdown_flag: Arc<AtomicBool>,
-) -> Result<(), String> {
- // Include shutdown_flag in parameters and check it inside loop to quickly react to stop signals.
-
- if let Some(actual_options) = options {
- let retry_interval = Duration::from_secs(2);
- let upload_timeout = Duration::from_secs(15);
- let file_stability_timeout = Duration::from_secs(1);
- let file_stability_checks = 2;
-
- // Adjusted for immediate reaction to shutdown_flag.
- if shutdown_flag.load(Ordering::SeqCst) {
- return Ok(());
- }
-
- let entries = std::fs::read_dir(chunks_dir).map_err(|e| format!("Error reading directory: {}", e))?;
-
- let semaphore = Arc::new(Semaphore::new(16));
-
- 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 == "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();
- let shutdown_flag_clone = shutdown_flag.clone();
-
- Some(tokio::spawn(async move {
- let _permit = semaphore_clone.acquire().await;
- let filepath_str = path.to_str().unwrap_or_default().to_owned();
-
- // Quick exit if shutdown signal is received.
- if shutdown_flag_clone.load(Ordering::SeqCst) {
- return;
- }
-
- // Check for file size stability
- let mut last_size = 0;
- let mut stable_count = 0;
- while stable_count < file_stability_checks {
- if !path.exists() {
- eprintln!("File does not exist: {}", path.display());
- break; // Exit the loop if the file does not exist
- }
- match std::fs::metadata(&path) {
- Ok(metadata) => {
- let current_size = metadata.len();
- if last_size == current_size {
- stable_count += 1;
- } else {
- last_size = current_size;
- stable_count = 0;
- }
- },
- Err(e) => {
- eprintln!("Failed to get file metadata: {}", e);
- break; // Exit the loop if any other error occurs
- }
- }
- tokio::time::sleep(file_stability_timeout).await;
- }
-
- println!("File size stable: {}", filepath_str);
-
- // Proceed with upload after confirming file stability
- let mut attempts = 0;
- // Retry loop with timeout
- while attempts < 3 {
- attempts += 1;
- match timeout(upload_timeout, upload_file(Some(actual_options_clone.clone()), filepath_str.clone(), video_type.clone())).await {
- Ok(Ok(_)) => {
- // Upload succeeded
- println!("Successful upload on attempt {}", attempts);
- break; // Break out of the loop on success
- }
- Ok(Err(e)) => {
- // Upload failed but did not timeout
- eprintln!("Failed to upload (attempt {}): {}", attempts, e);
- }
- Err(_) => {
- // Upload attempt timed out
- eprintln!("Upload attempt timed out (attempt {})", attempts);
- }
- }
- // Wait for retry_interval before retrying
- tokio::time::sleep(retry_interval).await;
- }
- }))
- } else {
- None
- }
- })
- .collect();
-
- // Await all tasks concurrently.
- let _ = futures::future::try_join_all(tasks).await;
-
- Ok(())
- } else {
- Err("No recording options provided".to_string())
- }
-}
+// Unused for now
+// async fn upload_remaining_chunks(
+// chunks_dir: &PathBuf,
+// options: Option<RecordingOptions>,
+// video_type: &str,
+// shutdown_flag: Arc<AtomicBool>,
+// ) -> Result<(), String> {
+// // Include shutdown_flag in parameters and check it inside loop to quickly react to stop signals.
+
+// if let Some(actual_options) = options {
+// let retry_interval = Duration::from_secs(2);
+// let upload_timeout = Duration::from_secs(15);
+// let file_stability_timeout = Duration::from_secs(1);
+// let file_stability_checks = 2;
+
+// // Adjusted for immediate reaction to shutdown_flag.
+// if shutdown_flag.load(Ordering::SeqCst) {
+// return Ok(());
+// }
+
+// let entries = std::fs::read_dir(chunks_dir).map_err(|e| format!("Error reading directory: {}", e))?;
+
+// let semaphore = Arc::new(Semaphore::new(16));
+
+// 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 == "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();
+// let shutdown_flag_clone = shutdown_flag.clone();
+
+// Some(tokio::spawn(async move {
+// let _permit = semaphore_clone.acquire().await;
+// let filepath_str = path.to_str().unwrap_or_default().to_owned();
+
+// // Quick exit if shutdown signal is received.
+// if shutdown_flag_clone.load(Ordering::SeqCst) {
+// return;
+// }
+
+// // Check for file size stability
+// let mut last_size = 0;
+// let mut stable_count = 0;
+// while stable_count < file_stability_checks {
+// if !path.exists() {
+// eprintln!("File does not exist: {}", path.display());
+// break; // Exit the loop if the file does not exist
+// }
+// match std::fs::metadata(&path) {
+// Ok(metadata) => {
+// let current_size = metadata.len();
+// if last_size == current_size {
+// stable_count += 1;
+// } else {
+// last_size = current_size;
+// stable_count = 0;
+// }
+// },
+// Err(e) => {
+// eprintln!("Failed to get file metadata: {}", e);
+// break; // Exit the loop if any other error occurs
+// }
+// }
+// tokio::time::sleep(file_stability_timeout).await;
+// }
+
+// println!("File size stable: {}", filepath_str);
+
+// // Proceed with upload after confirming file stability
+// let mut attempts = 0;
+// // Retry loop with timeout
+// while attempts < 3 {
+// attempts += 1;
+// match timeout(upload_timeout, upload_file(Some(actual_options_clone.clone()), filepath_str.clone(), video_type.clone())).await {
+// Ok(Ok(_)) => {
+// // Upload succeeded
+// println!("Successful upload on attempt {}", attempts);
+// break; // Break out of the loop on success
+// }
+// Ok(Err(e)) => {
+// // Upload failed but did not timeout
+// eprintln!("Failed to upload (attempt {}): {}", attempts, e);
+// }
+// Err(_) => {
+// // Upload attempt timed out
+// eprintln!("Upload attempt timed out (attempt {})", attempts);
+// }
+// }
+// // Wait for retry_interval before retrying
+// tokio::time::sleep(retry_interval).await;
+// }
+// }))
+// } else {
+// None
+// }
+// })
+// .collect();
+
+// // Await all tasks concurrently.
+// let _ = futures::future::try_join_all(tasks).await;
+
+// Ok(())
+// } else {
+// Err("No recording options provided".to_string())
+// }
+// }
async fn take_screenshot(
ffmpeg_binary_path_str: String,
@@ -626,7 +634,6 @@ async fn send_metadata_api(video_id: &str, server_url_base: &str) -> Result<(),
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()),
@@ -647,4 +654,10 @@ async fn send_metadata_api(video_id: &str, server_url_base: &str) -> Result<(),
},
Err(err) => Err(err.to_string()),
}
+}
+
+async fn graceful_stop_ffmpeg(mut stdin: tokio::process::ChildStdin) -> Result<(), std::io::Error> {
+ // Sending 'q' followed by newline tells FFmpeg to quit gracefully
+ stdin.write_all(b"q\n").await?;
+ Ok(())
}
\ No newline at end of file
diff --git a/apps/desktop/src/app/page.tsx b/apps/desktop/src/app/page.tsx
index 5433ac48f..5db195de9 100644
--- a/apps/desktop/src/app/page.tsx
+++ b/apps/desktop/src/app/page.tsx
@@ -5,94 +5,83 @@ import { getCookie } from "cookies-next";
import { SignIn } from "@/components/windows/inner/SignIn";
import { Recorder } from "@/components/windows/inner/Recorder";
import { WindowActions } from "@/components/WindowActions";
-import { WebviewWindow, currentMonitor } from "@tauri-apps/api/window";
+import { LogoSpinner } from "@cap/ui";
export default function CameraPage() {
const [isSignedIn, setIsSignedIn] = useState(false);
const [cameraWindowOpen, setCameraWindowOpen] = useState(false);
+ const [loading, setLoading] = useState(true); // Added loading state
useEffect(() => {
- const cookie = getCookie("next-auth.session-token");
- setIsSignedIn(!!cookie);
- }, []);
-
- useEffect(() => {
- const interval = setInterval(() => {
+ const checkSignInStatus = async () => {
const cookie = getCookie("next-auth.session-token");
setIsSignedIn(!!cookie);
- }, 1000);
+ setLoading(false); // Set loading to false after checking sign-in status
+ };
+
+ checkSignInStatus();
+
+ const interval = setInterval(checkSignInStatus, 1000);
return () => clearInterval(interval);
}, []);
useEffect(() => {
- if (isSignedIn) {
- setCameraWindowOpen(true);
- if (cameraWindowOpen) {
- return;
- }
-
- currentMonitor().then((monitor) => {
- const paddingRatio = 0.125;
- const windowWidth = 250;
- const windowHeight = 250;
-
- if (monitor && monitor.size) {
- const monitorWidth = monitor.size.width;
- const monitorHeight = monitor.size.height;
-
- // calculate padding in pixels
- const horizontalPadding = monitorWidth * paddingRatio;
- const verticalPadding = monitorHeight * paddingRatio;
-
- // calculate x and y
- const x = 100;
- const y = monitorHeight - windowHeight - verticalPadding - 100;
-
- console.log("Opening camera window at", x, y);
- console.log("Monitor size", monitorWidth, monitorHeight);
- console.log("Window size", windowWidth, windowHeight);
- console.log("Padding", horizontalPadding, verticalPadding);
- console.log("Padding ratio", paddingRatio);
-
- const existingCameraWindow = WebviewWindow.getByLabel("camera");
-
- if (existingCameraWindow) {
- console.log("Camera window already open.");
- existingCameraWindow.close();
- }
-
- const cameraWindow = new WebviewWindow("camera", {
- url: "/camera",
- title: "Cap Camera",
- width: windowWidth,
- height: windowHeight,
- x: x / 2,
- y: y / 2,
- maximized: false,
- resizable: false,
- fullscreen: false,
- transparent: true,
- decorations: false,
- alwaysOnTop: true,
- center: false,
+ if (isSignedIn && !cameraWindowOpen) {
+ import("@tauri-apps/api/window").then(
+ ({ currentMonitor, WebviewWindow }) => {
+ setCameraWindowOpen(true);
+
+ currentMonitor().then((monitor) => {
+ const windowWidth = 250;
+ const windowHeight = 250;
+
+ if (monitor && monitor.size) {
+ const x = 100;
+ const y = monitor.size.height - windowHeight - 100;
+ const scalingFactor = monitor.scaleFactor;
+
+ const existingCameraWindow = WebviewWindow.getByLabel("camera");
+ if (existingCameraWindow) {
+ console.log("Camera window already open.");
+ existingCameraWindow.close();
+ } else {
+ new WebviewWindow("camera", {
+ url: "/camera",
+ title: "Cap Camera",
+ width: windowWidth,
+ height: windowHeight,
+ x: x / scalingFactor,
+ y: y / scalingFactor,
+ maximized: false,
+ resizable: false,
+ fullscreen: false,
+ transparent: true,
+ decorations: false,
+ alwaysOnTop: true,
+ center: false,
+ });
+ }
+ }
});
-
- console.log("Camera window opened:", cameraWindow);
}
- });
+ );
}
}, [isSignedIn, cameraWindowOpen]);
+ // Show loading screen, a spinner or similar, to prevent flash
+ if (loading) {
+ return (
+ <div className="w-full h-full flex items-center justify-center">
+ <LogoSpinner className="w-10 h-auto animate-spin" />
+ </div>
+ );
+ }
+
return (
- <div
- id="app"
- data-tauri-drag-region
- style={{ borderRadius: "16px" }}
- className="pt-4"
- >
+ <div id="app" data-tauri-drag-region style={{ borderRadius: "16px" }}>
<WindowActions />
- {isSignedIn ? <Recorder /> : <SignIn />}
+ {!isSignedIn ? <SignIn /> : <Recorder />}
</div>
);
}
diff --git a/apps/desktop/src/components/windows/Camera.tsx b/apps/desktop/src/components/windows/Camera.tsx
index 46fce922f..38702c147 100644
--- a/apps/desktop/src/components/windows/Camera.tsx
+++ b/apps/desktop/src/components/windows/Camera.tsx
@@ -1,44 +1,47 @@
// @refresh reset
-import React, { useEffect, useRef, useMemo, useState } from "react";
+import React, { useEffect, useRef, useState } from "react";
import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";
export const Camera = () => {
const videoRef = useRef<HTMLVideoElement>(null);
- const { sharedStream } = useMediaDevices();
+ const { selectedVideoDevice } = useMediaDevices();
const [isLoading, setIsLoading] = useState(true);
- const attemptPlayback = () => {
- const videoElement = videoRef.current;
- if (videoElement && !videoElement.srcObject) {
- console.log("Assigning stream to video element.");
- videoElement.srcObject = sharedStream;
- setIsLoading(false);
- }
+ useEffect(() => {
+ if (!videoRef.current || !selectedVideoDevice) return;
+ const video = videoRef.current;
+ const constraints = {
+ video: {
+ deviceId: selectedVideoDevice.deviceId,
+ },
+ };
- 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}`);
- });
- }
- };
+ navigator.mediaDevices
+ .getUserMedia(constraints)
+ .then((stream) => {
+ video.srcObject = stream;
+ video.play();
+ setIsLoading(false);
+ })
+ .catch((err) => {
+ console.error(err);
+ });
- useEffect(() => {
- if (sharedStream) {
- attemptPlayback();
- }
- }, [sharedStream]);
+ return () => {
+ if (video.srcObject) {
+ const stream = video.srcObject as MediaStream;
+ stream.getTracks().forEach((track) => {
+ track.stop();
+ });
+ }
+ };
+ }, [selectedVideoDevice]);
return (
<div
data-tauri-drag-region
- className="w-[250px] h-[250px] bg-gray-200 rounded-full m-0 p-0 relative overflow-hidden flex items-center justify-center"
+ className="w-full h-full bg-gray-200 rounded-full m-0 p-0 relative overflow-hidden flex items-center justify-center border-none outline-none focus:outline-none"
>
{isLoading && (
<div className="w-full h-full absolute top-0 left-0 bg-gray-200 z-10 flex items-center justify-center">
diff --git a/apps/desktop/src/components/windows/Options.tsx b/apps/desktop/src/components/windows/Options.tsx
index 4a9c74c80..88dcb4434 100644
--- a/apps/desktop/src/components/windows/Options.tsx
+++ b/apps/desktop/src/components/windows/Options.tsx
@@ -2,14 +2,22 @@
// import { Recorder } from "@/components/windows/inner/Recorder";
import { SignIn } from "@/components/windows/inner/SignIn";
+import { listen } from "@tauri-apps/api/event";
+import { appWindow } from "@tauri-apps/api/window";
// import { useAuth } from "@/utils/database/AuthContext";
export const Options = () => {
- // const { session, userRef } = useAuth();
- // const currentUser = userRef.current;
+ // async function setupWindowReShow() {
+ // await listen("tauri://focus", () => {
+ // if (appWindow.isVisible) return;
- // if (currentUser) {
- // return <Recorder session={session} />;
+ // appWindow
+ // .show()
+ // .catch((err) => console.error("Error showing window:", err));
+ // });
// }
+
+ // setupWindowReShow();
+
return <SignIn />;
};
diff --git a/apps/desktop/src/components/windows/inner/Countdown.tsx b/apps/desktop/src/components/windows/inner/Countdown.tsx
index 9c2e427af..e53e55645 100644
--- a/apps/desktop/src/components/windows/inner/Countdown.tsx
+++ b/apps/desktop/src/components/windows/inner/Countdown.tsx
@@ -29,7 +29,7 @@ export const Countdown: React.FC<CountdownOverlayProps> = ({
<div
className="absolute inset-0 z-50 flex items-center justify-center rounded-[16px]"
style={{
- backgroundColor: "rgba(0, 0, 0, 0.75)",
+ backgroundColor: "rgba(0, 0, 0, 0.6)",
}}
>
<span className="text-white text-6xl font-bold">{countdown}</span>
diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsx
index 4a0c8a2b8..99617d2f0 100644
--- a/apps/desktop/src/components/windows/inner/Recorder.tsx
+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx
@@ -10,16 +10,12 @@ import { ActionButton } from "@/components/recording/ActionButton";
import { Button } from "@cap/ui";
import { Logo } from "@/components/icons/Logo";
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 { useMediaRecorder } from "@/utils/recording/useMediaRecorder";
import { getSelectedVideoProperties } from "@/utils/recording/utils";
import { getLatestVideoId, saveLatestVideoId } from "@/utils/database/utils";
import { openLinkInBrowser } from "@/utils/helpers";
import toast, { Toaster } from "react-hot-toast";
-import { LogicalSize, WebviewWindow, appWindow } from "@tauri-apps/api/window";
export const Recorder = () => {
const {
@@ -31,15 +27,16 @@ export const Recorder = () => {
setIsRecording,
startingRecording,
setStartingRecording,
- sharedStream,
} = useMediaDevices();
const [countdownActive, setCountdownActive] = useState(false);
const [stoppingRecording, setStoppingRecording] = useState(false);
const [currentStoppingMessage, setCurrentStoppingMessage] =
useState("Stopping Recording");
- const { startMediaRecording, stopMediaRecording } = useMediaRecorder();
+ const [recordingTime, setRecordingTime] = useState("00:00");
const handleContextClick = async (option: string) => {
+ const { showMenu } = await import("tauri-plugin-context-menu");
+
const filteredDevices = devices
.filter((device) =>
option === "video"
@@ -74,8 +71,6 @@ export const Recorder = () => {
};
const handleOverlayFinished = () => {
- // appWindow.hide();
- // WebviewWindow.getByLabel("camera")?.hide();
setIsRecording(true);
setStartingRecording(false);
setCountdownActive(false);
@@ -140,8 +135,7 @@ export const Recorder = () => {
try {
const videoData = await prepareVideoData();
console.log("Video data:", videoData);
- console.log("Shared stream:", sharedStream);
- if (videoData && sharedStream) {
+ if (videoData) {
setStartingRecording(true);
setCountdownActive(true);
await startDualRecording(videoData);
@@ -197,7 +191,7 @@ export const Recorder = () => {
nextMessage();
- const intervalId = setInterval(nextMessage, 2000);
+ const intervalId = setInterval(nextMessage, 2500);
return () => clearInterval(intervalId);
} else {
@@ -205,7 +199,26 @@ export const Recorder = () => {
}
}, [stoppingRecording]);
- console.log("Test...");
+ useEffect(() => {
+ let intervalId: NodeJS.Timeout;
+
+ if (isRecording && !startingRecording) {
+ const startTime = Date.now();
+
+ intervalId = setInterval(() => {
+ const seconds = Math.floor((Date.now() - startTime) / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const formattedSeconds =
+ seconds % 60 < 10 ? `0${seconds % 60}` : seconds % 60;
+ setRecordingTime(`${minutes}:${formattedSeconds}`);
+ }, 1000);
+ }
+
+ return () => {
+ clearInterval(intervalId);
+ setRecordingTime("00:00");
+ };
+ }, [isRecording, startingRecording]);
return (
<>
@@ -217,71 +230,78 @@ export const Recorder = () => {
)}
<div
data-tauri-drag-region
- className="relative flex items-center justify-center"
+ className="pt-4 relative flex items-center justify-center"
>
<div className="w-full">
- <div className="flex items-center justify-between mb-4">
- <div>
- <Logo className="w-24 h-auto" />
- </div>
- </div>
- <div className="space-y-4 w-full">
- <div>
- <label className="text-sm font-medium">Display</label>
- <div className="flex items-center space-x-1">
- <ActionButton
- handler={() => console.log("Screen option selected")}
- icon={<Screen className="w-5 h-5" />}
- label="Screen"
- active={selectedDisplayType === "screen"}
- />
- <ActionButton
- handler={() => toast.error("This option is coming soon!")}
- icon={<Window className="w-5 h-5" />}
- label="Window"
- active={selectedDisplayType === "window"}
- />
+ <div
+ className={`${
+ isRecording === true && "blur-sm pointer-events-none"
+ } mb-4`}
+ >
+ <div className="flex items-center justify-between mb-4">
+ <div>
+ <Logo className="w-24 h-auto" />
</div>
</div>
- <div>
- <label className="text-sm font-medium">Webcam / Video</label>
- <div className="space-y-1">
- <ActionButton
- width="full"
- handler={() => handleContextClick("video")}
- icon={<Video className="w-5 h-5" />}
- label={selectedVideoDevice?.label || "Video"}
- active={selectedVideoDevice !== null}
- />
- <ActionButton
- width="full"
- handler={() => handleContextClick("audio")}
- icon={<Microphone className="w-5 h-5" />}
- label={selectedAudioDevice?.label || "Mic"}
- active={selectedAudioDevice !== null}
- />
+ <div className="space-y-4 mb-4 w-full">
+ <div>
+ <label className="text-sm font-medium">Display</label>
+ <div className="flex items-center space-x-1">
+ <ActionButton
+ handler={() => console.log("Screen option selected")}
+ icon={<Screen className="w-5 h-5" />}
+ label="Screen"
+ active={selectedDisplayType === "screen"}
+ />
+ <ActionButton
+ handler={() => toast.error("This option is coming soon!")}
+ icon={<Window className="w-5 h-5" />}
+ label="Window"
+ active={selectedDisplayType === "window"}
+ />
+ </div>
+ </div>
+ <div>
+ <label className="text-sm font-medium">Webcam / Video</label>
+ <div className="space-y-1">
+ <ActionButton
+ width="full"
+ handler={() => handleContextClick("video")}
+ icon={<Video className="w-5 h-5" />}
+ label={selectedVideoDevice?.label || "Video"}
+ active={selectedVideoDevice !== null}
+ />
+ <ActionButton
+ width="full"
+ handler={() => handleContextClick("audio")}
+ icon={<Microphone className="w-5 h-5" />}
+ label={selectedAudioDevice?.label || "Mic"}
+ active={selectedAudioDevice !== null}
+ />
+ </div>
</div>
</div>
- <Button
- className="w-[97.6%] flex mx-auto"
- onClick={() => {
- if (isRecording) {
- handleStopAllRecordings();
- } else {
- handleStartAllRecordings();
- }
- }}
- spinner={startingRecording || stoppingRecording}
- >
- {startingRecording
- ? "Starting..."
- : isRecording
- ? stoppingRecording
- ? currentStoppingMessage
- : "Stop Recording"
- : "Start Recording"}
- </Button>
</div>
+ <Button
+ {...(isRecording && { variant: "destructive" })}
+ className="w-[97.6%] flex mx-auto"
+ onClick={() => {
+ if (isRecording) {
+ handleStopAllRecordings();
+ } else {
+ handleStartAllRecordings();
+ }
+ }}
+ spinner={startingRecording || stoppingRecording}
+ >
+ {startingRecording
+ ? "Starting..."
+ : isRecording
+ ? stoppingRecording
+ ? currentStoppingMessage
+ : `Stop - ${recordingTime}`
+ : "Start Recording"}
+ </Button>
</div>
<Toaster />
</div>
diff --git a/apps/desktop/src/components/windows/inner/SignIn.tsx b/apps/desktop/src/components/windows/inner/SignIn.tsx
index 920d85281..dc31cbfe8 100644
--- a/apps/desktop/src/components/windows/inner/SignIn.tsx
+++ b/apps/desktop/src/components/windows/inner/SignIn.tsx
@@ -16,23 +16,22 @@ export const SignIn = () => {
return (
<div
data-tauri-drag-region
- className="flex items-center justify-center overflow-hidden flex-col items-center justify-center"
+ className="flex items-center justify-center flex-col items-center justify-center w-full"
>
- <div className="wrapper wrapper-sm">
+ <div className="w-full wrapper wrapper-sm">
<div className="mb-12">
- <Logo className="w-32 h-auto mx-auto" />
+ <Logo className="w-[110px] h-auto mx-auto" />
</div>
<div>
<Button
onClick={() => {
handleSignIn();
}}
- variant="default"
type="button"
disabled={loading}
- className="w-full"
+ className="mx-auto block"
>
- Sign in with browser
+ Sign in with your browser
</Button>
</div>
</div>
diff --git a/apps/desktop/src/utils/auth/index.ts b/apps/desktop/src/utils/auth/index.ts
index 90f9b2170..c79dfe6cf 100644
--- a/apps/desktop/src/utils/auth/index.ts
+++ b/apps/desktop/src/utils/auth/index.ts
@@ -1,11 +1,17 @@
-import { invoke } from "@tauri-apps/api";
-import { listen } from "@tauri-apps/api/event";
+"use client";
+
import callbackTemplate from "./callback.template";
-import { open } from "@tauri-apps/api/shell";
-import { parse } from "url";
+import { URL } from "url";
+
+const dynamicImports = {
+ invoke: () => import("@tauri-apps/api").then(({ invoke }) => invoke),
+ listen: () => import("@tauri-apps/api/event").then(({ listen }) => listen),
+ shell: () => import("@tauri-apps/api/shell"),
+};
export const openSignIn = async (port: string) => {
- if (typeof window !== "undefined") {
+ if (typeof window !== "undefined" && typeof navigator !== "undefined") {
+ const { open } = await dynamicImports.shell(); // Correctly accessing the shell module
await open(
`${process.env.NEXT_PUBLIC_URL}/api/desktop/session/request?redirectUrl=http://localhost:${port}`
);
@@ -13,32 +19,38 @@ export const openSignIn = async (port: string) => {
};
export const login = () => {
- listen("oauth://url", (data: { payload: string }) => {
- if (!data.payload.includes("token")) {
- return;
- }
-
- const urlObject = parse(data.payload, true);
-
- const token = urlObject.query.token as string;
- const expires = urlObject.query.expires as string;
-
- if (!token || !expires) {
- return;
- }
-
- const expiresDate = new Date(parseInt(expires) * 1000);
-
- if (typeof document !== "undefined") {
- document.cookie = `next-auth.session-token=${token}; expires=${expiresDate.toUTCString()}; path=/`;
- }
- });
-
- invoke("plugin:oauth|start", {
- config: {
- response: callbackTemplate,
- },
- }).then(async (port) => {
- await openSignIn(port as string);
- });
+ if (typeof window !== "undefined" && typeof navigator !== "undefined") {
+ dynamicImports.listen().then((listen) => {
+ listen("oauth://url", async (data: { payload: string }) => {
+ if (!data.payload.includes("token")) {
+ return;
+ }
+
+ const urlObject = new URL(data.payload);
+
+ const token = urlObject.searchParams.get("token");
+ const expires = urlObject.searchParams.get("expires");
+
+ if (!token || !expires) {
+ return;
+ }
+
+ const expiresDate = new Date(parseInt(expires) * 1000);
+
+ if (typeof document !== "undefined") {
+ document.cookie = `next-auth.session-token=${token}; expires=${expiresDate.toUTCString()}; path=/`;
+ }
+ });
+ });
+
+ dynamicImports.invoke().then((invoke) => {
+ invoke("plugin:oauth|start", {
+ config: {
+ response: callbackTemplate,
+ },
+ }).then(async (port) => {
+ await openSignIn(port as string);
+ });
+ });
+ }
};
diff --git a/apps/desktop/src/utils/helpers.ts b/apps/desktop/src/utils/helpers.ts
index 09f2e8489..af44241d8 100644
--- a/apps/desktop/src/utils/helpers.ts
+++ b/apps/desktop/src/utils/helpers.ts
@@ -1,48 +1,20 @@
"use client";
-import { appWindow, LogicalPosition } from "@tauri-apps/api/window";
-import { open } from "@tauri-apps/api/shell";
-import { MediaDeviceContextData } from "./recording/MediaDeviceContext";
-
-export const setWindowPosition = (
- position: "bottom_center" | "bottom_right"
-) => {
- if (typeof window === "undefined") {
- return;
- }
-
- appWindow.outerSize().then((size) => {
- const appWidth = size.width / 2;
- const appHeight = size.height / 2;
- const windowHeight = window.screen.availHeight;
- const windowWidth = window.screen.availWidth;
- const calculatedWidth = (windowWidth - appWidth) / 2;
- const calculatedHeight = (windowHeight - appHeight) / 2;
-
- switch (position) {
- case "bottom_center":
- appWindow.setPosition(
- new LogicalPosition(calculatedWidth, calculatedHeight)
- );
- return;
- case "bottom_right":
- appWindow.setPosition(
- new LogicalPosition(
- windowWidth - appWidth - 75,
- windowHeight - appHeight
- )
- );
- return;
- }
+export const openLinkInBrowser = async (url: string) => {
+ let open:
+ | ((path: string, openWith?: string) => Promise<void>)
+ | ((arg0: string) => any);
+ import("@tauri-apps/api/shell").then((shell) => {
+ open = shell.open;
});
-};
-export const openLinkInBrowser = async (url: string) => {
if (typeof window === "undefined") {
return;
}
- await open(url);
+ if (!open) {
+ await open(url);
+ }
return;
};
@@ -64,47 +36,6 @@ export function concatenateTypedArrays(
return result;
}
-export const getVideoSettings = async (
- videoDevice: MediaDeviceContextData["selectedVideoDevice"]
-) => {
- if (!videoDevice) {
- return Promise.reject("Video device not selected");
- }
-
- try {
- if (typeof navigator !== "undefined" && typeof window !== "undefined") {
- const devices = await navigator.mediaDevices.enumerateDevices();
- const videoDevices = devices.filter(
- (device) => device.kind === "videoinput"
- );
- const videoDeviceInfo = videoDevices[videoDevice.index].deviceId;
-
- if (!videoDeviceInfo) {
- return Promise.reject("Cannot find video device info");
- }
-
- const stream = await navigator.mediaDevices.getUserMedia({
- video: {
- deviceId: { exact: videoDeviceInfo },
- },
- });
-
- const settings = stream.getVideoTracks()[0].getSettings();
- stream.getTracks().forEach((track) => track.stop());
-
- return {
- framerate: String(settings.frameRate),
- resolution: settings.width + "x" + settings.height,
- };
- } else {
- return {};
- }
- } catch (error) {
- console.error("Error obtaining video settings:", error);
- return {};
- }
-};
-
export const requestMediaDevicesPermission = async () => {
try {
if (typeof navigator !== "undefined" && typeof window !== "undefined") {
diff --git a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
index 5ace383d6..12d0cf774 100644
--- a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
+++ b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
@@ -33,9 +33,6 @@ export interface MediaDeviceContextData {
setIsRecording: React.Dispatch<React.SetStateAction<boolean>>;
startingRecording: boolean;
setStartingRecording: React.Dispatch<React.SetStateAction<boolean>>;
- sharedStream: MediaStream | null;
- startSharedStream: () => Promise<void>;
- stopSharedStream: () => void;
updateTrigger: number;
}
@@ -64,43 +61,6 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
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");
- if (typeof navigator === "undefined" || typeof window === "undefined")
- return;
- 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");
await enumerateAndStoreDevices();
@@ -147,27 +107,6 @@ 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;
@@ -226,9 +165,9 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
setIsRecording,
startingRecording,
setStartingRecording,
- sharedStream: sharedStream.current,
- startSharedStream,
- stopSharedStream,
+ // sharedStream: sharedStream.current,
+ // startSharedStream,
+ // stopSharedStream,
updateTrigger,
}}
>
diff --git a/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx b/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx
index 109620ec1..b7eead87b 100644
--- a/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx
+++ b/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx
@@ -1,32 +1,42 @@
-import React, { forwardRef, useEffect } from "react";
+import { memo, forwardRef, useEffect } from "react";
import Hls from "hls.js";
-interface AudioPlayerProps {
- src: string;
-}
+export const AudioPlayer = memo(
+ forwardRef<HTMLAudioElement, { src: string; onReady: () => void }>(
+ ({ src, onReady }, ref) => {
+ useEffect(() => {
+ const audio = ref as React.MutableRefObject<HTMLAudioElement | null>;
-export const AudioPlayer = forwardRef<HTMLAudioElement, AudioPlayerProps>(
- ({ src }, ref) => {
- useEffect(() => {
- if (!ref || typeof ref === "function") return;
- const audio = ref.current;
+ if (!audio.current) return;
- if (Hls.isSupported()) {
- const hls = new Hls();
- hls.loadSource(src);
- if (audio) {
- hls.attachMedia(audio);
+ let hls: Hls | null = null;
+
+ if (Hls.isSupported()) {
+ hls = new Hls();
+ hls.loadSource(src);
+ hls.attachMedia(audio.current);
+ hls.on(Hls.Events.MANIFEST_PARSED, () => {
+ onReady();
+ });
+ } else if (audio.current.canPlayType("application/vnd.apple.mpegurl")) {
+ audio.current.src = src;
+ audio.current.addEventListener(
+ "loadedmetadata",
+ () => {
+ onReady();
+ },
+ { once: true }
+ );
}
+
return () => {
- if (audio) {
+ if (hls) {
hls.destroy();
}
};
- } else if (audio && audio.canPlayType("application/vnd.apple.mpegurl")) {
- audio.src = src;
- }
- }, [src, ref]);
+ }, [src, onReady, ref]);
- return <audio ref={ref} controls={true} style={{ display: "none" }} />;
- }
+ return <audio ref={ref} controls={false} style={{ display: "none" }} />;
+ }
+ )
);
diff --git a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
index 6e5f317ca..e323f3a89 100644
--- a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
@@ -3,7 +3,6 @@ import { VideoPlayer } from "./VideoPlayer";
import { useState, useEffect, useRef } from "react";
import { Play, Pause, Maximize, VolumeX, Volume2 } from "lucide-react";
import { LogoSpinner } from "@cap/ui";
-import { AudioPlayer } from "./AudioPlayer";
const formatTime = (time: number) => {
const minutes = Math.floor(time / 60);
@@ -15,138 +14,133 @@ const formatTime = (time: number) => {
export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
const video2Ref = useRef<HTMLVideoElement>(null);
- const audioPlayerRef = useRef<HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
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 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;
-
- console.log("Start times:");
- console.log("audioStartTime: ", data.audioStartTime);
- console.log("videoStartTime: ", data.videoStartTime);
- console.log("length of video", video2Ref.current.duration);
- console.log("length of audio", audioPlayerRef.current.duration);
-
- const timeDifference = (audioStartTime - videoStartTime) / 1000;
- const lengthDifference = Math.abs(
- video2Ref.current.duration - audioPlayerRef.current.duration
- );
-
- console.log("Time difference", timeDifference);
- console.log("Length difference", lengthDifference);
-
- if (timeDifference > 0) {
- audioPlayerRef.current.currentTime =
- video2Ref.current.currentTime + timeDifference;
- } else if (timeDifference < 0) {
- audioPlayerRef.current.currentTime =
- video2Ref.current.currentTime - timeDifference;
- }
-
- console.log("refs:");
- console.log(video2Ref.current.currentTime);
- console.log(audioPlayerRef.current.currentTime);
-
- console.log("Start times adjusted");
+ if (videoMetadataLoaded) {
+ console.log("Metadata loaded");
setIsLoading(false);
- };
-
- if (videoMetadataLoaded && audioMetadataLoaded) {
- adjustForStartTimes();
}
- }, [
- videoMetadataLoaded,
- audioMetadataLoaded,
- data.videoStartTime,
- data.audioStartTime,
- ]);
+ }, [videoMetadataLoaded]);
useEffect(() => {
const onVideoLoadedMetadata = () => {
+ console.log("Video metadata loaded");
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;
videoElement?.addEventListener("loadedmetadata", onVideoLoadedMetadata);
- audioElement?.addEventListener("loadedmetadata", onAudioLoadedMetadata);
return () => {
videoElement?.removeEventListener(
"loadedmetadata",
onVideoLoadedMetadata
);
- audioElement?.removeEventListener(
- "loadedmetadata",
- onAudioLoadedMetadata
- );
};
}, []);
+ const handlePlayPauseClick = async () => {
+ setIsPlaying(!isPlaying);
+
+ const videoElement = video2Ref.current;
+
+ if (!videoElement) return;
+
+ if (isPlaying) {
+ videoElement.pause();
+ } else {
+ try {
+ await videoElement.play();
+ } catch (error) {
+ console.error("Error with playing:", error);
+ setIsPlaying(false); // Revert the isPlaying state on error
+ }
+ }
+ };
+
+ const applyTimeToVideos = (time: number) => {
+ if (video2Ref.current) video2Ref.current.currentTime = time;
+ setCurrentTime(time);
+ };
+
+ // Update useEffect for playback synchronization
useEffect(() => {
- const handleTimeUpdate = () => {
- if (video2Ref.current && !seeking) {
- const currentTime = Math.min(
- video2Ref.current.currentTime,
- audioPlayerRef.current?.currentTime || Infinity
- );
- setCurrentTime(currentTime);
+ const syncPlayback = () => {
+ const videoElement = video2Ref.current;
+
+ if (!isPlaying || isLoading || !videoElement) return;
+
+ const handleTimeUpdate = () => {
+ // Avoid setting state on every time update to reduce re-renders
+ setCurrentTime(videoElement.currentTime);
+ };
+
+ videoElement.play().catch((error) => {
+ console.error("Error playing video", error);
+ setIsPlaying(false);
+ });
+ videoElement.addEventListener("timeupdate", handleTimeUpdate);
+
+ return () =>
+ videoElement.removeEventListener("timeupdate", handleTimeUpdate);
+ };
+
+ syncPlayback();
+ }, [isPlaying, isLoading]); // Add isLoading to the dependency array
+
+ // Add a useEffect for seeking behavior
+ useEffect(() => {
+ const handleSeeking = () => {
+ if (seeking && video2Ref.current) {
+ // Optional: add throttling here to reduce frequency of seek updates
+ setCurrentTime(video2Ref.current.currentTime);
}
};
const videoElement = video2Ref.current;
- const audioElement = audioPlayerRef.current;
- videoElement?.addEventListener("timeupdate", handleTimeUpdate);
- audioElement?.addEventListener("timeupdate", handleTimeUpdate);
+ videoElement?.addEventListener("seeking", handleSeeking);
return () => {
- videoElement?.removeEventListener("timeupdate", handleTimeUpdate);
- audioElement?.removeEventListener("timeupdate", handleTimeUpdate);
+ videoElement?.removeEventListener("seeking", handleSeeking);
};
- }, [seeking]);
+ }, [seeking]); // seeking state controls when this effect re-runs
- const handlePlayPauseClick = () => {
- setIsPlaying(!isPlaying);
- if (!isPlaying) {
+ const calculateNewTime = (event: any, seekBar: any) => {
+ const rect = seekBar.getBoundingClientRect();
+ const offsetX = event.clientX - rect.left;
+ const relativePosition = offsetX / rect.width;
+ return relativePosition * longestDuration;
+ };
+
+ // Changes specifically in handleSeekMouseMove, handleSeekMouseUp to use applyTimeToVideos directly
+ const handleSeekMouseUp = (event: any) => {
+ // Similar change as handleSeekMouseMove, no need for isPlaying check here
+ if (!seeking) return;
+ setSeeking(false);
+ const seekBar = event.currentTarget;
+ const seekTo = calculateNewTime(event, seekBar);
+ applyTimeToVideos(seekTo);
+ if (isPlaying) {
video2Ref.current?.play();
- audioPlayerRef.current?.play();
- } else {
- video2Ref.current?.pause();
- audioPlayerRef.current?.pause();
}
};
const handleMuteClick = () => {
- const muted = !video2Ref.current?.muted;
- if (video2Ref.current) video2Ref.current.muted = muted;
+ if (video2Ref.current) {
+ console.log("Mute clicked");
+ video2Ref.current.muted = video2Ref.current.muted ? false : true;
+ }
};
const handleFullscreenClick = () => {
@@ -164,45 +158,6 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
}
};
- const handleSeekMouseDown = (event: any) => setSeeking(true);
-
- const handleSeekMouseUp = (event: any) => {
- if (!seeking) return;
- setSeeking(false);
- const seekBar = event.currentTarget;
- const seekTo = calculateNewTime(event, seekBar);
-
- // Pause both videos before adjusting the time.
- if (isPlaying) {
- video2Ref.current?.pause();
- }
-
- applyTimeToVideos(seekTo);
-
- if (isPlaying) {
- video2Ref.current?.play();
- }
- };
-
- const handleSeekMouseMove = (event: any) => {
- if (!seeking) return;
- const seekBar = event.currentTarget;
- const seekTo = calculateNewTime(event, seekBar);
- applyTimeToVideos(seekTo);
- };
-
- const calculateNewTime = (event: any, seekBar: any) => {
- const rect = seekBar.getBoundingClientRect();
- const offsetX = event.clientX - rect.left;
- const relativePosition = offsetX / rect.width;
- return relativePosition * longestDuration;
- };
-
- const applyTimeToVideos = (time: number) => {
- if (video2Ref.current) video2Ref.current.currentTime = time;
- setCurrentTime(time);
- };
-
const watchedPercentage =
longestDuration > 0 ? (currentTime / longestDuration) * 100 : 0;
@@ -227,44 +182,6 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
}
}, [isPlaying, isLoading]);
- // useEffect(() => {
- // const video = video2Ref.current;
- // const audio = audioPlayerRef.current;
-
- // // 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);
-
- // // 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
- // }
- // };
-
- // // 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]);
-
return (
<div
className="relative flex h-full w-full overflow-hidden shadow-lg rounded-lg group"
@@ -294,29 +211,22 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
</button>
</div>
)}
- <AudioPlayer
- ref={audioPlayerRef}
- src={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=audio`}
- />
<div
className="relative block w-full h-full rounded-lg bg-black"
style={{ paddingBottom: "min(806px, 56.25%)" }}
>
<VideoPlayer
ref={video2Ref}
- src={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=screen`}
+ videoSrc={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=screen`}
+ audioSrc={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=audio`}
/>
</div>
<div className="absolute bottom-0 z-20 w-full text-white bg-black bg-opacity-50 opacity-0 group-hover:opacity-100 transition-all">
<div
id="seek"
className="drag-seek absolute left-0 right-0 block h-4 mx-4 -mt-2 group z-20 cursor-pointer"
- onMouseDown={handleSeekMouseDown}
- onMouseMove={handleSeekMouseMove}
onMouseUp={handleSeekMouseUp}
onMouseLeave={() => setSeeking(false)}
- onTouchStart={handleSeekMouseDown}
- onTouchMove={handleSeekMouseMove}
onTouchEnd={handleSeekMouseUp}
>
<div className="absolute top-1.5 w-full h-1 bg-white bg-opacity-50 rounded-full z-0" />
diff --git a/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx b/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
index f0e0304ab..b490902e1 100644
--- a/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
+++ b/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
@@ -1,42 +1,108 @@
-import React, { forwardRef, useEffect } from "react";
+import {
+ memo,
+ forwardRef,
+ useEffect,
+ useRef,
+ useImperativeHandle,
+} from "react";
import Hls from "hls.js";
interface VideoPlayerProps {
- src: string;
+ videoSrc: string;
+ audioSrc?: string;
}
-export const VideoPlayer = forwardRef<HTMLVideoElement, VideoPlayerProps>(
- ({ src }, ref) => {
- useEffect(() => {
- if (!ref || typeof ref === "function") return;
- const video = ref.current;
-
- if (Hls.isSupported()) {
- const hls = new Hls();
- hls.loadSource(src);
- if (video) {
- hls.attachMedia(video);
+export const VideoPlayer = memo(
+ forwardRef<HTMLVideoElement, VideoPlayerProps>(
+ ({ videoSrc, audioSrc }, ref) => {
+ const videoRef = useRef<HTMLVideoElement>(null);
+ const audioRef = useRef<HTMLAudioElement>(null);
+ const videoHlsInstance = useRef<Hls | null>(null);
+ const audioHlsInstance = useRef<Hls | null>(null);
+
+ useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
+
+ const initializeHls = (
+ src: string,
+ media: HTMLMediaElement,
+ hlsInstance: React.MutableRefObject<Hls | null>
+ ) => {
+ if (Hls.isSupported()) {
+ const hls = new Hls();
+ hlsInstance.current = hls;
+ hls.loadSource(src);
+ hls.attachMedia(media);
+ } else if (media.canPlayType("application/vnd.apple.mpegurl")) {
+ media.src = src;
}
+ };
+
+ useEffect(() => {
+ if (!videoRef.current) return;
+ initializeHls(videoSrc, videoRef.current, videoHlsInstance);
+
return () => {
- if (video) {
- hls.destroy();
- }
+ videoHlsInstance.current?.destroy();
};
- } else if (video && video.canPlayType("application/vnd.apple.mpegurl")) {
- video.src = src;
- }
- }, [src, ref]);
-
- return (
- <video
- ref={ref}
- className="absolute top-0 left-0 rounded-lg w-full h-full object-contain"
- preload="auto"
- playsInline
- controls={false}
- />
- );
- }
-);
+ }, [videoSrc]);
+
+ useEffect(() => {
+ if (!audioSrc || !audioRef.current) return;
+ initializeHls(audioSrc, audioRef.current, audioHlsInstance);
-export default VideoPlayer;
+ return () => {
+ audioHlsInstance.current?.destroy();
+ };
+ }, [audioSrc]);
+
+ // Synchronize play, pause, and seek operations between video and audio
+ useEffect(() => {
+ if (!audioSrc || !videoRef.current || !audioRef.current) return;
+ const video = videoRef.current;
+ const audio = audioRef.current;
+
+ const playListener = async () => {
+ await audio.play();
+ };
+
+ const pauseListener = () => {
+ audio.pause();
+ };
+
+ const seekListener = () => {
+ audio.currentTime = video.currentTime;
+ };
+
+ video.addEventListener("play", playListener);
+ video.addEventListener("pause", pauseListener);
+ video.addEventListener("seeked", seekListener);
+
+ return () => {
+ video.removeEventListener("play", playListener);
+ video.removeEventListener("pause", pauseListener);
+ video.removeEventListener("seeked", seekListener);
+ };
+ }, [audioSrc]);
+
+ return (
+ <>
+ <video
+ ref={videoRef}
+ className="absolute top-0 left-0 rounded-lg w-full h-full object-contain"
+ preload="metadata"
+ playsInline
+ controls={false}
+ />
+ {audioSrc && (
+ <audio
+ muted={false}
+ ref={audioRef}
+ style={{ display: "none" }}
+ preload="metadata"
+ />
+ )}
+ </>
+ );
+ }
+ )
+);
diff --git a/packages/ui/src/components/Button.tsx b/packages/ui/src/components/Button.tsx
index 303065bf0..5d088cd89 100644
--- a/packages/ui/src/components/Button.tsx
+++ b/packages/ui/src/components/Button.tsx
@@ -11,7 +11,8 @@ const buttonVariants = cva(
variant: {
default:
"group relative isolate font-medium inline-flex items-center justify-center overflow-hidden text-sm transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-full ring-1 before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-full before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-full after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay dark:ring-0 bg-primary ring-2 text-white ring-primary",
- destructive: "bg-red-500 text-red-900 hover:bg-red-600",
+ destructive:
+ "group relative isolate font-medium inline-flex items-center justify-center overflow-hidden text-sm transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-full ring-1 before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-full before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-full after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay dark:ring-0 bg-red-900 ring-2 text-white ring-900",
outline: "border border-input bg-white text-primary hover:bg-gray-50",
secondary: "bg-secondary text-white hover:bg-secondary-1",
},
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 680a44953..e7303b1ff 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -56,6 +56,9 @@ importers:
dotenv:
specifier: ^16.3.1
version: 16.3.1
+ hls.js:
+ specifier: ^1.5.3
+ version: 1.5.3
million:
specifier: ^2.6.4
version: 2.6.4