Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

screen & camera recording

Brendan Allan91f8006a2db4
diff --git a/Cargo.lock b/Cargo.lock
index d3f0b84c1..bb0cb02a1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -776,7 +776,7 @@ dependencies = [
"bitflags 1.2.1",
"block",
"core-foundation 0.9.4",
- "core-graphics-types",
+ "core-graphics-types 0.1.3",
"libc",
"objc",
]
@@ -852,7 +852,17 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
- "core-foundation-sys 0.8.6",
+ "core-foundation-sys 0.8.7",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63"
+dependencies = [
+ "core-foundation-sys 0.8.7",
"libc",
]
@@ -864,9 +874,9 @@ checksum = "b3a71ab494c0b5b860bdc8407ae08978052417070c2ced38573a9157ad75b8ac"
[[package]]
name = "core-foundation-sys"
-version = "0.8.6"
+version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "core-graphics"
@@ -888,7 +898,20 @@ checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
dependencies = [
"bitflags 1.2.1",
"core-foundation 0.9.4",
- "core-graphics-types",
+ "core-graphics-types 0.1.3",
+ "foreign-types 0.5.0",
+ "libc",
+]
+
+[[package]]
+name = "core-graphics"
+version = "0.24.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1"
+dependencies = [
+ "bitflags 2.6.0",
+ "core-foundation 0.10.0",
+ "core-graphics-types 0.2.0",
"foreign-types 0.5.0",
"libc",
]
@@ -901,7 +924,7 @@ checksum = "32eb7c354ae9f6d437a6039099ce7ecd049337a8109b23d73e48e8ffba8e9cd5"
dependencies = [
"bitflags 2.6.0",
"core-foundation 0.9.4",
- "core-graphics-types",
+ "core-graphics-types 0.1.3",
"foreign-types 0.5.0",
"libc",
]
@@ -917,6 +940,17 @@ dependencies = [
"libc",
]
+[[package]]
+name = "core-graphics-types"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
+dependencies = [
+ "bitflags 2.6.0",
+ "core-foundation 0.10.0",
+ "libc",
+]
+
[[package]]
name = "core-media-sys"
version = "0.1.2"
@@ -949,7 +983,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "321077172d79c662f64f5071a03120748d5bb652f5231570141be24cfcd2bace"
dependencies = [
"bitflags 1.2.1",
- "core-foundation-sys 0.8.6",
+ "core-foundation-sys 0.8.7",
"coreaudio-sys",
]
@@ -969,7 +1003,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "873dab07c8f743075e57f524c583985fbaf745602acbe916a01539364369a779"
dependencies = [
"alsa",
- "core-foundation-sys 0.8.6",
+ "core-foundation-sys 0.8.7",
"coreaudio-rs",
"dasp_sample",
"jni",
@@ -1185,9 +1219,13 @@ dependencies = [
name = "desktop-solid"
version = "0.1.0"
dependencies = [
+ "core-foundation 0.10.0",
+ "core-graphics 0.24.0",
"nix 0.29.0",
"nokhwa",
"nokhwa-bindings-macos",
+ "objc2-app-kit",
+ "scap",
"serde",
"serde_json",
"specta",
@@ -2282,7 +2320,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141"
dependencies = [
"android_system_properties",
- "core-foundation-sys 0.8.6",
+ "core-foundation-sys 0.8.7",
"iana-time-zone-haiku",
"js-sys",
"wasm-bindgen",
@@ -3056,6 +3094,7 @@ dependencies = [
"nokhwa-bindings-macos",
"nokhwa-core",
"paste",
+ "serde",
"thiserror",
]
@@ -3082,6 +3121,7 @@ dependencies = [
"bytes",
"image",
"mozjpeg",
+ "serde",
"thiserror",
]
@@ -4403,7 +4443,7 @@ checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
dependencies = [
"bitflags 2.6.0",
"core-foundation 0.9.4",
- "core-foundation-sys 0.8.6",
+ "core-foundation-sys 0.8.7",
"libc",
"security-framework-sys",
]
@@ -4414,7 +4454,7 @@ version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75da29fe9b9b08fe9d6b22b5b4bcbc75d8db3aa31e639aa56bb62e9d46bfceaf"
dependencies = [
- "core-foundation-sys 0.8.6",
+ "core-foundation-sys 0.8.7",
"libc",
]
@@ -5085,7 +5125,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a5b4ddaee55fb2bea2bf0e5000747e5f5c0de765e5a5ff87f4cd106439f4bb3"
dependencies = [
"cfg-if 1.0.0",
- "core-foundation-sys 0.8.6",
+ "core-foundation-sys 0.8.7",
"libc",
"ntapi",
"once_cell",
@@ -5110,7 +5150,7 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9"
dependencies = [
- "core-foundation-sys 0.8.6",
+ "core-foundation-sys 0.8.7",
"libc",
]
@@ -5173,7 +5213,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "271450eb289cb4d8d0720c6ce70c72c8c858c93dd61fc625881616752e6b98f6"
dependencies = [
"cfg-if 1.0.0",
- "core-foundation-sys 0.8.6",
+ "core-foundation-sys 0.8.7",
"libc",
"objc",
]
diff --git a/apps/desktop-solid/package.json b/apps/desktop-solid/package.json
index 8fed93119..8e337fb39 100644
--- a/apps/desktop-solid/package.json
+++ b/apps/desktop-solid/package.json
@@ -11,10 +11,13 @@
"@cap/utils": "workspace:*",
"@solid-primitives/context": "^0.2.3",
"@solid-primitives/storage": "^4.0.0",
+ "@solid-primitives/timer": "^1.3.9",
"@solidjs/router": "^0.14.2",
"@solidjs/start": "^1.0.6",
+ "@tanstack/solid-query": "^5.51.21",
"@tauri-apps/api": ">=2.0.0-rc.0",
"@tauri-apps/plugin-shell": ">=2.0.0-rc.0",
+ "cva": "npm:class-variance-authority@^0.7.0",
"solid-js": "^1.7.8",
"vinxi": "^0.4.1"
},
diff --git a/apps/desktop-solid/src-tauri/Cargo.toml b/apps/desktop-solid/src-tauri/Cargo.toml
index 0e3106a99..d414cb3de 100644
--- a/apps/desktop-solid/src-tauri/Cargo.toml
+++ b/apps/desktop-solid/src-tauri/Cargo.toml
@@ -27,9 +27,13 @@ tauri-plugin-decorum = "1.0.0"
swift-rs = "1.0.6"
nokhwa = { git = "https://github.com/Brendonovich/nokhwa", rev = "2de5a760d5f1", features = [
"input-avfoundation",
+ "serialize",
] }
nokhwa-bindings-macos = { git = "https://github.com/Brendonovich/nokhwa", rev = "2de5a760d5f1" }
-
nix = { version = "0.29.0", features = ["fs"] }
tokio = { version = "1.39.2", features = ["macros"] }
uuid = { version = "1.10.0", features = ["v4"] }
+scap = { git = "https://github.com/CapSoftware/scap" }
+objc2-app-kit = { version = "0.2.2", features = ["NSWindow", "NSResponder"] }
+core-graphics = "0.24.0"
+core-foundation = "0.10.0"
diff --git a/apps/desktop-solid/src-tauri/src/camera.rs b/apps/desktop-solid/src-tauri/src/camera.rs
index 860f6889f..ff3658b31 100644
--- a/apps/desktop-solid/src-tauri/src/camera.rs
+++ b/apps/desktop-solid/src-tauri/src/camera.rs
@@ -1,18 +1,20 @@
-use nokhwa::utils::{CameraInfo, Resolution};
+use nokhwa::utils::{CameraFormat, FrameFormat, Resolution};
+use serde::Serialize;
+use specta::Type;
use std::{
io::Write,
path::{Path, PathBuf},
- process::{ChildStdin, Command, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
- time::Duration,
};
-use tokio::{sync::oneshot, time::sleep};
+use tokio::sync::oneshot;
use tauri::{AppHandle, Manager, WebviewUrl};
+use crate::ffmpeg::{FFmpegRawVideoSource, NamedPipeCapture};
+
pub const CAMERA_WINDOW: &str = "camera";
const CAMERA_ROUTE: &str = "/camera";
const WINDOW_SIZE: f64 = 230.0;
@@ -54,65 +56,80 @@ pub fn create_camera_window(app: AppHandle) {
}
}
-#[cfg(unix)]
-pub fn create_named_pipe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
- use nix::sys::stat;
- use nix::unistd;
- unistd::mkfifo(path, stat::Mode::S_IRWXU)?;
- Ok(())
+#[tauri::command]
+#[specta::specta]
+pub fn get_cameras() -> Vec<CameraInfo> {
+ nokhwa::query(nokhwa::utils::ApiBackend::Auto)
+ .unwrap()
+ .into_iter()
+ .map(|i| CameraInfo {
+ human_name: i.human_name().to_string(),
+ description: i.description().to_string(),
+ misc: i.misc().to_string(),
+ index: match i.index() {
+ nokhwa::utils::CameraIndex::Index(i) => CameraIndex::Index(*i),
+ nokhwa::utils::CameraIndex::String(s) => CameraIndex::String(s.to_string()),
+ },
+ })
+ .collect()
+}
+
+#[derive(Serialize, Type)]
+pub struct CameraInfo {
+ pub human_name: String,
+ pub description: String,
+ pub misc: String,
+ pub index: CameraIndex,
}
-pub struct FfmpegRecording {
- folder_path: PathBuf,
- ffmpeg_stdin: ChildStdin,
- capture: NamedPipeCapture,
+#[derive(Serialize, Type)]
+pub enum CameraIndex {
+ Index(u32),
+ String(String),
}
-impl FfmpegRecording {
- pub fn stop(mut self) {
- self.ffmpeg_stdin.write_all(b"q").ok();
- self.capture.stop();
+impl From<CameraIndex> for nokhwa::utils::CameraIndex {
+ fn from(value: CameraIndex) -> Self {
+ match value {
+ CameraIndex::Index(i) => nokhwa::utils::CameraIndex::Index(i),
+ CameraIndex::String(s) => nokhwa::utils::CameraIndex::String(s),
+ }
}
}
-pub async fn start_recording(folder_path: &Path, camera_info: CameraInfo) -> FfmpegRecording {
- std::fs::create_dir_all(folder_path).ok();
- let pipe_path = folder_path.join("output.pipe");
- std::fs::remove_file(&pipe_path).ok();
+pub async fn start_recording(
+ output_folder: &Path,
+ output_name: &str,
+ camera_info: CameraInfo,
+) -> FFmpegRawVideoSource {
+ std::fs::create_dir_all(output_folder).ok();
+
+ let pipe_path = output_folder.join(format!("{output_name}.pipe"));
- let output_path = folder_path.join("output.mp4");
+ let output_path = output_folder.join(format!("{output_name}.mp4"));
std::fs::remove_file(&output_path).ok();
- println!("Beginning camera capture");
-
- let ((resolution, frame_rate), capture) = start_capturing(pipe_path.clone(), camera_info).await;
-
- println!("Received video info: {:?}", (resolution, frame_rate));
-
- let size = format!("{}x{}", resolution.width(), resolution.height());
-
- let mut cmd = Command::new("ffmpeg")
- .args(&["-f", "rawvideo", "-pix_fmt", "uyvy422"])
- .args(["-s", &size, "-r", &frame_rate.to_string()])
- .args(["-thread_queue_size", "4096", "-i"])
- .arg(pipe_path.to_str().unwrap())
- .args(["-f", "mp4"])
- .args(["-codec:v", "libx264", "-preset", "ultrafast"])
- .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
- .args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
- .args(["-movflags", "frag_keyframe+empty_moov"])
- .args([
- "-vf",
- &format!("fps={frame_rate},scale=in_range=full:out_range=limited"),
- ])
- .arg(output_path)
- .stdin(Stdio::piped())
- .spawn()
- .expect("Failed to execute command");
-
- FfmpegRecording {
- folder_path: folder_path.to_path_buf(),
- ffmpeg_stdin: cmd.stdin.take().unwrap(),
+ println!("Beginning camera recording");
+
+ let (camera_format, capture) = start_capturing(pipe_path.clone(), camera_info).await;
+
+ println!(
+ "Received video info: {:?}",
+ (camera_format.resolution(), camera_format.frame_rate())
+ );
+
+ FFmpegRawVideoSource {
+ width: camera_format.resolution().width(),
+ height: camera_format.resolution().height(),
+ fps: camera_format.frame_rate(),
+ input: pipe_path,
+ output: output_path,
+ pix_fmt: match camera_format.format() {
+ FrameFormat::YUYV => "uyvy422",
+ FrameFormat::RAWRGB => "rgb24",
+ FrameFormat::NV12 => "nv12",
+ _ => panic!("unimplemented"),
+ },
capture,
}
}
@@ -120,17 +137,10 @@ pub async fn start_recording(folder_path: &Path, camera_info: CameraInfo) -> Ffm
async fn start_capturing(
pipe_path: PathBuf,
camera_info: CameraInfo,
-) -> ((Resolution, u32), NamedPipeCapture) {
- std::fs::remove_file(&pipe_path).ok();
- create_named_pipe(&pipe_path).unwrap();
-
- let stop = Arc::new(AtomicBool::new(false));
+) -> (CameraFormat, NamedPipeCapture) {
let (video_info_tx, video_info_rx) = oneshot::channel();
- let capture = NamedPipeCapture {
- path: pipe_path.clone(),
- stop: stop.clone(),
- };
+ let (capture, is_stopped) = NamedPipeCapture::new(&pipe_path);
std::thread::spawn(move || {
use nokhwa::{pixel_format::*, utils::*, *};
@@ -145,11 +155,9 @@ async fn start_capturing(
let format =
RequestedFormat::new::<RgbFormat>(RequestedFormatType::AbsoluteHighestFrameRate);
- let mut camera = Camera::new(camera_info.index().clone(), format).unwrap();
+ let mut camera = Camera::new(camera_info.index.into(), format).unwrap();
- video_info_tx
- .send((camera.resolution(), camera.frame_rate()))
- .ok();
+ video_info_tx.send(camera.camera_format()).ok();
camera.open_stream().unwrap();
@@ -159,28 +167,17 @@ async fn start_capturing(
println!("Receiving frames");
loop {
- if stop.load(Ordering::Relaxed) {
- println!("Stopping receiving frames");
+ if is_stopped.load(Ordering::Relaxed) {
+ println!("Stopping receiving camera frames");
return;
}
- file.write_all(camera.frame().unwrap().buffer()).ok();
+ let frame = camera.frame().unwrap();
+ dbg!(frame.source_frame_format());
+ dbg!(frame.buffer().len());
+ dbg!(frame.resolution());
+ file.write_all(frame.buffer()).ok();
}
});
(video_info_rx.await.unwrap(), capture)
}
-
-struct NamedPipeCapture {
- path: PathBuf,
- stop: Arc<AtomicBool>,
-}
-
-impl NamedPipeCapture {
- fn path(&self) -> &PathBuf {
- &self.path
- }
-
- fn stop(&self) {
- self.stop.store(true, Ordering::Relaxed);
- }
-}
diff --git a/apps/desktop-solid/src-tauri/src/display.rs b/apps/desktop-solid/src-tauri/src/display.rs
new file mode 100644
index 000000000..dd7a89d77
--- /dev/null
+++ b/apps/desktop-solid/src-tauri/src/display.rs
@@ -0,0 +1,161 @@
+use std::{
+ io::Write,
+ path::{Path, PathBuf},
+ sync::atomic::Ordering,
+};
+
+use scap::{
+ capturer::{Area, Capturer, Options, Point, Resolution, Size},
+ frame::{Frame, FrameType},
+ Target,
+};
+use serde::{Deserialize, Serialize};
+use specta::Type;
+
+use crate::{
+ ffmpeg::{FFmpegRawVideoSource, NamedPipeCapture},
+ macos,
+};
+
+#[derive(Type, Serialize)]
+pub struct CaptureWindow {
+ id: u32,
+ name: String,
+}
+
+#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub enum CaptureTarget {
+ Display,
+ Window(u32),
+}
+
+#[tauri::command]
+#[specta::specta]
+pub fn get_capture_windows() -> Vec<CaptureWindow> {
+ let targets = scap::get_all_targets();
+
+ let windows = macos::get_on_screen_windows();
+
+ targets
+ .into_iter()
+ .filter_map(|target| match target {
+ Target::Window(scap_window)
+ if windows
+ .iter()
+ .any(|window| window.window_number == scap_window.raw_handle) =>
+ {
+ Some(scap_window)
+ }
+ _ => None,
+ })
+ .map(|target| CaptureWindow {
+ id: target.id,
+ name: target.title,
+ })
+ .collect::<Vec<_>>()
+}
+
+const FPS: u32 = 30;
+
+pub fn start_recording(
+ output_folder: &Path,
+ output_name: &str,
+ capture_target: &CaptureTarget,
+ camera_target: Option<Target>,
+) -> FFmpegRawVideoSource {
+ std::fs::create_dir_all(output_folder).ok();
+
+ let pipe_path = output_folder.join(format!("{output_name}.pipe"));
+
+ let output_path = output_folder.join(format!("{output_name}.mp4"));
+ std::fs::remove_file(&output_path).ok();
+
+ println!("Beginning capture recording");
+
+ let ((width, height), capture) =
+ start_capturing(pipe_path.clone(), &capture_target, camera_target);
+
+ FFmpegRawVideoSource {
+ width,
+ height,
+ fps: FPS,
+ input: pipe_path,
+ output: output_path,
+ pix_fmt: "bgra",
+ capture,
+ }
+}
+
+fn start_capturing(
+ pipe_path: PathBuf,
+ capture_target: &CaptureTarget,
+ camera_target: Option<Target>,
+) -> ((u32, u32), NamedPipeCapture) {
+ let mut capturer = {
+ let crop_area = match capture_target {
+ CaptureTarget::Window(id) => {
+ let windows = macos::get_on_screen_windows();
+
+ let window = windows
+ .into_iter()
+ .find(|w| w.window_number == *id)
+ .unwrap();
+
+ Some(Area {
+ size: Size {
+ width: window.bounds.width as f64,
+ height: window.bounds.height as f64,
+ },
+ origin: Point {
+ x: window.bounds.x as f64,
+ y: window.bounds.y as f64,
+ },
+ })
+ }
+ _ => None,
+ };
+
+ let options = Options {
+ fps: FPS,
+ excluded_targets: camera_target.map(|t| vec![t]),
+ show_cursor: true,
+ show_highlight: true,
+ output_type: FrameType::BGRAFrame,
+ output_resolution: Resolution::Captured,
+ crop_area,
+ ..Default::default()
+ };
+
+ Capturer::new(dbg!(options))
+ };
+
+ let [width, height] = capturer.get_output_frame_size();
+
+ let (capture, is_stopped) = NamedPipeCapture::new(&pipe_path);
+
+ std::thread::spawn(move || {
+ capturer.start_capture();
+
+ println!("Opening pipe");
+ let mut file = std::fs::File::create(&pipe_path).unwrap();
+ println!("Pipe opened");
+
+ loop {
+ if is_stopped.load(Ordering::Relaxed) {
+ println!("Stopping receiving capture frames");
+ return;
+ }
+
+ match capturer.get_next_frame() {
+ Ok(Frame::BGRA(frame)) => {
+ println!("bruh");
+ file.write_all(&frame.data).ok();
+ }
+ _ => println!("Failed to get frame"),
+ }
+ }
+ });
+
+ ((width, height), capture)
+}
diff --git a/apps/desktop-solid/src-tauri/src/ffmpeg.rs b/apps/desktop-solid/src-tauri/src/ffmpeg.rs
new file mode 100644
index 000000000..3621fd0a9
--- /dev/null
+++ b/apps/desktop-solid/src-tauri/src/ffmpeg.rs
@@ -0,0 +1,129 @@
+use std::{
+ io::Write,
+ path::PathBuf,
+ process::{Child, ChildStdin, Command, Stdio},
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
+};
+
+use crate::utils::create_named_pipe;
+
+pub struct FFmpegRecording {
+ ffmpeg_stdin: ChildStdin,
+}
+
+impl FFmpegRecording {
+ pub fn create(mut command: Command) -> Self {
+ let mut cmd = command
+ .stdin(Stdio::piped())
+ .spawn()
+ .expect("Failed to start ffmpeg");
+
+ Self {
+ ffmpeg_stdin: cmd.stdin.take().unwrap(),
+ }
+ }
+
+ pub fn stop(mut self) {
+ self.ffmpeg_stdin.write_all(b"q").ok();
+ }
+}
+
+pub struct NamedPipeCapture {
+ path: PathBuf,
+ is_stopped: Arc<AtomicBool>,
+}
+
+impl NamedPipeCapture {
+ pub fn new(path: &PathBuf) -> (Self, Arc<AtomicBool>) {
+ create_named_pipe(&path).unwrap();
+
+ let stop = Arc::new(AtomicBool::new(false));
+
+ (
+ Self {
+ path: path.clone(),
+ is_stopped: stop.clone(),
+ },
+ stop.clone(),
+ )
+ }
+
+ pub fn path(&self) -> &PathBuf {
+ &self.path
+ }
+
+ pub fn stop(&self) {
+ self.is_stopped.store(true, Ordering::Relaxed);
+ }
+}
+
+pub struct FFmpegRawVideoSource {
+ pub width: u32,
+ pub height: u32,
+ pub fps: u32,
+ pub input: PathBuf,
+ pub output: PathBuf,
+ pub pix_fmt: &'static str,
+ pub capture: NamedPipeCapture,
+}
+
+impl FFmpegRawVideoSource {
+ pub fn apply_to_ffmpeg(
+ self,
+ command: &mut std::process::Command,
+ index: u8,
+ ) -> NamedPipeCapture {
+ let size = format!("{}x{}", self.width, self.height);
+
+ println!("applying to ffmpeg: size: {size}");
+
+ command
+ // input
+ .args(&["-f", "rawvideo", "-pix_fmt", self.pix_fmt])
+ .args(["-s", &size])
+ .args(["-r", &self.fps.to_string()])
+ .args(["-thread_queue_size", "4096", "-i"])
+ .arg(self.input)
+ // output
+ .args(["-f", "mp4", "-map", &format!("{index}:v")])
+ .args(["-codec:v", "libx264", "-preset", "ultrafast"])
+ .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
+ .args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
+ .args(["-movflags", "frag_keyframe+empty_moov"])
+ .args([
+ "-vf",
+ &format!("fps={},scale=in_range=full:out_range=limited", self.fps),
+ ])
+ .arg(self.output);
+
+ self.capture
+ }
+}
+
+pub struct FFmpegRawSourceEncoder {
+ command: Command,
+ source_index: u8,
+}
+
+impl FFmpegRawSourceEncoder {
+ pub fn new() -> Self {
+ Self {
+ command: Command::new("ffmpeg"),
+ source_index: 0,
+ }
+ }
+
+ pub fn add_source<R>(&mut self, source: impl FnOnce(&mut Command, u8) -> R) -> R {
+ let source_index = self.source_index;
+ self.source_index += 1;
+
+ source(&mut self.command, source_index)
+ }
+
+ pub fn start(self) -> FFmpegRecording {
+ FFmpegRecording::create(self.command)
+ }
+}
diff --git a/apps/desktop-solid/src-tauri/src/lib.rs b/apps/desktop-solid/src-tauri/src/lib.rs
index 9c06b5009..5b9524117 100644
--- a/apps/desktop-solid/src-tauri/src/lib.rs
+++ b/apps/desktop-solid/src-tauri/src/lib.rs
@@ -1,29 +1,40 @@
mod camera;
+mod display;
+mod ffmpeg;
+mod macos;
+mod utils;
+use ffmpeg::{FFmpegRawSourceEncoder, FFmpegRecording, NamedPipeCapture};
+use scap::Target;
use serde::{Deserialize, Serialize};
-use std::sync::Arc;
+use std::{path::PathBuf, sync::Arc};
use tauri::{AppHandle, Manager, State};
use tauri_specta::Event;
use tokio::sync::RwLock;
-use camera::create_camera_window;
+use camera::{create_camera_window, get_cameras};
+use display::{get_capture_windows, CaptureTarget};
-#[derive(Default, specta::Type, Serialize, Deserialize, Clone)]
+#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct RecordingOptions {
+ capture_target: CaptureTarget,
camera_label: Option<String>,
}
-pub struct CurrentRecording {
- camera_recording: Option<camera::FfmpegRecording>,
+pub struct InProgressRecording {
+ recording_path: PathBuf,
+ ffmpeg_recording: FFmpegRecording,
+ display_capture: NamedPipeCapture,
+ camera_capture: Option<NamedPipeCapture>,
}
-#[derive(Default, specta::Type, Serialize)]
+#[derive(specta::Type, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AppState {
start_recording_options: RecordingOptions,
#[serde(skip)]
- current_recording: Option<CurrentRecording>,
+ current_recording: Option<InProgressRecording>,
}
#[derive(specta::Type, Serialize, tauri_specta::Event, Clone)]
@@ -59,6 +70,8 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, AppState>) -> R
let mut state = state.write().await;
let recording_options = &state.start_recording_options;
+ dbg!(&recording_options);
+
let id = uuid::Uuid::new_v4().to_string();
let recording_path = app
@@ -67,28 +80,59 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, AppState>) -> R
.unwrap()
.join("recordings")
.join(format!("{id}.cap"));
-
std::fs::create_dir_all(&recording_path).unwrap();
+ let content_path = recording_path.join("content");
+
+ let mut ffmpeg = FFmpegRawSourceEncoder::new();
+
+ let camera_capture = {
+ let Some(camera_info) = recording_options
+ .camera_label
+ .as_ref()
+ .and_then(|camera_label| {
+ camera::get_cameras()
+ .into_iter()
+ .find(|c| &c.human_name == camera_label)
+ })
+ else {
+ todo!()
+ };
+ let source = camera::start_recording(&content_path, "camera", camera_info).await;
+
+ Some(ffmpeg.add_source(move |cmd, i| source.apply_to_ffmpeg(cmd, i)))
+ };
- let camera_info = recording_options
- .camera_label
- .as_ref()
- .and_then(|camera_label| {
- let cameras = dbg!(nokhwa::query(nokhwa::utils::ApiBackend::AVFoundation)).unwrap();
-
- cameras
- .into_iter()
- .find(|c| c.human_name().as_str() == camera_label)
- });
-
- let camera_recording = match camera_info {
- Some(camera_info) => {
- Some(camera::start_recording(&recording_path.join("camera"), camera_info).await)
- }
- _ => None,
+ let display_capture = {
+ let camera_window_target =
+ app.get_webview_window(camera::CAMERA_WINDOW)
+ .and_then(|window| {
+ let ns_window = window.ns_window().unwrap() as *const objc2_app_kit::NSWindow;
+
+ let window_id = unsafe { (*ns_window).windowNumber() };
+ scap::get_all_targets()
+ .into_iter()
+ .find(|target| match target {
+ Target::Window(window) => window.raw_handle as isize == window_id,
+ _ => false,
+ })
+ });
+
+ let display_source = display::start_recording(
+ &content_path,
+ "display",
+ &recording_options.capture_target,
+ camera_window_target,
+ );
+
+ ffmpeg.add_source(move |cmd, i| display_source.apply_to_ffmpeg(cmd, i))
};
- let current_recording = CurrentRecording { camera_recording };
+ let current_recording = InProgressRecording {
+ recording_path,
+ ffmpeg_recording: ffmpeg.start(),
+ display_capture,
+ camera_capture,
+ };
state.current_recording = Some(current_recording);
@@ -104,8 +148,10 @@ async fn stop_recording(state: MutableState<'_, AppState>) -> Result<(), String>
return Err("Recording not in progress".to_string());
};
- if let Some(camera_recording) = current_recording.camera_recording {
- camera_recording.stop();
+ current_recording.ffmpeg_recording.stop();
+ current_recording.display_capture.stop();
+ if let Some(camera_capture) = current_recording.camera_capture {
+ camera_capture.stop();
};
Ok(())
@@ -133,7 +179,9 @@ pub fn run() {
set_recording_options,
create_camera_window,
start_recording,
- stop_recording
+ stop_recording,
+ get_cameras,
+ get_capture_windows
])
.events(tauri_specta::collect_events![RecordingOptionsChanged]);
@@ -151,7 +199,13 @@ pub fn run() {
.setup(move |app| {
specta_builder.mount_events(app);
- app.manage(Arc::new(RwLock::new(AppState::default())));
+ app.manage(Arc::new(RwLock::new(AppState {
+ start_recording_options: RecordingOptions {
+ capture_target: CaptureTarget::Display,
+ camera_label: None,
+ },
+ current_recording: None,
+ })));
Ok(())
})
diff --git a/apps/desktop-solid/src-tauri/src/macos.rs b/apps/desktop-solid/src-tauri/src/macos.rs
new file mode 100644
index 000000000..3c851b065
--- /dev/null
+++ b/apps/desktop-solid/src-tauri/src/macos.rs
@@ -0,0 +1,179 @@
+use core_graphics::{
+ base::boolean_t,
+ display::{CFDictionaryRef, CGRect},
+ window::kCGWindowBounds,
+};
+
+#[derive(Debug)]
+pub struct Window {
+ pub window_number: u32,
+ pub name: String,
+ pub owner_name: String,
+ pub level: u32,
+ pub bounds: Bounds,
+}
+
+#[derive(Debug)]
+pub struct Bounds {
+ pub x: u32,
+ pub y: u32,
+ pub width: u32,
+ pub height: u32,
+}
+
+pub fn get_on_screen_windows() -> Vec<Window> {
+ use std::ffi::c_void;
+
+ use core_foundation::{
+ array::CFArrayGetCount,
+ base::FromVoid,
+ dictionary::CFDictionaryGetValue,
+ number::{kCFNumberIntType, CFNumberGetValue, CFNumberRef},
+ string::CFString,
+ };
+ use core_graphics::{
+ display::{CFArrayGetValueAtIndex, CFDictionaryRef},
+ window::{
+ kCGNullWindowID, kCGWindowLayer, kCGWindowListExcludeDesktopElements,
+ kCGWindowListOptionOnScreenOnly, kCGWindowName, kCGWindowNumber, kCGWindowOwnerName,
+ CGWindowListCopyWindowInfo,
+ },
+ };
+
+ let mut array = vec![];
+
+ unsafe {
+ let cf_win_array = CGWindowListCopyWindowInfo(
+ kCGWindowListExcludeDesktopElements | kCGWindowListOptionOnScreenOnly,
+ kCGNullWindowID,
+ );
+
+ if cf_win_array.is_null() {
+ return array;
+ }
+
+ let count = CFArrayGetCount(cf_win_array);
+
+ for i in 0..count {
+ let window_cf_dictionary_ref =
+ CFArrayGetValueAtIndex(cf_win_array, i) as CFDictionaryRef;
+
+ if window_cf_dictionary_ref.is_null() {
+ continue;
+ }
+
+ let level = {
+ let level_ref =
+ CFDictionaryGetValue(window_cf_dictionary_ref, kCGWindowLayer as *const c_void);
+ if level_ref.is_null() {
+ continue;
+ }
+
+ let mut value: u32 = 0;
+ let is_success = CFNumberGetValue(
+ level_ref as CFNumberRef,
+ kCFNumberIntType,
+ &mut value as *mut _ as *mut c_void,
+ );
+
+ if !is_success {
+ continue;
+ }
+
+ value
+ };
+
+ let bounds = {
+ let value_ref = CFDictionaryGetValue(
+ window_cf_dictionary_ref,
+ kCGWindowBounds as *const c_void,
+ );
+ if value_ref.is_null() {
+ continue;
+ }
+
+ let rect: CGRect = {
+ let mut rect = std::mem::zeroed();
+ CGRectMakeWithDictionaryRepresentation(value_ref.cast(), &mut rect);
+ rect
+ };
+
+ Bounds {
+ x: rect.origin.x as u32,
+ y: rect.origin.y as u32,
+ width: rect.size.width as u32,
+ height: rect.size.height as u32,
+ }
+ };
+
+ let window_number = {
+ let level_ref = CFDictionaryGetValue(
+ window_cf_dictionary_ref,
+ kCGWindowNumber as *const c_void,
+ );
+ if level_ref.is_null() {
+ continue;
+ }
+
+ let mut value: u32 = 0;
+ let is_success = CFNumberGetValue(
+ level_ref as CFNumberRef,
+ kCFNumberIntType,
+ &mut value as *mut _ as *mut c_void,
+ );
+
+ if !is_success {
+ continue;
+ }
+
+ value
+ };
+
+ let name = {
+ let value_ref =
+ CFDictionaryGetValue(window_cf_dictionary_ref, kCGWindowName as *const c_void);
+ if value_ref.is_null() {
+ continue;
+ }
+
+ CFString::from_void(value_ref).to_string()
+ };
+
+ let owner_name = {
+ let value_ref = CFDictionaryGetValue(
+ window_cf_dictionary_ref,
+ kCGWindowOwnerName as *const c_void,
+ );
+ if value_ref.is_null() {
+ continue;
+ }
+
+ CFString::from_void(value_ref).to_string()
+ };
+
+ if owner_name == "Window Server" {
+ continue;
+ }
+
+ if level == 0 && name != "" {
+ array.push(Window {
+ name,
+ owner_name,
+ window_number,
+ level,
+ bounds,
+ });
+ }
+ }
+ }
+
+ array
+}
+
+#[link(name = "CoreGraphics", kind = "framework")]
+extern "C" {
+ pub fn CGRectMakeWithDictionaryRepresentation(
+ dict: CFDictionaryRef,
+ rect: *mut CGRect,
+ ) -> boolean_t;
+}
diff --git a/apps/desktop-solid/src-tauri/src/utils.rs b/apps/desktop-solid/src-tauri/src/utils.rs
new file mode 100644
index 000000000..fed6c0163
--- /dev/null
+++ b/apps/desktop-solid/src-tauri/src/utils.rs
@@ -0,0 +1,10 @@
+use std::path::Path;
+
+#[cfg(unix)]
+pub fn create_named_pipe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
+ use nix::sys::stat;
+ use nix::unistd;
+ std::fs::remove_file(&path).ok();
+ unistd::mkfifo(path, stat::Mode::S_IRWXU)?;
+ Ok(())
+}
diff --git a/apps/desktop-solid/src/App.tsx b/apps/desktop-solid/src/App.tsx
index 0767acb37..c5e3d0e1a 100644
--- a/apps/desktop-solid/src/App.tsx
+++ b/apps/desktop-solid/src/App.tsx
@@ -1,13 +1,18 @@
import { Router } from "@solidjs/router";
import { FileRoutes } from "@solidjs/start/router";
import { Suspense } from "solid-js";
+import { QueryClient, QueryClientProvider } from "@tanstack/solid-query";
import "@cap/ui/style";
+const queryClient = new QueryClient();
+
export default function App() {
return (
- <Router root={(props) => <Suspense>{props.children}</Suspense>}>
- <FileRoutes />
- </Router>
+ <QueryClientProvider client={queryClient}>
+ <Router root={(props) => <Suspense>{props.children}</Suspense>}>
+ <FileRoutes />
+ </Router>
+ </QueryClientProvider>
);
}
diff --git a/apps/desktop-solid/src/routes/camera.tsx b/apps/desktop-solid/src/routes/camera.tsx
index b14c0a011..bfc5355c3 100644
--- a/apps/desktop-solid/src/routes/camera.tsx
+++ b/apps/desktop-solid/src/routes/camera.tsx
@@ -1,17 +1,19 @@
-import { createEffect, createResource, createSignal, on, Show } from "solid-js";
import { makePersisted } from "@solid-primitives/storage";
-import { createStore } from "solid-js/store";
import {
- currentMonitor,
- getCurrentWindow,
LogicalPosition,
LogicalSize,
+ currentMonitor,
+ getCurrentWindow,
} from "@tauri-apps/api/window";
+import { Show, createEffect, createResource, createSignal, on } from "solid-js";
+import { createStore } from "solid-js/store";
-import { commands } from "../utils/tauri";
-import { createCameraForLabel } from "../utils/media";
-import { makeInvalidated } from "../utils/events";
+import { createQuery } from "@tanstack/solid-query";
import { CloseX, Expand, Flip, Minimize, Squircle } from "../icons";
+import { createQueryInvalidate, makeInvalidated } from "../utils/events";
+import { createCameraForLabel } from "../utils/media";
+import { createOptionsQuery, getOptions } from "../utils/queries";
+import { commands } from "../utils/tauri";
namespace CameraWindow {
export type Size = "sm" | "lg";
@@ -24,36 +26,11 @@ namespace CameraWindow {
}
export default function () {
- const [options] = makeInvalidated(
- createResource(async () => {
- const o = await commands.getRecordingOptions();
- if (o.status === "ok") return o.data;
- }),
- "recordingOptionsChanged"
- );
+ const options = createOptionsQuery();
- const camera = createCameraForLabel(() => options()?.cameraLabel ?? "");
+ const camera = createCameraForLabel(() => options.data?.cameraLabel ?? "");
- const [cameraStream] = createResource(
- () => camera()?.deviceId,
- (cameraInputId) =>
- navigator.mediaDevices.getUserMedia({
- video: { deviceId: cameraInputId },
- })
- );
-
- const [cameraRef, setCameraRef] = createSignal<HTMLVideoElement>();
-
- createEffect(() => {
- const stream = cameraStream();
- const ref = cameraRef();
-
- if (ref && stream) {
- if (ref.srcObject === stream) return;
- ref.srcObject = stream;
- ref.play();
- }
- });
+ const [cameraPreviewRef] = createCameraPreview(() => camera()?.deviceId);
const [state, setState] = makePersisted(
createStore<CameraWindow.State>({
@@ -66,7 +43,7 @@ export default function () {
createEffect(on(() => state.size, resizeWindow));
return (
- <Show when={options()}>
+ <Show when={options.data}>
{(options) => (
<div
data-tauri-drag-region
@@ -134,7 +111,7 @@ export default function () {
"absolute top-0 left-0 w-full h-full object-cover pointer-events-none"
}
style={{ transform: state.mirrored ? "scaleX(1)" : "scaleX(-1)" }}
- ref={setCameraRef}
+ ref={cameraPreviewRef}
/>
</div>
)}
@@ -166,3 +143,29 @@ async function resizeWindow(size: CameraWindow.Size) {
currentWindow.setSize(new LogicalSize(windowWidth, windowHeight));
currentWindow.setPosition(new LogicalPosition(x / scalingFactor, y));
}
+
+function createCameraPreview(deviceId: () => string | undefined) {
+ const [cameraStream] = createResource(
+ deviceId,
+
+ (cameraInputId) =>
+ navigator.mediaDevices.getUserMedia({
+ video: { deviceId: cameraInputId },
+ })
+ );
+
+ const [cameraRef, setCameraRef] = createSignal<HTMLVideoElement>();
+
+ createEffect(() => {
+ const stream = cameraStream();
+ const ref = cameraRef();
+
+ if (ref && stream) {
+ if (ref.srcObject === stream) return;
+ ref.srcObject = stream;
+ ref.play();
+ }
+ });
+
+ return [setCameraRef] as const;
+}
diff --git a/apps/desktop-solid/src/routes/index.tsx b/apps/desktop-solid/src/routes/index.tsx
index 3f2530cf1..64bd62ee0 100644
--- a/apps/desktop-solid/src/routes/index.tsx
+++ b/apps/desktop-solid/src/routes/index.tsx
@@ -1,64 +1,149 @@
-import { createResource, createSignal, For, Show, Suspense } from "solid-js";
+import { cx } from "cva";
+import { For, Show, Suspense, createSignal } from "solid-js";
-import { commands } from "../utils/tauri";
-import { makeInvalidated } from "../utils/events";
import { createCameraForLabel, createCameras } from "../utils/media";
+import { createOptionsQuery, createWindowsQuery } from "../utils/queries";
+import { commands } from "../utils/tauri";
export default function () {
const cameras = createCameras();
+ const options = createOptionsQuery();
+ const windows = createWindowsQuery();
- const [options] = makeInvalidated(
- createResource(async () => {
- const o = await commands.getRecordingOptions();
- if (o.status === "ok") return o.data;
- }),
- "recordingOptionsChanged"
- );
-
- const camera = createCameraForLabel(() => options()?.cameraLabel ?? "");
+ const camera = createCameraForLabel(() => options.data?.cameraLabel ?? "");
// temporary
const [isRecording, setIsRecording] = createSignal(false);
return (
- <Suspense>
- <Show when={options()}>
+ <Suspense fallback="LOADING">
+ <Show when={options.data}>
{(options) => (
<>
- <div>
- <select
- value={camera()?.deviceId}
- onChange={(e) => {
- const o = options();
- const deviceId = e.target.value;
- const label = cameras().find(
- (c) => c.deviceId === deviceId
- )?.label;
- if (!label) return;
+ <div class="max-w-64 space-y-4">
+ <div class="flex flex-col gap-1">
+ <label>Camera</label>
+ <div>
+ <select
+ class="w-full"
+ value={camera()?.deviceId}
+ onChange={(e) => {
+ const o = options();
+ const deviceId = e.target.value;
+ const label = cameras().find(
+ (c) => c.deviceId === deviceId
+ )?.label;
+ if (!label) return;
- commands.setRecordingOptions({ ...o, cameraLabel: label });
- }}
- >
- <For each={cameras()}>
- {(camera) => (
- <option value={camera.deviceId}>{camera.label}</option>
+ commands.setRecordingOptions({
+ ...o,
+ cameraLabel: label,
+ });
+ }}
+ >
+ <For each={cameras()}>
+ {(camera) => (
+ <option value={camera.deviceId}>{camera.label}</option>
+ )}
+ </For>
+ </select>
+ {options().cameraLabel && (
+ <button
+ type="button"
+ onClick={() =>
+ commands.setRecordingOptions({
+ ...options(),
+ cameraLabel: null,
+ })
+ }
+ >
+ Remove
+ </button>
)}
- </For>
- </select>
- {options().cameraLabel && (
- <button
- type="button"
- onClick={() =>
- commands.setRecordingOptions({
- ...options,
- cameraLabel: null,
- })
- }
+ </div>
+ </div>
+ <div>
+ <label>Capture</label>
+ <div class="flex flex-row justify-between gap-1">
+ <button
+ type="button"
+ class={cx(
+ "flex-1",
+ "display" === options().captureTarget
+ ? "bg-neutral-200"
+ : "bg-neutral-100"
+ )}
+ onClick={() =>
+ commands.setRecordingOptions({
+ ...options(),
+ captureTarget: "display",
+ })
+ }
+ >
+ Screen
+ </button>
+ <Show when={windows.data?.[0]}>
+ {(window) => (
+ <button
+ type="button"
+ class={cx(
+ "flex-1",
+ options().captureTarget !== "display"
+ ? "bg-neutral-200"
+ : "bg-neutral-100"
+ )}
+ onClick={() => {
+ const captureTarget = options();
+ if (
+ typeof captureTarget === "object" &&
+ "window" in captureTarget
+ )
+ return;
+
+ commands.setRecordingOptions({
+ ...options(),
+ captureTarget: { window: window().id },
+ });
+ }}
+ >
+ Window
+ </button>
+ )}
+ </Show>
+ </div>
+ <Show
+ when={(() => {
+ const captureTarget = options().captureTarget;
+ if (captureTarget === "display") return;
+
+ return {
+ windows: windows.data,
+ windowId: captureTarget.window,
+ };
+ })()}
>
- Remove
- </button>
- )}
- {camera() && (
+ {(data) => (
+ <select
+ class="w-full"
+ value={data().windowId}
+ onChange={(e) => {
+ const o = options();
+ commands.setRecordingOptions({
+ ...o,
+ captureTarget: { window: Number(e.target.value) },
+ });
+ }}
+ >
+ <For each={data().windows}>
+ {(window) => (
+ <option value={window.id}>{window.name}</option>
+ )}
+ </For>
+ </select>
+ )}
+ </Show>
+ </div>
+ {
<div>
{!isRecording() ? (
<button
@@ -84,7 +169,7 @@ export default function () {
</button>
)}
</div>
- )}
+ }
</div>
</>
)}
diff --git a/apps/desktop-solid/src/utils/events.ts b/apps/desktop-solid/src/utils/events.ts
index 7b5a4e049..2e169bd59 100644
--- a/apps/desktop-solid/src/utils/events.ts
+++ b/apps/desktop-solid/src/utils/events.ts
@@ -1,5 +1,6 @@
import { onCleanup, onMount, type ResourceReturn } from "solid-js";
import { events } from "./tauri";
+import { CreateQueryResult } from "@tanstack/solid-query";
export function makeInvalidated<R>(
resource: ResourceReturn<R>,
@@ -14,3 +15,13 @@ export function makeInvalidated<R>(
return resource;
}
+
+export function createQueryInvalidate<T extends CreateQueryResult<any, any>>(
+ query: T,
+ event: keyof typeof events
+) {
+ onMount(() => {
+ const cleanup = events[event].listen(() => query.refetch());
+ onCleanup(() => cleanup.then((c) => c()));
+ });
+}
diff --git a/apps/desktop-solid/src/utils/media.ts b/apps/desktop-solid/src/utils/media.ts
index cadf42c1b..489b018cd 100644
--- a/apps/desktop-solid/src/utils/media.ts
+++ b/apps/desktop-solid/src/utils/media.ts
@@ -1,4 +1,13 @@
-import { type Accessor, createResource, onCleanup } from "solid-js";
+import { createTimer } from "@solid-primitives/timer";
+import {
+ type Accessor,
+ createEffect,
+ createResource,
+ on,
+ onCleanup,
+ onMount,
+} from "solid-js";
+import { commands } from "./tauri";
export function createDevices() {
const [devices, { refetch }] = createResource(async () => {
@@ -6,10 +15,12 @@ export function createDevices() {
return await navigator.mediaDevices.enumerateDevices();
});
- navigator.mediaDevices.addEventListener("devicechange", refetch);
- onCleanup(() =>
- navigator.mediaDevices.removeEventListener("devicechange", refetch)
- );
+ onMount(() => {
+ navigator.mediaDevices.addEventListener("devicechange", refetch);
+ onCleanup(() =>
+ navigator.mediaDevices.removeEventListener("devicechange", refetch)
+ );
+ });
return () => devices.latest ?? [];
}
@@ -17,7 +28,24 @@ export function createDevices() {
export function createCameras() {
const devices = createDevices();
- return () => devices().filter((device) => device.kind === "videoinput");
+ const [rustCameras, { refetch }] = createResource(() =>
+ commands.getCameras()
+ );
+
+ createTimer(refetch, 5 * 1000, setInterval);
+ createEffect(on(devices, refetch));
+
+ return () => {
+ const videoDevices = devices().filter(
+ (device) => device.kind === "videoinput"
+ );
+
+ const cameras = rustCameras.latest ?? [];
+
+ return videoDevices.filter((device) =>
+ cameras.some((c) => c.human_name === device.label)
+ );
+ };
}
export function createCameraForLabel(label: Accessor<string>) {
diff --git a/apps/desktop-solid/src/utils/queries.ts b/apps/desktop-solid/src/utils/queries.ts
new file mode 100644
index 000000000..0f28ead7f
--- /dev/null
+++ b/apps/desktop-solid/src/utils/queries.ts
@@ -0,0 +1,31 @@
+import { createQuery, queryOptions } from "@tanstack/solid-query";
+import { commands } from "./tauri";
+import { createQueryInvalidate } from "./events";
+import { createTimer } from "@solid-primitives/timer";
+
+export const getWindows = queryOptions({
+ queryKey: ["capture", "windows"] as const,
+ queryFn: () => commands.getCaptureWindows(),
+});
+
+const getOptions = queryOptions({
+ queryKey: ["recordingOptions"] as const,
+ queryFn: async () => {
+ const o = await commands.getRecordingOptions();
+ if (o.status === "ok") return o.data;
+ },
+});
+
+export function createOptionsQuery() {
+ const options = createQuery(() => getOptions);
+ createQueryInvalidate(options, "recordingOptionsChanged");
+
+ return options;
+}
+
+export function createWindowsQuery() {
+ const windows = createQuery(() => getWindows);
+ createTimer(() => windows.refetch(), 1000, setInterval);
+
+ return windows;
+}
diff --git a/apps/desktop-solid/src/utils/tauri.ts b/apps/desktop-solid/src/utils/tauri.ts
index 957c09f9f..8e4e23e4b 100644
--- a/apps/desktop-solid/src/utils/tauri.ts
+++ b/apps/desktop-solid/src/utils/tauri.ts
@@ -39,6 +39,12 @@ async stopRecording() : Promise<Result<null, string>> {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
+},
+async getCameras() : Promise<CameraInfo[]> {
+ return await TAURI_INVOKE("get_cameras");
+},
+async getCaptureWindows() : Promise<CaptureWindow[]> {
+ return await TAURI_INVOKE("get_capture_windows");
}
}
@@ -57,7 +63,11 @@ recordingOptionsChanged: "recording-options-changed"
/** user-defined types **/
-export type RecordingOptions = { cameraLabel: string | null }
+export type CameraIndex = { Index: number } | { String: string }
+export type CameraInfo = { human_name: string; description: string; misc: string; index: CameraIndex }
+export type CaptureTarget = "display" | { window: number }
+export type CaptureWindow = { id: number; name: string }
+export type RecordingOptions = { captureTarget: CaptureTarget; cameraLabel: string | null }
export type RecordingOptionsChanged = null
/** tauri-specta globals **/
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 52f55c8ee..409646d25 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -132,18 +132,27 @@ importers:
'@solid-primitives/storage':
specifier: ^4.0.0
version: 4.0.0([email protected])
+ '@solid-primitives/timer':
+ specifier: ^1.3.9
+ version: 1.3.9([email protected])
'@solidjs/router':
specifier: ^0.14.2
version: 0.14.2([email protected])
'@solidjs/start':
specifier: ^1.0.6
+ '@tanstack/solid-query':
+ specifier: ^5.51.21
+ version: 5.51.21([email protected])
'@tauri-apps/api':
specifier: '>=2.0.0-rc.0'
version: 2.0.0-rc.0
'@tauri-apps/plugin-shell':
specifier: '>=2.0.0-rc.0'
version: 2.0.0-rc.0
+ cva:
+ specifier: npm:class-variance-authority@^0.7.0
solid-js:
specifier: ^1.7.8
version: 1.8.19
@@ -4696,6 +4705,11 @@ packages:
solid-start:
optional: true
+ '@solid-primitives/[email protected]':
+ resolution: {integrity: sha512-uD+4+boV7k+5W+hL5d30eodUXSwOfOQz8AfbMPVmLOHaTmd0mdfpw0NkYhyn1rgcx1bSn/nHTd8lraHiMhO/6w==}
+ peerDependencies:
+ solid-js: ^1.6.12
+
'@solid-primitives/[email protected]':
resolution: {integrity: sha512-CqAwKb2T5Vi72+rhebSsqNZ9o67buYRdEJrIFzRXz3U59QqezuuxPsyzTSVCacwS5Pf109VRsgCJQoxKRoECZQ==}
peerDependencies:
@@ -4785,11 +4799,11 @@ packages:
react-dom:
optional: true
- '@storybook/[email protected]':
- resolution: {integrity: sha512-fAP7MEjTd+fzdhWhPQ7uNtfh2z68OKkoSvBHeWpaNpauSh7EFWTmRVATdz4bItGmK2na/FFHEayHPTnfQWkU0g==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-r8O+6hRBNCql6f5NykbDUr5U/clNeDRJoBF+FpWkpQT9dXFoYor54u6JMEJmseHPdmiJemhiIZ0xo54ktWUJLg==}
peerDependencies:
'@preact/preset-vite': '*'
- storybook: ^8.3.0-alpha.5
+ storybook: ^8.3.0-alpha.6
typescript: '>= 4.3.x'
vite: ^4.0.0 || ^5.0.0
vite-plugin-glimmerx: '*'
@@ -4812,10 +4826,10 @@ packages:
peerDependencies:
storybook: ^8.2.7
- '@storybook/[email protected]':
- resolution: {integrity: sha512-NgArxKGtrdeCTM7H0L3ppYpXRsxqUfaw5jGk2QykMqOFbrSfyVgKeL8iZPClFH6YjopYL1GtlziHLCL2Cju1JA==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-zGJ3qaF/Zx1EQZr5blS611vBzR0U+EwFjs7qwl0gYYrV+TSTCCZpIP6v7jDtpJ8vF2QVeem7iXreERi0L5Y8sQ==}
peerDependencies:
- storybook: ^8.3.0-alpha.5
+ storybook: ^8.3.0-alpha.6
'@storybook/[email protected]':
resolution: {integrity: sha512-dHYFQH3mA+EtnCkHXzicbLgsvzYjcDJ1JWsogbItZogkPHgSJM/Wr71uMkcvw8v9mmCyP4NpXJuu6bPoVsOnzg==}
@@ -4874,6 +4888,9 @@ packages:
peerDependencies:
tailwindcss: '>=3.0.0 || insiders'
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-POQxm42IUp6n89kKWF4IZi18v3fxQWFRolvBA6phNVmA8psdfB1MvDnGacCJdS+EOX12w/CyHM62z//rHmYmvw==}
+
'@tanstack/[email protected]':
resolution: {integrity: sha512-HsAwaY5J19MD18ykZDS3aVVh+bAt0i7m6uQlFC2b77DLV9djo+xEN7MWQAQQTR8IM+7r/zbozTQ7P0xr0bHuew==}
@@ -4894,6 +4911,11 @@ packages:
react: ^16.8.0 || ^17.0.0 || ^18.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-ZwiTMpownN5qwEZE7UB7ccfGkbzSECkZOv/P1+SQ+dKchNtkF9sA0Zz8IVnr6lgqumkCwS8M65ciBdzI0JfTAQ==}
+ peerDependencies:
+ solid-js: ^1.6.0
+
'@tanstack/[email protected]':
resolution: {integrity: sha512-EOSrgdDAJExbvRZEQ/Xhh9iZchXpMN+ga1Bnk8Nmygzs8TfiE6hbzThF+Pr2G19uHL6+DTDTHhJ8VQiOd7l4tA==}
@@ -16457,6 +16479,10 @@ snapshots:
'@solid-primitives/utils': 6.2.3([email protected])
solid-js: 1.8.19
+ '@solid-primitives/[email protected]([email protected])':
+ dependencies:
+ solid-js: 1.8.19
+
'@solid-primitives/[email protected]([email protected])':
dependencies:
solid-js: 1.8.19
@@ -16620,9 +16646,9 @@ snapshots:
react: 18.2.0
react-dom: 18.2.0([email protected])
dependencies:
- '@storybook/csf-plugin': 8.3.0-alpha.5([email protected](@babel/[email protected](@babel/[email protected]))([email protected])([email protected]))
+ '@storybook/csf-plugin': 8.3.0-alpha.6([email protected](@babel/[email protected](@babel/[email protected]))([email protected])([email protected]))
'@types/find-cache-dir': 3.2.1
browser-assert: 1.2.1
es-module-lexer: 1.5.4
@@ -16681,7 +16707,7 @@ snapshots:
unplugin: 1.6.0
dependencies:
unplugin: 1.12.1
@@ -16759,6 +16785,8 @@ snapshots:
postcss-selector-parser: 6.0.10
+ '@tanstack/[email protected]': {}
+
'@tanstack/[email protected]': {}
@@ -16779,6 +16807,11 @@ snapshots:
react: 18.2.0
react-dom: 18.2.0([email protected])
+ dependencies:
+ '@tanstack/query-core': 5.51.21
+ solid-js: 1.8.19
+
'@tanstack/[email protected]': {}
'@tanstack/[email protected]': {}
@@ -23856,7 +23889,7 @@ snapshots:
dependencies:
transitivePeerDependencies:
- '@preact/preset-vite'
- storybook