Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

wip: Rust audio recorder implementation - moving away from JS

Richie McIlroy1ebca09c17dc
diff --git a/apps/desktop/next.config.mjs b/apps/desktop/next.config.mjs
index 354ca33b8..e089be570 100644
--- a/apps/desktop/next.config.mjs
+++ b/apps/desktop/next.config.mjs
@@ -11,7 +11,7 @@ const packageJson = JSON.parse(
const { version } = packageJson;
const nextConfig = {
- reactStrictMode: true,
+ reactStrictMode: false,
swcMinify: true,
output: "export",
transpilePackages: ["@cap/ui", "@cap/utils"],
diff --git a/apps/desktop/public/app-icon.png b/apps/desktop/public/app-icon.png
new file mode 100644
index 000000000..f5e262a46
Binary files /dev/null and b/apps/desktop/public/app-icon.png differ
diff --git a/apps/desktop/public/splashscreen.html b/apps/desktop/public/splashscreen.html
new file mode 100644
index 000000000..0f17b1067
--- /dev/null
+++ b/apps/desktop/public/splashscreen.html
@@ -0,0 +1,38 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Splash Screen</title>
+</head>
+<body>
+ <style>
+ body {
+ margin: 0;
+ padding: 0;
+ }
+ .splashscreen {
+ width: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100vh;
+ }
+ .splashscreen__logo img {
+ width: 100px;
+ height: auto;
+ margin: 0 auto;
+ }
+ p {
+ margin-top: 10px;
+ text-align: center;
+ font-size: 1rem;
+ color: #000;
+ }
+ </style>
+
+ <div class="splashscreen">
+ <div class="splashscreen__logo">
+ <img src="app-icon.png" alt="Logo">
+ <p>Loading...</p>
+ </div>
+ </div>
+</html>
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock
index a7dcfc39b..e2c50cd91 100644
--- a/apps/desktop/src-tauri/Cargo.lock
+++ b/apps/desktop/src-tauri/Cargo.lock
@@ -41,6 +41,28 @@ dependencies = [
"alloc-no-stdlib",
]
+[[package]]
+name = "alsa"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2562ad8dcf0f789f65c6fdaad8a8a9708ed6b488e649da28c01656ad66b8b47"
+dependencies = [
+ "alsa-sys",
+ "bitflags 1.3.2",
+ "libc",
+ "nix 0.24.3",
+]
+
+[[package]]
+name = "alsa-sys"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db8fee663d06c4e303404ef5f40488a53e062f89ba8bfed81f42325aafad1527"
+dependencies = [
+ "libc",
+ "pkg-config",
+]
+
[[package]]
name = "android-tzdata"
version = "0.1.1"
@@ -315,6 +337,26 @@ version = "0.21.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
+[[package]]
+name = "bindgen"
+version = "0.69.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0"
+dependencies = [
+ "bitflags 2.4.2",
+ "cexpr",
+ "clang-sys",
+ "itertools",
+ "lazy_static",
+ "lazycell",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "rustc-hash",
+ "shlex",
+ "syn 2.0.48",
+]
+
[[package]]
name = "bit_field"
version = "0.10.2"
@@ -450,10 +492,14 @@ dependencies = [
name = "cap"
version = "0.0.0"
dependencies = [
+ "byteorder",
"chrono",
+ "cpal",
"dotenv_codegen",
"ffmpeg-sidecar",
"futures",
+ "hound",
+ "num-traits",
"reqwest",
"serde",
"serde_json",
@@ -486,6 +532,7 @@ version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0"
dependencies = [
+ "jobserver",
"libc",
]
@@ -495,6 +542,15 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
+[[package]]
+name = "cexpr"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
+dependencies = [
+ "nom",
+]
+
[[package]]
name = "cfb"
version = "0.7.3"
@@ -546,6 +602,17 @@ dependencies = [
"windows-targets 0.52.0",
]
+[[package]]
+name = "clang-sys"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67523a3b4be3ce1989d607a828d036249522dd9c1c8de7f4dd2dae43a37369d1"
+dependencies = [
+ "glob",
+ "libc",
+ "libloading 0.8.1",
+]
+
[[package]]
name = "clipboard-win"
version = "4.5.0"
@@ -687,6 +754,51 @@ dependencies = [
"libc",
]
+[[package]]
+name = "coreaudio-rs"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "321077172d79c662f64f5071a03120748d5bb652f5231570141be24cfcd2bace"
+dependencies = [
+ "bitflags 1.3.2",
+ "core-foundation-sys",
+ "coreaudio-sys",
+]
+
+[[package]]
+name = "coreaudio-sys"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f01585027057ff5f0a5bf276174ae4c1594a2c5bde93d5f46a016d76270f5a9"
+dependencies = [
+ "bindgen",
+]
+
+[[package]]
+name = "cpal"
+version = "0.15.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d959d90e938c5493000514b446987c07aed46c668faaa7d34d6c7a67b1a578c"
+dependencies = [
+ "alsa",
+ "core-foundation-sys",
+ "coreaudio-rs",
+ "dasp_sample",
+ "jni 0.19.0",
+ "js-sys",
+ "libc",
+ "mach2",
+ "ndk 0.7.0",
+ "ndk-context",
+ "oboe",
+ "once_cell",
+ "parking_lot",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "windows 0.46.0",
+]
+
[[package]]
name = "cpufeatures"
version = "0.2.12"
@@ -827,6 +939,12 @@ dependencies = [
"syn 2.0.48",
]
+[[package]]
+name = "dasp_sample"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
+
[[package]]
name = "deranged"
version = "0.3.11"
@@ -1762,6 +1880,12 @@ 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"
@@ -2006,6 +2130,15 @@ version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3"
+[[package]]
+name = "itertools"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
version = "0.4.8"
@@ -2041,6 +2174,20 @@ dependencies = [
"system-deps 5.0.0",
]
+[[package]]
+name = "jni"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6df18c2e3db7e453d3c6ac5b3e9d5182664d28788126d39b91f2d1e22b017ec"
+dependencies = [
+ "cesu8",
+ "combine",
+ "jni-sys",
+ "log",
+ "thiserror",
+ "walkdir",
+]
+
[[package]]
name = "jni"
version = "0.20.0"
@@ -2061,6 +2208,15 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
+[[package]]
+name = "jobserver"
+version = "0.1.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab46a6e9526ddef3ae7f787c06f0f2600639ba80ea3eade3d8e670a2230f51d6"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "jpeg-decoder"
version = "0.3.1"
@@ -2110,6 +2266,12 @@ version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
+[[package]]
+name = "lazycell"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
+
[[package]]
name = "lebe"
version = "0.5.2"
@@ -2136,7 +2298,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1b3b6681973cea8cc3bce7391e6d7d5502720b80a581c9a95c9cbaf592826aa"
dependencies = [
"gtk-sys",
- "libloading",
+ "libloading 0.7.4",
"once_cell",
]
@@ -2156,6 +2318,16 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "libloading"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c571b676ddfc9a8c12f1f3d3085a7b163966a8fd8098a90640953ce5f6170161"
+dependencies = [
+ "cfg-if",
+ "windows-sys 0.48.0",
+]
+
[[package]]
name = "libredox"
version = "0.0.1"
@@ -2238,6 +2410,15 @@ dependencies = [
"time",
]
+[[package]]
+name = "mach2"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19b955cdeb2a02b9117f121ce63aa52d08ade45de53e48fe6a38b39c10f6f709"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "malloc_buf"
version = "0.0.6"
@@ -2316,6 +2497,12 @@ dependencies = [
"unicase",
]
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
[[package]]
name = "miniz_oxide"
version = "0.7.1"
@@ -2363,11 +2550,25 @@ checksum = "2032c77e030ddee34a6787a64166008da93f6a352b629261d0fee232b8742dd4"
dependencies = [
"bitflags 1.3.2",
"jni-sys",
- "ndk-sys",
+ "ndk-sys 0.3.0",
"num_enum",
"thiserror",
]
+[[package]]
+name = "ndk"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "451422b7e4718271c8b5b3aadf5adedba43dc76312454b387e98fae0fc951aa0"
+dependencies = [
+ "bitflags 1.3.2",
+ "jni-sys",
+ "ndk-sys 0.4.1+23.1.7779620",
+ "num_enum",
+ "raw-window-handle",
+ "thiserror",
+]
+
[[package]]
name = "ndk-context"
version = "0.1.1"
@@ -2383,12 +2584,32 @@ dependencies = [
"jni-sys",
]
+[[package]]
+name = "ndk-sys"
+version = "0.4.1+23.1.7779620"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3cf2aae958bd232cac5069850591667ad422d263686d75b52a065f9badeee5a3"
+dependencies = [
+ "jni-sys",
+]
+
[[package]]
name = "new_debug_unreachable"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54"
+[[package]]
+name = "nix"
+version = "0.24.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa52e972a9a719cecb6864fb88568781eb706bac2cd1d4f04a648542dbf78069"
+dependencies = [
+ "bitflags 1.3.2",
+ "cfg-if",
+ "libc",
+]
+
[[package]]
name = "nix"
version = "0.26.4"
@@ -2407,6 +2628,16 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
[[package]]
name = "notify-rust"
version = "4.10.0"
@@ -2430,6 +2661,17 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "num-derive"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "876a53fff98e03a936a674b29568b0e605f06b29372c2489ff4de23f1949743d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "num-traits"
version = "0.2.17"
@@ -2540,6 +2782,29 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "oboe"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8868cc237ee02e2d9618539a23a8d228b9bb3fc2e7a5b11eed3831de77c395d0"
+dependencies = [
+ "jni 0.20.0",
+ "ndk 0.7.0",
+ "ndk-context",
+ "num-derive",
+ "num-traits",
+ "oboe-sys",
+]
+
+[[package]]
+name = "oboe-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f44155e7fb718d3cfddcf70690b2b51ac4412f347cd9e4fbe511abe9cd7b5f2"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "once_cell"
version = "1.19.0"
@@ -3274,6 +3539,12 @@ version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
+[[package]]
+name = "rustc-hash"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+
[[package]]
name = "rustc_version"
version = "0.4.0"
@@ -3575,6 +3846,12 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
[[package]]
name = "signal-hook-registry"
version = "1.4.1"
@@ -3835,14 +4112,14 @@ dependencies = [
"gtk",
"image",
"instant",
- "jni",
+ "jni 0.20.0",
"lazy_static",
"libappindicator",
"libc",
"log",
- "ndk",
+ "ndk 0.6.0",
"ndk-context",
- "ndk-sys",
+ "ndk-sys 0.3.0",
"objc",
"once_cell",
"parking_lot",
@@ -4928,6 +5205,15 @@ dependencies = [
"windows_x86_64_msvc 0.39.0",
]
+[[package]]
+name = "windows"
+version = "0.46.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdacb41e6a96a052c6cb63a144f24900236121c6f63f4f8219fef5977ecb0c25"
+dependencies = [
+ "windows-targets 0.42.2",
+]
+
[[package]]
name = "windows"
version = "0.48.0"
@@ -5384,7 +5670,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1641b26d4dec61337c35a1b1aaf9e3cba8f46f0b43636c609ab0291a648040a"
dependencies = [
"gethostname",
- "nix",
+ "nix 0.26.4",
"winapi",
"winapi-wsapoll",
"x11rb-protocol",
@@ -5396,7 +5682,7 @@ version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82d6c3f9a0fb6701fab8f6cea9b0c0bd5d6876f1f89f7fada07e558077c344bc"
dependencies = [
- "nix",
+ "nix 0.26.4",
]
[[package]]
@@ -5416,7 +5702,7 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2769203cd13a0c6015d515be729c526d041e9cf2c0cc478d57faee85f40c6dcd"
dependencies = [
- "nix",
+ "nix 0.26.4",
"winapi",
]
@@ -5444,7 +5730,7 @@ dependencies = [
"futures-sink",
"futures-util",
"hex",
- "nix",
+ "nix 0.26.4",
"once_cell",
"ordered-stream",
"rand 0.8.5",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 5e3cf672b..589649c2a 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -19,6 +19,8 @@ serde_json = "1.0"
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"] }
@@ -30,6 +32,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"
[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
new file mode 100644
index 000000000..0f34a20dc
--- /dev/null
+++ b/apps/desktop/src-tauri/src/audio.rs
@@ -0,0 +1,205 @@
+use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
+use cpal::SampleFormat;
+use std::io::{BufReader, BufRead};
+use std::process::{Stdio, Command};
+use std::thread;
+use std::io::Write;
+use byteorder::{ByteOrder, LittleEndian};
+use std::sync::{Arc, Mutex};
+
+use crate::recording::RecordingOptions;
+use crate::utils::ffmpeg_path_as_str;
+
+pub struct AudioRecorder {
+ pub options: Option<RecordingOptions>,
+ ffmpeg_stdin: Arc<Mutex<Option<std::process::ChildStdin>>>,
+}
+
+impl AudioRecorder {
+
+ pub fn new() -> Self {
+ AudioRecorder {
+ options: None,
+ ffmpeg_stdin: Arc::new(Mutex::new(None)),
+ }
+ }
+
+ pub fn setup_recording(&mut self, options: RecordingOptions, audio_file_path: &str) {
+ self.options = Some(options);
+
+ let host = cpal::default_host();
+ let device = host.default_input_device().expect("No input device available");
+ let config = device.default_input_config().expect("Failed to get default input config");
+ 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",
+ _ => panic!("Unsupported sample format."),
+ };
+
+ println!("Sample rate: {}", sample_rate);
+ println!("Channels: {}", channels);
+ println!("Sample format: {}", sample_format);
+ println!("Audio file path: {}", audio_file_path);
+
+ let ffmpeg_binary_path_str = ffmpeg_path_as_str().unwrap().to_owned();
+ let audio_file_path_owned = audio_file_path.to_owned();
+ let sample_rate_str = sample_rate.to_string();
+ let channels_str = channels.to_string();
+
+ 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 ffmpeg_command = vec![
+ "-f", sample_format,
+ "-ar", &sample_rate_str,
+ "-ac", &channels_str,
+ "-i", "-",
+ "-c:a", "aac",
+ "-b:a", "128k",
+ "-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())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("ffmpeg command failed to start");
+
+ thread::spawn(move || {
+ let stdout = BufReader::new(child.stdout.take().expect("failed to get stdout"));
+ for line in stdout.lines() {
+ match line {
+ Ok(line) => eprintln!("Audio stdout: {}", line),
+ Err(e) => eprintln!("Error reading FFmpeg stdout: {}", e),
+ }
+ }
+ });
+
+ thread::spawn(move || {
+ let stderr = BufReader::new(child.stderr.take().expect("failed to get stderr"));
+ for line in stderr.lines() {
+ match line {
+ Ok(line) => eprintln!("Audio stderr: {}", line),
+ Err(e) => eprintln!("Error reading FFmpeg stderr: {}", e),
+ }
+ }
+ });
+
+ let stdin = child.stdin.take().expect("failed to get stdin");
+ *self.ffmpeg_stdin.lock().unwrap() = Some(stdin);
+
+ self.start_audio_recording().expect("Failed to start audio recording");
+ }
+
+ pub fn start_audio_recording(&mut self) -> Result<(), &'static str> {
+ let host = cpal::default_host();
+ let device = host.default_input_device().ok_or("Unable to find default input device")?;
+ let config: cpal::SupportedStreamConfig = device
+ .default_input_config()
+ .expect("Failed to get default input config");
+ println!("Default input config: {:?}", config);
+ let sample_format = config.sample_format();
+
+ println!("Starting audio recording with sample format: {:?}", sample_format);
+
+ let err_fn = move |err| {
+ eprintln!("an error occurred on stream: {}", err);
+ };
+
+ 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"),
+ };
+
+ stream.play().unwrap();
+
+ Ok(())
+ }
+
+ pub fn stop_audio_recording(&mut self) -> Result<(), &'static str> {
+ let mut ffmpeg_stdin_opt = self.ffmpeg_stdin.lock().map_err(|_| "Failed to acquire lock on ffmpeg stdin")?;
+
+ if ffmpeg_stdin_opt.is_some() {
+ *ffmpeg_stdin_opt = None;
+ println!("Stopped audio recording and signaled FFmpeg to terminate.");
+ } else {
+ return Err("Recording was not started or FFmpeg stdin was already closed");
+ }
+
+ Ok(())
+ }
+}
+
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 4bdd421ce..4b243552a 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -14,6 +14,7 @@ mod recording;
mod upload;
mod devices;
mod utils;
+mod audio;
use recording::{RecordingState, start_dual_recording, stop_all_recordings};
use upload::upload_file;
@@ -76,7 +77,7 @@ fn main() {
set_shadow(&camera_window, true).expect("Unsupported platform!");
}
- if let Some(options_window) = app.get_window("options") {
+ if let Some(options_window) = app.get_window("main") {
let _ = options_window.move_window(Position::Center);
#[cfg(target_os = "macos")]
apply_vibrancy(&options_window, NSVisualEffectMaterial::MediumLight, None, Some(16.0)).expect("Unsupported platform! 'apply_vibrancy' is only supported on macOS");
@@ -91,6 +92,7 @@ fn main() {
let recording_state = RecordingState {
screen_process: None,
video_process: None,
+ audio_process: None,
upload_handles: Mutex::new(vec![]),
recording_options: None,
shutdown_flag: Arc::new(AtomicBool::new(false)),
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 27b08b328..40d5c75c5 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -8,24 +8,29 @@ use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::{Semaphore, Mutex};
use tokio::task::JoinHandle;
use tokio::time::{timeout, Duration};
+use tokio::io::AsyncBufReadExt;
+use tokio::io::{BufReader as TokioBufReader, AsyncRead};
use serde::{Serialize, Deserialize};
-use std::env;
use chrono::Utc;
use reqwest::Client;
use tauri::State;
use crate::utils::ffmpeg_path_as_str;
use crate::upload::upload_file;
+use crate::audio::AudioRecorder;
pub struct RecordingState {
pub screen_process: Option<tokio::process::Child>,
pub video_process: Option<tokio::process::Child>,
+ pub audio_process: Option<AudioRecorder>,
pub upload_handles: Mutex<Vec<JoinHandle<Result<(), String>>>>,
pub recording_options: Option<RecordingOptions>,
pub shutdown_flag: Arc<AtomicBool>,
pub data_dir: Option<PathBuf>,
}
+unsafe impl Send for RecordingState {}
+
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RecordingOptions {
pub user_id: String,
@@ -46,6 +51,23 @@ 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()?;
@@ -57,10 +79,8 @@ 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);
@@ -118,16 +138,25 @@ pub async fn start_dual_recording(
// .spawn()
// .map_err(|e| e.to_string())?;
- let screen_stdout = screen_child.stdout.take().unwrap();
+ // In the part where you spawn the FFmpeg process and handle its output:
+
let screen_stderr = screen_child.stderr.take().unwrap();
- tokio::spawn(log_output(screen_stdout, "Screen stdout".to_string()));
- tokio::spawn(log_output(screen_stderr, "Screen stderr".to_string()));
+ let ffmpeg_start_trigger = "time=00:00:00.00".to_string();
+
+ let server_url_base: String = dotenv_codegen::dotenv!("NEXT_PUBLIC_URL").into();
+ let video_id_clone = options.video_id.clone();
+
+ let started_callback = Arc::new(move || {
+ let server_url_base = server_url_base.clone();
+ let video_id_clone = video_id_clone.clone();
+ tokio::spawn(async move {
+ if let Err(e) = send_metadata_api(&video_id_clone, &server_url_base).await {
+ eprintln!("Failed to send metadata API request: {}", e);
+ }
+ });
+ });
- 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);
- }
+ 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();
let ffmpeg_screen_screenshot_args_clone = ffmpeg_screen_screenshot_args.clone();
@@ -154,17 +183,16 @@ 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 audio_upload = start_upload_loop(state.clone(), audio_chunks_dir, options.clone(), "audio".to_string(), shutdown_flag.clone());
+ // let screen_upload = start_upload_loop(state.clone(), screen_chunks_dir, options.clone(), "screen".to_string(), shutdown_flag.clone());
- match tokio::try_join!(screen_upload, audio_upload) {
- Ok(_) => {
- println!("Both upload loops completed successfully.");
- },
- Err(e) => {
- eprintln!("An error occurred: {}", e);
- },
- }
+ // match tokio::try_join!(screen_upload) {
+ // Ok(_) => {
+ // println!("Both upload loops completed successfully.");
+ // },
+ // Err(e) => {
+ // eprintln!("An error occurred: {}", e);
+ // },
+ // }
Ok(())
}
@@ -183,6 +211,10 @@ pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -
if let Some(child_process) = &mut guard.screen_process {
let _ = child_process.kill().await;
}
+
+ if let Some(audio_process) = &mut guard.audio_process {
+ audio_process.stop_audio_recording();
+ }
// Assuming there's a video_process similar to screen_process.
//if let Some(child_process) = &mut guard.video_process {
// let _ = child_process.kill().await;
@@ -203,7 +235,7 @@ pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -
let state_guard = state.lock().await;
let data_dir_option = state_guard.data_dir.clone();
let options_clone = state_guard.recording_options.clone();
- let shutdown_flag_clone = state_guard.shutdown_flag.clone();
+ let _shutdown_flag_clone = state_guard.shutdown_flag.clone();
drop(state_guard);
if let Some(data_dir) = data_dir_option {
@@ -238,12 +270,27 @@ fn clean_and_create_dir(dir: &Path) -> Result<(), String> {
}
}
-async fn log_output(reader: impl tokio::io::AsyncRead + Unpin + Send + 'static, desc: String) {
- use tokio::io::{AsyncBufReadExt, BufReader};
- let mut reader = BufReader::new(reader).lines();
-
- while let Ok(Some(line)) = reader.next_line().await {
- println!("{}: {}", desc, line);
+async fn log_output<R>(
+ mut reader: R,
+ description: String,
+ start_trigger: Option<String>,
+ started_callback: Option<Arc<dyn Fn() + Send + Sync>>
+)
+where
+ R: AsyncRead + Unpin + Send + 'static,
+{
+ let mut buf_reader = TokioBufReader::new(reader).lines();
+
+ while let Ok(Some(line)) = buf_reader.next_line().await {
+ println!("{}: {}", description, line);
+
+ if let Some(trigger) = &start_trigger {
+ if line.contains(trigger) {
+ if let Some(callback) = &started_callback {
+ callback();
+ }
+ }
+ }
}
}
@@ -550,8 +597,8 @@ async fn take_screenshot(
let screen_screenshot_stdout = screen_screenshot_child.stdout.take().unwrap();
let screen_screenshot_stderr = screen_screenshot_child.stderr.take().unwrap();
- tokio::spawn(log_output(screen_screenshot_stdout, "Screen screenshot stdout".to_string()));
- tokio::spawn(log_output(screen_screenshot_stderr, "Screen screenshot stderr".to_string()));
+ tokio::spawn(log_output(screen_screenshot_stdout, "Screen screenshot stdout".to_string(), None, None));
+ tokio::spawn(log_output(screen_screenshot_stderr, "Screen screenshot stderr".to_string(), None, None));
Ok(())
}
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index 1c0811be2..7e4c7210a 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -76,36 +76,6 @@
"title": "Cap",
"label": "main",
"url": "/",
- "width": 0,
- "height": 0,
- "maximized": false,
- "resizable": true,
- "fullscreen": false,
- "transparent": true,
- "decorations": false,
- "alwaysOnTop": false,
- "center": true
- },
- {
- "title": "Cap",
- "label": "camera",
- "url": "/camera",
- "width": 250,
- "height": 250,
- "maximized": false,
- "resizable": false,
- "fullscreen": false,
- "transparent": true,
- "decorations": false,
- "alwaysOnTop": true,
- "center": false,
- "x": 0,
- "y": 0
- },
- {
- "title": "Cap",
- "label": "options",
- "url": "/options",
"width": 285,
"height": 410,
"maximized": false,
@@ -114,8 +84,7 @@
"transparent": true,
"decorations": false,
"alwaysOnTop": false,
- "center": true,
- "y": 0
+ "center": true
}
]
}
diff --git a/apps/desktop/src/app/camera/page.tsx b/apps/desktop/src/app/camera/page.tsx
index f44d2f4b8..79c99cdaf 100644
--- a/apps/desktop/src/app/camera/page.tsx
+++ b/apps/desktop/src/app/camera/page.tsx
@@ -1,10 +1,8 @@
"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/app/options/page.tsx b/apps/desktop/src/app/options/page.tsx
deleted file mode 100644
index 60d064d14..000000000
--- a/apps/desktop/src/app/options/page.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-"use client";
-
-import React, { useState, useEffect } from "react";
-import { getCookie } from "cookies-next";
-import { SignIn } from "@/components/windows/inner/SignIn";
-import { Recorder } from "@/components/windows/inner/Recorder";
-import { WindowActions } from "@/components/WindowActions";
-
-export default function CameraPage() {
- const [isSignedIn, setIsSignedIn] = useState(false);
-
- useEffect(() => {
- const cookie = getCookie("next-auth.session-token");
- setIsSignedIn(!!cookie);
- }, []);
-
- useEffect(() => {
- const interval = setInterval(() => {
- const cookie = getCookie("next-auth.session-token");
- setIsSignedIn(!!cookie);
- }, 1000);
-
- return () => clearInterval(interval);
- }, []);
-
- return (
- <div
- id="app"
- data-tauri-drag-region
- style={{ borderRadius: "16px" }}
- className="pt-4"
- >
- <WindowActions />
- {isSignedIn ? <Recorder /> : <SignIn />}
- </div>
- );
-}
diff --git a/apps/desktop/src/app/page.tsx b/apps/desktop/src/app/page.tsx
index d760bafa1..5433ac48f 100644
--- a/apps/desktop/src/app/page.tsx
+++ b/apps/desktop/src/app/page.tsx
@@ -1,8 +1,98 @@
"use client";
-import { useRouter } from "next/navigation";
+import React, { useState, useEffect } from "react";
+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";
-export default function IndexPage() {
- const router = useRouter();
- router.replace("/options");
+export default function CameraPage() {
+ const [isSignedIn, setIsSignedIn] = useState(false);
+ const [cameraWindowOpen, setCameraWindowOpen] = useState(false);
+
+ useEffect(() => {
+ const cookie = getCookie("next-auth.session-token");
+ setIsSignedIn(!!cookie);
+ }, []);
+
+ useEffect(() => {
+ const interval = setInterval(() => {
+ const cookie = getCookie("next-auth.session-token");
+ setIsSignedIn(!!cookie);
+ }, 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,
+ });
+
+ console.log("Camera window opened:", cameraWindow);
+ }
+ });
+ }
+ }, [isSignedIn, cameraWindowOpen]);
+
+ return (
+ <div
+ id="app"
+ data-tauri-drag-region
+ style={{ borderRadius: "16px" }}
+ className="pt-4"
+ >
+ <WindowActions />
+ {isSignedIn ? <Recorder /> : <SignIn />}
+ </div>
+ );
}
diff --git a/apps/desktop/src/components/WindowActions.tsx b/apps/desktop/src/components/WindowActions.tsx
index f84fb99b7..c00dbd3b5 100644
--- a/apps/desktop/src/components/WindowActions.tsx
+++ b/apps/desktop/src/components/WindowActions.tsx
@@ -7,8 +7,8 @@ export const WindowActions = () => {
<div className="absolute top-3 left-3 w-full flex items-center justify-start gap-x-2">
<div>
<button
- onClick={() => {
- exit();
+ onClick={async () => {
+ await exit();
}}
className={`bg-red-500 hover:bg-red-700 transition-all ${actionButtonBase}`}
></button>
diff --git a/apps/desktop/src/components/windows/Camera.tsx b/apps/desktop/src/components/windows/Camera.tsx
index c0ba26a76..46fce922f 100644
--- a/apps/desktop/src/components/windows/Camera.tsx
+++ b/apps/desktop/src/components/windows/Camera.tsx
@@ -32,16 +32,6 @@ export const Camera = () => {
useEffect(() => {
if (sharedStream) {
attemptPlayback();
- const handleTrackAdded = () => attemptPlayback();
- const handleTrackRemoved = () => attemptPlayback();
-
- sharedStream.addEventListener("addtrack", handleTrackAdded);
- sharedStream.addEventListener("removetrack", handleTrackRemoved);
-
- return () => {
- sharedStream.removeEventListener("addtrack", handleTrackAdded);
- sharedStream.removeEventListener("removetrack", handleTrackRemoved);
- };
}
}, [sharedStream]);
diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsx
index d3a8c6e4d..4a0c8a2b8 100644
--- a/apps/desktop/src/components/windows/inner/Recorder.tsx
+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx
@@ -61,7 +61,7 @@ export const Recorder = () => {
},
}));
- showMenu({
+ await showMenu({
items: [...filteredDevices],
...(filteredDevices.length === 0 && {
items: [
@@ -144,10 +144,7 @@ export const Recorder = () => {
if (videoData && sharedStream) {
setStartingRecording(true);
setCountdownActive(true);
- await Promise.all([
- startMediaRecording(sharedStream),
- startDualRecording(videoData),
- ]);
+ await startDualRecording(videoData);
} else {
throw new Error("Failed to prepare video data.");
}
@@ -162,28 +159,6 @@ export const Recorder = () => {
try {
console.log("Stopping recordings...");
- 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");
diff --git a/apps/desktop/src/utils/auth/callback.template.ts b/apps/desktop/src/utils/auth/callback.template.ts
index cd4490f08..9de85f695 100644
--- a/apps/desktop/src/utils/auth/callback.template.ts
+++ b/apps/desktop/src/utils/auth/callback.template.ts
@@ -19,7 +19,7 @@ export default `
</style>
</head>
<body>
- <h2>You are now signed in, and can return to the Cap desktop app.</h2>
+ <h1>You are now signed in. Please re-open the Cap desktop app to continue.</h1>
</body>
</html>
`;
diff --git a/apps/desktop/src/utils/auth/index.ts b/apps/desktop/src/utils/auth/index.ts
index 24124fa90..90f9b2170 100644
--- a/apps/desktop/src/utils/auth/index.ts
+++ b/apps/desktop/src/utils/auth/index.ts
@@ -5,9 +5,11 @@ import { open } from "@tauri-apps/api/shell";
import { parse } from "url";
export const openSignIn = async (port: string) => {
- await open(
- `${process.env.NEXT_PUBLIC_URL}/api/desktop/session/request?redirectUrl=http://localhost:${port}`
- );
+ if (typeof window !== "undefined") {
+ await open(
+ `${process.env.NEXT_PUBLIC_URL}/api/desktop/session/request?redirectUrl=http://localhost:${port}`
+ );
+ }
};
export const login = () => {
@@ -27,14 +29,16 @@ export const login = () => {
const expiresDate = new Date(parseInt(expires) * 1000);
- document.cookie = `next-auth.session-token=${token}; expires=${expiresDate.toUTCString()}; path=/`;
+ if (typeof document !== "undefined") {
+ document.cookie = `next-auth.session-token=${token}; expires=${expiresDate.toUTCString()}; path=/`;
+ }
});
invoke("plugin:oauth|start", {
config: {
response: callbackTemplate,
},
- }).then((port) => {
- openSignIn(port as string);
+ }).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 f295c24f0..09f2e8489 100644
--- a/apps/desktop/src/utils/helpers.ts
+++ b/apps/desktop/src/utils/helpers.ts
@@ -1,3 +1,5 @@
+"use client";
+
import { appWindow, LogicalPosition } from "@tauri-apps/api/window";
import { open } from "@tauri-apps/api/shell";
import { MediaDeviceContextData } from "./recording/MediaDeviceContext";
@@ -5,6 +7,10 @@ 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;
@@ -32,6 +38,10 @@ export const setWindowPosition = (
};
export const openLinkInBrowser = async (url: string) => {
+ if (typeof window === "undefined") {
+ return;
+ }
+
await open(url);
return;
@@ -62,29 +72,33 @@ export const getVideoSettings = async (
}
try {
- 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");
- }
+ 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 stream = await navigator.mediaDevices.getUserMedia({
+ video: {
+ deviceId: { exact: videoDeviceInfo },
+ },
+ });
- const settings = stream.getVideoTracks()[0].getSettings();
- stream.getTracks().forEach((track) => track.stop());
+ const settings = stream.getVideoTracks()[0].getSettings();
+ stream.getTracks().forEach((track) => track.stop());
- return {
- framerate: String(settings.frameRate),
- resolution: settings.width + "x" + settings.height,
- };
+ return {
+ framerate: String(settings.frameRate),
+ resolution: settings.width + "x" + settings.height,
+ };
+ } else {
+ return {};
+ }
} catch (error) {
console.error("Error obtaining video settings:", error);
return {};
@@ -93,8 +107,14 @@ export const getVideoSettings = async (
export const requestMediaDevicesPermission = async () => {
try {
- await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
- console.log("Permissions to access media devices have been granted.");
+ if (typeof navigator !== "undefined" && typeof window !== "undefined") {
+ await navigator.mediaDevices.getUserMedia({
+ video: true,
+ audio: true,
+ });
+
+ console.log("Permissions to access media devices have been granted.");
+ }
} catch (error) {
console.error("Permissions to access media devices were denied.", error);
}
diff --git a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
index c9fdc8499..5ace383d6 100644
--- a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
+++ b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
@@ -82,6 +82,8 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
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);
diff --git a/apps/desktop/src/utils/recording/useMediaRecorder.ts b/apps/desktop/src/utils/recording/useMediaRecorder.ts
index 81739c7e4..4fc18e990 100644
--- a/apps/desktop/src/utils/recording/useMediaRecorder.ts
+++ b/apps/desktop/src/utils/recording/useMediaRecorder.ts
@@ -1,3 +1,5 @@
+"use client";
+
import { useState, useRef, useCallback, useEffect } from "react";
import { FFmpeg as FfmpegType } from "@ffmpeg/ffmpeg";
import { fetchFile } from "@ffmpeg/util";
@@ -18,6 +20,7 @@ export const useMediaRecorder = () => {
const queue = useRef<Blob[]>([]);
const processingQueue = useRef(false);
const segmentCounter = useRef(0);
+ const [metadataRecorded, setMetadataRecorded] = useState(false);
useEffect(() => {
const loadFfmpeg = async () => {
@@ -209,7 +212,7 @@ export const useMediaRecorder = () => {
console.log("stream.getTracks():");
console.log(stream.getTracks());
- const initRecorder = () => {
+ const initRecorder = async () => {
if (
mediaRecorder.current &&
mediaRecorder.current.state !== "inactive"
@@ -228,7 +231,7 @@ export const useMediaRecorder = () => {
};
mediaRecorder.current = new MediaRecorder(stream, options);
- mediaRecorder.current.ondataavailable = (event) => {
+ mediaRecorder.current.ondataavailable = async (event) => {
console.log(`Blob size: ${event.data.size}`);
if (event.data.size > 0) {
queue.current.push(event.data);
@@ -241,12 +244,10 @@ export const useMediaRecorder = () => {
};
mediaRecorder.current.start();
- console.log("MediaRecorder started:", mediaRecorder.current);
};
isRecording.current = true;
initRecorder();
- await sendMetadataAPI();
const requestDataInterval = setInterval(() => {
if (mediaRecorder.current && isRecording.current === true) {
@@ -260,6 +261,14 @@ export const useMediaRecorder = () => {
}
}, 3000);
+ mediaRecorder.current.onstart = async () => {
+ if (metadataRecorded === false) {
+ setMetadataRecorded(true);
+ await sendMetadataAPI();
+ }
+ console.log("MediaRecorder started:", mediaRecorder.current);
+ };
+
return () => {
clearInterval(requestDataInterval);
if (
@@ -282,6 +291,7 @@ export const useMediaRecorder = () => {
}
isRecording.current = false;
+ setMetadataRecorded(false);
while (processingQueue.current || queue.current.length > 0) {
await new Promise((resolve) => setTimeout(resolve, 100));
diff --git a/apps/desktop/src/utils/recording/utils.ts b/apps/desktop/src/utils/recording/utils.ts
index a29f97e88..7db971b15 100644
--- a/apps/desktop/src/utils/recording/utils.ts
+++ b/apps/desktop/src/utils/recording/utils.ts
@@ -1,6 +1,11 @@
+"use client";
+
export const enumerateAndStoreDevices = async () => {
if (typeof navigator !== "undefined" && typeof window !== "undefined") {
- await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
+ await navigator.mediaDevices.getUserMedia({
+ video: true,
+ audio: true,
+ });
const devices = await navigator.mediaDevices.enumerateDevices();
const videoDevices = devices.filter(
@@ -16,6 +21,10 @@ export const enumerateAndStoreDevices = async () => {
};
export const getLocalDevices = async () => {
+ if (typeof window === "undefined") {
+ return { audioDevices: [], videoDevices: [] };
+ }
+
const videoDevices = JSON.parse(
window.localStorage.getItem("videoDevices") || "[]"
) as MediaDeviceInfo[];
diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.json
index a10b6c816..ae096eec2 100644
--- a/apps/desktop/tsconfig.json
+++ b/apps/desktop/tsconfig.json
@@ -7,7 +7,7 @@
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
- "strict": true,
+ "strict": false,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
diff --git a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
index b3c377385..6e5f317ca 100644
--- a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
@@ -36,33 +36,26 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
? new Date(data.audioStartTime).getTime()
: 0;
- const timeDifference = videoStartTime - audioStartTime;
+ 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 = timeDifference / 1000;
- video2Ref.current.currentTime = 0; // Ensure video starts from the beginning
+ audioPlayerRef.current.currentTime =
+ video2Ref.current.currentTime + timeDifference;
} 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;
- }
+ audioPlayerRef.current.currentTime =
+ video2Ref.current.currentTime - timeDifference;
}
console.log("refs:");
diff --git a/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx b/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
index 658689e48..f0e0304ab 100644
--- a/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
+++ b/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
@@ -30,7 +30,7 @@ export const VideoPlayer = forwardRef<HTMLVideoElement, VideoPlayerProps>(
return (
<video
ref={ref}
- className="absolute top-0 left-0 rounded-lg w-full h-full object-cover"
+ className="absolute top-0 left-0 rounded-lg w-full h-full object-contain"
preload="auto"
playsInline
controls={false}
diff --git a/package.json b/package.json
index 83d9fa002..f8cdbcedf 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,8 @@
"dev": "dotenv -e .env -- turbo run dev --no-cache",
"lint": "turbo run lint",
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
- "db:push": "dotenv -e .env -- pnpm --dir packages/database db:push"
+ "db:push": "dotenv -e .env -- pnpm --dir packages/database db:push",
+ "tauri:build": "dotenv -e .env -- pnpm --dir apps/desktop tauri build"
},
"devDependencies": {
"@turbo/gen": "^1.9.7",