Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: Audio/video sync.

Richie McIlroy46aec22573f6
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock
index 3ec7d95ae..785caaae0 100644
--- a/apps/desktop/src-tauri/Cargo.lock
+++ b/apps/desktop/src-tauri/Cargo.lock
@@ -99,7 +99,7 @@ dependencies = [
"objc_id",
"parking_lot",
"thiserror",
- "winapi",
+ "winapi 0.3.9",
"x11rb",
]
@@ -160,7 +160,7 @@ checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af"
dependencies = [
"async-lock 2.8.0",
"autocfg",
- "cfg-if",
+ "cfg-if 1.0.0",
"concurrent-queue",
"futures-lite 1.13.0",
"log",
@@ -179,7 +179,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f97ab0c5b00a7cdbe5a371b9a782ee7be1316095885c8a4ea1daf490eb0ef65"
dependencies = [
"async-lock 3.3.0",
- "cfg-if",
+ "cfg-if 1.0.0",
"concurrent-queue",
"futures-io",
"futures-lite 2.2.0",
@@ -221,7 +221,7 @@ dependencies = [
"async-lock 2.8.0",
"async-signal",
"blocking",
- "cfg-if",
+ "cfg-if 1.0.0",
"event-listener 3.1.0",
"futures-lite 1.13.0",
"rustix 0.38.30",
@@ -248,7 +248,7 @@ dependencies = [
"async-io 2.3.1",
"async-lock 2.8.0",
"atomic-waker",
- "cfg-if",
+ "cfg-if 1.0.0",
"futures-core",
"futures-io",
"rustix 0.38.30",
@@ -318,7 +318,7 @@ checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837"
dependencies = [
"addr2line",
"cc",
- "cfg-if",
+ "cfg-if 1.0.0",
"libc",
"miniz_oxide",
"object",
@@ -494,6 +494,7 @@ version = "0.0.0"
dependencies = [
"bytemuck",
"byteorder",
+ "capture",
"chrono",
"cpal",
"dotenv_codegen",
@@ -516,6 +517,16 @@ dependencies = [
"window-vibrancy",
]
+[[package]]
+name = "capture"
+version = "0.0.1"
+dependencies = [
+ "block",
+ "cfg-if 0.1.10",
+ "libc",
+ "winapi 0.2.8",
+]
+
[[package]]
name = "cargo_toml"
version = "0.15.3"
@@ -581,6 +592,12 @@ dependencies = [
"target-lexicon",
]
+[[package]]
+name = "cfg-if"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
+
[[package]]
name = "cfg-if"
version = "1.0.0"
@@ -621,7 +638,7 @@ checksum = "7191c27c2357d9b7ef96baac1773290d4ca63b24205b82a3fd8a0637afcf0362"
dependencies = [
"error-code",
"str-buf",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -814,7 +831,7 @@ version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
]
[[package]]
@@ -1004,7 +1021,7 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"dirs-sys-next",
]
@@ -1028,7 +1045,7 @@ checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d"
dependencies = [
"libc",
"redox_users",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -1119,7 +1136,7 @@ version = "0.8.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
]
[[package]]
@@ -1269,7 +1286,7 @@ version = "0.2.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ee447700ac8aa0b2f2bd7bc4462ad686ba06baa6727ac149a2d6277f0d240fd"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"libc",
"redox_syscall",
"windows-sys 0.52.0",
@@ -1603,7 +1620,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb65d4ba3173c56a500b555b532f72c42e8d1fe64962b518897f8959fae2c177"
dependencies = [
"libc",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -1612,7 +1629,7 @@ version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"libc",
"wasi 0.9.0+wasi-snapshot-preview1",
]
@@ -1623,7 +1640,7 @@ version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"libc",
"wasi 0.11.0+wasi-snapshot-preview1",
]
@@ -1671,7 +1688,7 @@ dependencies = [
"gobject-sys",
"libc",
"system-deps 6.2.0",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -2091,7 +2108,7 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
]
[[package]]
@@ -2100,11 +2117,11 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81f2533f3be42fffe3b5e63b71aeca416c1c3bc33e4e27be018521e76b1f38fb"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"libc",
"rustc_version",
"to_method",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -2308,8 +2325,8 @@ version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"
dependencies = [
- "cfg-if",
- "winapi",
+ "cfg-if 1.0.0",
+ "winapi 0.3.9",
]
[[package]]
@@ -2318,7 +2335,7 @@ version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c571b676ddfc9a8c12f1f3d3085a7b163966a8fd8098a90640953ce5f6170161"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"windows-sys 0.48.0",
]
@@ -2376,7 +2393,7 @@ version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff50ecb28bb86013e935fb6683ab1f6d3a20016f123c76fd4c27470076ac30f5"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"generator",
"scoped-tls",
"serde",
@@ -2600,7 +2617,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa52e972a9a719cecb6864fb88568781eb706bac2cd1d4f04a648542dbf78069"
dependencies = [
"bitflags 1.3.2",
- "cfg-if",
+ "cfg-if 1.0.0",
"libc",
]
@@ -2611,7 +2628,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b"
dependencies = [
"bitflags 1.3.2",
- "cfg-if",
+ "cfg-if 1.0.0",
"libc",
"memoffset 0.7.1",
]
@@ -2652,7 +2669,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"
dependencies = [
"overload",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -2822,7 +2839,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15c9d69dd87a29568d4d017cfe8ec518706046a05184e5aea92d0af890b803c8"
dependencies = [
"bitflags 2.4.2",
- "cfg-if",
+ "cfg-if 1.0.0",
"foreign-types 0.3.2",
"libc",
"once_cell",
@@ -2883,7 +2900,7 @@ checksum = "006e42d5b888366f1880eda20371fedde764ed2213dc8496f49622fa0c99cd5e"
dependencies = [
"log",
"serde",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -2949,7 +2966,7 @@ version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"libc",
"redox_syscall",
"smallvec",
@@ -3166,7 +3183,7 @@ checksum = "4b2d323e8ca7996b3e23126511a523f7e62924d93ecd5ae73b333815b0eb3dce"
dependencies = [
"autocfg",
"bitflags 1.3.2",
- "cfg-if",
+ "cfg-if 1.0.0",
"concurrent-queue",
"libc",
"log",
@@ -3180,7 +3197,7 @@ version = "3.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "545c980a3880efd47b2e262f6a4bb6daad6555cf3367aa9c4e52895f69537a41"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"concurrent-queue",
"pin-project-lite",
"rustix 0.38.30",
@@ -3805,7 +3822,7 @@ version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"cpufeatures",
"digest",
]
@@ -3816,7 +3833,7 @@ version = "0.10.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"cpufeatures",
"digest",
]
@@ -3837,7 +3854,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0d94659ad3c2137fef23ae75b03d5241d633f8acded53d672decfa0e6e0caef"
dependencies = [
"libc",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -3889,7 +3906,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d"
dependencies = [
"libc",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -4289,7 +4306,7 @@ dependencies = [
"serde",
"tauri",
"time",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -4429,7 +4446,7 @@ version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"fastrand 2.0.1",
"redox_syscall",
"rustix 0.38.30",
@@ -4479,7 +4496,7 @@ version = "1.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"once_cell",
]
@@ -4762,7 +4779,7 @@ checksum = "89daebc3e6fd160ac4aa9fc8b3bf71e1f74fbf92367ae71fb83a037e8bf164b9"
dependencies = [
"memoffset 0.9.0",
"tempfile",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -4921,7 +4938,7 @@ version = "0.2.90"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1223296a201415c7fad14792dbefaace9bd52b62d33453ade1c5b5f07555406"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"wasm-bindgen-macro",
]
@@ -4946,7 +4963,7 @@ version = "0.4.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bde2032aeb86bdfaecc8b261eef3cba735cc426c1f3a3416d1e0791be95fc461"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"js-sys",
"wasm-bindgen",
"web-sys",
@@ -5107,6 +5124,12 @@ dependencies = [
"rustix 0.38.30",
]
+[[package]]
+name = "winapi"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"
+
[[package]]
name = "winapi"
version = "0.3.9"
@@ -5129,7 +5152,7 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596"
dependencies = [
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -5138,7 +5161,7 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c17110f57155602a80dca10be03852116403c9ff3cd25b079d666f2aa3df6e"
dependencies = [
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -5574,7 +5597,7 @@ version = "0.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"windows-sys 0.48.0",
]
@@ -5584,7 +5607,7 @@ version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "937f3df7948156640f46aacef17a70db0de5917bda9c92b0f751f3a955b588fc"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"windows-sys 0.48.0",
]
@@ -5594,7 +5617,7 @@ version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5"
dependencies = [
- "cfg-if",
+ "cfg-if 1.0.0",
"windows-sys 0.48.0",
]
@@ -5665,7 +5688,7 @@ checksum = "b1641b26d4dec61337c35a1b1aaf9e3cba8f46f0b43636c609ab0291a648040a"
dependencies = [
"gethostname",
"nix 0.26.4",
- "winapi",
+ "winapi 0.3.9",
"winapi-wsapoll",
"x11rb-protocol",
]
@@ -5697,7 +5720,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2769203cd13a0c6015d515be729c526d041e9cf2c0cc478d57faee85f40c6dcd"
dependencies = [
"nix 0.26.4",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
@@ -5734,7 +5757,7 @@ dependencies = [
"static_assertions",
"tracing",
"uds_windows",
- "winapi",
+ "winapi 0.3.9",
"xdg-home",
"zbus_macros",
"zbus_names",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index d358dd16d..7680278dc 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -34,6 +34,7 @@ dotenv_codegen = "0.15.0"
byteorder = "1.4.3"
bytemuck = "1.14.3"
regex = "1"
+capture = { path = "./src/capture" }
[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 8f4c9acab..2ffa79a81 100644
--- a/apps/desktop/src-tauri/src/audio.rs
+++ b/apps/desktop/src-tauri/src/audio.rs
@@ -2,22 +2,34 @@ use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::SampleFormat;
use std::process::{Stdio};
use byteorder::{ByteOrder, LittleEndian};
-use std::sync::{Arc};
+use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
+use std::io::{ErrorKind::WouldBlock, Error};
+use std::time::{Instant, Duration};
use tokio::io::{AsyncWriteExt};
-use tokio::process::{Command, ChildStdin};
+use tokio::process::{Command, Child, ChildStdin};
use tokio::sync::{mpsc, Mutex};
+use tokio::time::{self};
use crate::recording::RecordingOptions;
use crate::utils::{ffmpeg_path_as_str, monitor_and_log_recording_start};
+use capture::{Capturer, Display};
+
+const FRAME_RATE: u64 = 30;
pub struct AudioRecorder {
pub options: Option<RecordingOptions>,
- ffmpeg_process: Option<tokio::process::Child>,
- ffmpeg_stdin: Option<Arc<Mutex<ChildStdin>>>,
+ ffmpeg_audio_process: Option<tokio::process::Child>,
+ ffmpeg_video_process: Option<tokio::process::Child>,
+ ffmpeg_audio_stdin: Option<Arc<Mutex<Option<tokio::process::ChildStdin>>>>,
+ ffmpeg_video_stdin: Option<Arc<Mutex<Option<tokio::process::ChildStdin>>>>,
device_name: Option<String>,
stream: Option<cpal::Stream>,
audio_channel_sender: Option<mpsc::Sender<Vec<u8>>>,
+ audio_channel_receiver: Option<mpsc::Receiver<Vec<u8>>>,
+ video_channel_sender: Option<mpsc::Sender<Vec<u8>>>,
+ video_channel_receiver: Option<mpsc::Receiver<Vec<u8>>>,
+ should_stop: Arc<AtomicBool>,
}
impl AudioRecorder {
@@ -25,22 +37,49 @@ impl AudioRecorder {
pub fn new() -> Self {
AudioRecorder {
options: None,
- ffmpeg_process: None,
- ffmpeg_stdin: None,
+ ffmpeg_audio_process: None,
+ ffmpeg_video_process: None,
+ ffmpeg_audio_stdin: None,
+ ffmpeg_video_stdin: None,
device_name: None,
stream: None,
audio_channel_sender: None,
+ audio_channel_receiver: None,
+ video_channel_sender: None,
+ video_channel_receiver: None,
+ should_stop: Arc::new(AtomicBool::new(false)),
}
}
- pub async fn start_audio_recording(&mut self, options: RecordingOptions, audio_file_path: &str, custom_device: Option<&str>) -> Result<(), String> {
+ pub async fn start_audio_recording(&mut self, options: RecordingOptions, audio_file_path: &str, video_file_path: &str, custom_device: Option<&str>) -> Result<(), String> {
self.options = Some(options);
let host = cpal::default_host();
let devices = host.devices().expect("Failed to get devices");
- let (tx, mut rx) = tokio::sync::mpsc::channel::<Vec<u8>>(32);
- let tx_clone = tx.clone();
- self.audio_channel_sender = Some(tx);
+ let display = Display::primary().map_err(|_| "Failed to find primary display".to_string())?;
+ let (w, h) = (display.width(), display.height());
+ let adjusted_height = h & !1;
+ let capture_size = w * adjusted_height * 4;
+ let (audio_tx, audio_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(2048);
+ let (video_tx, video_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(2048);
+
+ let audio_start_time = Arc::new(Mutex::new(None));
+ let video_start_time = Arc::new(Mutex::new(None));
+
+ self.audio_channel_sender = Some(audio_tx);
+ self.audio_channel_receiver = Some(audio_rx);
+ self.video_channel_sender = Some(video_tx);
+ self.video_channel_receiver = Some(video_rx);
+ self.ffmpeg_audio_stdin = Some(Arc::new(Mutex::new(None)));
+ self.ffmpeg_video_stdin = Some(Arc::new(Mutex::new(None)));
+
+ let audio_channel_sender = self.audio_channel_sender.clone();
+ let video_channel_sender = self.video_channel_sender.clone();
+
+ let audio_channel_receiver = Arc::new(Mutex::new(self.audio_channel_receiver.take()));
+ let video_channel_receiver = Arc::new(Mutex::new(self.video_channel_receiver.take()));
+
+ let should_stop = Arc::clone(&self.should_stop);
let mut input_devices = devices.filter_map(|device| {
let supported_input_configs = device.supported_input_configs();
@@ -82,78 +121,44 @@ impl AudioRecorder {
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 video_file_path_owned = video_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 mut audio_filters = Vec::new();
-
- if channels > 2 {
- audio_filters.push("pan=stereo|FL=FL+0.5*FC|FR=FR+0.5*FC");
- }
-
- audio_filters.push("loudnorm");
-
- let audio_filters_str = audio_filters.join(",");
-
- let ffmpeg_command: Vec<String> = vec![
- "-f", sample_format,
- "-ar", &sample_rate_str,
- "-ac", &channels_str,
- "-i", "pipe:0",
- "-c:a", "aac",
- "-b:a", "128k",
- "-af", &audio_filters_str,
- "-f", "segment",
- "-segment_time", "3",
- "-segment_list", &segment_list_filename,
- "-reset_timestamps", "1",
- "-use_wallclock_as_timestamps", "1",
- "-fflags", "nobuffer",
- "-flags", "low_delay",
- "-strict", "experimental",
- &output_chunk_pattern,
- ].into_iter().map(|s| s.to_string()).collect();
-
- let video_id = self.options.as_ref().unwrap().video_id.clone();
-
- let mut child = start_audio_recording_process(&ffmpeg_binary_path_str, &video_id, &ffmpeg_command)
- .await
- .map_err(|e| e.to_string())?;
-
- let stdin = child.stdin.take().expect("failed to take child stdin");
- let stdin_arc = Arc::new(Mutex::new(stdin));
- let stdin_clone = Arc::clone(&stdin_arc);
- let stdin_global = Arc::clone(&stdin_arc);
-
- tokio::spawn(async move {
- while let Some(bytes) = rx.recv().await {
- let mut stdin_guard = stdin_clone.lock().await;
- if stdin_guard.write_all(&bytes).await.is_err() {
- eprintln!("Failed to write to FFmpeg stdin");
- break;
- }
- }
- });
+
+ let ffmpeg_audio_stdin = self.ffmpeg_audio_stdin.clone();
+ let ffmpeg_video_stdin = self.ffmpeg_video_stdin.clone();
let err_fn = move |err| {
eprintln!("an error occurred on stream: {}", err);
};
+ println!("Building input stream...");
+
let stream_result: Result<cpal::Stream, cpal::BuildStreamError> = match config.sample_format() {
SampleFormat::I8 => device.build_input_stream(
&config.into(),
- move |data: &[i8], _: &_| {
- let bytes = data.iter().map(|&sample| sample as u8).collect::<Vec<u8>>();
- if tx_clone.try_send(bytes).is_err() {
- eprintln!("Channel send error. Dropping data.");
+ {
+ let audio_start_time = Arc::clone(&audio_start_time);
+ move |data: &[i8], _: &_| {
+ let mut first_frame_time_guard = audio_start_time.try_lock();
+
+ let bytes = data.iter().map(|&sample| sample as u8).collect::<Vec<u8>>();
+ if let Some(sender) = &audio_channel_sender {
+ if sender.try_send(bytes).is_err() {
+ eprintln!("Channel send error. Dropping data.");
+ }
+ }
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
+ println!("Audio start time captured");
+ }
+ }
}
},
err_fn,
@@ -161,11 +166,26 @@ impl AudioRecorder {
),
SampleFormat::I16 => device.build_input_stream(
&config.into(),
- move |data: &[i16], _: &_| {
- let mut bytes = vec![0; data.len() * 2];
- LittleEndian::write_i16_into(data, &mut bytes);
- if tx_clone.try_send(bytes).is_err() {
- eprintln!("Channel send error. Dropping data.");
+ {
+ let audio_start_time = Arc::clone(&audio_start_time);
+ move |data: &[i16], _: &_| {
+ let mut first_frame_time_guard = audio_start_time.try_lock();
+
+ let mut bytes = vec![0; data.len() * 2];
+ LittleEndian::write_i16_into(data, &mut bytes);
+ if let Some(sender) = &audio_channel_sender {
+ if sender.try_send(bytes).is_err() {
+ eprintln!("Channel send error. Dropping data.");
+ }
+ }
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
+ println!("Audio start time captured");
+ }
+ }
}
},
err_fn,
@@ -173,22 +193,53 @@ impl AudioRecorder {
),
SampleFormat::I32 => device.build_input_stream(
&config.into(),
- move |data: &[i32], _: &_| {
- let mut bytes = vec![0; data.len() * 4];
- LittleEndian::write_i32_into(data, &mut bytes);
- if tx_clone.try_send(bytes).is_err() {
- eprintln!("Channel send error. Dropping data.");
+ {
+ let audio_start_time = Arc::clone(&audio_start_time);
+ move |data: &[i32], _: &_| {
+ let mut first_frame_time_guard = audio_start_time.try_lock();
+
+ let mut bytes = vec![0; data.len() * 2];
+ LittleEndian::write_i32_into(data, &mut bytes);
+ if let Some(sender) = &audio_channel_sender {
+ if sender.try_send(bytes).is_err() {
+ eprintln!("Channel send error. Dropping data.");
+ }
+ }
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
+ println!("Audio start time captured");
+ }
+ }
}
},
err_fn,
- None,
+ None,
),
SampleFormat::F32 => device.build_input_stream(
&config.into(),
- move |data: &[f32], _: &_| {
- let bytes = bytemuck::cast_slice::<f32, u8>(data).to_vec();
- if tx_clone.try_send(bytes).is_err() {
- eprintln!("Channel send error. Dropping data.");
+ {
+ let audio_start_time = Arc::clone(&audio_start_time);
+ move |data: &[f32], _: &_| {
+ let mut first_frame_time_guard = audio_start_time.try_lock();
+
+ let mut bytes = vec![0; data.len() * 4];
+ LittleEndian::write_f32_into(data, &mut bytes);
+ if let Some(sender) = &audio_channel_sender {
+ if sender.try_send(bytes).is_err() {
+ eprintln!("Channel send error. Dropping data.");
+ }
+ }
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
+ println!("Audio start time captured");
+ }
+ }
}
},
err_fn,
@@ -198,14 +249,187 @@ impl AudioRecorder {
};
let stream = stream_result.map_err(|_| "Failed to build input stream")?;
-
self.stream = Some(stream);
- self.ffmpeg_process = Some(child);
- self.ffmpeg_stdin = Some(stdin_global);
- self.device_name = Some(device.name().expect("Failed to get device name"));
-
self.trigger_play()?;
+ let video_start_time_clone = Arc::clone(&video_start_time);
+ std::thread::spawn(move || {
+ println!("Starting video recording capture thread...");
+
+ let mut capturer = Capturer::new(Display::primary().expect("Failed to find primary display")).expect("Failed to start capture");
+
+ let fps = FRAME_RATE;
+ let spf = Duration::from_nanos(1_000_000_000 / fps);
+
+ let mut frame_count = 0u32;
+ let start_time = Instant::now();
+ let mut time_next = Instant::now() + spf;
+
+ while !should_stop.load(Ordering::SeqCst) {
+ let now = Instant::now();
+
+ if now >= time_next {
+ let mut frame_data = Vec::with_capacity(capture_size);
+
+ match capturer.frame() {
+ Ok(frame) => {
+ let stride = frame[..capture_size].len() / adjusted_height;
+ for row in 0..adjusted_height {
+ let start = row * stride;
+ let end = start + stride;
+ frame_data.extend_from_slice(&frame[start..end]);
+ }
+ if let Some(sender) = &video_channel_sender {
+ if sender.try_send(frame_data).is_err() {
+ eprintln!("Channel send error. Dropping data.");
+ }
+ }
+
+ let mut first_frame_time_guard = video_start_time_clone.try_lock();
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
+ println!("Video start time captured");
+ }
+ }
+
+ frame_count += 1;
+ },
+ Err(error) if error.kind() == WouldBlock => {
+ std::thread::sleep(Duration::from_millis(1));
+ continue;
+ },
+ Err(error) => {
+ eprintln!("Capture error: {}", error);
+ break;
+ },
+ }
+
+ time_next += spf;
+ }
+
+ // Sleep until the next frame time
+ let now = Instant::now();
+ if time_next > now {
+ std::thread::sleep(time_next - now);
+ }
+ }
+
+ let elapsed_total_time = start_time.elapsed();
+ let fps = frame_count as f64 / elapsed_total_time.as_secs_f64();
+ println!("Current FPS: {}", fps);
+ });
+
+ println!("Starting audio recording and processing...");
+ let audio_output_chunk_pattern = format!("{}/audio_recording_%03d.aac", audio_file_path_owned);
+ let audio_segment_list_filename = format!("{}/segment_list.txt", audio_file_path_owned);
+ let video_output_chunk_pattern = format!("{}/video_recording_%03d.ts", video_file_path_owned);
+ let video_segment_list_filename = format!("{}/segment_list.txt", video_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");
+ }
+
+ audio_filters.push("loudnorm");
+
+ let audio_filters_str = audio_filters.join(",");
+
+ let mut ffmpeg_audio_command: Vec<String> = vec![
+ "-f", sample_format,
+ "-ar", &sample_rate_str,
+ "-ac", &channels_str,
+ "-thread_queue_size", "4096",
+ "-i", "pipe:0",
+ "-af", "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
+ "-c:a", "aac",
+ "-b:a", "128k",
+ "-async", "1",
+ "-f", "segment",
+ "-segment_time", "3",
+ "-segment_list", &audio_segment_list_filename,
+ "-reset_timestamps", "1",
+ &audio_output_chunk_pattern,
+ ].into_iter().map(|s| s.to_string()).collect();
+
+ let mut ffmpeg_video_command: Vec<String> = vec![
+ "-f", "rawvideo",
+ "-pix_fmt", "bgra",
+ "-s", &format!("{}x{}", w, adjusted_height),
+ "-r", "30",
+ "-thread_queue_size", "4096",
+ "-i", "pipe:0",
+ "-vf", "fps=30",
+ "-c:v", "libx264",
+ "-preset", "ultrafast",
+ "-pix_fmt", "yuv420p",
+ "-tune", "zerolatency",
+ "-vsync", "1",
+ "-f", "segment",
+ "-segment_time", "3",
+ "-segment_list", &video_segment_list_filename,
+ "-segment_format", "mpegts",
+ "-reset_timestamps", "1",
+ &video_output_chunk_pattern,
+ ].into_iter().map(|s| s.to_string()).collect();
+
+ println!("Adjusting FFmpeg commands based on start times...");
+ adjust_ffmpeg_commands_based_on_start_times(
+ Arc::clone(&audio_start_time),
+ Arc::clone(&video_start_time),
+ &mut ffmpeg_audio_command,
+ &mut ffmpeg_video_command,
+ ).await;
+
+ println!("Starting FFmpeg audio and video processes...");
+
+ let ((audio_child, audio_stdin), (video_child, video_stdin)) = self.start_ffmpeg_processes(&ffmpeg_binary_path_str, &ffmpeg_audio_command, &ffmpeg_video_command).await.map_err(|e| e.to_string())?;
+
+ if let Some(ffmpeg_audio_stdin) = &self.ffmpeg_audio_stdin {
+ let mut audio_stdin_lock = ffmpeg_audio_stdin.lock().await;
+ *audio_stdin_lock = Some(audio_stdin);
+ drop(audio_stdin_lock);
+ }
+
+ if let Some(ffmpeg_video_stdin) = &self.ffmpeg_video_stdin {
+ let mut video_stdin_lock = ffmpeg_video_stdin.lock().await;
+ *video_stdin_lock = Some(video_stdin);
+ drop(video_stdin_lock);
+ }
+
+ tokio::spawn(async move {
+ while let Some(bytes) = &audio_channel_receiver.lock().await.as_mut().unwrap().recv().await {
+ if let Some(audio_stdin_arc) = &ffmpeg_audio_stdin{
+ let mut audio_stdin_guard = audio_stdin_arc.lock().await;
+ if let Some(ref mut stdin) = *audio_stdin_guard {
+ stdin.write_all(&bytes).await.expect("Failed to write audio data to FFmpeg stdin");
+ }
+ drop(audio_stdin_guard);
+ }
+ }
+ });
+
+ tokio::spawn(async move {
+ while let Some(bytes) = &video_channel_receiver.lock().await.as_mut().unwrap().recv().await {
+ if let Some(video_stdin_arc) = &ffmpeg_video_stdin {
+ let mut video_stdin_guard = video_stdin_arc.lock().await;
+ if let Some(ref mut stdin) = *video_stdin_guard {
+ stdin.write_all(&bytes).await.expect("Failed to write video data to FFmpeg stdin");
+ }
+ drop(video_stdin_guard);
+ }
+ }
+ });
+
+ self.ffmpeg_audio_process = Some(audio_child);
+ self.ffmpeg_video_process = Some(video_child);
+ self.device_name = Some(device.name().expect("Failed to get device name"));
+
+ println!("End of the start_audio_recording function");
+
Ok(())
}
@@ -221,10 +445,30 @@ impl AudioRecorder {
}
pub async fn stop_audio_recording(&mut self) -> Result<(), String> {
+ if let Some(ref ffmpeg_audio_stdin) = self.ffmpeg_audio_stdin {
+ let mut audio_stdin_guard = ffmpeg_audio_stdin.lock().await;
+ if let Some(mut audio_stdin) = audio_stdin_guard.take() {
+ let _ = audio_stdin.shutdown().await.map_err(|e| e.to_string());
+ }
+ }
+
+ if let Some(ref ffmpeg_video_stdin) = self.ffmpeg_video_stdin {
+ let mut video_stdin_guard = ffmpeg_video_stdin.lock().await;
+ if let Some(mut video_stdin) = video_stdin_guard.take() {
+ let _ = video_stdin.shutdown().await.map_err(|e| e.to_string());
+ }
+ }
+
+ self.should_stop.store(true, Ordering::SeqCst);
+
if let Some(sender) = self.audio_channel_sender.take() {
drop(sender);
}
+ if let Some(sender) = self.video_channel_sender.take() {
+ drop(sender);
+ }
+
if let Some(ref mut stream) = self.stream {
stream.pause().map_err(|_| "Failed to pause stream")?;
println!("Audio recording paused.");
@@ -232,27 +476,33 @@ impl AudioRecorder {
return Err("Recording was not started".to_string());
}
- println!("Sending quit command to FFmpeg...");
- if let Some(stdin_arc) = self.ffmpeg_stdin.take() {
- let mut stdin_guard = stdin_arc.lock().await;
- if let Err(e) = stdin_guard.write_all(b"q\n").await {
- eprintln!("Failed to send quit command to FFmpeg: {}", e);
- return Err("Failed to send quit command to FFmpeg".to_string());
- }
-
- stdin_guard.flush().await.expect("Failed to flush FFmpeg stdin");
-
- println!("Quit command sent to FFmpeg. Waiting for FFmpeg to process...");
-
- tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ if let Some(process) = &mut self.ffmpeg_audio_process {
+ let _ = process.kill().await.map_err(|e| e.to_string());
+ }
- println!("Finalizing FFmpeg process...");
+ if let Some(process) = &mut self.ffmpeg_video_process {
+ let _ = process.kill().await.map_err(|e| e.to_string());
}
println!("Audio recording stopped.");
Ok(())
}
+ async fn start_ffmpeg_processes(
+ &self,
+ ffmpeg_binary_path: &str,
+ audio_ffmpeg_command: &[String],
+ video_ffmpeg_command: &[String],
+ ) -> Result<((Child, ChildStdin), (Child, ChildStdin)), Error> {
+ let mut audio_process = start_recording_process(ffmpeg_binary_path, audio_ffmpeg_command).await.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
+ let mut video_process = start_recording_process(ffmpeg_binary_path, video_ffmpeg_command).await.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
+
+ let audio_stdin = audio_process.stdin.take().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "Failed to take audio stdin"))?;
+ let video_stdin = video_process.stdin.take().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "Failed to take video stdin"))?;
+
+ Ok(((audio_process, audio_stdin), (video_process, video_stdin)))
+ }
+
}
#[tauri::command]
@@ -279,23 +529,83 @@ pub fn enumerate_audio_devices() -> Vec<String> {
input_device_names
}
-async fn start_audio_recording_process(ffmpeg_binary_path_str: &str, video_id: &str, audio_args: &[String]) -> Result<(tokio::process::Child), std::io::Error> {
- let mut child = Command::new(ffmpeg_binary_path_str)
- .args(audio_args)
+use tokio::io::{BufReader, AsyncBufReadExt};
+
+async fn start_recording_process(
+ ffmpeg_binary_path_str: &str,
+ args: &[String],
+) -> Result<tokio::process::Child, std::io::Error> {
+ let mut process = Command::new(ffmpeg_binary_path_str)
+ .args(args)
.stdin(Stdio::piped())
- .stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
-
- let stderr = child.stderr.take().expect("failed to take child stdout");
- let video_id_owned = video_id.to_owned();
+ if let Some(process_stderr) = process.stderr.take() {
+ tokio::spawn(async move {
+ let mut process_reader = BufReader::new(process_stderr).lines();
+ while let Ok(Some(line)) = process_reader.next_line().await {
+ eprintln!("FFmpeg process STDERR: {}", line);
+ }
+ });
+ }
- tokio::spawn(async move {
- if let Err(e) = monitor_and_log_recording_start(stderr, &video_id_owned, "audio").await {
- eprintln!("Failed to monitor and log audio recording start: {}", e);
+ Ok(process)
+}
+
+async fn wait_for_start_times(
+ audio_start_time: Arc<Mutex<Option<Instant>>>,
+ video_start_time: Arc<Mutex<Option<Instant>>>,
+) -> (Instant, Instant) {
+ loop {
+ let audio_start_locked = audio_start_time.lock().await;
+ let video_start_locked = video_start_time.lock().await;
+
+ if audio_start_locked.is_some() && video_start_locked.is_some() {
+ let audio_start = *audio_start_locked.as_ref().unwrap();
+ let video_start = *video_start_locked.as_ref().unwrap();
+ return (audio_start, video_start);
}
- });
+ drop(audio_start_locked);
+ drop(video_start_locked);
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
+async fn adjust_ffmpeg_commands_based_on_start_times(
+ audio_start_time: Arc<Mutex<Option<Instant>>>,
+ video_start_time: Arc<Mutex<Option<Instant>>>,
+ ffmpeg_audio_command: &mut Vec<String>,
+ ffmpeg_video_command: &mut Vec<String>,
+) {
+ let (audio_start, video_start) = wait_for_start_times(audio_start_time, video_start_time).await;
+ let duration_difference = if audio_start > video_start {
+ audio_start.duration_since(video_start)
+ } else {
+ video_start.duration_since(audio_start)
+ };
+
+ println!("Duration difference: {:?}", duration_difference);
+ println!("Audio start: {:?}", audio_start);
+ println!("Video start: {:?}", video_start);
+
+ // Convert the duration difference to a float representing seconds
+ let offset_seconds = duration_difference.as_secs() as f64
+ + duration_difference.subsec_nanos() as f64 * 1e-9;
+
+ // Depending on which started first, adjust the relevant FFmpeg command
+ if audio_start > video_start {
+ // Offset the video start time
+ ffmpeg_video_command.splice(0..0, vec![
+ "-itsoffset".to_string(), format!("{:.3}", offset_seconds)
+ ]);
+ println!("Applying -itsoffset {:.3} to video", offset_seconds);
+ } else if video_start > audio_start {
+ // Offset the audio start time
+ ffmpeg_audio_command.splice(0..0, vec![
+ "-itsoffset".to_string(), format!("{:.3}", offset_seconds)
+ ]);
+ println!("Applying -itsoffset {:.3} to audio", offset_seconds);
+ }
- Ok(child)
}
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/capture/Cargo.lock b/apps/desktop/src-tauri/src/capture/Cargo.lock
new file mode 100644
index 000000000..794c627da
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/Cargo.lock
@@ -0,0 +1,37 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "block"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
+
+[[package]]
+name = "capture"
+version = "0.0.1"
+dependencies = [
+ "block",
+ "cfg-if",
+ "libc",
+ "winapi",
+]
+
+[[package]]
+name = "cfg-if"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
+
+[[package]]
+name = "libc"
+version = "0.2.153"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
+
+[[package]]
+name = "winapi"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"
diff --git a/apps/desktop/src-tauri/src/capture/Cargo.toml b/apps/desktop/src-tauri/src/capture/Cargo.toml
new file mode 100644
index 000000000..da873ddea
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "capture"
+description = "Bindings for cross-platform screen capture."
+version = "0.0.1"
+
+[dependencies]
+block = "0.1"
+cfg-if = "0.1"
+libc = "0.2"
+winapi = "0.2"
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/capture/build.rs b/apps/desktop/src-tauri/src/capture/build.rs
new file mode 100644
index 000000000..04fa2aa91
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/build.rs
@@ -0,0 +1,12 @@
+fn main() {
+ if cfg!(windows) {
+ // The first choice is Windows because DXGI is amazing.
+ println!("cargo:rustc-cfg=dxgi");
+ } else if cfg!(target_os="macos") {
+ // Quartz is second because macOS is the (annoying) exception.
+ println!("cargo:rustc-cfg=quartz");
+ } else if cfg!(unix) {
+ // On UNIX we pray that X11 (with XCB) is available.
+ println!("cargo:rustc-cfg=x11");
+ }
+}
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/capture/src/common/dxgi.rs b/apps/desktop/src-tauri/src/capture/src/common/dxgi.rs
new file mode 100644
index 000000000..55194a3a6
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/common/dxgi.rs
@@ -0,0 +1,73 @@
+use dxgi;
+use std::{io, ops};
+use std::io::ErrorKind::{WouldBlock, TimedOut, NotFound};
+
+pub struct Capturer {
+ inner: dxgi::Capturer,
+ width: usize,
+ height: usize
+}
+
+unsafe impl Send for Capturer {}
+
+impl Capturer {
+ pub fn new(display: Display) -> io::Result<Capturer> {
+ let width = display.width();
+ let height = display.height();
+ let inner = dxgi::Capturer::new(&display.0)?;
+ Ok(Capturer { inner, width, height })
+ }
+
+ pub fn width(&self) -> usize {
+ self.width
+ }
+
+ pub fn height(&self) -> usize {
+ self.height
+ }
+
+ pub fn frame<'a>(&'a mut self) -> io::Result<Frame<'a>> {
+ const MILLISECONDS_PER_FRAME: u32 = 0;
+ match self.inner.frame(MILLISECONDS_PER_FRAME) {
+ Ok(frame) => Ok(Frame(frame)),
+ Err(ref error) if error.kind() == TimedOut => {
+ Err(WouldBlock.into())
+ },
+ Err(error) => Err(error)
+ }
+ }
+}
+
+pub struct Frame<'a>(&'a [u8]);
+
+impl<'a> ops::Deref for Frame<'a> {
+ type Target = [u8];
+ fn deref(&self) -> &[u8] {
+ self.0
+ }
+}
+
+pub struct Display(dxgi::Display);
+
+impl Display {
+ pub fn primary() -> io::Result<Display> {
+ match dxgi::Displays::new()?.next() {
+ Some(inner) => Ok(Display(inner)),
+ None => Err(NotFound.into())
+ }
+ }
+
+ pub fn all() -> io::Result<Vec<Display>> {
+ Ok(dxgi::Displays::new()?
+ .map(Display)
+ .collect::<Vec<_>>())
+ }
+
+ pub fn width(&self) -> usize {
+ self.0.width() as usize
+ }
+
+ pub fn height(&self) -> usize {
+ self.0.height() as usize
+ }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/common/mod.rs b/apps/desktop/src-tauri/src/capture/src/common/mod.rs
new file mode 100644
index 000000000..210793326
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/common/mod.rs
@@ -0,0 +1,14 @@
+cfg_if! {
+ if #[cfg(quartz)] {
+ mod quartz;
+ pub use self::quartz::*;
+ } else if #[cfg(x11)] {
+ mod x11;
+ pub use self::x11::*;
+ } else if #[cfg(dxgi)] {
+ mod dxgi;
+ pub use self::dxgi::*;
+ } else {
+ //TODO: Fallback implementation.
+ }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/common/quartz.rs b/apps/desktop/src-tauri/src/capture/src/common/quartz.rs
new file mode 100644
index 000000000..3004aeb69
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/common/quartz.rs
@@ -0,0 +1,102 @@
+use quartz;
+use std::{io, ops, mem};
+use std::marker::PhantomData;
+use std::sync::{Arc, Mutex, TryLockError};
+
+pub struct Capturer {
+ inner: quartz::Capturer,
+ frame: Arc<Mutex<Option<quartz::Frame>>>
+}
+
+unsafe impl Send for Capturer {}
+
+impl Capturer {
+ pub fn new(display: Display) -> io::Result<Capturer> {
+ let frame = Arc::new(Mutex::new(None));
+
+ let f = frame.clone();
+ let inner = quartz::Capturer::new(
+ display.0,
+ display.width(),
+ display.height(),
+ quartz::PixelFormat::Argb8888,
+ Default::default(),
+ move |inner| {
+ if let Ok(mut f) = f.lock() {
+ *f = Some(inner);
+ }
+ }
+ ).map_err(|_| io::Error::from(io::ErrorKind::Other))?;
+
+ Ok(Capturer { inner, frame })
+ }
+
+ pub fn width(&self) -> usize {
+ self.inner.width()
+ }
+
+ pub fn height(&self) -> usize {
+ self.inner.height()
+ }
+
+ pub fn frame<'a>(&'a mut self) -> io::Result<Frame<'a>> {
+ match self.frame.try_lock() {
+ Ok(mut handle) => {
+ let mut frame = None;
+ mem::swap(&mut frame, &mut handle);
+
+ match frame {
+ Some(frame) =>
+ Ok(Frame(frame, PhantomData)),
+
+ None =>
+ Err(io::ErrorKind::WouldBlock.into())
+ }
+ }
+
+ Err(TryLockError::WouldBlock) =>
+ Err(io::ErrorKind::WouldBlock.into()),
+
+ Err(TryLockError::Poisoned(..)) =>
+ Err(io::ErrorKind::Other.into())
+ }
+ }
+}
+
+pub struct Frame<'a>(
+ quartz::Frame,
+ PhantomData<&'a [u8]>
+);
+
+impl<'a> ops::Deref for Frame<'a> {
+ type Target = [u8];
+ fn deref(&self) -> &[u8] {
+ &*self.0
+ }
+}
+
+pub struct Display(quartz::Display);
+
+impl Display {
+ pub fn primary() -> io::Result<Display> {
+ Ok(Display(quartz::Display::primary()))
+ }
+
+ pub fn all() -> io::Result<Vec<Display>> {
+ Ok(
+ quartz::Display::online()
+ .map_err(|_| io::Error::from(io::ErrorKind::Other))?
+ .into_iter()
+ .map(Display)
+ .collect()
+ )
+ }
+
+ pub fn width(&self) -> usize {
+ self.0.width()
+ }
+
+ pub fn height(&self) -> usize {
+ self.0.height()
+ }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/common/x11.rs b/apps/desktop/src-tauri/src/capture/src/common/x11.rs
new file mode 100644
index 000000000..fb8cbae93
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/common/x11.rs
@@ -0,0 +1,73 @@
+use x11;
+use std::{io, ops};
+use std::rc::Rc;
+
+pub struct Capturer(x11::Capturer);
+
+unsafe impl Send for Capturer {}
+
+impl Capturer {
+ pub fn new(display: Display) -> io::Result<Capturer> {
+ x11::Capturer::new(display.0).map(Capturer)
+ }
+
+ pub fn width(&self) -> usize {
+ self.0.display().rect().w as usize
+ }
+
+ pub fn height(&self) -> usize {
+ self.0.display().rect().h as usize
+ }
+
+ pub fn frame<'a>(&'a mut self) -> io::Result<Frame<'a>> {
+ Ok(Frame(self.0.frame()))
+ }
+}
+
+pub struct Frame<'a>(&'a [u8]);
+
+impl<'a> ops::Deref for Frame<'a> {
+ type Target = [u8];
+ fn deref(&self) -> &[u8] {
+ self.0
+ }
+}
+
+pub struct Display(x11::Display);
+
+impl Display {
+ pub fn primary() -> io::Result<Display> {
+ let server = Rc::new(match x11::Server::default() {
+ Ok(server) => server,
+ Err(_) => return Err(io::ErrorKind::ConnectionRefused.into())
+ });
+
+ let mut displays = x11::Server::displays(server);
+ let mut best = displays.next();
+ if best.as_ref().map(|x| x.is_default()) == Some(false) {
+ best = displays.find(|x| x.is_default()).or(best);
+ }
+
+ match best {
+ Some(best) => Ok(Display(best)),
+ None => Err(io::ErrorKind::NotFound.into())
+ }
+ }
+
+ pub fn all() -> io::Result<Vec<Display>> {
+ let server = Rc::new(match x11::Server::default() {
+ Ok(server) => server,
+ Err(_) => return Err(io::ErrorKind::ConnectionRefused.into())
+ });
+
+ Ok(x11::Server::displays(server).map(Display).collect())
+ }
+
+ pub fn width(&self) -> usize {
+ self.0.rect().w as usize
+ }
+
+ pub fn height(&self) -> usize {
+ self.0.rect().h as usize
+ }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/dxgi/ffi.rs b/apps/desktop/src-tauri/src/capture/src/dxgi/ffi.rs
new file mode 100644
index 000000000..5bfe317d0
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/dxgi/ffi.rs
@@ -0,0 +1,65 @@
+use winapi::{
+ GUID,
+ HRESULT,
+ REFIID,
+ IDXGIFactory1,
+ IDXGIAdapter,
+ D3D_DRIVER_TYPE,
+ HMODULE,
+ UINT,
+ ID3D11Device,
+ D3D_FEATURE_LEVEL,
+ ID3D11DeviceContext
+};
+
+pub const DXGI_MAP_READ: UINT = 1;
+
+pub const IID_IDXGIFACTORY1: GUID = GUID {
+ Data1: 0x770aae78,
+ Data2: 0xf26f,
+ Data3: 0x4dba,
+ Data4: [0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87]
+};
+
+pub const IID_IDXGIOUTPUT1: GUID = GUID {
+ Data1: 0x00cddea8,
+ Data2: 0x939b,
+ Data3: 0x4b83,
+ Data4: [0xa3, 0x40, 0xa6, 0x85, 0x22, 0x66, 0x66, 0xcc]
+};
+
+pub const IID_IDXGISURFACE: GUID = GUID {
+ Data1: 3405559148,
+ Data2: 27331,
+ Data3: 18569,
+ Data4: [191, 71, 158, 35, 187, 210, 96, 236]
+};
+
+pub const IID_ID3D11TEXTURE2D: GUID = GUID {
+ Data1: 1863690994,
+ Data2: 53768,
+ Data3: 20105,
+ Data4: [154, 180, 72, 149, 53, 211, 79, 156]
+};
+
+#[link(name="dxgi")]
+#[link(name="d3d11")]
+extern "system" {
+ pub fn CreateDXGIFactory1(
+ id: REFIID,
+ pp_factory: *mut *mut IDXGIFactory1
+ ) -> HRESULT;
+
+ pub fn D3D11CreateDevice(
+ pAdapter: *mut IDXGIAdapter,
+ DriverType: D3D_DRIVER_TYPE,
+ Software: HMODULE,
+ Flags: UINT,
+ pFeatureLevels: *mut D3D_FEATURE_LEVEL,
+ FeatureLevels: UINT,
+ SDKVersion: UINT,
+ ppDevice: *mut *mut ID3D11Device,
+ pFeatureLevel: *mut D3D_FEATURE_LEVEL,
+ ppImmediateContext: *mut *mut ID3D11DeviceContext
+ ) -> HRESULT;
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/dxgi/mod.rs b/apps/desktop/src-tauri/src/capture/src/dxgi/mod.rs
new file mode 100644
index 000000000..b2ad8a116
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/dxgi/mod.rs
@@ -0,0 +1,433 @@
+use self::ffi::*;
+use std::{io, mem, ptr, slice};
+use winapi::{
+ HRESULT,
+ IDXGIAdapter1,
+ IDXGIFactory1,
+ IDXGIOutput1,
+ S_OK,
+ UINT,
+ DXGI_OUTPUT_DESC,
+ LONG,
+ DXGI_MODE_ROTATION,
+ ID3D11Device,
+ ID3D11DeviceContext,
+ IDXGIOutputDuplication,
+ D3D11_SDK_VERSION,
+ D3D_DRIVER_TYPE_UNKNOWN,
+ D3D_FEATURE_LEVEL_9_1,
+ DXGI_ERROR_ACCESS_LOST,
+ DXGI_ERROR_WAIT_TIMEOUT,
+ DXGI_ERROR_INVALID_CALL,
+ E_ACCESSDENIED,
+ DXGI_ERROR_UNSUPPORTED,
+ ID3D11Texture2D,
+ DXGI_ERROR_NOT_CURRENTLY_AVAILABLE,
+ DXGI_ERROR_SESSION_DISCONNECTED,
+ TRUE,
+ IDXGISurface,
+ IDXGIResource,
+ DXGI_RESOURCE_PRIORITY_MAXIMUM,
+ D3D11_CPU_ACCESS_READ,
+ D3D11_USAGE_STAGING
+};
+
+mod ffi;
+
+//TODO: Split up into files.
+
+pub struct Capturer {
+ device: *mut ID3D11Device,
+ context: *mut ID3D11DeviceContext,
+ duplication: *mut IDXGIOutputDuplication,
+ fastlane: bool, surface: *mut IDXGISurface,
+ data: *mut u8, len: usize,
+ height: usize,
+}
+
+impl Capturer {
+ pub fn new(display: &Display) -> io::Result<Capturer> {
+ let mut device = ptr::null_mut();
+ let mut context = ptr::null_mut();
+ let mut duplication = ptr::null_mut();
+ let mut desc = unsafe { mem::uninitialized() };
+
+ if unsafe {
+ D3D11CreateDevice(
+ &mut **display.adapter,
+ D3D_DRIVER_TYPE_UNKNOWN,
+ ptr::null_mut(), // No software rasterizer.
+ 0, // No device flags.
+ ptr::null_mut(), // Feature levels.
+ 0, // Feature levels' length.
+ D3D11_SDK_VERSION,
+ &mut device,
+ &mut D3D_FEATURE_LEVEL_9_1,
+ &mut context
+ )
+ } != S_OK {
+ // Unknown error.
+ return Err(io::ErrorKind::Other.into());
+ }
+
+ let res = wrap_hresult(unsafe {
+ (*display.inner).DuplicateOutput(
+ &mut **device,
+ &mut duplication
+ )
+ });
+
+ if let Err(err) = res {
+ unsafe {
+ (*device).Release();
+ (*context).Release();
+ }
+ return Err(err);
+ }
+
+ unsafe {
+ (*duplication).GetDesc(&mut desc);
+ }
+
+ Ok(unsafe {
+ let mut capturer = Capturer {
+ device, context, duplication,
+ fastlane: desc.DesktopImageInSystemMemory == TRUE,
+ surface: ptr::null_mut(),
+ height: display.height() as usize,
+ data: ptr::null_mut(),
+ len: 0
+ };
+ let _ = capturer.load_frame(0);
+ capturer
+ })
+ }
+
+ unsafe fn load_frame(&mut self, timeout: UINT) -> io::Result<()> {
+ let mut frame = ptr::null_mut();
+ let mut info = mem::uninitialized();
+ self.data = ptr::null_mut();
+
+ wrap_hresult((*self.duplication).AcquireNextFrame(
+ timeout,
+ &mut info,
+ &mut frame
+ ))?;
+
+ if self.fastlane {
+ let mut rect = mem::uninitialized();
+ let res = wrap_hresult(
+ (*self.duplication).MapDesktopSurface(&mut rect)
+ );
+
+ (*frame).Release();
+
+ if let Err(err) = res {
+ Err(err)
+ } else {
+ self.data = rect.pBits;
+ self.len = self.height * rect.Pitch as usize;
+ Ok(())
+ }
+ } else {
+ self.surface = ptr::null_mut();
+ self.surface = self.ohgodwhat(frame)?;
+
+ let mut rect = mem::uninitialized();
+ wrap_hresult((*self.surface).Map(
+ &mut rect,
+ DXGI_MAP_READ
+ ))?;
+
+ self.data = rect.pBits;
+ self.len = self.height * rect.Pitch as usize;
+ Ok(())
+ }
+ }
+
+ unsafe fn ohgodwhat(
+ &mut self,
+ frame: *mut IDXGIResource
+ ) -> io::Result<*mut IDXGISurface> {
+ let mut texture: *mut ID3D11Texture2D = ptr::null_mut();
+ (*frame).QueryInterface(
+ &IID_ID3D11TEXTURE2D,
+ &mut texture as *mut *mut _ as *mut *mut _
+ );
+
+ let mut texture_desc = mem::uninitialized();
+ (*texture).GetDesc(&mut texture_desc);
+
+ texture_desc.Usage = D3D11_USAGE_STAGING;
+ texture_desc.BindFlags = 0;
+ texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0;
+ texture_desc.MiscFlags = 0;
+
+ let mut readable = ptr::null_mut();
+ let res = wrap_hresult((*self.device).CreateTexture2D(
+ &mut texture_desc,
+ ptr::null(),
+ &mut readable
+ ));
+
+ if let Err(err) = res {
+ (*frame).Release();
+ (*texture).Release();
+ (*readable).Release();
+ Err(err)
+ } else {
+ (*readable).SetEvictionPriority(DXGI_RESOURCE_PRIORITY_MAXIMUM);
+
+ let mut surface = ptr::null_mut();
+ (*readable).QueryInterface(
+ &IID_IDXGISURFACE,
+ &mut surface as *mut *mut _ as *mut *mut _
+ );
+
+ (*self.context).CopyResource(
+ &mut **readable,
+ &mut **texture
+ );
+
+ (*frame).Release();
+ (*texture).Release();
+ (*readable).Release();
+ Ok(surface)
+ }
+ }
+
+ pub fn frame<'a>(&'a mut self, timeout: UINT) -> io::Result<&'a [u8]> {
+ unsafe {
+ // Release last frame.
+ // No error checking needed because we don't care.
+ // None of the errors crash anyway.
+
+ if self.fastlane {
+ (*self.duplication).UnMapDesktopSurface();
+ } else {
+ if !self.surface.is_null() {
+ (*self.surface).Unmap();
+ (*self.surface).Release();
+ self.surface = ptr::null_mut();
+ }
+ }
+
+ (*self.duplication).ReleaseFrame();
+
+ // Get next frame.
+
+ self.load_frame(timeout)?;
+ Ok(slice::from_raw_parts(self.data, self.len))
+ }
+ }
+}
+
+impl Drop for Capturer {
+ fn drop(&mut self) {
+ unsafe {
+ if !self.surface.is_null() {
+ (*self.surface).Unmap();
+ (*self.surface).Release();
+ }
+ (*self.duplication).Release();
+ (*self.device).Release();
+ (*self.context).Release();
+ }
+ }
+}
+
+pub struct Displays {
+ factory: *mut IDXGIFactory1,
+ adapter: *mut IDXGIAdapter1,
+ /// Index of the CURRENT adapter.
+ nadapter: UINT,
+ /// Index of the NEXT display to fetch.
+ ndisplay: UINT
+}
+
+impl Displays {
+ pub fn new() -> io::Result<Displays> {
+ let mut factory = ptr::null_mut();
+ wrap_hresult(unsafe {
+ CreateDXGIFactory1(&IID_IDXGIFACTORY1, &mut factory)
+ })?;
+
+ let mut adapter = ptr::null_mut();
+ unsafe {
+ // On error, our adapter is null, so it's fine.
+ (*factory).EnumAdapters1(0, &mut adapter);
+ };
+
+ Ok(Displays {
+ factory,
+ adapter,
+ nadapter: 0,
+ ndisplay: 0
+ })
+ }
+
+ // No Adapter => Some(None)
+ // Non-Empty Adapter => Some(Some(OUTPUT))
+ // End of Adapter => None
+ fn read_and_invalidate(&mut self) -> Option<Option<Display>> {
+ // If there is no adapter, there is nothing left for us to do.
+
+ if self.adapter.is_null() {
+ return Some(None);
+ }
+
+ // Otherwise, we get the next output of the current adapter.
+
+ let output = unsafe {
+ let mut output = ptr::null_mut();
+ (*self.adapter).EnumOutputs(self.ndisplay, &mut output);
+ output
+ };
+
+ // If the current adapter is done, we free it.
+ // We return None so the caller gets the next adapter and tries again.
+
+ if output.is_null() {
+ unsafe {
+ (*self.adapter).Release();
+ self.adapter = ptr::null_mut();
+ }
+ return None;
+ }
+
+ // Advance to the next display.
+
+ self.ndisplay += 1;
+
+ // We get the display's details.
+
+ let desc = unsafe {
+ let mut desc = mem::uninitialized();
+ (*output).GetDesc(&mut desc);
+ desc
+ };
+
+ // We cast it up to the version needed for desktop duplication.
+
+ let mut inner = ptr::null_mut();
+ unsafe {
+ (*output).QueryInterface(
+ &IID_IDXGIOUTPUT1,
+ &mut inner as *mut *mut _ as *mut *mut _
+ );
+ (*output).Release();
+ }
+
+ // If it's null, we have an error.
+ // So we act like the adapter is done.
+
+ if inner.is_null() {
+ unsafe {
+ (*self.adapter).Release();
+ self.adapter = ptr::null_mut();
+ }
+ return None;
+ }
+
+ unsafe {
+ (*self.adapter).AddRef();
+ }
+
+ Some(Some(Display { inner, adapter: self.adapter, desc }))
+ }
+}
+
+impl Iterator for Displays {
+ type Item = Display;
+ fn next(&mut self) -> Option<Display> {
+ if let Some(res) = self.read_and_invalidate() {
+ res
+ } else {
+ // We need to replace the adapter.
+
+ self.ndisplay = 0;
+ self.nadapter += 1;
+
+ self.adapter = unsafe {
+ let mut adapter = ptr::null_mut();
+ (*self.factory).EnumAdapters1(
+ self.nadapter,
+ &mut adapter
+ );
+ adapter
+ };
+
+ if let Some(res) = self.read_and_invalidate() {
+ res
+ } else {
+ // All subsequent adapters will also be empty.
+ None
+ }
+ }
+ }
+}
+
+impl Drop for Displays {
+ fn drop(&mut self) {
+ unsafe {
+ (*self.factory).Release();
+ if !self.adapter.is_null() {
+ (*self.adapter).Release();
+ }
+ }
+ }
+}
+
+pub struct Display {
+ inner: *mut IDXGIOutput1,
+ adapter: *mut IDXGIAdapter1,
+ desc: DXGI_OUTPUT_DESC
+}
+
+impl Display {
+ pub fn width(&self) -> LONG {
+ self.desc.DesktopCoordinates.right -
+ self.desc.DesktopCoordinates.left
+ }
+
+ pub fn height(&self) -> LONG {
+ self.desc.DesktopCoordinates.bottom -
+ self.desc.DesktopCoordinates.top
+ }
+
+ pub fn rotation(&self) -> DXGI_MODE_ROTATION {
+ self.desc.Rotation
+ }
+
+ pub fn name(&self) -> &[u16] {
+ let s = &self.desc.DeviceName;
+ let i = s.iter()
+ .position(|&x| x == 0)
+ .unwrap_or(s.len());
+ &s[..i]
+ }
+}
+
+impl Drop for Display {
+ fn drop(&mut self) {
+ unsafe {
+ (*self.inner).Release();
+ (*self.adapter).Release();
+ }
+ }
+}
+
+fn wrap_hresult(x: HRESULT) -> io::Result<()> {
+ use std::io::ErrorKind::*;
+ Err((match x {
+ S_OK => return Ok(()),
+ DXGI_ERROR_ACCESS_LOST => ConnectionReset,
+ DXGI_ERROR_WAIT_TIMEOUT => TimedOut,
+ DXGI_ERROR_INVALID_CALL => InvalidData,
+ E_ACCESSDENIED => PermissionDenied,
+ DXGI_ERROR_UNSUPPORTED => ConnectionRefused,
+ DXGI_ERROR_NOT_CURRENTLY_AVAILABLE => Interrupted,
+ DXGI_ERROR_SESSION_DISCONNECTED => ConnectionAborted,
+ _ => Other
+ }).into())
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/lib.rs b/apps/desktop/src-tauri/src/capture/src/lib.rs
new file mode 100644
index 000000000..115c6e0f6
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/lib.rs
@@ -0,0 +1,14 @@
+#[macro_use]
+extern crate cfg_if;
+extern crate libc;
+
+#[cfg(quartz)] extern crate block;
+#[cfg(quartz)] pub mod quartz;
+
+#[cfg(x11)] pub mod x11;
+
+#[cfg(dxgi)] extern crate winapi;
+#[cfg(dxgi)] pub mod dxgi;
+
+mod common;
+pub use common::*;
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/capturer.rs b/apps/desktop/src-tauri/src/capture/src/quartz/capturer.rs
new file mode 100644
index 000000000..8232a539d
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/quartz/capturer.rs
@@ -0,0 +1,83 @@
+use block::{Block, ConcreteBlock};
+use libc::c_void;
+use super::ffi::*;
+use super::config::Config;
+use super::display::Display;
+use super::frame::Frame;
+use std::ptr;
+
+pub struct Capturer {
+ stream: CGDisplayStreamRef,
+ queue: DispatchQueue,
+
+ width: usize,
+ height: usize,
+ format: PixelFormat,
+ display: Display
+}
+
+unsafe impl Send for Capturer {}
+
+impl Capturer {
+ pub fn new<F: Fn(Frame) + 'static>(
+ display: Display,
+ width: usize,
+ height: usize,
+ format: PixelFormat,
+ config: Config,
+ handler: F
+ ) -> Result<Capturer, CGError> {
+ let handler: FrameAvailableHandler =
+ ConcreteBlock::new(move |status, _, surface, _| {
+ use self::CGDisplayStreamFrameStatus::*;
+ if status == FrameComplete {
+ handler(unsafe { Frame::new(surface) });
+ }
+ }).copy();
+
+ let queue = unsafe {
+ dispatch_queue_create(
+ b"quadrupleslap.scrap\0".as_ptr() as *const i8,
+ ptr::null_mut()
+ )
+ };
+
+ let stream = unsafe {
+ let config = config.build();
+ let stream = CGDisplayStreamCreateWithDispatchQueue(
+ display.id(),
+ width,
+ height,
+ format,
+ config,
+ queue,
+ &*handler as *const Block<_, _> as *const c_void
+ );
+ CFRelease(config);
+ stream
+ };
+
+ match unsafe { CGDisplayStreamStart(stream) } {
+ CGError::Success => Ok(Capturer {
+ stream, queue, width, height, format, display
+ }),
+ x => Err(x)
+ }
+ }
+
+ pub fn width(&self) -> usize { self.width }
+ pub fn height(&self) -> usize { self.height }
+ pub fn format(&self) -> PixelFormat { self.format }
+ pub fn display(&self) -> Display { self.display }
+}
+
+impl Drop for Capturer {
+ fn drop(&mut self) {
+ unsafe {
+ //TODO: Maybe it should wait until `Stopped` before releasing?
+ let _ = CGDisplayStreamStop(self.stream);
+ CFRelease(self.stream);
+ dispatch_release(self.queue);
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/config.rs b/apps/desktop/src-tauri/src/capture/src/quartz/config.rs
new file mode 100644
index 000000000..76f1192dc
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/quartz/config.rs
@@ -0,0 +1,73 @@
+use super::ffi::*;
+use libc::c_void;
+use std::ptr;
+
+//TODO: Color space, YCbCr matrix.
+pub struct Config {
+ /// Whether the cursor is visible.
+ pub cursor: bool,
+ /// Whether it should letterbox or stretch.
+ pub letterbox: bool,
+ /// Minimum seconds per frame.
+ pub throttle: f64,
+ /// How many frames are allocated.
+ /// 3 is the recommended value.
+ /// 8 is the maximum value.
+ pub queue_length: i8
+}
+
+impl Config {
+ /// Don't forget to CFRelease this!
+ pub fn build(self) -> CFDictionaryRef {
+ unsafe {
+ let throttle = CFNumberCreate(
+ ptr::null_mut(),
+ CFNumberType::Float64,
+ &self.throttle as *const _ as *const c_void
+ );
+ let queue_length = CFNumberCreate(
+ ptr::null_mut(),
+ CFNumberType::SInt8,
+ &self.queue_length as *const _ as *const c_void
+ );
+
+ let keys: [CFStringRef; 4] = [
+ kCGDisplayStreamShowCursor,
+ kCGDisplayStreamPreserveAspectRatio,
+ kCGDisplayStreamMinimumFrameTime,
+ kCGDisplayStreamQueueDepth
+ ];
+ let values: [*mut c_void; 4] = [
+ cfbool(self.cursor),
+ cfbool(self.letterbox),
+ throttle,
+ queue_length
+ ];
+
+ let res = CFDictionaryCreate(
+ ptr::null_mut(),
+ keys.as_ptr(),
+ values.as_ptr(),
+ 4,
+ &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks
+ );
+
+ CFRelease(throttle);
+ CFRelease(queue_length);
+
+ res
+ }
+ }
+}
+
+impl Default for Config {
+ fn default() -> Config {
+ Config {
+ cursor: true,
+ letterbox: true,
+ throttle: 0.0166,
+ queue_length: 1
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/display.rs b/apps/desktop/src-tauri/src/capture/src/quartz/display.rs
new file mode 100644
index 000000000..5944f5a94
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/quartz/display.rs
@@ -0,0 +1,58 @@
+use super::ffi::*;
+use std::mem;
+
+#[derive(PartialEq, Eq, Debug, Clone, Copy)]
+#[repr(C)]
+pub struct Display(u32);
+
+impl Display {
+ pub fn primary() -> Display {
+ Display(unsafe { CGMainDisplayID() })
+ }
+
+ pub fn online() -> Result<Vec<Display>, CGError> {
+ unsafe {
+ let mut arr: [u32; 16] = mem::uninitialized();
+ let mut len: u32 = 0;
+
+ match CGGetOnlineDisplayList(16, arr.as_mut_ptr(), &mut len) {
+ CGError::Success => (),
+ x => return Err(x)
+ }
+
+ let mut res = Vec::with_capacity(16);
+ for i in 0..len as usize {
+ res.push(Display(*arr.get_unchecked(i)));
+ }
+ Ok(res)
+ }
+ }
+
+ pub fn id(self) -> u32 {
+ self.0
+ }
+
+ pub fn width(self) -> usize {
+ unsafe { CGDisplayPixelsWide(self.0) }
+ }
+
+ pub fn height(self) -> usize {
+ unsafe { CGDisplayPixelsHigh(self.0) }
+ }
+
+ pub fn is_builtin(self) -> bool {
+ unsafe { CGDisplayIsBuiltin(self.0) != 0 }
+ }
+
+ pub fn is_primary(self) -> bool {
+ unsafe { CGDisplayIsMain(self.0) != 0 }
+ }
+
+ pub fn is_active(self) -> bool {
+ unsafe { CGDisplayIsActive(self.0) != 0 }
+ }
+
+ pub fn is_online(self) -> bool {
+ unsafe { CGDisplayIsOnline(self.0) != 0 }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/ffi.rs b/apps/desktop/src-tauri/src/capture/src/quartz/ffi.rs
new file mode 100644
index 000000000..7653fec39
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/quartz/ffi.rs
@@ -0,0 +1,228 @@
+#![allow(dead_code)]
+
+use block::RcBlock;
+use libc::c_void;
+
+pub type CGDisplayStreamRef = *mut c_void;
+pub type CFDictionaryRef = *mut c_void;
+pub type CFBooleanRef = *mut c_void;
+pub type CFNumberRef = *mut c_void;
+pub type CFStringRef = *mut c_void;
+pub type CGDisplayStreamUpdateRef = *mut c_void;
+pub type IOSurfaceRef = *mut c_void;
+pub type DispatchQueue = *mut c_void;
+pub type DispatchQueueAttr = *mut c_void;
+pub type CFAllocatorRef = *mut c_void;
+
+#[repr(C)]
+pub struct CFDictionaryKeyCallBacks {
+ callbacks: [usize; 5],
+ version: i32
+}
+
+#[repr(C)]
+pub struct CFDictionaryValueCallBacks {
+ callbacks: [usize; 4],
+ version: i32
+}
+
+macro_rules! pixel_format {
+ ($a:expr, $b:expr, $c:expr, $d:expr) => {
+ ($a as i32) << 24
+ | ($b as i32) << 16
+ | ($c as i32) << 8
+ | ($d as i32)
+ }
+}
+
+pub const SURFACE_LOCK_READ_ONLY: u32 = 0x0000_0001;
+pub const SURFACE_LOCK_AVOID_SYNC: u32 = 0x0000_0002;
+
+pub fn cfbool(x: bool) -> CFBooleanRef {
+ unsafe {
+ if x { kCFBooleanTrue } else { kCFBooleanFalse }
+ }
+}
+
+#[repr(i32)]
+#[derive(PartialEq, Eq, Debug, Clone, Copy)]
+pub enum CGDisplayStreamFrameStatus {
+ /// A new frame was generated.
+ FrameComplete = 0,
+ /// A new frame was not generated because the display did not change.
+ FrameIdle = 1,
+ /// A new frame was not generated because the display has gone blank.
+ FrameBlank = 2,
+ /// The display stream was stopped.
+ Stopped = 3,
+ #[doc(hidden)]
+ __Nonexhaustive
+}
+
+#[repr(i32)]
+#[derive(PartialEq, Eq, Debug, Clone, Copy)]
+pub enum CFNumberType {
+ /* Fixed-width types */
+ SInt8 = 1,
+ SInt16 = 2,
+ SInt32 = 3,
+ SInt64 = 4,
+ Float32 = 5,
+ Float64 = 6, /* 64-bit IEEE 754 */
+ /* Basic C types */
+ Char = 7,
+ Short = 8,
+ Int = 9,
+ Long = 10,
+ LongLong = 11,
+ Float = 12,
+ Double = 13,
+ /* Other */
+ CFIndex = 14,
+ NSInteger = 15,
+ CGFloat = 16
+}
+
+#[repr(i32)]
+#[derive(PartialEq, Eq, Debug, Clone, Copy)]
+#[must_use]
+pub enum CGError {
+ Success = 0,
+ Failure = 1000,
+ IllegalArgument = 1001,
+ InvalidConnection = 1002,
+ InvalidContext = 1003,
+ CannotComplete = 1004,
+ NotImplemented = 1006,
+ RangeCheck = 1007,
+ TypeCheck = 1008,
+ InvalidOperation = 1010,
+ NoneAvailable = 1011,
+ #[doc(hidden)]
+ __Nonexhaustive
+}
+
+#[repr(i32)]
+#[derive(PartialEq, Eq, Debug, Clone, Copy)]
+pub enum PixelFormat {
+ /// Packed Little Endian ARGB8888
+ Argb8888 = pixel_format!('B','G','R','A'),
+ /// Packed Little Endian ARGB2101010
+ Argb2101010 = pixel_format!('l','1','0','r'),
+ /// 2-plane "video" range YCbCr 4:2:0
+ YCbCr420Video = pixel_format!('4','2','0','v'),
+ /// 2-plane "full" range YCbCr 4:2:0
+ YCbCr420Full = pixel_format!('4','2','0','f'),
+ #[doc(hidden)]
+ __Nonexhaustive
+}
+
+pub type CGDisplayStreamFrameAvailableHandler = *const c_void;
+
+pub type FrameAvailableHandler = RcBlock<(
+ CGDisplayStreamFrameStatus, // status
+ u64, // displayTime
+ IOSurfaceRef, // frameSurface
+ CGDisplayStreamUpdateRef // updateRef
+), ()>;
+
+#[link(name="System", kind="dylib")]
+#[link(name="CoreGraphics", kind="framework")]
+#[link(name="CoreFoundation", kind="framework")]
+#[link(name="IOSurface", kind="framework")]
+extern {
+ // CoreGraphics
+
+ pub static kCGDisplayStreamShowCursor: CFStringRef;
+ pub static kCGDisplayStreamPreserveAspectRatio: CFStringRef;
+ pub static kCGDisplayStreamMinimumFrameTime: CFStringRef;
+ pub static kCGDisplayStreamQueueDepth: CFStringRef;
+
+ pub fn CGDisplayStreamCreateWithDispatchQueue(
+ display: u32,
+ output_width: usize,
+ output_height: usize,
+ pixel_format: PixelFormat,
+ properties: CFDictionaryRef,
+ queue: DispatchQueue,
+ handler: CGDisplayStreamFrameAvailableHandler
+ ) -> CGDisplayStreamRef;
+
+ pub fn CGDisplayStreamStart(
+ displayStream: CGDisplayStreamRef
+ ) -> CGError;
+
+ pub fn CGDisplayStreamStop(
+ displayStream: CGDisplayStreamRef
+ ) -> CGError;
+
+ pub fn CGMainDisplayID() -> u32;
+ pub fn CGDisplayPixelsWide(display: u32) -> usize;
+ pub fn CGDisplayPixelsHigh(display: u32) -> usize;
+
+ pub fn CGGetOnlineDisplayList(
+ max_displays: u32,
+ online_displays: *mut u32,
+ display_count: *mut u32
+ ) -> CGError;
+
+ pub fn CGDisplayIsBuiltin(display: u32) -> i32;
+ pub fn CGDisplayIsMain(display: u32) -> i32;
+ pub fn CGDisplayIsActive(display: u32) -> i32;
+ pub fn CGDisplayIsOnline(display: u32) -> i32;
+
+ // IOSurface
+
+ pub fn IOSurfaceGetAllocSize(buffer: IOSurfaceRef) -> usize;
+ pub fn IOSurfaceGetBaseAddress(buffer: IOSurfaceRef) -> *mut c_void;
+ pub fn IOSurfaceIncrementUseCount(buffer: IOSurfaceRef);
+ pub fn IOSurfaceDecrementUseCount(buffer: IOSurfaceRef);
+ pub fn IOSurfaceLock(
+ buffer: IOSurfaceRef,
+ options: u32,
+ seed: *mut u32
+ ) -> i32;
+ pub fn IOSurfaceUnlock(
+ buffer: IOSurfaceRef,
+ options: u32,
+ seed: *mut u32
+ ) -> i32;
+
+ // Dispatch
+
+ pub fn dispatch_queue_create(
+ label: *const i8,
+ attr: DispatchQueueAttr
+ ) -> DispatchQueue;
+
+ pub fn dispatch_release(
+ object: DispatchQueue
+ );
+
+ // Core Foundation
+
+ pub static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks;
+ pub static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks;
+
+ // EVEN THE BOOLEANS ARE REFERENCES.
+ pub static kCFBooleanTrue: CFBooleanRef;
+ pub static kCFBooleanFalse: CFBooleanRef;
+
+ pub fn CFNumberCreate(
+ allocator: CFAllocatorRef,
+ theType: CFNumberType,
+ valuePtr: *const c_void
+ ) -> CFNumberRef;
+
+ pub fn CFDictionaryCreate(
+ allocator: CFAllocatorRef,
+ keys: *const *mut c_void,
+ values: *const *mut c_void,
+ numValues: i64,
+ keyCallBacks: *const CFDictionaryKeyCallBacks,
+ valueCallBacks: *const CFDictionaryValueCallBacks
+ ) -> CFDictionaryRef;
+
+ pub fn CFRetain(cf: *const c_void);
+ pub fn CFRelease(cf: *const c_void);
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/frame.rs b/apps/desktop/src-tauri/src/capture/src/quartz/frame.rs
new file mode 100644
index 000000000..3b6b0496d
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/quartz/frame.rs
@@ -0,0 +1,49 @@
+use super::ffi::*;
+use std::{ops, ptr, slice};
+
+pub struct Frame {
+ surface: IOSurfaceRef,
+ inner: &'static [u8]
+}
+
+impl Frame {
+ pub unsafe fn new(surface: IOSurfaceRef) -> Frame {
+ CFRetain(surface);
+ IOSurfaceIncrementUseCount(surface);
+
+ IOSurfaceLock(
+ surface,
+ SURFACE_LOCK_READ_ONLY,
+ ptr::null_mut()
+ );
+
+ let inner = slice::from_raw_parts(
+ IOSurfaceGetBaseAddress(surface) as *const u8,
+ IOSurfaceGetAllocSize(surface)
+ );
+
+ Frame { surface, inner }
+ }
+}
+
+impl ops::Deref for Frame {
+ type Target = [u8];
+ fn deref<'a>(&'a self) -> &'a [u8] {
+ self.inner
+ }
+}
+
+impl Drop for Frame {
+ fn drop(&mut self) {
+ unsafe {
+ IOSurfaceUnlock(
+ self.surface,
+ SURFACE_LOCK_READ_ONLY,
+ ptr::null_mut()
+ );
+
+ IOSurfaceDecrementUseCount(self.surface);
+ CFRelease(self.surface);
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/mod.rs b/apps/desktop/src-tauri/src/capture/src/quartz/mod.rs
new file mode 100644
index 000000000..fce89e3b3
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/quartz/mod.rs
@@ -0,0 +1,11 @@
+mod capturer;
+mod config;
+mod display;
+mod ffi;
+mod frame;
+
+pub use self::capturer::Capturer;
+pub use self::config::Config;
+pub use self::display::Display;
+pub use self::ffi::{CGError, PixelFormat};
+pub use self::frame::Frame;
diff --git a/apps/desktop/src-tauri/src/capture/src/x11/capturer.rs b/apps/desktop/src-tauri/src/capture/src/x11/capturer.rs
new file mode 100644
index 000000000..8b76248b7
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/x11/capturer.rs
@@ -0,0 +1,162 @@
+use libc;
+use std::{io, ptr, slice};
+use super::Display;
+use super::ffi::*;
+
+pub struct Capturer {
+ display: Display,
+ shmid: i32,
+ xcbid: u32,
+ buffer: *const u8,
+
+ request: xcb_shm_get_image_cookie_t,
+ loading: usize,
+ size: usize
+}
+
+unsafe impl Send for Capturer {}
+
+impl Capturer {
+ pub fn new(
+ display: Display
+ ) -> io::Result<Capturer> {
+ // Calculate dimensions.
+
+ let pixel_width = 4;
+ let rect = display.rect();
+ let size = (rect.w as usize) * (rect.h as usize) * pixel_width;
+
+ // Create a shared memory segment.
+
+ let shmid = unsafe {
+ libc::shmget(
+ libc::IPC_PRIVATE,
+ size * 2,
+ // Everyone can do anything.
+ libc::IPC_CREAT | 0o777
+ )
+ };
+
+ if shmid == -1 {
+ return Err(io::Error::last_os_error());
+ }
+
+ // Attach the segment to a readable address.
+
+ let buffer = unsafe {
+ libc::shmat(
+ shmid,
+ ptr::null(),
+ libc::SHM_RDONLY
+ )
+ } as *mut u8;
+
+ if buffer as isize == -1 {
+ return Err(io::Error::last_os_error());
+ }
+
+ // Attach the segment to XCB.
+
+ let server = display.server().raw();
+ let xcbid = unsafe { xcb_generate_id(server) };
+ unsafe {
+ xcb_shm_attach(
+ server,
+ xcbid,
+ shmid as u32,
+ 0 // False, i.e. not read-only.
+ );
+ }
+
+ // Start the first screenshot early.
+
+ let request = unsafe {
+ xcb_shm_get_image_unchecked(
+ server,
+ display.root(),
+ rect.x, rect.y,
+ rect.w, rect.h,
+ !0, // Plane mask.
+ XCB_IMAGE_FORMAT_Z_PIXMAP,
+ xcbid,
+ 0 // Byte offset.
+ )
+ };
+
+ // Return!
+
+ Ok(Capturer {
+ display, shmid, xcbid, buffer,
+ request, loading: 0, size
+ })
+ }
+
+ pub fn display(&self) -> &Display {
+ &self.display
+ }
+
+ pub fn frame<'b>(&'b mut self) -> &'b [u8] {
+ // Get the return value.
+
+ let result = unsafe {
+ let off = self.loading & self.size;
+ slice::from_raw_parts(
+ self.buffer.offset(off as isize),
+ self.size
+ )
+ };
+
+ // Block for response.
+
+ unsafe {
+ self.handle_response();
+ }
+
+ // Start next request.
+
+ let rect = self.display.rect();
+
+ self.loading ^= !0;
+ self.request = unsafe {
+ xcb_shm_get_image_unchecked(
+ self.display.server().raw(),
+ self.display.root(),
+ rect.x, rect.y,
+ rect.w, rect.h,
+ !0,
+ XCB_IMAGE_FORMAT_Z_PIXMAP,
+ self.xcbid,
+ (self.loading & self.size) as u32
+ )
+ };
+
+ // Return!
+
+ result
+ }
+
+ unsafe fn handle_response(&self) {
+ let response = xcb_shm_get_image_reply(
+ self.display.server().raw(),
+ self.request,
+ ptr::null_mut()
+ );
+
+ libc::free(response as *mut _);
+ }
+}
+
+impl Drop for Capturer {
+ fn drop(&mut self) {
+ unsafe {
+ // Process pending request.
+ self.handle_response();
+ // Detach segment from XCB.
+ xcb_shm_detach(self.display.server().raw(), self.xcbid);
+ // Detach segment from our space.
+ libc::shmdt(self.buffer as *mut _);
+ // Destroy the shared memory segment.
+ libc::shmctl(self.shmid, libc::IPC_RMID, ptr::null_mut());
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/x11/display.rs b/apps/desktop/src-tauri/src/capture/src/x11/display.rs
new file mode 100644
index 000000000..e71a6df1f
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/x11/display.rs
@@ -0,0 +1,35 @@
+use std::rc::Rc;
+use super::Server;
+use super::ffi::*;
+
+#[derive(Debug)]
+pub struct Display {
+ server: Rc<Server>,
+ default: bool,
+ rect: Rect,
+ root: xcb_window_t,
+}
+
+#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
+pub struct Rect {
+ pub x: i16,
+ pub y: i16,
+ pub w: u16,
+ pub h: u16,
+}
+
+impl Display {
+ pub unsafe fn new(
+ server: Rc<Server>,
+ default: bool,
+ rect: Rect,
+ root: xcb_window_t
+ ) -> Display {
+ Display { server, default, rect, root }
+ }
+
+ pub fn server(&self) -> &Rc<Server> { &self.server }
+ pub fn is_default(&self) -> bool { self.default }
+ pub fn rect(&self) -> Rect { self.rect }
+ pub fn root(&self) -> xcb_window_t { self.root }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/x11/ffi.rs b/apps/desktop/src-tauri/src/capture/src/x11/ffi.rs
new file mode 100644
index 000000000..6e31cbf0a
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/x11/ffi.rs
@@ -0,0 +1,225 @@
+#![allow(non_camel_case_types)]
+
+use libc::c_void;
+
+#[link(name="xcb")]
+#[link(name="xcb-shm")]
+#[link(name="xcb-randr")]
+extern {
+ pub fn xcb_connect(
+ displayname: *const i8,
+ screenp: *mut i32
+ ) -> *mut xcb_connection_t;
+
+ pub fn xcb_disconnect(
+ c: *mut xcb_connection_t
+ );
+
+ pub fn xcb_connection_has_error(
+ c: *mut xcb_connection_t
+ ) -> i32;
+
+ pub fn xcb_get_setup(
+ c: *mut xcb_connection_t
+ ) -> *const xcb_setup_t;
+
+ pub fn xcb_setup_roots_iterator(
+ r: *const xcb_setup_t
+ ) -> xcb_screen_iterator_t;
+
+ pub fn xcb_screen_next(
+ i: *mut xcb_screen_iterator_t
+ );
+
+ pub fn xcb_generate_id(
+ c: *mut xcb_connection_t
+ ) -> u32;
+
+ pub fn xcb_shm_attach(
+ c: *mut xcb_connection_t,
+ shmseg: xcb_shm_seg_t,
+ shmid: u32,
+ read_only: u8
+ ) -> xcb_void_cookie_t;
+
+ pub fn xcb_shm_detach(
+ c: *mut xcb_connection_t,
+ shmseg: xcb_shm_seg_t
+ ) -> xcb_void_cookie_t;
+
+ pub fn xcb_shm_get_image_unchecked(
+ c: *mut xcb_connection_t,
+ drawable: xcb_drawable_t,
+ x: i16,
+ y: i16,
+ width: u16,
+ height: u16,
+ plane_mask: u32,
+ format: u8,
+ shmseg: xcb_shm_seg_t,
+ offset: u32
+ ) -> xcb_shm_get_image_cookie_t;
+
+ pub fn xcb_shm_get_image_reply(
+ c: *mut xcb_connection_t,
+ cookie: xcb_shm_get_image_cookie_t,
+ e: *mut *mut xcb_generic_error_t
+ ) -> *mut xcb_shm_get_image_reply_t;
+
+ pub fn xcb_randr_get_monitors_unchecked(
+ c: *mut xcb_connection_t,
+ window: xcb_window_t,
+ get_active: u8,
+ ) -> xcb_randr_get_monitors_cookie_t;
+
+ pub fn xcb_randr_get_monitors_reply(
+ c: *mut xcb_connection_t,
+ cookie: xcb_randr_get_monitors_cookie_t,
+ e: *mut *mut xcb_generic_error_t,
+ ) -> *mut xcb_randr_get_monitors_reply_t;
+
+ pub fn xcb_randr_get_monitors_monitors_iterator(
+ r: *const xcb_randr_get_monitors_reply_t,
+ ) -> xcb_randr_monitor_info_iterator_t;
+
+ pub fn xcb_randr_monitor_info_next(
+ i: *mut xcb_randr_monitor_info_iterator_t,
+ );
+}
+
+pub const XCB_IMAGE_FORMAT_Z_PIXMAP: u8 = 2;
+
+pub type xcb_atom_t = u32;
+pub type xcb_connection_t = c_void;
+pub type xcb_window_t = u32;
+pub type xcb_keycode_t = u8;
+pub type xcb_visualid_t = u32;
+pub type xcb_timestamp_t = u32;
+pub type xcb_colormap_t = u32;
+pub type xcb_shm_seg_t = u32;
+pub type xcb_drawable_t = u32;
+
+#[repr(C)]
+pub struct xcb_setup_t {
+ pub status: u8,
+ pub pad0: u8,
+ pub protocol_major_version: u16,
+ pub protocol_minor_version: u16,
+ pub length: u16,
+ pub release_number: u32,
+ pub resource_id_base: u32,
+ pub resource_id_mask: u32,
+ pub motion_buffer_size: u32,
+ pub vendor_len: u16,
+ pub maximum_request_length: u16,
+ pub roots_len: u8,
+ pub pixmap_formats_len: u8,
+ pub image_byte_order: u8,
+ pub bitmap_format_bit_order: u8,
+ pub bitmap_format_scanline_unit: u8,
+ pub bitmap_format_scanline_pad: u8,
+ pub min_keycode: xcb_keycode_t,
+ pub max_keycode: xcb_keycode_t,
+ pub pad1: [u8; 4]
+}
+
+#[repr(C)]
+pub struct xcb_screen_iterator_t {
+ pub data: *mut xcb_screen_t,
+ pub rem: i32,
+ pub index: i32
+}
+
+#[repr(C)]
+pub struct xcb_screen_t {
+ pub root: xcb_window_t,
+ pub default_colormap: xcb_colormap_t,
+ pub white_pixel: u32,
+ pub black_pixel: u32,
+ pub current_input_masks: u32,
+ pub width_in_pixels: u16,
+ pub height_in_pixels: u16,
+ pub width_in_millimeters: u16,
+ pub height_in_millimeters: u16,
+ pub min_installed_maps: u16,
+ pub max_installed_maps: u16,
+ pub root_visual: xcb_visualid_t,
+ pub backing_stores: u8,
+ pub save_unders: u8,
+ pub root_depth: u8,
+ pub allowed_depths_len: u8
+}
+
+#[repr(C)]
+pub struct xcb_randr_monitor_info_iterator_t {
+ pub data: *mut xcb_randr_monitor_info_t,
+ pub rem: i32,
+ pub index: i32,
+}
+
+#[repr(C)]
+pub struct xcb_randr_monitor_info_t {
+ pub name: xcb_atom_t,
+ pub primary: u8,
+ pub automatic: u8,
+ pub n_output: u16,
+ pub x: i16,
+ pub y: i16,
+ pub width: u16,
+ pub height: u16,
+ pub width_mm: u32,
+ pub height_mm: u32,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct xcb_randr_get_monitors_cookie_t {
+ pub sequence: u32
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct xcb_shm_get_image_cookie_t {
+ pub sequence: u32
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct xcb_void_cookie_t {
+ pub sequence: u32
+}
+
+#[repr(C)]
+pub struct xcb_generic_error_t {
+ pub response_type: u8,
+ pub error_code: u8,
+ pub sequence: u16,
+ pub resource_id: u32,
+ pub minor_code: u16,
+ pub major_code: u8,
+ pub pad0: u8,
+ pub pad: [u32; 5],
+ pub full_sequence: u32
+}
+
+#[repr(C)]
+pub struct xcb_shm_get_image_reply_t {
+ pub response_type: u8,
+ pub depth: u8,
+ pub sequence: u16,
+ pub length: u32,
+ pub visual: xcb_visualid_t,
+ pub size: u32
+}
+
+#[repr(C)]
+pub struct xcb_randr_get_monitors_reply_t {
+ pub response_type: u8,
+ pub pad0: u8,
+ pub sequence: u16,
+ pub length: u32,
+ pub timestamp: xcb_timestamp_t,
+ pub n_monitors: u32,
+ pub n_outputs: u32,
+ pub pad1: [u8; 12],
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/x11/iter.rs b/apps/desktop/src-tauri/src/capture/src/x11/iter.rs
new file mode 100644
index 000000000..f705294bd
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/x11/iter.rs
@@ -0,0 +1,89 @@
+use libc;
+use std::ptr;
+use std::rc::Rc;
+use super::{Display, Rect, Server};
+use super::ffi::*;
+
+//TODO: Do I have to free the displays?
+
+pub struct DisplayIter {
+ outer: xcb_screen_iterator_t,
+ inner: Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)>,
+ server: Rc<Server>,
+}
+
+impl DisplayIter {
+ pub unsafe fn new(server: Rc<Server>) -> DisplayIter {
+ let mut outer = xcb_setup_roots_iterator(server.setup());
+ let inner = Self::next_screen(&mut outer, &server);
+ DisplayIter { outer, inner, server }
+ }
+
+ fn next_screen(
+ outer: &mut xcb_screen_iterator_t,
+ server: &Server
+ ) -> Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)> {
+ if outer.rem == 0 {
+ return None;
+ }
+
+ unsafe {
+ let root = (*outer.data).root;
+
+ let cookie = xcb_randr_get_monitors_unchecked(
+ server.raw(),
+ root,
+ 1, //TODO: I don't know if this should be true or false.
+ );
+
+ let response = xcb_randr_get_monitors_reply(
+ server.raw(),
+ cookie,
+ ptr::null_mut(),
+ );
+
+ let inner = xcb_randr_get_monitors_monitors_iterator(response);
+
+ libc::free(response as *mut _);
+ xcb_screen_next(outer);
+
+ Some((inner, root))
+ }
+ }
+}
+
+impl Iterator for DisplayIter {
+ type Item = Display;
+
+ fn next(&mut self) -> Option<Display> {
+ loop {
+ if let Some((ref mut inner, root)) = self.inner {
+ // If there is something in the current screen, return that.
+ if inner.rem != 0 {unsafe {
+ let data = &*inner.data;
+
+ let display = Display::new(
+ self.server.clone(),
+ data.primary != 0,
+ Rect {
+ x: data.x,
+ y: data.y,
+ w: data.width,
+ h: data.height,
+ },
+ root
+ );
+
+ xcb_randr_monitor_info_next(inner);
+ return Some(display);
+ }}
+ } else {
+ // If there is no current screen, the screen iterator is empty.
+ return None;
+ }
+
+ // The current screen was empty, so try the next screen.
+ self.inner = Self::next_screen(&mut self.outer, &self.server);
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/capture/src/x11/mod.rs b/apps/desktop/src-tauri/src/capture/src/x11/mod.rs
new file mode 100644
index 000000000..600027f65
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/x11/mod.rs
@@ -0,0 +1,10 @@
+mod capturer;
+mod display;
+mod ffi;
+mod iter;
+mod server;
+
+pub use self::capturer::*;
+pub use self::display::*;
+pub use self::iter::*;
+pub use self::server::*;
diff --git a/apps/desktop/src-tauri/src/capture/src/x11/server.rs b/apps/desktop/src-tauri/src/capture/src/x11/server.rs
new file mode 100644
index 000000000..16461a646
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/src/x11/server.rs
@@ -0,0 +1,75 @@
+use std::ptr;
+use std::rc::Rc;
+use super::DisplayIter;
+use super::ffi::*;
+
+#[derive(Debug)]
+pub struct Server {
+ raw: *mut xcb_connection_t,
+ screenp: i32,
+ setup: *const xcb_setup_t
+}
+
+impl Server {
+ pub fn displays(slf: Rc<Server>) -> DisplayIter {
+ unsafe {
+ DisplayIter::new(slf)
+ }
+ }
+
+ pub fn default() -> Result<Server, Error> {
+ Server::connect(ptr::null())
+ }
+
+ pub fn connect(addr: *const i8) -> Result<Server, Error> {
+ unsafe {
+ let mut screenp = 0;
+ let raw = xcb_connect(addr, &mut screenp);
+
+ let error = xcb_connection_has_error(raw);
+ if error != 0 {
+ xcb_disconnect(raw);
+ Err(Error::from(error))
+ } else {
+ let setup = xcb_get_setup(raw);
+ Ok(Server { raw, screenp, setup })
+ }
+ }
+ }
+
+ pub fn raw(&self) -> *mut xcb_connection_t { self.raw }
+ pub fn screenp(&self) -> i32 { self.screenp }
+ pub fn setup(&self) -> *const xcb_setup_t { self.setup }
+}
+
+impl Drop for Server {
+ fn drop(&mut self) {
+ unsafe {
+ xcb_disconnect(self.raw);
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub enum Error {
+ Generic,
+ UnsupportedExtension,
+ InsufficientMemory,
+ RequestTooLong,
+ ParseError,
+ InvalidScreen
+}
+
+impl From<i32> for Error {
+ fn from(x: i32) -> Error {
+ use self::Error::*;
+ match x {
+ 2 => UnsupportedExtension,
+ 3 => InsufficientMemory,
+ 4 => RequestTooLong,
+ 5 => ParseError,
+ 6 => InvalidScreen,
+ _ => Generic
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index b7dbc03b8..781e6926c 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1,10 +1,11 @@
use std::path::{Path, PathBuf};
use std::collections::HashSet;
-use std::io::{self, BufReader, BufRead, ErrorKind};
+use std::io::{self, BufReader, BufRead, ErrorKind, ErrorKind::WouldBlock};
use std::fs::File;
-use std::sync::Arc;
+use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
+use std::ops::{Deref, DerefMut};
use std::process::Stdio;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::{Instant};
use tokio::sync:: {Mutex};
use tokio::task::JoinHandle;
use tokio::time::{Duration};
@@ -13,14 +14,18 @@ use serde::{Serialize, Deserialize};
use tauri::State;
use tokio::process::{Command, ChildStderr, ChildStdin};
use tokio::join;
+use futures::future::join_all;
use crate::utils::{ffmpeg_path_as_str, monitor_and_log_recording_start};
use crate::upload::upload_file;
+
use crate::audio::AudioRecorder;
+const FRAME_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1000 / 30);
+
pub struct RecordingState {
pub screen_process: Option<tokio::process::Child>,
- pub screen_process_stdin: Option<tokio::process::ChildStdin>,
+ pub screen_process_stdin: Option<Arc<Mutex<ChildStdin>>>,
pub video_process: Option<tokio::process::Child>,
pub audio_process: Option<AudioRecorder>,
pub upload_handles: Mutex<Vec<JoinHandle<Result<(), String>>>>,
@@ -59,17 +64,21 @@ pub async fn start_dual_recording(
let shutdown_flag = Arc::new(AtomicBool::new(false));
- let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;
+ // let (tx, mut rx) = tokio::sync::mpsc::channel::<Vec<u8>>(32);
+ // let display = Display::primary().map_err(|_| "Failed to find primary display".to_string())?;
+ // let (w, h) = (display.width(), display.height());
+ // let adjusted_height = h & !1;
+ // let capture_size = w * adjusted_height * 4;
let data_dir = state_guard.data_dir.as_ref()
.ok_or("Data directory is not set in the recording state".to_string())?.clone();
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)?;
+ let video_chunks_dir = data_dir.join("chunks/video");
clean_and_create_dir(&audio_chunks_dir)?;
+ clean_and_create_dir(&video_chunks_dir)?;
let audio_name = if options.audio_name.is_empty() {
None
@@ -77,8 +86,8 @@ pub async fn start_dual_recording(
Some(options.audio_name.clone())
};
- let ffmpeg_screen_args_future = construct_recording_args(&options, &screen_chunks_dir, "screen", &options.screen_index);
- let ffmpeg_screen_args = ffmpeg_screen_args_future.await.map_err(|e| e.to_string())?;
+ // let ffmpeg_screen_args_future = construct_recording_args(&options, &screen_chunks_dir, "screen", &options.screen_index, w, adjusted_height);
+ // let ffmpeg_screen_args = ffmpeg_screen_args_future.await.map_err(|e| e.to_string())?;
let screenshot_output_path = data_dir.join("screen-capture.jpg").to_str().unwrap().to_string();
let ffmpeg_screen_screenshot_args = match std::env::consts::OS {
@@ -115,22 +124,30 @@ pub async fn start_dual_recording(
_ => return Err("Unsupported OS".to_string()),
};
- println!("Screen args: {:?}", ffmpeg_screen_args);
+ // println!("Screen args: {:?}", ffmpeg_screen_args);
// Prepare screen and audio recording concurrently
let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;
- let screen_recording_preparation = prepare_screen_recording(&ffmpeg_binary_path_str, &options, &screen_chunks_dir);
- let audio_recording_preparation = prepare_audio_recording(&options, &audio_chunks_dir);
+ // let screen_recording_preparation = prepare_screen_recording(&ffmpeg_binary_path_str, &options, &screen_chunks_dir, w, adjusted_height);
+ let audio_recording_preparation = prepare_audio_recording(&options, &audio_chunks_dir, &video_chunks_dir, audio_name);
- // Start both recordings concurrently
- let (screen_recording_result, audio_recording_result) = join!(
- screen_recording_preparation,
- audio_recording_preparation
- );
+ let audio_recording_result = audio_recording_preparation.await.map_err(|e| e.to_string())?;
// Handle the results of both operations
- let (screen_child, screen_stdin) = screen_recording_result.map_err(|e| e.to_string())?;
- let audio_process = audio_recording_result.map_err(|e| e.to_string())?;
+ // let (screen_child, screen_stdin) = screen_recording_result.map_err(|e| e.to_string())?;
+
+ // let screen_stdin_arc = Arc::new(Mutex::new(screen_stdin));
+ // let stdin_clone = Arc::clone(&screen_stdin_arc);
+
+ // tokio::spawn(async move {
+ // while let Some(frame_data) = rx.recv().await {
+ // let mut stdin_locked = stdin_clone.lock().await;
+ // if let Err(e) = stdin_locked.write_all(&frame_data).await {
+ // eprintln!("Failed to write frame data to FFmpeg's stdin: {}", e);
+ // break;
+ // }
+ // }
+ // });
let options_clone = state_guard.recording_options.clone();
@@ -146,18 +163,62 @@ pub async fn start_dual_recording(
}
});
- state_guard.screen_process = Some(screen_child);
- println!("Set screen child");
- state_guard.screen_process_stdin = Some(screen_stdin);
- println!("Set screen stdin");
- state_guard.audio_process = Some(audio_process);
+ // state_guard.screen_process = Some(screen_child);
+ // println!("Set screen child");
+ // state_guard.screen_process_stdin = Some(screen_stdin_arc);
+ // println!("Set screen stdin");
+ state_guard.audio_process = Some(audio_recording_result);
state_guard.upload_handles = Mutex::new(vec![]);
state_guard.recording_options = Some(options.clone());
state_guard.shutdown_flag = shutdown_flag.clone();
state_guard.video_uploading_finished = Arc::new(AtomicBool::new(false));
state_guard.audio_uploading_finished = Arc::new(AtomicBool::new(false));
- let screen_upload = start_upload_loop(screen_chunks_dir, options.clone(), "screen".to_string(), shutdown_flag.clone(), state_guard.video_uploading_finished.clone());
+ // let _capturer_thread = {
+ // println!("Starting video capture thread...");
+ // let shutdown_flag = shutdown_flag.clone();
+ // tokio::spawn(async move {
+ // println!("Starting video capture...");
+
+ // let mut safe_capturer = SafeCapturer(Capturer::new(display).expect("Failed to start capture"));
+ // let mut next_frame_time = Instant::now();
+ // while !shutdown_flag.load(Ordering::SeqCst) {
+ // let now = Instant::now();
+ // if now < next_frame_time {
+ // std::thread::sleep(next_frame_time - now);
+ // }
+ // next_frame_time = Instant::now() + FRAME_INTERVAL;
+
+ // let frame_data = match safe_capturer.frame() {
+ // Ok(frame) => {
+ // let stride = frame[..capture_size].len() / adjusted_height;
+ // let mut frame_data = Vec::with_capacity(capture_size);
+ // for row in 0..adjusted_height {
+ // let start = row * stride;
+ // let end = start + stride;
+ // frame_data.extend_from_slice(&frame[start..end]);
+ // }
+ // Some(frame_data)
+ // },
+ // Err(error) if error.kind() == WouldBlock => {
+ // continue;
+ // },
+ // Err(error) => return Err(format!("Capture error: {}", error)),
+ // };
+
+ // if let Some(frame_data) = frame_data {
+ // if let Err(e) = tx.send(frame_data).await {
+ // eprintln!("Failed to send frame data through channel: {}", e);
+ // break;
+ // }
+ // }
+ // }
+
+ // Ok(())
+ // })
+ // };
+
+ let screen_upload = start_upload_loop(video_chunks_dir.clone(), options.clone(), "video".to_string(), shutdown_flag.clone(), state_guard.video_uploading_finished.clone());
let audio_upload = start_upload_loop(audio_chunks_dir, options.clone(), "audio".to_string(), shutdown_flag.clone(), state_guard.audio_uploading_finished.clone());
drop(state_guard);
@@ -184,21 +245,22 @@ pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -
let mut guard = state.lock().await;
println!("Stopping screen recording...");
+
+ guard.shutdown_flag.store(true, Ordering::SeqCst);
- if let Some(stdin) = guard.screen_process_stdin.take() {
- println!("Sending quit command to FFmpeg...");
- if let Err(e) = graceful_stop_ffmpeg(stdin).await {
- eprintln!("Failed to send quit command to FFmpeg: {}", e);
- }
- }
+ // if let Some(stdin) = guard.screen_process_stdin.take() {
+ // println!("Sending quit command to FFmpeg...");
+ // let mut stdin_locked = stdin.lock().await;
+ // if let Err(e) = graceful_stop_ffmpeg(&mut stdin_locked).await {
+ // eprintln!("Failed to send quit command to FFmpeg: {}", e);
+ // }
+ // }
if let Some(mut audio_process) = guard.audio_process.take() {
println!("Stopping audio recording...");
audio_process.stop_audio_recording().await.expect("Failed to stop audio recording");
}
- guard.shutdown_flag.store(true, Ordering::SeqCst);
-
while !guard.video_uploading_finished.load(Ordering::SeqCst)
|| !guard.audio_uploading_finished.load(Ordering::SeqCst) {
println!("Waiting for uploads to finish...");
@@ -228,103 +290,95 @@ fn clean_and_create_dir(dir: &Path) -> Result<(), String> {
}
}
-async fn construct_recording_args(
- options: &RecordingOptions,
- chunks_dir: &Path,
- video_type: &str,
- input_index: &str,
-) -> Result<Vec<String>, String> {
- let output_filename_pattern = format!("{}/recording_chunk_%03d.ts", chunks_dir.display());
- let segment_list_filename = format!("{}/segment_list.txt", chunks_dir.display());
+// async fn construct_recording_args(
+// options: &RecordingOptions,
+// chunks_dir: &Path,
+// video_type: &str,
+// input_index: &str,
+// w: usize,
+// adjusted_height: usize,
+// ) -> Result<Vec<String>, String> {
+// let output_filename_pattern = format!("{}/recording_chunk_%03d.ts", chunks_dir.display());
+// let segment_list_filename = format!("{}/segment_list.txt", chunks_dir.display());
- ensure_segment_list_exists(PathBuf::from(&segment_list_filename))
- .map_err(|e| format!("Failed to ensure segment list file exists: {}", e))?;
+// ensure_segment_list_exists(PathBuf::from(&segment_list_filename))
+// .map_err(|e| format!("Failed to ensure segment list file exists: {}", e))?;
- let fps = if video_type == "screen" { "30" } else { &options.framerate };
- let preset = "ultrafast".to_string();
- let crf = "28".to_string();
- let pix_fmt = "yuv420p".to_string();
- let codec = "libx264".to_string();
- let gop = "30".to_string();
- let segment_time = "3".to_string();
- let segment_list_type = "flat".to_string();
-
- match std::env::consts::OS {
- "macos" => {
- Ok(vec![
- "-f".to_string(), "avfoundation".to_string(),
- "-framerate".to_string(), "240".to_string(),
- "-capture_cursor".to_string(), "1".to_string(),
- "-thread_queue_size".to_string(), "512".to_string(),
- "-i".to_string(), format!("{}", input_index),
- "-probesize".to_string(), "32".to_string(),
- "-analyzeduration".to_string(), "0".to_string(),
- "-c:v".to_string(), codec,
- "-preset".to_string(), preset,
- "-tune".to_string(), "zerolatency".to_string(),
- "-pix_fmt".to_string(), pix_fmt,
- "-g".to_string(), gop,
- "-r".to_string(), "60".to_string(),
- "-an".to_string(),
- "-f".to_string(), "segment".to_string(),
- "-segment_time".to_string(), segment_time,
- "-segment_format".to_string(), "mpegts".to_string(),
- "-segment_list".to_string(), segment_list_filename,
- "-segment_list_type".to_string(), segment_list_type,
- "-reset_timestamps".to_string(), "1".to_string(),
- "-use_wallclock_as_timestamps".to_string(), "1".to_string(),
- "-fflags".to_string(), "nobuffer".to_string(),
- "-flags".to_string(), "low_delay".to_string(),
- "-strict".to_string(), "experimental".to_string(),
- output_filename_pattern,
- ])
- },
- "linux" => {
- Ok(vec![
- "-f".to_string(), "x11grab".to_string(),
- "-i".to_string(), format!("{}+0,0", input_index),
- "-draw_mouse".to_string(), "1".to_string(),
- "-pix_fmt".to_string(), pix_fmt,
- "-c:v".to_string(), codec,
- "-crf".to_string(), crf,
- "-preset".to_string(), preset,
- "-g".to_string(), gop,
- "-r".to_string(), fps.to_string(),
- "-an".to_string(),
- "-f".to_string(), "segment".to_string(),
- "-segment_time".to_string(), segment_time,
- "-segment_format".to_string(), "mpegts".to_string(),
- "-segment_list".to_string(), segment_list_filename,
- "-segment_list_type".to_string(), segment_list_type,
- "-reset_timestamps".to_string(), "1".to_string(),
- output_filename_pattern,
- ])
- },
- "windows" => {
- Ok(vec![
- "-f".to_string(), "gdigrab".to_string(),
- "-i".to_string(), "desktop".to_string(),
- "-pixel_format".to_string(), pix_fmt,
- "-c:v".to_string(), codec,
- "-crf".to_string(), crf,
- "-preset".to_string(), preset,
- "-g".to_string(), gop,
- "-r".to_string(), fps.to_string(),
- "-an".to_string(), // This is the argument to skip audio recording.
- "-f".to_string(), "segment".to_string(),
- "-segment_time".to_string(), segment_time,
- "-segment_format".to_string(), "mpegts".to_string(),
- "-segment_list".to_string(), segment_list_filename,
- "-segment_list_type".to_string(), segment_list_type,
- "-reset_timestamps".to_string(), "1".to_string(),
- output_filename_pattern,
- ])
- },
- _ => Err("Unsupported OS".to_string()),
- }
-}
-
-use futures::future::join_all;
+// let fps = if video_type == "screen" { "30" } else { &options.framerate };
+// let preset = "veryfast".to_string();
+// let crf = "28".to_string();
+// let pix_fmt = "yuv420p".to_string();
+// let codec = "libx264".to_string();
+// let segment_time = "3".to_string();
+// let segment_list_type = "flat".to_string();
+
+// match std::env::consts::OS {
+// "macos" => {
+// Ok(vec![
+// "-f".to_string(), "rawvideo".to_string(),
+// "-pix_fmt".to_string(), "bgra".to_string(),
+// "-s".to_string(), format!("{}x{}", w, adjusted_height),
+// "-r".to_string(), "30".to_string(),
+// "-thread_queue_size".to_string(), "8192".to_string(),
+// "-i".to_string(), "pipe:0".to_string(),
+// "-c:v".to_string(), "libx264".to_string(),
+// "-preset".to_string(), preset,
+// "-pix_fmt".to_string(), pix_fmt,
+// "-vsync".to_string(), "1".to_string(),
+// "-r".to_string(), "30".to_string(),
+// "-an".to_string(),
+// "-f".to_string(), "segment".to_string(),
+// "-segment_time".to_string(), segment_time,
+// "-segment_format".to_string(), "mpegts".to_string(),
+// "-segment_list".to_string(), segment_list_filename,
+// "-segment_list_type".to_string(), segment_list_type,
+// "-reset_timestamps".to_string(), "1".to_string(),
+// "-use_wallclock_as_timestamps".to_string(), "1".to_string(),
+// output_filename_pattern,
+// ])
+// },
+// "linux" => {
+// Ok(vec![
+// "-f".to_string(), "x11grab".to_string(),
+// "-i".to_string(), format!("{}+0,0", input_index),
+// "-draw_mouse".to_string(), "1".to_string(),
+// "-pix_fmt".to_string(), pix_fmt,
+// "-c:v".to_string(), codec,
+// "-crf".to_string(), crf,
+// "-preset".to_string(), preset,
+// "-r".to_string(), fps.to_string(),
+// "-an".to_string(),
+// "-f".to_string(), "segment".to_string(),
+// "-segment_time".to_string(), segment_time,
+// "-segment_format".to_string(), "mpegts".to_string(),
+// "-segment_list".to_string(), segment_list_filename,
+// "-segment_list_type".to_string(), segment_list_type,
+// "-reset_timestamps".to_string(), "1".to_string(),
+// output_filename_pattern,
+// ])
+// },
+// "windows" => {
+// Ok(vec![
+// "-f".to_string(), "gdigrab".to_string(),
+// "-i".to_string(), "desktop".to_string(),
+// "-pixel_format".to_string(), pix_fmt,
+// "-c:v".to_string(), codec,
+// "-crf".to_string(), crf,
+// "-preset".to_string(), preset,
+// "-r".to_string(), fps.to_string(),
+// "-an".to_string(), // This is the argument to skip audio recording.
+// "-f".to_string(), "segment".to_string(),
+// "-segment_time".to_string(), segment_time,
+// "-segment_format".to_string(), "mpegts".to_string(),
+// "-segment_list".to_string(), segment_list_filename,
+// "-segment_list_type".to_string(), segment_list_type,
+// "-reset_timestamps".to_string(), "1".to_string(),
+// output_filename_pattern,
+// ])
+// },
+// _ => Err("Unsupported OS".to_string()),
+// }
+// }
async fn start_upload_loop(
chunks_dir: PathBuf,
@@ -459,51 +513,56 @@ async fn upload_jpeg_files(
Ok(())
}
-async fn prepare_screen_recording(
- ffmpeg_binary_path_str: &str,
- options: &RecordingOptions,
- screen_chunks_dir: &Path,
-) -> Result<(tokio::process::Child, ChildStdin), String> {
- let ffmpeg_screen_args = construct_recording_args(options, screen_chunks_dir, "screen", &options.screen_index).await.map_err(|e| e.to_string())?;
- let (screen_child, mut screen_stderr, screen_stdin) = start_screen_recording_process(ffmpeg_binary_path_str, &ffmpeg_screen_args).await.map_err(|e| e.to_string())?;
+// async fn prepare_screen_recording(
+// ffmpeg_binary_path_str: &str,
+// options: &RecordingOptions,
+// screen_chunks_dir: &Path,
+// w: usize,
+// adjusted_height: usize,
+// ) -> Result<(tokio::process::Child, ChildStdin), String> {
+// let ffmpeg_screen_args = construct_recording_args(options, screen_chunks_dir, "screen", &options.screen_index, w, adjusted_height).await.map_err(|e| e.to_string())?;
+// let (screen_child, screen_stderr, screen_stdin) = start_screen_recording_process(ffmpeg_binary_path_str, &ffmpeg_screen_args).await.map_err(|e| e.to_string())?;
- let video_id = options.video_id.clone();
- tokio::spawn(async move {
- if let Err(e) = monitor_and_log_recording_start(screen_stderr, &video_id, "video").await {
- eprintln!("Error monitoring screen recording start: {}", e);
- }
- });
+// let video_id = options.video_id.clone();
+// tokio::spawn(async move {
+// if let Err(e) = monitor_and_log_recording_start(screen_stderr, &video_id, "video").await {
+// eprintln!("Error monitoring screen recording start: {}", e);
+// }
+// });
- Ok((screen_child, screen_stdin))
-}
+// Ok((screen_child, screen_stdin))
+// }
async fn prepare_audio_recording(
options: &RecordingOptions,
audio_chunks_dir: &Path,
+ video_chunks_dir: &Path,
+ audio_name: Option<String>,
) -> Result<AudioRecorder, String> {
// Assuming `AudioRecorder::start_audio_recording` is an async function.
// Prepare your AudioRecorder and start recording
let mut audio_recorder = AudioRecorder::new();
- let audio_file_path = audio_chunks_dir.to_str().unwrap(); // Handle errors as needed
- audio_recorder.start_audio_recording(options.clone(), audio_file_path, None).await?;
+ let audio_file_path = audio_chunks_dir.to_str().unwrap();
+ let video_file_path = video_chunks_dir.to_str().unwrap();
+ audio_recorder.start_audio_recording(options.clone(), audio_file_path, video_file_path, audio_name.as_ref().map(String::as_str)).await?;
Ok(audio_recorder)
}
-async fn start_screen_recording_process(ffmpeg_binary_path_str: &str, ffmpeg_screen_args: &[String]) -> Result<(tokio::process::Child, ChildStderr, ChildStdin), io::Error> {
- let mut child = Command::new(ffmpeg_binary_path_str)
- .args(ffmpeg_screen_args)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()?;
+// async fn start_screen_recording_process(ffmpeg_binary_path_str: &str, ffmpeg_screen_args: &[String]) -> Result<(tokio::process::Child, ChildStderr, ChildStdin), io::Error> {
+// let mut child = Command::new(ffmpeg_binary_path_str)
+// .args(ffmpeg_screen_args)
+// .stdin(Stdio::piped())
+// .stdout(Stdio::piped())
+// .stderr(Stdio::piped())
+// .spawn()?;
- let stderr = child.stderr.take().expect("failed to take child stdout");
- let stdin = child.stdin.take().expect("failed to take child stdin");
+// let stderr = child.stderr.take().expect("failed to take child stdout");
+// let stdin = child.stdin.take().expect("failed to take child stdin");
- Ok((child, stderr, stdin))
-}
+// Ok((child, stderr, stdin))
+// }
-async fn graceful_stop_ffmpeg(mut stdin: tokio::process::ChildStdin) -> Result<(), std::io::Error> {
- stdin.write_all(b"q\n").await?;
- Ok(())
-}
\ No newline at end of file
+// async fn graceful_stop_ffmpeg(stdin: &mut tokio::process::ChildStdin) -> Result<(), std::io::Error> {
+// stdin.write_all(b"q\n").await?;
+// Ok(())
+// }
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/utils.rs b/apps/desktop/src-tauri/src/utils.rs
index f33cb3031..348b95131 100644
--- a/apps/desktop/src-tauri/src/utils.rs
+++ b/apps/desktop/src-tauri/src/utils.rs
@@ -37,23 +37,28 @@ pub async fn send_metadata_api(video_id: &str, start_timestamp: f64, log_type: &
pub async fn monitor_and_log_recording_start(stderr: ChildStderr, video_id: &str, log_type: &str) -> Result<(), std::io::Error> {
use tokio::io::{BufReader, AsyncBufReadExt};
- use chrono::Utc;
-
+ use regex::Regex;
+
let reader = BufReader::new(stderr);
let mut lines = reader.lines();
+ let start_regex = Regex::new(r"Duration: N/A, start: (\d+\.\d+)").unwrap();
while let Some(line) = lines.next_line().await? {
- if line.contains("001") && line.contains("for writing") {
- let timestamp = Utc::now().timestamp_millis() as f64;
- println!("{} recording started at timestamp: {}", log_type, timestamp);
- if send_metadata_api(video_id, timestamp, log_type).await.is_err() {
- eprintln!("Failed to send metadata to API.");
- }
- return Ok(());
- }
+ //log stderr with log_type
+ println!("{} stderok: {}", log_type, line);
+ // if let Some(caps) = start_regex.captures(&line) {
+ // if let Some(start_match) = caps.get(1) {
+ // let start_time = start_match.as_str().parse::<f64>().unwrap();
+ // println!("{} recording started at timestamp: {}", log_type, start_time);
+ // if send_metadata_api(video_id, start_time, log_type).await.is_err() {
+ // eprintln!("Failed to send metadata to API.");
+ // }
+ // return Ok(());
+ // }
+ // }
}
- Err(IoError::new(std::io::ErrorKind::Other, "Screen recording did not start successfully or start timestamp was not found."))
+ Err(std::io::Error::new(std::io::ErrorKind::Other, "Screen recording did not start successfully or start timestamp was not found."))
}
pub fn run_command(command: &str, args: Vec<&str>) -> Result<(String, String), String> {
diff --git a/apps/web/app/api/desktop/video/metadata/create/route.ts b/apps/web/app/api/desktop/video/metadata/create/route.ts
index e97beb126..c71ce2d6a 100644
--- a/apps/web/app/api/desktop/video/metadata/create/route.ts
+++ b/apps/web/app/api/desktop/video/metadata/create/route.ts
@@ -12,7 +12,12 @@ export async function GET(request: NextRequest) {
const startTime = url.searchParams.get("startTime");
const logType = url.searchParams.get("logType");
- if (!videoId || (!startTime && !logType)) {
+ console.log("...Updating video or audio start time...");
+ console.log("videoId", videoId);
+ console.log("startTime", startTime);
+ console.log("logType", logType);
+
+ if (!videoId || !startTime || !logType) {
return new Response(
JSON.stringify({ error: "Missing required fields" }),
{
@@ -28,7 +33,7 @@ export async function GET(request: NextRequest) {
console.log("...Updating video start time...");
await db
.update(videos)
- .set({ videoStartTime: Number(startTime) })
+ .set({ videoStartTime: startTime.toString() })
.where(eq(videos.id, videoId));
}
@@ -36,7 +41,7 @@ export async function GET(request: NextRequest) {
console.log("...Updating audio start time...");
await db
.update(videos)
- .set({ audioStartTime: Number(startTime) })
+ .set({ audioStartTime: startTime.toString() })
.where(eq(videos.id, videoId));
}
diff --git a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
index a1bfb69c2..d1e82c434 100644
--- a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
@@ -217,9 +217,7 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
>
<VideoPlayer
ref={video2Ref}
- videoStartTime={data.videoStartTime}
- audioStartTime={data.audioStartTime}
- videoSrc={`${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=video`}
audioSrc={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=audio`}
/>
</div>
diff --git a/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx b/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
index 95f3daf65..95948ea4b 100644
--- a/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
+++ b/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
@@ -10,13 +10,11 @@ import Hls from "hls.js";
interface VideoPlayerProps {
videoSrc: string;
audioSrc?: string;
- videoStartTime: number | null;
- audioStartTime: number | null;
}
export const VideoPlayer = memo(
forwardRef<HTMLVideoElement, VideoPlayerProps>(
- ({ videoSrc, audioSrc, videoStartTime, audioStartTime }, ref) => {
+ ({ videoSrc, audioSrc }, ref) => {
const videoRef = useRef<HTMLVideoElement>(null);
const audioRef = useRef<HTMLAudioElement>(null);
const videoHlsInstance = useRef<Hls | null>(null);
@@ -57,30 +55,6 @@ export const VideoPlayer = memo(
};
}, [audioSrc]);
- useEffect(() => {
- if (
- !videoRef.current ||
- !audioSrc ||
- !audioRef.current ||
- videoStartTime === null ||
- audioStartTime === null
- )
- return;
-
- const timeDifferenceInSeconds =
- (audioStartTime - videoStartTime) / 1000;
-
- console.log("timeDifferenceInSeconds", timeDifferenceInSeconds);
-
- if (timeDifferenceInSeconds > 0) {
- videoRef.current.currentTime = timeDifferenceInSeconds;
- audioRef.current.currentTime = 0;
- } else {
- audioRef.current.currentTime = -timeDifferenceInSeconds;
- videoRef.current.currentTime = 0;
- }
- }, [videoStartTime, audioStartTime, audioSrc]);
-
useEffect(() => {
if (!audioSrc || !videoRef.current || !audioRef.current) return;
const video = videoRef.current;
@@ -98,24 +72,14 @@ export const VideoPlayer = memo(
}
};
- const seekListener = () => {
- if (audioStartTime !== null && videoStartTime !== null) {
- const startOffsetSeconds = (audioStartTime - videoStartTime) / 1000;
- console.log("startOffsetSeconds", startOffsetSeconds);
- audio.currentTime = video.currentTime + startOffsetSeconds;
- }
- };
-
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, videoStartTime, audioStartTime]);
+ }, [audioSrc]);
return (
<>
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 963b21a35..fe934789a 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -11,6 +11,7 @@ import {
uniqueIndex,
varchar,
bigint,
+ decimal,
} from "drizzle-orm/mysql-core";
import { relations } from "drizzle-orm/relations";
import { nanoIdLength } from "./helpers";
@@ -143,8 +144,8 @@ export const videos = mysqlTable(
awsBucket: varchar("awsBucket", { length: 255 }),
metadata: json("metadata"),
public: boolean("public").notNull().default(true),
- videoStartTime: bigint("videoStartTime", { mode: "number" }),
- audioStartTime: bigint("audioStartTime", { mode: "number" }),
+ videoStartTime: varchar("videoStartTime", { length: 255 }),
+ audioStartTime: varchar("audioStartTime", { length: 255 }),
createdAt: timestamp("createdAt").notNull().defaultNow(),
updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),
},