Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

cap-recording crate (#173)

Brendan Allan4114f5e23d23
diff --git a/Cargo.lock b/Cargo.lock
index 5ee0b83f4..d2842af87 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -29,12 +29,6 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"
-[[package]]
-name = "ahash"
-version = "0.4.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0453232ace82dee0dd0b4c87a59bd90f7b53b314f3e0f61fe2ee7c8a16482289"
-
[[package]]
name = "ahash"
version = "0.8.11"
@@ -753,17 +747,14 @@ name = "cap-editor"
version = "0.1.0"
dependencies = [
"axum",
- "cap-ffmpeg-cli",
"cap-media",
"cap-project",
"cap-rendering",
"cpal 0.15.3 (git+https://github.com/RustAudio/cpal?rev=f43d36e55494993bbbde3299af0c53e5cdf4d4cf)",
"ffmpeg-next",
"serde",
- "serde_json",
"specta",
"tokio",
- "tracing",
]
[[package]]
@@ -787,8 +778,6 @@ dependencies = [
name = "cap-ffmpeg-cli"
version = "0.1.0"
dependencies = [
- "cap-utils",
- "ffmpeg-sidecar 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"nix 0.29.0",
"tauri",
"tauri-plugin-shell",
@@ -813,7 +802,6 @@ dependencies = [
name = "cap-media"
version = "0.1.0"
dependencies = [
- "anyhow",
"cap-flags",
"cap-gpu-converters",
"cap-project",
@@ -822,9 +810,7 @@ dependencies = [
"core-foundation 0.10.0",
"core-graphics 0.24.0",
"cpal 0.15.3 (git+https://github.com/RustAudio/cpal?rev=f43d36e55494993bbbde3299af0c53e5cdf4d4cf)",
- "ffmpeg-hw-device",
"ffmpeg-next",
- "ffmpeg-sys-next",
"flume 0.11.0",
"futures",
"indexmap 2.5.0",
@@ -841,7 +827,6 @@ dependencies = [
"specta",
"tempfile",
"thiserror",
- "tokio",
"tracing",
"windows 0.58.0",
"windows-capture",
@@ -851,9 +836,32 @@ dependencies = [
name = "cap-project"
version = "0.1.0"
dependencies = [
+ "either",
+ "serde",
+ "serde_json",
+ "specta",
+]
+
+[[package]]
+name = "cap-recording"
+version = "0.1.0"
+dependencies = [
+ "cap-flags",
+ "cap-media",
+ "cap-project",
+ "chrono",
+ "cocoa 0.26.0",
+ "device_query",
+ "either",
+ "flume 0.11.0",
+ "image 0.25.2",
+ "objc",
"serde",
"serde_json",
"specta",
+ "thiserror",
+ "tokio",
+ "tracing",
]
[[package]]
@@ -862,7 +870,6 @@ version = "0.1.0"
dependencies = [
"anyhow",
"bytemuck",
- "cap-ffmpeg-cli",
"cap-flags",
"cap-project",
"ffmpeg-hw-device",
@@ -871,10 +878,8 @@ dependencies = [
"futures",
"futures-intrusive",
"image 0.25.2",
- "lru",
"nix 0.29.0",
"serde",
- "serde_json",
"specta",
"tokio",
"wgpu",
@@ -1695,13 +1700,13 @@ dependencies = [
"anyhow",
"axum",
"base64 0.22.1",
- "bytemuck",
"cap-editor",
"cap-export",
"cap-ffmpeg-cli",
"cap-flags",
"cap-media",
"cap-project",
+ "cap-recording",
"cap-rendering",
"cap-utils",
"chrono",
@@ -1711,18 +1716,14 @@ dependencies = [
"cpal 0.15.3 (git+https://github.com/RustAudio/cpal?rev=f43d36e55494993bbbde3299af0c53e5cdf4d4cf)",
"device_query",
"dotenvy_macro",
- "fast_image_resize",
"ffmpeg-next",
- "ffmpeg-sidecar 1.1.0 (git+https://github.com/CapSoftware/ffmpeg-sidecar?branch=main)",
"futures",
"futures-intrusive",
"global-hotkey",
"image 0.25.2",
- "indexmap 2.5.0",
"keyed_priority_queue",
"mp4",
"nix 0.29.0",
- "num-traits",
"objc",
"objc2-app-kit",
"png",
@@ -1738,7 +1739,6 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-nspanel",
- "tauri-plugin-decorum",
"tauri-plugin-dialog",
"tauri-plugin-fs",
"tauri-plugin-global-shortcut",
@@ -1756,7 +1756,6 @@ dependencies = [
"tokio",
"tracing",
"uuid",
- "wgpu",
"windows 0.58.0",
"windows-sys 0.59.0",
]
@@ -1877,15 +1876,6 @@ dependencies = [
"syn 2.0.85",
]
-[[package]]
-name = "dlv-list"
-version = "0.2.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "68df3f2b690c1b86e65ef7830956aededf3cb0a16f898f79b9a6f421a7b6211b"
-dependencies = [
- "rand 0.8.5",
-]
-
[[package]]
name = "document-features"
version = "0.2.10"
@@ -1996,19 +1986,6 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3d8a32ae18130a3c84dd492d4215c3d913c3b07c6b63c2eb3eb7ff1101ab7bf"
-[[package]]
-name = "enigo"
-version = "0.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "802e4b2ae123615659085369b453cba87c5562e46ed8050a909fee18a9bc3157"
-dependencies = [
- "core-graphics 0.23.2",
- "libc",
- "objc",
- "pkg-config",
- "windows 0.51.1",
-]
-
[[package]]
name = "enumflags2"
version = "0.7.10"
@@ -2106,18 +2083,6 @@ dependencies = [
"zune-inflate",
]
-[[package]]
-name = "fast_image_resize"
-version = "4.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2ca4b58827213977eabab8ee8d8258db8441338f3a1832a1c0f2de3372175531"
-dependencies = [
- "cfg-if 1.0.0",
- "document-features",
- "num-traits",
- "thiserror",
-]
-
[[package]]
name = "fastrand"
version = "2.1.1"
@@ -2151,23 +2116,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "ffmpeg-sidecar"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bec830aba6cd3da7621c58e8f06727e3b750e8383bcd934d789f2b9c3c4ea595"
-dependencies = [
- "anyhow",
-]
-
-[[package]]
-name = "ffmpeg-sidecar"
-version = "1.1.0"
-source = "git+https://github.com/CapSoftware/ffmpeg-sidecar?branch=main#a0f074c7efcb54111359f8ab800ce50b336b1897"
-dependencies = [
- "anyhow",
-]
-
[[package]]
name = "ffmpeg-sys-next"
version = "7.1.0"
@@ -2192,15 +2140,6 @@ dependencies = [
"rustc_version",
]
-[[package]]
-name = "file-locker"
-version = "1.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d6c3e69656680c6c3d76750b46dfa64bf07626bd2130c540d6cf2d306ba595a8"
-dependencies = [
- "nix 0.29.0",
-]
-
[[package]]
name = "filetime"
version = "0.2.25"
@@ -2314,16 +2253,6 @@ dependencies = [
"percent-encoding",
]
-[[package]]
-name = "freedesktop_entry_parser"
-version = "1.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "db9c27b72f19a99a895f8ca89e2d26e4ef31013376e56fdafef697627306c3e4"
-dependencies = [
- "nom 7.1.3",
- "thiserror",
-]
-
[[package]]
name = "futf"
version = "0.1.5"
@@ -2893,15 +2822,6 @@ dependencies = [
"crunchy",
]
-[[package]]
-name = "hashbrown"
-version = "0.9.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04"
-dependencies = [
- "ahash 0.4.8",
-]
-
[[package]]
name = "hashbrown"
version = "0.12.3"
@@ -2914,7 +2834,7 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
- "ahash 0.8.11",
+ "ahash",
"allocator-api2",
]
@@ -3640,29 +3560,6 @@ dependencies = [
"system-deps",
]
-[[package]]
-name = "linicon"
-version = "2.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ee8c5653188a809616c97296180a0547a61dba205bcdcbdd261dbd022a25fd9"
-dependencies = [
- "file-locker",
- "freedesktop_entry_parser",
- "linicon-theme",
- "memmap2",
- "thiserror",
-]
-
-[[package]]
-name = "linicon-theme"
-version = "1.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a4f8240c33bb08c5d8b8cdea87b683b05e61037aa76ff26bef40672cc6ecbb80"
-dependencies = [
- "freedesktop_entry_parser",
- "rust-ini",
-]
-
[[package]]
name = "linux-raw-sys"
version = "0.4.14"
@@ -3700,15 +3597,6 @@ dependencies = [
"imgref",
]
-[[package]]
-name = "lru"
-version = "0.12.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "37ee39891760e7d94734f6f63fedc29a2e4a152f836120753a72503f09fcf904"
-dependencies = [
- "hashbrown 0.14.5",
-]
-
[[package]]
name = "mac"
version = "0.1.1"
@@ -3797,15 +3685,6 @@ version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
-[[package]]
-name = "memmap2"
-version = "0.5.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "83faa42c0a078c393f6b29d5db232d8be22776a891f8f56e5284faee4a20b327"
-dependencies = [
- "libc",
-]
-
[[package]]
name = "memoffset"
version = "0.9.1"
@@ -4673,16 +4552,6 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
-[[package]]
-name = "ordered-multimap"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1c672c7ad9ec066e428c00eb917124a06f08db19e2584de982cc34b1f4c12485"
-dependencies = [
- "dlv-list",
- "hashbrown 0.9.1",
-]
-
[[package]]
name = "ordered-stream"
version = "0.2.0"
@@ -5623,16 +5492,6 @@ dependencies = [
"thiserror",
]
-[[package]]
-name = "rust-ini"
-version = "0.17.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "63471c4aa97a1cf8332a5f97709a79a4234698de6a1f5087faf66f2dae810e22"
-dependencies = [
- "cfg-if 1.0.0",
- "ordered-multimap",
-]
-
[[package]]
name = "rustc-demangle"
version = "0.1.24"
@@ -6693,23 +6552,6 @@ dependencies = [
"walkdir",
]
-[[package]]
-name = "tauri-plugin-decorum"
-version = "1.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "db925c61a04a937028bc91ad8ae64a93b84a1715b964530925a54e793d494999"
-dependencies = [
- "anyhow",
- "cocoa 0.25.0",
- "enigo",
- "linicon",
- "objc",
- "rand 0.8.5",
- "serde",
- "tauri",
- "tauri-plugin",
-]
-
[[package]]
name = "tauri-plugin-dialog"
version = "2.0.3"
@@ -8149,16 +7991,6 @@ dependencies = [
"windows-targets 0.48.5",
]
-[[package]]
-name = "windows"
-version = "0.51.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ca229916c5ee38c2f2bc1e9d8f04df975b4bd93f9955dc69fabb5d91270045c9"
-dependencies = [
- "windows-core 0.51.1",
- "windows-targets 0.48.5",
-]
-
[[package]]
name = "windows"
version = "0.52.0"
@@ -8211,15 +8043,6 @@ dependencies = [
"windows 0.58.0",
]
-[[package]]
-name = "windows-core"
-version = "0.51.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1f8cf84f35d2db49a46868f947758c7a1138116f7fac3bc844f43ade1292e64"
-dependencies = [
- "windows-targets 0.48.5",
-]
-
[[package]]
name = "windows-core"
version = "0.52.0"
diff --git a/Cargo.toml b/Cargo.toml
index e77bd9b4f..0512956d4 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -27,6 +27,8 @@ nokhwa = { git = "https://github.com/CapSoftware/nokhwa", rev = "0d3d1f30a78b",
] }
nokhwa-bindings-macos = { git = "https://github.com/CapSoftware/nokhwa", rev = "0d3d1f30a78b" }
wgpu = "22.1.0"
+flume = "0.11.0"
+thiserror = "1.0"
windows = "0.58.0"
windows-sys = "0.59.0"
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index d5ed00620..ec2277a3a 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -28,7 +28,6 @@ tauri-plugin-shell = "2.0.0"
tauri-plugin-store = "2.0.0"
tauri-plugin-os = "2.0.0"
tauri-plugin-process = "2.0.0"
-tauri-plugin-decorum = "1.0.0"
tauri-plugin-dialog = "2.0.0"
tauri-plugin-updater = "2.0.0"
tauri-plugin-notification = "2.0.0-rc"
@@ -42,28 +41,21 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
specta.workspace = true
specta-typescript = "0.0.7"
-swift-rs = "1.0.6"
-nix = { version = "0.29.0", features = ["fs"] }
tokio.workspace = true
uuid = { version = "1.10.0", features = ["v4"] }
scap.workspace = true
-ffmpeg-sidecar = { git = "https://github.com/CapSoftware/ffmpeg-sidecar", branch = "main" }
-wgpu.workspace = true
-bytemuck = { version = "1.7", features = ["derive"] }
image = "0.25.2"
+mp4 = "0.14.0"
tauri-plugin-fs = "2.0.0-rc.0"
futures-intrusive = "0.5.0"
anyhow.workspace = true
futures = "0.3"
axum = { version = "0.7.5", features = ["ws"] }
tracing = "0.1.40"
-indexmap = "2.5.0"
-num-traits = "0.2.19"
tempfile = "3.12.0"
ffmpeg.workspace = true
chrono = "0.4.38"
rodio = "0.19.0"
-fast_image_resize = "4.2.1"
png = "0.17.13"
device_query = "2.1.0"
base64 = "0.22.1"
@@ -73,7 +65,6 @@ global-hotkey = "0.6.3"
rand = "0.8.5"
cpal.workspace = true
keyed_priority_queue = "0.4.2"
-mp4 = "0.14.0"
cap-utils = { path = "../../../crates/utils" }
cap-project = { path = "../../../crates/project" }
@@ -82,6 +73,7 @@ cap-ffmpeg-cli = { path = "../../../crates/ffmpeg-cli" }
cap-editor = { path = "../../../crates/editor" }
cap-media = { path = "../../../crates/media" }
cap-flags = { path = "../../../crates/flags" }
+cap-recording = { path = "../../../crates/recording" }
cap-export = { path = "../../../crates/export" }
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json
index 4a3ca09ec..3e84e0d14 100644
--- a/apps/desktop/src-tauri/capabilities/default.json
+++ b/apps/desktop/src-tauri/capabilities/default.json
@@ -22,12 +22,7 @@
"core:webview:allow-create-webview-window",
"core:app:allow-version",
"shell:default",
- "fs:default",
- "fs:read-files",
- "fs:allow-picture-read",
- "fs:allow-font-meta",
"core:image:default",
- "fs:allow-audio-read",
"dialog:default",
"store:default",
"process:default",
diff --git a/apps/desktop/src-tauri/src/fake_window.rs b/apps/desktop/src-tauri/src/fake_window.rs
new file mode 100644
index 000000000..6428ae42e
--- /dev/null
+++ b/apps/desktop/src-tauri/src/fake_window.rs
@@ -0,0 +1,42 @@
+use cap_media::platform::Bounds;
+use std::{collections::HashMap, sync::Arc};
+use tokio::sync::RwLock;
+
+pub struct FakeWindowBounds(pub Arc<RwLock<HashMap<String, HashMap<String, Bounds>>>>);
+
+#[tauri::command]
+#[specta::specta]
+pub async fn set_fake_window_bounds(
+ window: tauri::Window,
+ name: String,
+ bounds: Bounds,
+ state: tauri::State<'_, FakeWindowBounds>,
+) -> Result<(), String> {
+ let mut state = state.0.write().await;
+ let map = state.entry(window.label().to_string()).or_default();
+
+ map.insert(name, bounds);
+
+ Ok(())
+}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn remove_fake_window(
+ window: tauri::Window,
+ name: String,
+ state: tauri::State<'_, FakeWindowBounds>,
+) -> Result<(), String> {
+ let mut state = state.0.write().await;
+ let Some(map) = state.get_mut(window.label()) else {
+ return Ok(());
+ };
+
+ map.remove(&name);
+
+ if map.is_empty() {
+ state.remove(window.label());
+ }
+
+ Ok(())
+}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 11ddbe30c..19b7e067c 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -10,7 +10,7 @@ mod platform;
mod recording;
// mod resource;
mod audio_meter;
-mod cursor;
+mod fake_window;
mod tray;
mod upload;
mod web_api;
@@ -23,19 +23,18 @@ use cap_editor::{EditorState, ProjectRecordings};
use cap_media::feeds::{AudioInputFeed, AudioInputSamplesSender};
use cap_media::sources::CaptureScreen;
use cap_media::{
- feeds::{CameraFeed, CameraFrameSender},
- platform::Bounds,
+ feeds::{AudioFrameBuffer, CameraFeed, CameraFrameSender},
sources::ScreenCaptureTarget,
};
-use cap_project::{
- ProjectConfiguration, RecordingMeta, SharingMeta, TimelineConfiguration, TimelineSegment,
- ZoomSegment,
-};
-use cap_rendering::ZOOM_DURATION;
+use cap_project::{ProjectConfiguration, RecordingMeta, SharingMeta};
+use cap_recording::RecordingOptions;
+use cap_rendering::ProjectUniforms;
+use fake_window::FakeWindowBounds;
+// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use general_settings::GeneralSettingsStore;
use mp4::Mp4Reader;
+use notifications::NotificationType;
use png::{ColorType, Encoder};
-use recording::{list_cameras, list_capture_screens, list_capture_windows, InProgressRecording};
use scap::capturer::Capturer;
use scap::frame::Frame;
use serde::{Deserialize, Serialize};
@@ -43,18 +42,15 @@ use serde_json::json;
use specta::Type;
use std::fs::File;
use std::io::BufWriter;
-use std::io::{BufReader, Write};
use std::str::FromStr;
-use std::time::{Instant, SystemTime, UNIX_EPOCH};
use std::{
- collections::HashMap, marker::PhantomData, path::PathBuf, process::Command, sync::Arc,
- time::Duration,
+ collections::HashMap, io::BufReader, marker::PhantomData, path::PathBuf, process::Command,
+ sync::Arc, time::Duration,
};
use tauri::{AppHandle, Emitter, Manager, Runtime, State, WindowEvent};
use tauri_plugin_notification::{NotificationExt, PermissionState};
use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
-use tokio::io::AsyncWriteExt;
use tokio::{
sync::{Mutex, RwLock},
time::sleep,
@@ -62,24 +58,6 @@ use tokio::{
use upload::{get_s3_config, upload_image, upload_video, S3UploadMeta};
use windows::{CapWindowId, ShowCapWindow};
-#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
-#[serde(rename_all = "camelCase")]
-pub struct RecordingOptions {
- capture_target: ScreenCaptureTarget,
- camera_label: Option<String>,
- audio_input_name: Option<String>,
-}
-
-impl RecordingOptions {
- fn camera_label(&self) -> Option<&str> {
- self.camera_label.as_deref()
- }
-
- fn audio_input_name(&self) -> Option<&str> {
- self.audio_input_name.as_deref()
- }
-}
-
#[derive(specta::Type, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct App {
@@ -88,7 +66,7 @@ pub struct App {
camera_tx: CameraFrameSender,
camera_ws_port: u16,
#[serde(skip)]
- camera_feed: Option<CameraFeed>,
+ camera_feed: Option<Arc<Mutex<CameraFeed>>>,
#[serde(skip)]
audio_input_feed: Option<AudioInputFeed>,
#[serde(skip)]
@@ -96,7 +74,7 @@ pub struct App {
#[serde(skip)]
handle: AppHandle,
#[serde(skip)]
- current_recording: Option<InProgressRecording>,
+ current_recording: Option<cap_recording::ActorHandle>,
#[serde(skip)]
pre_created_video: Option<PreCreatedVideo>,
}
@@ -124,24 +102,25 @@ struct PreCreatedVideo {
}
impl App {
- pub fn set_current_recording(&mut self, new_value: InProgressRecording) {
- let option = Some(new_value);
- let json = JsonValue::new(&option);
-
- let new_value = option.unwrap();
-
- let current_recording = self.current_recording.insert(new_value);
-
- CurrentRecordingChanged(json).emit(&self.handle).ok();
-
- if let ScreenCaptureTarget::Window { .. } = &current_recording.display_source {
+ pub fn set_current_recording(
+ &mut self,
+ actor: cap_recording::ActorHandle, /* new_value: InProgressRecording */
+ ) {
+ let current_recording = self.current_recording.insert(actor);
+
+ CurrentRecordingChanged.emit(&self.handle).ok();
+
+ if matches!(
+ current_recording.options.capture_target,
+ ScreenCaptureTarget::Window(_)
+ ) {
let _ = ShowCapWindow::WindowCaptureOccluder.show(&self.handle);
} else {
self.close_occluder_window();
}
}
- pub fn clear_current_recording(&mut self) -> Option<InProgressRecording> {
+ pub fn clear_current_recording(&mut self) -> Option<cap_recording::ActorHandle> {
self.close_occluder_window();
self.current_recording.take()
@@ -155,11 +134,11 @@ impl App {
async fn set_start_recording_options(&mut self, new_options: RecordingOptions) {
match CapWindowId::Camera.get(&self.handle) {
- Some(window) if new_options.camera_label.is_none() => {
+ Some(window) if new_options.camera_label().is_none() => {
println!("closing camera window");
window.close().ok();
}
- None if new_options.camera_label.is_some() => {
+ None if new_options.camera_label().is_some() => {
println!("creating camera window");
ShowCapWindow::Camera {
ws_port: self.camera_ws_port,
@@ -172,8 +151,10 @@ impl App {
match new_options.camera_label() {
Some(camera_label) => {
- if let Some(camera_feed) = self.camera_feed.as_mut() {
+ if let Some(camera_feed) = self.camera_feed.as_ref() {
camera_feed
+ .lock()
+ .await
.switch_cameras(camera_label)
.await
.map_err(|error| eprintln!("{error}"))
@@ -181,6 +162,8 @@ impl App {
} else {
self.camera_feed = CameraFeed::init(camera_label, self.camera_tx.clone())
.await
+ .map(Mutex::new)
+ .map(Arc::new)
.map_err(|error| eprintln!("{error}"))
.ok();
}
@@ -314,332 +297,27 @@ impl<T: Serialize> JsonValue<T> {
}
}
+#[derive(Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct RecordingInfo {
+ capture_target: ScreenCaptureTarget,
+}
+
#[tauri::command]
#[specta::specta]
async fn get_current_recording(
state: MutableState<'_, App>,
-) -> Result<JsonValue<Option<InProgressRecording>>, ()> {
+) -> Result<JsonValue<Option<RecordingInfo>>, ()> {
let state = state.read().await;
- Ok(JsonValue::new(&state.current_recording))
-}
-
-#[derive(Serialize, Type, tauri_specta::Event, Clone)]
-pub struct CurrentRecordingChanged(JsonValue<Option<InProgressRecording>>);
-
-#[tauri::command]
-#[specta::specta]
-async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
- let mut state = state.write().await;
-
- let id = uuid::Uuid::new_v4().to_string();
-
- let recording_dir = app
- .path()
- .app_data_dir()
- .unwrap()
- .join("recordings")
- .join(format!("{id}.cap"));
-
- // Check if auto_create_shareable_link is true and user is upgraded
- let general_settings = GeneralSettingsStore::get(&app)?;
- let auto_create_shareable_link = general_settings
- .map(|settings| settings.auto_create_shareable_link)
- .unwrap_or(false);
-
- if auto_create_shareable_link {
- if let Ok(Some(auth)) = AuthStore::get(&app) {
- if auth.is_upgraded() {
- // Pre-create the video and get the shareable link
- if let Ok(s3_config) = get_s3_config(&app, false, None).await {
- let link = web_api::make_url(format!("/s/{}", s3_config.id()));
-
- state.pre_created_video = Some(PreCreatedVideo {
- id: s3_config.id().to_string(),
- link: link.clone(),
- config: s3_config,
- });
-
- println!("Pre-created shareable link: {}", link);
- };
- }
- }
- }
-
- match recording::start(
- id,
- recording_dir,
- &state.start_recording_options,
- state.camera_feed.as_ref(),
- state.audio_input_feed.as_ref(),
- )
- .await
- {
- Ok(recording) => state.set_current_recording(recording),
- Err(error) => {
- eprintln!("{error}");
- return Err(format!("Failed to set up recording: {error}"));
+ Ok(JsonValue::new(&state.current_recording.as_ref().map(|r| {
+ RecordingInfo {
+ capture_target: r.options.capture_target.clone(),
}
- };
-
- if let Some(window) = CapWindowId::Main.get(&app) {
- window.minimize().ok();
- }
-
- if let Some(window) = CapWindowId::InProgressRecording.get(&app) {
- window.eval("window.location.reload()").unwrap();
- window.show().unwrap();
- } else {
- ShowCapWindow::InProgressRecording { position: None }
- .show(&app)
- .ok();
- }
-
- AppSounds::StartRecording.play();
-
- RecordingStarted.emit(&app).ok();
-
- Ok(())
+ })))
}
-#[tauri::command]
-#[specta::specta]
-async fn pause_recording(state: MutableState<'_, App>) -> Result<(), String> {
- let mut state = state.write().await;
-
- if let Some(recording) = &mut state.current_recording {
- recording.pause().await?;
- recording.segments.push(
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap()
- .as_secs_f64(),
- );
- }
- Ok(())
-}
-
-#[tauri::command]
-#[specta::specta]
-async fn resume_recording(state: MutableState<'_, App>) -> Result<(), String> {
- let mut state = state.write().await;
-
- if let Some(recording) = &mut state.current_recording {
- recording.play().await?;
- recording.segments.push(
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap()
- .as_secs_f64(),
- );
- }
- Ok(())
-}
-
-#[tauri::command]
-#[specta::specta]
-async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
- let mut state = state.write().await;
- let Some(mut current_recording) = state.clear_current_recording() else {
- return Err("Recording not in progress".to_string());
- };
-
- current_recording.segments.push(
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap()
- .as_secs_f64(),
- );
-
- let now = Instant::now();
- let recording = current_recording.stop().await;
- println!("stopped recording in {:?}", now.elapsed());
-
- if let Some(window) = CapWindowId::InProgressRecording.get(&app) {
- window.hide().unwrap();
- }
-
- if let Some(window) = CapWindowId::Main.get(&app) {
- window.unminimize().ok();
- }
-
- let screenshots_dir = recording.recording_dir.join("screenshots");
- std::fs::create_dir_all(&screenshots_dir).ok();
-
- let display_screenshot = screenshots_dir.join("display.jpg");
- let now = Instant::now();
- create_screenshot(
- recording.display_output_path.clone(),
- display_screenshot.clone(),
- None,
- )
- .await?;
- println!("created screenshot in {:?}", now.elapsed());
-
- // let thumbnail = screenshots_dir.join("thumbnail.png");
- // let now = Instant::now();
- // create_thumbnail(display_screenshot, thumbnail, (100, 100)).await?;
- // println!("created thumbnail in {:?}", now.elapsed());
-
- let recording_dir = recording.recording_dir.clone();
-
- ShowCapturesPanel.emit(&app).ok();
-
- NewRecordingAdded {
- path: recording_dir.clone(),
- }
- .emit(&app)
- .ok();
-
- RecordingStopped {
- path: recording_dir,
- }
- .emit(&app)
- .ok();
-
- let recordings = ProjectRecordings::new(&recording.meta);
- let max_duration = recordings.duration();
-
- let config = {
- let segments = {
- let mut segments = vec![];
- let mut passed_duration = 0.0;
-
- for i in (0..recording.segments.len()).step_by(2) {
- let start = passed_duration;
- passed_duration += recording.segments[i + 1] - recording.segments[i];
- segments.push(TimelineSegment {
- start,
- end: passed_duration.min(recordings.duration()),
- timescale: 1.0,
- });
- }
- segments
- };
-
- let zoom_segments = {
- let mut segments = vec![];
-
- const ZOOM_SEGMENT_AFTER_CLICK_PADDING: f64 = 1.5;
-
- for click in &recording.cursor_data.clicks {
- let time = click.process_time_ms / 1000.0;
-
- if segments.last().is_none() {
- segments.push(ZoomSegment {
- start: (click.process_time_ms / 1000.0 - (ZOOM_DURATION + 0.2)).max(0.0),
- end: click.process_time_ms / 1000.0 + ZOOM_SEGMENT_AFTER_CLICK_PADDING,
- amount: 2.0,
- });
- } else {
- let last_segment = segments.last_mut().unwrap();
-
- if click.down {
- if last_segment.end > time {
- last_segment.end = (time + ZOOM_SEGMENT_AFTER_CLICK_PADDING)
- .min(recordings.duration());
- } else if time < max_duration - ZOOM_DURATION {
- segments.push(ZoomSegment {
- start: (time - ZOOM_DURATION).max(0.0),
- end: time + ZOOM_SEGMENT_AFTER_CLICK_PADDING,
- amount: 2.0,
- });
- }
- } else {
- last_segment.end =
- (time + ZOOM_SEGMENT_AFTER_CLICK_PADDING).min(recordings.duration());
- }
- }
- }
-
- segments
- };
-
- ProjectConfiguration {
- timeline: Some(TimelineConfiguration {
- segments,
- zoom_segments,
- }),
- ..Default::default()
- }
- };
-
- config.write(&recording.recording_dir).unwrap();
-
- AppSounds::StopRecording.play();
-
- if let Some((settings, auth)) = GeneralSettingsStore::get(&app)
- .ok()
- .flatten()
- .zip(AuthStore::get(&app).ok().flatten())
- {
- if auth.is_upgraded() && settings.auto_create_shareable_link {
- if let Some(pre_created_video) = state.pre_created_video.take() {
- // Copy link to clipboard
- #[cfg(target_os = "macos")]
- platform::write_string_to_pasteboard(&pre_created_video.link);
-
- // Send notification for shareable link
- notifications::send_notification(
- &app,
- notifications::NotificationType::ShareableLinkCopied,
- );
-
- // Open the pre-created shareable link
- open_external_link(app.clone(), pre_created_video.link.clone()).ok();
-
- // Start the upload process in the background with retry mechanism
- let app_clone = app.clone();
-
- tauri::async_runtime::spawn(async move {
- let max_retries = 3;
- let mut retry_count = 0;
-
- while retry_count < max_retries {
- match upload_rendered_video(
- app_clone.clone(),
- recording.id.clone(),
- ProjectConfiguration::default(),
- Some(pre_created_video.clone()),
- )
- .await
- {
- Ok(_) => {
- println!("Video uploaded successfully");
- // Don't send notification here since we already did it above
- break;
- }
- Err(e) => {
- retry_count += 1;
- println!(
- "Error during auto-upload (attempt {}/{}): {}",
- retry_count, max_retries, e
- );
-
- if retry_count < max_retries {
- tokio::time::sleep(std::time::Duration::from_secs(5)).await;
- } else {
- println!("Max retries reached. Upload failed.");
- notifications::send_notification(
- &app_clone,
- notifications::NotificationType::UploadFailed,
- );
- }
- }
- }
- }
- });
- }
- } else if settings.open_editor_after_recording {
- open_editor(app.clone(), recording.id);
- }
- }
-
- CurrentRecordingChanged(JsonValue::new(&None))
- .emit(&app)
- .ok();
-
- Ok(())
-}
+#[derive(Serialize, Type, tauri_specta::Event, Clone)]
+pub struct CurrentRecordingChanged; // (JsonValue<Option<InProgressRecording>>);
async fn create_screenshot(
input: PathBuf,
@@ -1256,45 +934,6 @@ async fn get_video_metadata(
Ok((duration, size))
}
-struct FakeWindowBounds(pub Arc<RwLock<HashMap<String, HashMap<String, Bounds>>>>);
-
-#[tauri::command]
-#[specta::specta]
-async fn set_fake_window_bounds(
- window: tauri::Window,
- name: String,
- bounds: Bounds,
- state: tauri::State<'_, FakeWindowBounds>,
-) -> Result<(), String> {
- let mut state = state.0.write().await;
- let map = state.entry(window.label().to_string()).or_default();
-
- map.insert(name, bounds);
-
- Ok(())
-}
-
-#[tauri::command]
-#[specta::specta]
-async fn remove_fake_window(
- window: tauri::Window,
- name: String,
- state: tauri::State<'_, FakeWindowBounds>,
-) -> Result<(), String> {
- let mut state = state.0.write().await;
- let Some(map) = state.get_mut(window.label()) else {
- return Ok(());
- };
-
- map.remove(&name);
-
- if map.is_empty() {
- state.remove(window.label());
- }
-
- Ok(())
-}
-
// #[tauri::command(async)]
// #[specta::specta]
// fn show_notifications_window(app: AppHandle) {
@@ -1560,7 +1199,6 @@ async fn upload_rendered_video(
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
let mut meta = editor_instance.meta();
- // Emit initial rendering progress
UploadProgress {
stage: "rendering".to_string(),
progress: 0.0,
@@ -1628,10 +1266,7 @@ async fn upload_rendered_video(
meta.save_for_project();
RecordingMetaChanged { id: video_id }.emit(&app).ok();
- notifications::send_notification(
- &app,
- notifications::NotificationType::ShareableLinkCopied,
- );
+ NotificationType::ShareableLinkCopied.send(&app);
#[cfg(target_os = "macos")]
platform::write_string_to_pasteboard(&uploaded_video.link);
@@ -1639,7 +1274,7 @@ async fn upload_rendered_video(
Ok(UploadResult::Success(uploaded_video.link))
}
Err(e) => {
- notifications::send_notification(&app, notifications::NotificationType::UploadFailed);
+ NotificationType::UploadFailed.send(&app);
Err(e)
}
}
@@ -2172,19 +1807,19 @@ pub async fn run() {
.commands(tauri_specta::collect_commands![
get_recording_options,
set_recording_options,
- start_recording,
- stop_recording,
- pause_recording,
- resume_recording,
+ recording::start_recording,
+ recording::stop_recording,
+ recording::pause_recording,
+ recording::resume_recording,
+ recording::list_cameras,
+ recording::list_capture_windows,
+ recording::list_capture_screens,
take_screenshot,
- list_cameras,
- list_capture_windows,
- list_capture_screens,
list_audio_devices,
show_previous_recordings_window,
close_previous_recordings_window,
- set_fake_window_bounds,
- remove_fake_window,
+ fake_window::set_fake_window_bounds,
+ fake_window::remove_fake_window,
focus_captures_panel,
get_current_recording,
render_to_file,
@@ -2307,6 +1942,7 @@ pub async fn run() {
let permissions = permissions::do_permissions_check(false);
println!("Permissions check result: {:?}", permissions);
+ ShowCapWindow::Setup.show(&app_handle).ok();
if !permissions.screen_recording.permitted()
|| !permissions.accessibility.permitted()
|| GeneralSettingsStore::get(app.handle())
@@ -2358,12 +1994,13 @@ pub async fn run() {
};
if is_recording {
- if let Err(e) = stop_recording(app_handle.clone(), app_handle.state()).await
+ if let Err(e) =
+ recording::stop_recording(app_handle.clone(), app_handle.state()).await
{
eprintln!("Failed to stop recording: {}", e);
}
} else if let Err(e) =
- start_recording(app_handle.clone(), app_handle.state()).await
+ recording::start_recording(app_handle.clone(), app_handle.state()).await
{
eprintln!("Failed to start recording: {}", e);
}
@@ -2374,7 +2011,9 @@ pub async fn run() {
RequestStopRecording::listen_any(app, move |_| {
let app_handle = app_handle_clone.clone();
tauri::async_runtime::spawn(async move {
- if let Err(e) = stop_recording(app_handle.clone(), app_handle.state()).await {
+ if let Err(e) =
+ recording::stop_recording(app_handle.clone(), app_handle.state()).await
+ {
eprintln!("Failed to stop recording: {}", e);
}
});
@@ -2389,16 +2028,18 @@ pub async fn run() {
// Stop and discard the current recording
{
let mut app_state = state.write().await;
- if let Some(mut recording) = app_state.clear_current_recording() {
- CurrentRecordingChanged(JsonValue::new(&None))
+ if let Some(recording) = app_state.clear_current_recording() {
+ CurrentRecordingChanged /*(JsonValue::new(&None))*/
.emit(&app_handle)
.ok();
- recording.stop_and_discard();
+ recording.stop().await.ok();
+
+ // recording.stop_and_discard();
}
}
- if let Err(e) = start_recording(app_handle.clone(), state).await {
+ if let Err(e) = recording::start_recording(app_handle.clone(), state).await {
eprintln!("Failed to start new recording: {}", e);
} else {
println!("New recording started successfully");
diff --git a/apps/desktop/src-tauri/src/notifications.rs b/apps/desktop/src-tauri/src/notifications.rs
index 7024de2f8..dcbc74af9 100644
--- a/apps/desktop/src-tauri/src/notifications.rs
+++ b/apps/desktop/src-tauri/src/notifications.rs
@@ -79,6 +79,10 @@ impl NotificationType {
_ => "",
}
}
+
+ pub fn send(self, app: &tauri::AppHandle) {
+ send_notification(app, self);
+ }
}
pub fn send_notification(app: &tauri::AppHandle, notification_type: NotificationType) {
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 6ad4eb1e5..c44a44cf1 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1,20 +1,21 @@
-use cap_flags::FLAGS;
-use cap_media::{encoders::*, feeds::*, filters::*, pipeline::*, sources::*, MediaError};
-use cap_project::{CursorClickEvent, CursorMoveEvent, RecordingMeta};
-use serde::Serialize;
-use specta::Type;
-use std::collections::HashMap;
-use std::fs::File;
-use std::path::PathBuf;
-use std::sync::atomic::AtomicBool;
-use std::sync::Arc;
-use std::time::{SystemTime, UNIX_EPOCH};
-use tokio::sync::oneshot;
-
-use crate::RecordingOptions;
-
-// TODO: Hacky, please fix
-pub const FPS: u32 = 30;
+use crate::audio::AppSounds;
+use crate::auth::AuthStore;
+use crate::general_settings::GeneralSettingsStore;
+use crate::upload::get_s3_config;
+use crate::windows::{CapWindowId, ShowCapWindow};
+use crate::{
+ create_screenshot, notifications, open_editor, open_external_link, platform,
+ upload_rendered_video, web_api, App, CurrentRecordingChanged, MutableState, NewRecordingAdded,
+ PreCreatedVideo, RecordingStarted, RecordingStopped, ShowCapturesPanel,
+};
+use cap_editor::ProjectRecordings;
+use cap_media::feeds::CameraFeed;
+use cap_media::sources::{AVFrameCapture, CaptureScreen, CaptureWindow, ScreenCaptureSource};
+use cap_project::{ProjectConfiguration, TimelineConfiguration, TimelineSegment, ZoomSegment};
+use cap_rendering::ZOOM_DURATION;
+use std::time::Instant;
+use tauri::{AppHandle, Manager};
+use tauri_specta::Event;
#[tauri::command(async)]
#[specta::specta]
@@ -34,284 +35,294 @@ pub fn list_cameras() -> Vec<String> {
CameraFeed::list_cameras()
}
-#[derive(Type, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct InProgressRecording {
- pub id: String,
- pub recording_dir: PathBuf,
- #[serde(skip)]
- pub pipeline: Pipeline<RealTimeClock<()>>,
- #[serde(skip)]
- pub display_output_path: PathBuf,
- #[serde(skip)]
- pub camera_output_path: Option<PathBuf>,
- #[serde(skip)]
- pub audio_output_path: Option<PathBuf>,
- pub display_source: ScreenCaptureTarget,
- pub segments: Vec<f64>,
- #[serde(skip)]
- pub cursor_moves: oneshot::Receiver<Vec<CursorMoveEvent>>,
- #[serde(skip)]
- pub cursor_clicks: oneshot::Receiver<Vec<CursorClickEvent>>,
- #[serde(skip)]
- pub stop_signal: Arc<AtomicBool>,
-}
+#[tauri::command]
+#[specta::specta]
+pub async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
+ let mut state = state.write().await;
+
+ let id = uuid::Uuid::new_v4().to_string();
+
+ let recording_dir = app
+ .path()
+ .app_data_dir()
+ .unwrap()
+ .join("recordings")
+ .join(format!("{id}.cap"));
+
+ // Check if auto_create_shareable_link is true and user is upgraded
+ let general_settings = GeneralSettingsStore::get(&app)?;
+ let auto_create_shareable_link = general_settings
+ .map(|settings| settings.auto_create_shareable_link)
+ .unwrap_or(false);
+
+ if auto_create_shareable_link {
+ if let Ok(Some(auth)) = AuthStore::get(&app) {
+ if auth.is_upgraded() {
+ // Pre-create the video and get the shareable link
+ if let Ok(s3_config) = get_s3_config(&app, false, None).await {
+ let link = web_api::make_url(format!("/s/{}", s3_config.id()));
+
+ state.pre_created_video = Some(PreCreatedVideo {
+ id: s3_config.id().to_string(),
+ link: link.clone(),
+ config: s3_config,
+ });
+
+ println!("Pre-created shareable link: {}", link);
+ };
+ }
+ }
+ }
-unsafe impl Send for InProgressRecording {}
-unsafe impl Sync for InProgressRecording {}
-
-pub struct CompletedRecording {
- pub id: String,
- pub recording_dir: PathBuf,
- pub display_output_path: PathBuf,
- pub camera_output_path: Option<PathBuf>,
- pub audio_output_path: Option<PathBuf>,
- pub display_source: ScreenCaptureTarget,
- pub segments: Vec<f64>,
- pub meta: RecordingMeta,
- pub cursor_data: cap_project::CursorData,
-}
+ let actor = cap_recording::spawn_recording_actor(
+ id,
+ recording_dir,
+ state.start_recording_options.clone(),
+ state.camera_feed.clone(),
+ state.audio_input_feed.clone(),
+ )
+ .await
+ .map_err(|e| e.to_string())?;
-impl InProgressRecording {
- pub async fn stop(mut self) -> CompletedRecording {
- use cap_project::*;
-
- let meta = RecordingMeta {
- project_path: self.recording_dir.clone(),
- sharing: None,
- pretty_name: format!(
- "Cap {}",
- chrono::Local::now().format("%Y-%m-%d at %H.%M.%S")
- ),
- display: Display {
- path: self
- .display_output_path
- .strip_prefix(&self.recording_dir)
- .unwrap()
- .to_owned(),
- },
- camera: self.camera_output_path.as_ref().map(|path| CameraMeta {
- path: path.strip_prefix(&self.recording_dir).unwrap().to_owned(),
- }),
- audio: self.audio_output_path.as_ref().map(|path| AudioMeta {
- path: path.strip_prefix(&self.recording_dir).unwrap().to_owned(),
- }),
- segments: {
- let relative_segments = self
- .segments
- .iter()
- .map(|s| s - self.segments[0])
- .collect::<Vec<_>>();
-
- let mut segments = vec![];
-
- let mut diff = 0.0;
-
- for (i, chunk) in relative_segments.chunks_exact(2).enumerate() {
- if i < relative_segments.len() / 2 {
- segments.push(RecordingSegment {
- start: diff,
- end: chunk[1] - chunk[0] + diff,
- });
- }
+ state.set_current_recording(actor);
- diff += chunk[1] - chunk[0];
- }
+ if let Some(window) = CapWindowId::Main.get(&app) {
+ window.minimize().ok();
+ }
- segments
- },
- cursor: Some(PathBuf::from("cursor.json")),
- };
+ if let Some(window) = CapWindowId::InProgressRecording.get(&app) {
+ window.eval("window.location.reload()").unwrap();
+ window.show().unwrap();
+ } else {
+ ShowCapWindow::InProgressRecording { position: None }
+ .show(&app)
+ .ok();
+ }
- // Signal the mouse event tracking to stop
- if let Err(error) = self.pipeline.shutdown().await {
- eprintln!("Error while stopping recording: {error}");
- }
+ AppSounds::StartRecording.play();
- self.stop_signal
- .store(true, std::sync::atomic::Ordering::Relaxed);
+ RecordingStarted.emit(&app).ok();
- let cursor_data = cap_project::CursorData {
- clicks: self.cursor_clicks.await.unwrap(),
- moves: self.cursor_moves.await.unwrap(),
- cursor_images: HashMap::new(), // This will be populated during recording
- };
+ Ok(())
+}
- if FLAGS.record_mouse {
- // Save mouse events to files
- let mut file = File::create(self.recording_dir.join("cursor.json")).unwrap();
- serde_json::to_writer_pretty(&mut file, &cursor_data).unwrap();
- }
+#[tauri::command]
+#[specta::specta]
+pub async fn pause_recording(state: MutableState<'_, App>) -> Result<(), String> {
+ let state = state.write().await;
- meta.save_for_project();
-
- CompletedRecording {
- id: self.id,
- recording_dir: self.recording_dir,
- display_output_path: self.display_output_path,
- camera_output_path: self.camera_output_path,
- audio_output_path: self.audio_output_path,
- display_source: self.display_source,
- segments: self.segments,
- meta,
- cursor_data,
- }
- }
+ // if let Some(recording) = &mut state.current_recording {
+ // recording.pause().await.map_err(|e| e.to_string())?;
+ // }
+ Ok(())
+}
- pub async fn stop_and_discard(&mut self) {
- // Signal the mouse event tracking to stop
- if let Err(error) = self.pipeline.shutdown().await {
- eprintln!("Error while stopping recording: {error}");
- }
+#[tauri::command]
+#[specta::specta]
+pub async fn resume_recording(state: MutableState<'_, App>) -> Result<(), String> {
+ let state = state.write().await;
- // Delete all recorded files
- if let Err(e) = std::fs::remove_dir_all(&self.recording_dir) {
- eprintln!("Failed to delete recording directory: {:?}", e);
- }
- }
+ // if let Some(recording) = &mut state.current_recording {
+ // recording.resume().await.map_err(|e| e.to_string())?;
+ // }
+ Ok(())
+}
- pub async fn pause(&mut self) -> Result<(), String> {
- let _ = self.pipeline.pause().await;
- Ok(())
+#[tauri::command]
+#[specta::specta]
+pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
+ let mut state = state.write().await;
+ let Some(current_recording) = state.clear_current_recording() else {
+ return Err("Recording not in progress".to_string())?;
+ };
+
+ let now = Instant::now();
+ let recording = current_recording.stop().await.map_err(|e| e.to_string())?;
+ println!("stopped recording in {:?}", now.elapsed());
+
+ if let Some(window) = CapWindowId::InProgressRecording.get(&app) {
+ window.hide().unwrap();
}
- pub async fn play(&mut self) -> Result<(), String> {
- let _ = self.pipeline.play().await;
- Ok(())
+ if let Some(window) = CapWindowId::Main.get(&app) {
+ window.unminimize().ok();
}
-}
-pub async fn start(
- id: String,
- recording_dir: PathBuf,
- recording_options: &RecordingOptions,
- camera_feed: Option<&CameraFeed>,
- audio_input_feed: Option<&AudioInputFeed>,
-) -> Result<InProgressRecording, MediaError> {
- let content_dir = recording_dir.join("content");
- let cursors_dir = content_dir.join("cursors");
+ let screenshots_dir = recording.recording_dir.join("screenshots");
+ std::fs::create_dir_all(&screenshots_dir).ok();
- std::fs::create_dir_all(&content_dir).unwrap();
- std::fs::create_dir_all(&cursors_dir).unwrap();
+ let display_screenshot = screenshots_dir.join("display.jpg");
+ let now = Instant::now();
+ create_screenshot(
+ recording.display_output_path.clone(),
+ display_screenshot.clone(),
+ None,
+ )
+ .await?;
+ println!("created screenshot in {:?}", now.elapsed());
- let clock = RealTimeClock::<()>::new();
- let mut pipeline_builder = Pipeline::builder(clock);
+ // let thumbnail = screenshots_dir.join("thumbnail.png");
+ // let now = Instant::now();
+ // create_thumbnail(display_screenshot, thumbnail, (100, 100)).await?;
+ // println!("created thumbnail in {:?}", now.elapsed());
- let display_output_path = content_dir.join("display.mp4");
- let mut audio_output_path = None;
- let mut camera_output_path = None;
+ let recording_dir = recording.recording_dir.clone();
- #[cfg(target_os = "macos")]
- {
- let screen_source = ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(
- dbg!(&recording_options.capture_target),
- None,
- None,
- );
- let screen_config = screen_source.info();
-
- let output_config = screen_config.scaled(1920, 30);
- let screen_encoder = cap_media::encoders::H264AVAssetWriterEncoder::init(
- "screen",
- output_config,
- Output::File(display_output_path.clone()),
- )?;
- pipeline_builder = pipeline_builder
- .source("screen_capture", screen_source)
- .sink("screen_capture_encoder", screen_encoder);
- }
- #[cfg(not(target_os = "macos"))]
- {
- let screen_source = ScreenCaptureSource::<AVFrameCapture>::init(
- dbg!(&recording_options.capture_target),
- None,
- None,
- );
- let screen_config = screen_source.info();
- // let screen_bounds = screen_source.bounds;
-
- let output_config = screen_config.scaled(1920, 30);
- let screen_filter = VideoFilter::init("screen", screen_config, output_config)?;
- let screen_encoder = H264Encoder::init(
- "screen",
- output_config,
- Output::File(display_output_path.clone()),
- )?;
- pipeline_builder = pipeline_builder
- .source("screen_capture", screen_source)
- .pipe("screen_capture_filter", screen_filter)
- .sink("screen_capture_encoder", screen_encoder);
- }
+ ShowCapturesPanel.emit(&app).ok();
- if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {
- let mic_config = mic_source.info();
- audio_output_path = Some(content_dir.join("audio-input.mp3"));
-
- // let mic_filter = AudioFilter::init("microphone", mic_config, "aresample=async=1:min_hard_comp=0.100000:first_pts=0")?;
- let mic_encoder = MP3Encoder::init(
- "microphone",
- mic_config,
- Output::File(audio_output_path.clone().unwrap()),
- )?;
-
- pipeline_builder = pipeline_builder
- .source("microphone_capture", mic_source)
- // .pipe("microphone_filter", mic_filter)
- .sink("microphone_encoder", mic_encoder);
+ NewRecordingAdded {
+ path: recording_dir.clone(),
}
+ .emit(&app)
+ .ok();
- if let Some(camera_source) = camera_feed.map(CameraSource::init) {
- let camera_config = camera_source.info();
- let output_config = camera_config.scaled(1920, 30);
- camera_output_path = Some(content_dir.join("camera.mp4"));
-
- let camera_filter = VideoFilter::init("camera", camera_config, output_config)?;
- let camera_encoder = H264Encoder::init(
- "camera",
- output_config,
- Output::File(camera_output_path.clone().unwrap()),
- )?;
-
- pipeline_builder = pipeline_builder
- .source("camera_capture", camera_source)
- .pipe("camera_filter", camera_filter)
- .sink("camera_encoder", camera_encoder);
+ RecordingStopped {
+ path: recording_dir,
}
+ .emit(&app)
+ .ok();
+
+ let recordings = ProjectRecordings::new(&recording.meta);
+ let max_duration = recordings.duration();
+
+ let config = {
+ let segments = {
+ let mut segments = vec![];
+ let mut passed_duration = 0.0;
+
+ for i in (0..recording.segments.len()).step_by(2) {
+ let start = passed_duration;
+ passed_duration += recording.segments[i + 1] - recording.segments[i];
+ segments.push(TimelineSegment {
+ start,
+ end: passed_duration.min(recordings.duration()),
+ timescale: 1.0,
+ });
+ }
+ segments
+ };
+
+ let zoom_segments = {
+ let mut segments = vec![];
+
+ const ZOOM_SEGMENT_AFTER_CLICK_PADDING: f64 = 1.5;
+
+ for click in &recording.cursor_data.clicks {
+ let time = click.process_time_ms / 1000.0;
+
+ if segments.last().is_none() {
+ segments.push(ZoomSegment {
+ start: (click.process_time_ms / 1000.0 - (ZOOM_DURATION + 0.2)).max(0.0),
+ end: click.process_time_ms / 1000.0 + ZOOM_SEGMENT_AFTER_CLICK_PADDING,
+ amount: 2.0,
+ });
+ } else {
+ let last_segment = segments.last_mut().unwrap();
+
+ if click.down {
+ if last_segment.end > time {
+ last_segment.end = (time + ZOOM_SEGMENT_AFTER_CLICK_PADDING)
+ .min(recordings.duration());
+ } else if time < max_duration - ZOOM_DURATION {
+ segments.push(ZoomSegment {
+ start: (time - ZOOM_DURATION).max(0.0),
+ end: time + ZOOM_SEGMENT_AFTER_CLICK_PADDING,
+ amount: 2.0,
+ });
+ }
+ } else {
+ last_segment.end =
+ (time + ZOOM_SEGMENT_AFTER_CLICK_PADDING).min(recordings.duration());
+ }
+ }
+ }
- let mut pipeline = pipeline_builder.build().await?;
- pipeline.play().await?;
+ segments
+ };
- let stop_signal = Arc::new(AtomicBool::new(false));
+ ProjectConfiguration {
+ timeline: Some(TimelineConfiguration {
+ segments,
+ zoom_segments,
+ }),
+ ..Default::default()
+ }
+ };
- // Initialize default values for cursor channels
- let (mouse_moves, mouse_clicks) =
- // if FLAGS.record_mouse
+ config
+ .write(&recording.recording_dir)
+ .map_err(|e| e.to_string())?;
+
+ AppSounds::StopRecording.play();
+
+ if let Some((settings, auth)) = GeneralSettingsStore::get(&app)
+ .ok()
+ .flatten()
+ .zip(AuthStore::get(&app).ok().flatten())
{
- // spawn_cursor_recorder(stop_signal.clone(), screen_bounds, content_dir, cursors_dir)
- // } else {
- // Create dummy channels that will never receive data
- let (move_tx, move_rx) = oneshot::channel();
- let (click_tx, click_rx) = oneshot::channel();
- // Send empty vectors immediately
- move_tx.send(vec![]).unwrap();
- click_tx.send(vec![]).unwrap();
- (move_rx, click_rx)
- };
+ if auth.is_upgraded() && settings.auto_create_shareable_link {
+ if let Some(pre_created_video) = state.pre_created_video.take() {
+ // Copy link to clipboard
+ #[cfg(target_os = "macos")]
+ platform::write_string_to_pasteboard(&pre_created_video.link);
+
+ // Send notification for shareable link
+ notifications::send_notification(
+ &app,
+ notifications::NotificationType::ShareableLinkCopied,
+ );
+
+ // Open the pre-created shareable link
+ open_external_link(app.clone(), pre_created_video.link.clone()).ok();
+
+ // Start the upload process in the background with retry mechanism
+ let app_clone = app.clone();
+
+ tauri::async_runtime::spawn(async move {
+ let max_retries = 3;
+ let mut retry_count = 0;
+
+ while retry_count < max_retries {
+ match upload_rendered_video(
+ app_clone.clone(),
+ recording.id.clone(),
+ ProjectConfiguration::default(),
+ Some(pre_created_video.clone()),
+ )
+ .await
+ {
+ Ok(_) => {
+ println!("Video uploaded successfully");
+ // Don't send notification here since we already did it above
+ break;
+ }
+ Err(e) => {
+ retry_count += 1;
+ println!(
+ "Error during auto-upload (attempt {}/{}): {}",
+ retry_count, max_retries, e
+ );
+
+ if retry_count < max_retries {
+ tokio::time::sleep(std::time::Duration::from_secs(5)).await;
+ } else {
+ println!("Max retries reached. Upload failed.");
+ notifications::send_notification(
+ &app_clone,
+ notifications::NotificationType::UploadFailed,
+ );
+ }
+ }
+ }
+ }
+ });
+ }
+ } else if settings.open_editor_after_recording {
+ open_editor(app.clone(), recording.id);
+ }
+ }
- Ok(InProgressRecording {
- id,
- segments: vec![SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap()
- .as_secs_f64()],
- pipeline,
- recording_dir,
- display_source: recording_options.capture_target.clone(),
- display_output_path,
- audio_output_path,
- camera_output_path,
- cursor_moves: mouse_moves,
- cursor_clicks: mouse_clicks,
- stop_signal,
- })
+ CurrentRecordingChanged.emit(&app).ok();
+
+ Ok(())
}
diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx
index ad6b8f0b2..31bb9f0f3 100644
--- a/apps/desktop/src/App.tsx
+++ b/apps/desktop/src/App.tsx
@@ -11,7 +11,7 @@ const queryClient = new QueryClient({
defaultOptions: {
mutations: {
onError: (e) =>
- alert("An error occured, here are the details:\n" + e.message),
+ alert("An error occured, here are the details:\n" + e.toString()),
},
},
});
diff --git a/apps/desktop/src/routes/prev-recordings.tsx b/apps/desktop/src/routes/prev-recordings.tsx
index 509be368d..c634e4ef1 100644
--- a/apps/desktop/src/routes/prev-recordings.tsx
+++ b/apps/desktop/src/routes/prev-recordings.tsx
@@ -554,31 +554,42 @@ export default function () {
<h3 class="text-sm font-medium mb-3 text-gray-50">
<Switch>
<Match
- when={progressState.type === "copying"}
+ when={
+ progressState.type === "copying" &&
+ progressState
+ }
>
{(state) => (
<h3 class="text-sm font-medium mb-3 text-gray-50">
- {state.stage === "rendering"
+ {state().stage === "rendering"
? "Rendering video"
: "Copying to clipboard"}
</h3>
)}
</Match>
- <Match when={progressState.type === "saving"}>
+ <Match
+ when={
+ progressState.type === "saving" &&
+ progressState
+ }
+ >
{(state) => (
<h3 class="text-sm font-medium mb-3 text-gray-50">
- {state.stage === "rendering"
+ {state().stage === "rendering"
? "Rendering video"
: "Saving file"}
</h3>
)}
</Match>
<Match
- when={progressState.type === "uploading"}
+ when={
+ progressState.type === "uploading" &&
+ progressState
+ }
>
{(state) => (
<h3 class="text-sm font-medium mb-3 text-gray-50">
- {state.stage === "rendering"
+ {state().stage === "rendering"
? "Rendering video"
: "Creating shareable link"}
</h3>
@@ -630,7 +641,9 @@ export default function () {
</div>
<p class="text-xs text-gray-50 mt-2">
- {progressState.message}
+ {"message" in progressState
+ ? progressState.message
+ : undefined}
</p>
</div>
</div>
diff --git a/apps/desktop/src/routes/window-capture-occluder.tsx b/apps/desktop/src/routes/window-capture-occluder.tsx
index 4878ebbc4..4c159e207 100644
--- a/apps/desktop/src/routes/window-capture-occluder.tsx
+++ b/apps/desktop/src/routes/window-capture-occluder.tsx
@@ -9,8 +9,8 @@ export default function () {
<Show
when={
currentRecording.data &&
- currentRecording.data.displaySource.variant === "window" &&
- currentRecording.data.displaySource.bounds
+ currentRecording.data.captureTarget.variant === "window" &&
+ currentRecording.data.captureTarget.bounds
}
>
{(bounds) => (
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 1c80a3eed..ede99e8a3 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -23,9 +23,6 @@ async pauseRecording() : Promise<null> {
async resumeRecording() : Promise<null> {
return await TAURI_INVOKE("resume_recording");
},
-async takeScreenshot() : Promise<null> {
- return await TAURI_INVOKE("take_screenshot");
-},
async listCameras() : Promise<string[]> {
return await TAURI_INVOKE("list_cameras");
},
@@ -35,6 +32,9 @@ async listCaptureWindows() : Promise<CaptureWindow[]> {
async listCaptureScreens() : Promise<CaptureScreen[]> {
return await TAURI_INVOKE("list_capture_screens");
},
+async takeScreenshot() : Promise<null> {
+ return await TAURI_INVOKE("take_screenshot");
+},
async listAudioDevices() : Promise<string[]> {
return await TAURI_INVOKE("list_audio_devices");
},
@@ -53,7 +53,7 @@ async removeFakeWindow(name: string) : Promise<null> {
async focusCapturesPanel() : Promise<void> {
await TAURI_INVOKE("focus_captures_panel");
},
-async getCurrentRecording() : Promise<JsonValue<InProgressRecording | null>> {
+async getCurrentRecording() : Promise<JsonValue<RecordingInfo | null>> {
return await TAURI_INVOKE("get_current_recording");
},
async renderToFile(outputPath: string, videoId: string, project: ProjectConfiguration, progressChannel: TAURI_CHANNEL<RenderProgress>) : Promise<void> {
@@ -235,7 +235,7 @@ export type CameraYPosition = "top" | "bottom"
export type CaptureScreen = { id: number; name: string }
export type CaptureWindow = { id: number; owner_name: string; name: string; bounds: Bounds }
export type Crop = { position: XY<number>; size: XY<number> }
-export type CurrentRecordingChanged = JsonValue<InProgressRecording | null>
+export type CurrentRecordingChanged = null
export type CursorAnimationStyle = "regular" | "slow" | "fast"
export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: CursorType; animationStyle: CursorAnimationStyle }
export type CursorType = "pointer" | "circle"
@@ -247,7 +247,6 @@ export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean;
export type HotkeyAction = "startRecording" | "stopRecording" | "restartRecording" | "takeScreenshot"
export type HotkeysConfiguration = { show: boolean }
export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }
-export type InProgressRecording = { id: string; recordingDir: string; displaySource: ScreenCaptureTarget; segments: number[] }
export type JsonValue<T> = [T]
export type NewNotification = { title: string; body: string; is_error: boolean }
export type NewRecordingAdded = { path: string }
@@ -259,6 +258,7 @@ export type Plan = { upgraded: boolean; last_checked: number }
export type PreCreatedVideo = { id: string; link: string; config: S3UploadMeta }
export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null; motionBlur: number | null }
export type ProjectRecordings = { display: Video; camera: Video | null; audio: Audio | null }
+export type RecordingInfo = { captureTarget: ScreenCaptureTarget }
export type RecordingMeta = { pretty_name: string; sharing?: SharingMeta | null; display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null; segments?: RecordingSegment[]; cursor: string | null }
export type RecordingMetaChanged = { id: string }
export type RecordingOptions = { captureTarget: ScreenCaptureTarget; cameraLabel: string | null; audioInputName: string | null }
diff --git a/crates/editor/Cargo.toml b/crates/editor/Cargo.toml
index ec8c9c08d..f512a7a6b 100644
--- a/crates/editor/Cargo.toml
+++ b/crates/editor/Cargo.toml
@@ -7,13 +7,10 @@ edition = "2021"
cap-media = { path = "../media" }
cap-project = { path = "../project" }
-cap-ffmpeg-cli = { path = "../ffmpeg-cli" }
cap-rendering = { path = "../rendering" }
tokio = { version = "1.39.2", features = ["macros", "process", "fs"] }
-tracing = "0.1.40"
cpal.workspace = true
-serde_json = "1.0.128"
axum = { version = "0.7.5", features = ["ws"] }
ffmpeg.workspace = true
specta.workspace = true
diff --git a/crates/ffmpeg-cli/Cargo.toml b/crates/ffmpeg-cli/Cargo.toml
index 572ff4318..6a92cf9d5 100644
--- a/crates/ffmpeg-cli/Cargo.toml
+++ b/crates/ffmpeg-cli/Cargo.toml
@@ -4,8 +4,6 @@ version = "0.1.0"
edition = "2021"
[dependencies]
-ffmpeg-sidecar = "1.1.0"
-cap-utils = { path = "../utils" }
tauri = { workspace = true }
tauri-plugin-shell = "2.0.0"
diff --git a/crates/flags/src/lib.rs b/crates/flags/src/lib.rs
index c287e0c64..bc733321b 100644
--- a/crates/flags/src/lib.rs
+++ b/crates/flags/src/lib.rs
@@ -8,8 +8,8 @@ pub struct Flags {
}
pub const FLAGS: Flags = Flags {
- record_mouse: cfg!(debug_assertions),
+ record_mouse: false, //cfg!(debug_assertions),
split: false,
- pause_resume: false,
- zoom: cfg!(debug_assertions),
+ pause_resume: false, //cfg!(debug_assertions),
+ zoom: false, //cfg!(debug_assertions),
};
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
index e5e6202ec..c94c55f48 100644
--- a/crates/media/Cargo.toml
+++ b/crates/media/Cargo.toml
@@ -6,15 +6,12 @@ edition = "2021"
rust-version = "1.80"
[dependencies]
-anyhow.workspace = true
cap-project = { path = "../project" }
cap-flags = { path = "../flags" }
cap-gpu-converters = { path = "../gpu-converters" }
cpal.workspace = true
ffmpeg.workspace = true
-ffmpeg-sys-next.workspace = true
-ffmpeg-hw-device = { path = "../ffmpeg-hw-device" }
-flume = "0.11.0"
+flume.workspace = true
indexmap = "2.5.0"
nokhwa = { workspace = true, features = ["input-native", "serialize"] }
num-traits = "0.2.19"
@@ -23,10 +20,9 @@ scap.workspace = true
serde = { version = "1", features = ["derive"] }
specta.workspace = true
tempfile = "3.12.0"
-thiserror = "1.0"
+thiserror.workspace = true
tracing = "0.1"
futures = "0.3.31"
-tokio.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
cocoa = "0.26.0"
diff --git a/crates/media/src/feeds/audio_input.rs b/crates/media/src/feeds/audio_input.rs
index d780bd3ab..de0906b9a 100644
--- a/crates/media/src/feeds/audio_input.rs
+++ b/crates/media/src/feeds/audio_input.rs
@@ -42,6 +42,7 @@ pub type AudioInputSamplesReceiver = Receiver<AudioInputSamples>;
pub type AudioInputDeviceMap = IndexMap<String, (Device, SupportedStreamConfig)>;
+#[derive(Clone)]
pub struct AudioInputFeed {
control_tx: Sender<AudioInputControl>,
audio_info: AudioInfo,
diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rs
index f3fd461a7..8ed9c977e 100644
--- a/crates/media/src/feeds/camera.rs
+++ b/crates/media/src/feeds/camera.rs
@@ -44,11 +44,12 @@ impl CameraConnection {
}
}
+// #[derive(Clone)]
pub struct CameraFeed {
camera_info: CameraInfo,
video_info: VideoInfo,
control: Sender<CameraControl>,
- join_handle: JoinHandle<()>,
+ // join_handle: JoinHandle<()>,
}
impl CameraFeed {
@@ -72,7 +73,7 @@ impl CameraFeed {
camera_info,
video_info,
control,
- join_handle,
+ // join_handle,
};
Ok(camera_feed)
diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs
index 6bad83ed6..4ecd8f34c 100644
--- a/crates/media/src/lib.rs
+++ b/crates/media/src/lib.rs
@@ -40,6 +40,9 @@ pub enum MediaError {
#[error("Camera error: {0}")]
Nokhwa(#[from] nokhwa::NokhwaError),
+ #[error("IO error: {0}")]
+ IO(#[from] std::io::Error),
+
#[error("Could not find a suitable codec for {0}")]
MissingCodec(&'static str),
diff --git a/crates/media/src/pipeline/builder.rs b/crates/media/src/pipeline/builder.rs
index 766d1d5f7..1a962a4d4 100644
--- a/crates/media/src/pipeline/builder.rs
+++ b/crates/media/src/pipeline/builder.rs
@@ -14,13 +14,13 @@ struct Task {
join_handle: JoinHandle<()>,
}
-pub struct PipelineBuilder<T: PipelineClock> {
+pub struct PipelineBuilder<T> {
clock: T,
control: ControlBroadcast,
tasks: IndexMap<String, Task>,
}
-impl<T: PipelineClock> PipelineBuilder<T> {
+impl<T> PipelineBuilder<T> {
pub fn new(clock: T) -> Self {
Self {
clock,
@@ -71,7 +71,9 @@ impl<T: PipelineClock> PipelineBuilder<T> {
},
);
}
+}
+impl<T: PipelineClock> PipelineBuilder<T> {
pub async fn build(self) -> Result<Pipeline<T>, MediaError> {
let Self {
clock,
@@ -105,14 +107,12 @@ impl<T: PipelineClock> PipelineBuilder<T> {
}
}
-pub struct PipelinePathBuilder<Clock: PipelineClock, PreviousOutput: Send> {
+pub struct PipelinePathBuilder<Clock, PreviousOutput: Send> {
pipeline: PipelineBuilder<Clock>,
next_input: Receiver<PreviousOutput>,
}
-impl<Clock: PipelineClock, PreviousOutput: Send + 'static>
- PipelinePathBuilder<Clock, PreviousOutput>
-{
+impl<Clock, PreviousOutput: Send + 'static> PipelinePathBuilder<Clock, PreviousOutput> {
pub fn pipe<Output: Send + 'static>(
self,
name: impl Into<String>,
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 385e17484..f95158d88 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -66,6 +66,21 @@ pub struct ScreenCaptureSource<T> {
phantom: std::marker::PhantomData<T>,
}
+impl<T> Clone for ScreenCaptureSource<T> {
+ fn clone(&self) -> Self {
+ Self {
+ target: self.target.clone(),
+ fps: self.fps,
+ resolution: self.resolution,
+ video_info: self.video_info,
+ phantom: Default::default(),
+ }
+ }
+}
+
+unsafe impl<T> Send for ScreenCaptureSource<T> {}
+unsafe impl<T> Sync for ScreenCaptureSource<T> {}
+
impl<T> ScreenCaptureSource<T> {
pub const DEFAULT_FPS: u32 = 30;
@@ -94,6 +109,15 @@ impl<T> ScreenCaptureSource<T> {
this
}
+ pub fn get_bounds(&self) -> Bounds {
+ match &self.target {
+ ScreenCaptureTarget::Window(capture_window) => capture_window.bounds,
+ ScreenCaptureTarget::Screen(capture_screen) => {
+ platform::monitor_bounds(capture_screen.id)
+ }
+ }
+ }
+
fn create_options(&self) -> Options {
let targets = dbg!(scap::get_all_targets());
@@ -106,23 +130,18 @@ impl<T> ScreenCaptureSource<T> {
.cloned()
.collect();
- let (crop_area, bounds) = match &self.target {
- ScreenCaptureTarget::Window(capture_window) => (
- Some(Area {
- size: Size {
- width: capture_window.bounds.width,
- height: capture_window.bounds.height,
- },
- origin: Point {
- x: capture_window.bounds.x,
- y: capture_window.bounds.y,
- },
- }),
- capture_window.bounds,
- ),
- ScreenCaptureTarget::Screen(capture_screen) => {
- (None, platform::monitor_bounds(capture_screen.id))
- }
+ let crop_area = match &self.target {
+ ScreenCaptureTarget::Window(capture_window) => Some(Area {
+ size: Size {
+ width: capture_window.bounds.width,
+ height: capture_window.bounds.height,
+ },
+ origin: Point {
+ x: capture_window.bounds.x,
+ y: capture_window.bounds.y,
+ },
+ }),
+ ScreenCaptureTarget::Screen(_) => None,
};
let target = match &self.target {
@@ -414,7 +433,7 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
Some(Control::Shutdown) | None => {
println!("Received shutdown signal");
if capturing {
- capturer.stop_capture();
+ // capturer.stop_capture();
}
break;
}
diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml
index 6fe9fb061..125233e42 100644
--- a/crates/project/Cargo.toml
+++ b/crates/project/Cargo.toml
@@ -7,3 +7,4 @@ edition = "2021"
specta = { workspace = true, features = ["derive"] }
serde = { version = "1.0.209", features = ["derive"] }
serde_json = "1.0.127"
+either = "1.13.0"
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
index 66b4c16c5..20aac3aa0 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -4,6 +4,7 @@ mod cursor;
pub use configuration::*;
pub use cursor::*;
+use either::Either;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
@@ -78,10 +79,11 @@ impl RecordingMeta {
Ok(meta)
}
- pub fn save_for_project(&self) {
+ pub fn save_for_project(&self) -> Result<(), Either<serde_json::Error, std::io::Error>> {
let meta_path = &self.project_path.join("recording-meta.json");
- let meta = serde_json::to_string_pretty(&self).unwrap();
- std::fs::write(meta_path, meta).unwrap();
+ let meta = serde_json::to_string_pretty(&self).map_err(Either::Left)?;
+ std::fs::write(meta_path, meta).map_err(Either::Right)?;
+ Ok(())
}
pub fn project_config(&self) -> ProjectConfiguration {
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
new file mode 100644
index 000000000..afcdf0bfd
--- /dev/null
+++ b/crates/recording/Cargo.toml
@@ -0,0 +1,26 @@
+[package]
+name = "cap-recording"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+cap-project = { path = "../project" }
+cap-media = { path = "../media" }
+cap-flags = { path = "../flags" }
+
+specta.workspace = true
+tokio.workspace = true
+flume.workspace = true
+thiserror.workspace = true
+
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+chrono = "0.4.38"
+tracing = "0.1.40"
+device_query = "2.1.0"
+image = "0.25.2"
+either = "1.13.0"
+
+[target.'cfg(target_os = "macos")'.dependencies]
+cocoa = "0.26.0"
+objc = "0.2.7"
diff --git a/crates/recording/src/actor.rs b/crates/recording/src/actor.rs
new file mode 100644
index 000000000..fb11e2c5f
--- /dev/null
+++ b/crates/recording/src/actor.rs
@@ -0,0 +1,425 @@
+use cap_flags::FLAGS;
+use cap_media::{
+ encoders::{H264Encoder, MP3Encoder, Output},
+ feeds::{AudioInputFeed, CameraFeed},
+ filters::VideoFilter,
+ pipeline::{builder::PipelineBuilder, Pipeline, RealTimeClock},
+ sources::{AudioInputSource, CameraSource, ScreenCaptureSource, ScreenCaptureTarget},
+ MediaError,
+};
+use cap_project::{CursorClickEvent, CursorMoveEvent, RecordingMeta};
+use either::Either;
+use std::{
+ collections::HashMap,
+ path::PathBuf,
+ sync::{atomic::AtomicBool, Arc},
+ time::{SystemTime, UNIX_EPOCH},
+};
+use thiserror::Error;
+use tokio::sync::{oneshot, Mutex};
+
+use crate::{cursor::spawn_cursor_recorder, RecordingOptions};
+
+pub enum ActorControlMessage {
+ Stop(oneshot::Sender<Result<CompletedRecording, RecordingError>>),
+}
+
+pub struct Actor {
+ id: String,
+ recording_dir: PathBuf,
+ options: RecordingOptions,
+ pipeline: RecordingPipeline,
+ start_time: f64,
+ stop_signal: Arc<AtomicBool>,
+ cursor_moves: oneshot::Receiver<Vec<CursorMoveEvent>>,
+ cursor_clicks: oneshot::Receiver<Vec<CursorClickEvent>>,
+}
+
+pub struct ActorHandle {
+ ctrl_tx: flume::Sender<ActorControlMessage>,
+ pub options: RecordingOptions,
+}
+
+#[derive(Error, Debug)]
+pub enum ActorError {
+ #[error("Actor has stopped")]
+ ActorStopped,
+
+ #[error("Failed to send to actor")]
+ SendFailed(#[from] flume::SendError<ActorControlMessage>),
+}
+
+#[derive(Error, Debug)]
+pub enum RecordingError {
+ #[error("Media/{0}")]
+ Media(#[from] MediaError),
+
+ #[error("Actor/{0}")]
+ Actor(#[from] ActorError),
+
+ #[error("Serde/{0}")]
+ Serde(#[from] serde_json::Error),
+
+ #[error("IO/{0}")]
+ Io(#[from] std::io::Error),
+}
+
+macro_rules! send_message {
+ ($ctrl_tx:expr, $variant:path) => {{
+ let (tx, rx) = oneshot::channel();
+ $ctrl_tx.send($variant(tx)).map_err(ActorError::from)?;
+ rx.await.map_err(|_| ActorError::ActorStopped)?
+ }};
+}
+
+impl ActorHandle {
+ pub async fn stop(&self) -> Result<CompletedRecording, RecordingError> {
+ send_message!(self.ctrl_tx, ActorControlMessage::Stop)
+ }
+}
+
+pub async fn spawn_recording_actor(
+ id: String,
+ recording_dir: impl Into<PathBuf>,
+ options: RecordingOptions,
+ camera_feed: Option<Arc<Mutex<CameraFeed>>>,
+ audio_input_feed: Option<AudioInputFeed>,
+) -> Result<ActorHandle, RecordingError> {
+ let recording_dir = recording_dir.into();
+
+ let content_dir = ensure_dir(recording_dir.join("content"))?;
+ let cursors_dir = ensure_dir(content_dir.join("cursors"))?;
+
+ let screen_source = create_screen_capture(&options);
+
+ let pipeline = create_pipeline(
+ &content_dir,
+ screen_source.clone(),
+ camera_feed.as_deref(),
+ audio_input_feed.as_ref(),
+ )
+ .await?;
+
+ let start_time = current_time_f64();
+
+ let (ctrl_tx, ctrl_rx) = flume::bounded(1);
+
+ let stop_signal = Arc::new(AtomicBool::new(false));
+
+ // Initialize default values for cursor channels
+ let (cursor_moves, cursor_clicks) = if FLAGS.record_mouse {
+ spawn_cursor_recorder(
+ stop_signal.clone(),
+ screen_source.get_bounds(),
+ content_dir,
+ cursors_dir,
+ )
+ } else {
+ // Create dummy channels that will never receive data
+ let (move_tx, move_rx) = oneshot::channel();
+ let (click_tx, click_rx) = oneshot::channel();
+ // Send empty vectors immediately
+ move_tx.send(vec![]).unwrap();
+ click_tx.send(vec![]).unwrap();
+ (move_rx, click_rx)
+ };
+
+ tokio::spawn({
+ let options = options.clone();
+ async move {
+ let actor = Actor {
+ recording_dir,
+ options,
+ pipeline,
+ start_time,
+ cursor_moves,
+ cursor_clicks,
+ stop_signal,
+ id,
+ };
+
+ loop {
+ let Ok(ActorControlMessage::Stop(tx)) = ctrl_rx.recv_async().await else {
+ return;
+ };
+
+ let resp = stop_recording(actor).await;
+
+ tx.send(resp).ok();
+ return;
+ }
+ }
+ });
+
+ Ok(ActorHandle { ctrl_tx, options })
+}
+
+pub struct CompletedRecording {
+ pub id: String,
+ pub recording_dir: PathBuf,
+ pub display_output_path: PathBuf,
+ pub camera_output_path: Option<PathBuf>,
+ pub audio_output_path: Option<PathBuf>,
+ pub display_source: ScreenCaptureTarget,
+ pub meta: RecordingMeta,
+ pub cursor_data: cap_project::CursorData,
+ pub segments: Vec<f64>,
+}
+
+async fn stop_recording(mut actor: Actor) -> Result<CompletedRecording, RecordingError> {
+ let segment = (actor.start_time, current_time_f64());
+
+ use cap_project::*;
+
+ let meta = RecordingMeta {
+ project_path: actor.recording_dir.clone(),
+ sharing: None,
+ pretty_name: format!(
+ "Cap {}",
+ chrono::Local::now().format("%Y-%m-%d at %H.%M.%S")
+ ),
+ display: Display {
+ path: actor
+ .pipeline
+ .display_output_path
+ .strip_prefix(&actor.recording_dir)
+ .unwrap()
+ .to_owned(),
+ },
+ camera: actor
+ .pipeline
+ .camera_output_path
+ .as_ref()
+ .map(|path| CameraMeta {
+ path: path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),
+ }),
+ audio: actor
+ .pipeline
+ .audio_output_path
+ .as_ref()
+ .map(|path| AudioMeta {
+ path: path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),
+ }),
+ segments: {
+ let segments = [segment];
+
+ let relative_segments = segments
+ .iter()
+ .map(|(l, r)| (l - segments[0].0, r - segments[0].0))
+ .collect::<Vec<_>>();
+
+ let mut segments = vec![];
+
+ let mut diff = 0.0;
+
+ for (i, chunk) in relative_segments.iter().enumerate() {
+ if i < relative_segments.len() / 2 {
+ segments.push(RecordingSegment {
+ start: diff,
+ end: chunk.1 - chunk.0 + diff,
+ });
+ }
+
+ diff += chunk.1 - chunk.0;
+ }
+
+ segments
+ },
+ cursor: Some(PathBuf::from("cursor.json")),
+ };
+
+ actor.pipeline.inner.shutdown().await?;
+
+ actor
+ .stop_signal
+ .store(true, std::sync::atomic::Ordering::Relaxed);
+
+ let cursor_data = cap_project::CursorData {
+ clicks: actor.cursor_clicks.await.unwrap_or_default(),
+ moves: actor.cursor_moves.await.unwrap_or_default(),
+ cursor_images: HashMap::new(), // This will be populated during recording
+ };
+
+ meta.save_for_project()
+ .map_err(Either::either_into::<RecordingError>)?;
+
+ Ok(CompletedRecording {
+ id: actor.id,
+ meta,
+ cursor_data,
+ recording_dir: actor.recording_dir,
+ display_output_path: actor.pipeline.display_output_path,
+ camera_output_path: actor.pipeline.camera_output_path,
+ audio_output_path: actor.pipeline.audio_output_path,
+ display_source: actor.options.capture_target,
+ segments: vec![segment.0, segment.1],
+ })
+}
+
+fn create_screen_capture(
+ recording_options: &RecordingOptions,
+) -> ScreenCaptureSource<impl MakeCapturePipeline> {
+ #[cfg(target_os = "macos")]
+ {
+ ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(
+ dbg!(&recording_options.capture_target),
+ None,
+ None,
+ )
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ ScreenCaptureSource::<AVFrameCapture>::init(
+ dbg!(&recording_options.capture_target),
+ None,
+ None,
+ )
+ }
+}
+
+struct RecordingPipeline {
+ pub inner: Pipeline<RealTimeClock<()>>,
+ pub display_output_path: PathBuf,
+ pub audio_output_path: Option<PathBuf>,
+ pub camera_output_path: Option<PathBuf>,
+}
+
+async fn create_pipeline<TCaptureFormat: MakeCapturePipeline>(
+ content_dir: &PathBuf,
+ screen_source: ScreenCaptureSource<TCaptureFormat>,
+ camera_feed: Option<&Mutex<CameraFeed>>,
+ audio_input_feed: Option<&AudioInputFeed>,
+) -> Result<RecordingPipeline, MediaError> {
+ let camera_feed = match camera_feed.as_ref() {
+ Some(camera_feed) => Some(camera_feed.lock().await),
+ None => None,
+ };
+ let camera_feed = camera_feed.as_deref();
+
+ let clock = RealTimeClock::<()>::new();
+ let mut pipeline_builder = Pipeline::builder(clock);
+
+ let display_output_path = content_dir.join("display.mp4");
+ let mut audio_output_path = None;
+ let mut camera_output_path = None;
+
+ pipeline_builder = TCaptureFormat::make_capture_pipeline(
+ pipeline_builder,
+ screen_source,
+ &display_output_path,
+ )?;
+
+ if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {
+ let mic_config = mic_source.info();
+ audio_output_path = Some(content_dir.join("audio-input.mp3"));
+
+ // let mic_filter = AudioFilter::init("microphone", mic_config, "aresample=async=1:min_hard_comp=0.100000:first_pts=0")?;
+ let mic_encoder = MP3Encoder::init(
+ "microphone",
+ mic_config,
+ Output::File(audio_output_path.clone().unwrap()),
+ )?;
+
+ pipeline_builder = pipeline_builder
+ .source("microphone_capture", mic_source)
+ // .pipe("microphone_filter", mic_filter)
+ .sink("microphone_encoder", mic_encoder);
+ }
+
+ if let Some(camera_source) = camera_feed.map(CameraSource::init) {
+ let camera_config = camera_source.info();
+ let output_config = camera_config.scaled(1920, 30);
+ camera_output_path = Some(content_dir.join("camera.mp4"));
+
+ let camera_filter = VideoFilter::init("camera", camera_config, output_config)?;
+ let camera_encoder = H264Encoder::init(
+ "camera",
+ output_config,
+ Output::File(camera_output_path.clone().unwrap()),
+ )?;
+
+ pipeline_builder = pipeline_builder
+ .source("camera_capture", camera_source)
+ .pipe("camera_filter", camera_filter)
+ .sink("camera_encoder", camera_encoder);
+ }
+
+ let mut pipeline = pipeline_builder.build().await?;
+
+ pipeline.play().await?;
+
+ Ok(RecordingPipeline {
+ inner: pipeline,
+ display_output_path,
+ audio_output_path,
+ camera_output_path,
+ })
+}
+
+fn ensure_dir(path: PathBuf) -> Result<PathBuf, MediaError> {
+ std::fs::create_dir_all(&path)?;
+ Ok(path)
+}
+
+type CapturePipelineBuilder = PipelineBuilder<RealTimeClock<()>>;
+
+trait MakeCapturePipeline: 'static {
+ fn make_capture_pipeline(
+ builder: CapturePipelineBuilder,
+ source: ScreenCaptureSource<Self>,
+ output_path: impl Into<PathBuf>,
+ ) -> Result<CapturePipelineBuilder, MediaError>
+ where
+ Self: Sized;
+}
+
+impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
+ fn make_capture_pipeline(
+ builder: CapturePipelineBuilder,
+ source: ScreenCaptureSource<Self>,
+ output_path: impl Into<PathBuf>,
+ ) -> Result<CapturePipelineBuilder, MediaError> {
+ let screen_config = source.info();
+
+ let output_config = screen_config.scaled(1920, 30);
+ let screen_encoder = cap_media::encoders::H264AVAssetWriterEncoder::init(
+ "screen",
+ output_config,
+ Output::File(output_path.into()),
+ )?;
+
+ Ok(builder
+ .source("screen_capture", source)
+ .sink("screen_capture_encoder", screen_encoder))
+ }
+}
+
+impl MakeCapturePipeline for cap_media::sources::AVFrameCapture {
+ fn make_capture_pipeline(
+ builder: CapturePipelineBuilder,
+ source: ScreenCaptureSource<Self>,
+ output_path: impl Into<PathBuf>,
+ ) -> Result<CapturePipelineBuilder, MediaError>
+ where
+ Self: Sized,
+ {
+ let screen_config = source.info();
+ // let screen_bounds = screen_source.bounds;
+
+ let output_config = screen_config.scaled(1920, 30);
+ let screen_filter = VideoFilter::init("screen", screen_config, output_config)?;
+ let screen_encoder =
+ H264Encoder::init("screen", output_config, Output::File(output_path.into()))?;
+ Ok(builder
+ .source("screen_capture", source)
+ .pipe("screen_capture_filter", screen_filter)
+ .sink("screen_capture_encoder", screen_encoder))
+ }
+}
+
+fn current_time_f64() -> f64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64()
+}
diff --git a/apps/desktop/src-tauri/src/cursor.rs b/crates/recording/src/cursor.rs
similarity index 100%
rename from apps/desktop/src-tauri/src/cursor.rs
rename to crates/recording/src/cursor.rs
diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs
new file mode 100644
index 000000000..a11b47591
--- /dev/null
+++ b/crates/recording/src/lib.rs
@@ -0,0 +1,82 @@
+mod actor;
+mod cursor;
+mod segmented_actor;
+
+pub use actor::{spawn_recording_actor, ActorHandle, RecordingError};
+
+use cap_media::{pipeline::*, sources::*};
+use cap_project::{CursorClickEvent, CursorMoveEvent};
+use serde::{Deserialize, Serialize};
+use specta::Type;
+use std::path::PathBuf;
+use std::sync::atomic::AtomicBool;
+use std::sync::Arc;
+use tokio::sync::oneshot;
+
+// TODO: Hacky, please fix
+pub const FPS: u32 = 30;
+
+#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct RecordingOptions {
+ pub capture_target: ScreenCaptureTarget,
+ pub camera_label: Option<String>,
+ pub audio_input_name: Option<String>,
+}
+
+impl RecordingOptions {
+ pub fn camera_label(&self) -> Option<&str> {
+ self.camera_label.as_deref()
+ }
+
+ pub fn audio_input_name(&self) -> Option<&str> {
+ self.audio_input_name.as_deref()
+ }
+}
+
+#[derive(Type, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct InProgressRecording {
+ pub id: String,
+ pub recording_dir: PathBuf,
+ #[serde(skip)]
+ pub pipeline: Pipeline<RealTimeClock<()>>,
+ #[serde(skip)]
+ pub display_output_path: PathBuf,
+ #[serde(skip)]
+ pub camera_output_path: Option<PathBuf>,
+ #[serde(skip)]
+ pub audio_output_path: Option<PathBuf>,
+ pub display_source: ScreenCaptureTarget,
+ pub segments: Vec<f64>,
+ #[serde(skip)]
+ pub cursor_moves: oneshot::Receiver<Vec<CursorMoveEvent>>,
+ #[serde(skip)]
+ pub cursor_clicks: oneshot::Receiver<Vec<CursorClickEvent>>,
+ #[serde(skip)]
+ pub stop_signal: Arc<AtomicBool>,
+}
+
+impl InProgressRecording {
+ pub async fn stop_and_discard(&mut self) {
+ // Signal the mouse event tracking to stop
+ if let Err(error) = self.pipeline.shutdown().await {
+ eprintln!("Error while stopping recording: {error}");
+ }
+
+ // Delete all recorded files
+ if let Err(e) = std::fs::remove_dir_all(&self.recording_dir) {
+ eprintln!("Failed to delete recording directory: {:?}", e);
+ }
+ }
+
+ // pub async fn pause(&mut self) -> Result<(), String> {
+ // let _ = self.pipeline.pause().await;
+ // Ok(())
+ // }
+
+ pub async fn play(&mut self) -> Result<(), String> {
+ let _ = self.pipeline.play().await;
+ Ok(())
+ }
+}
diff --git a/crates/recording/src/segmented_actor.rs b/crates/recording/src/segmented_actor.rs
new file mode 100644
index 000000000..e0e6da210
--- /dev/null
+++ b/crates/recording/src/segmented_actor.rs
@@ -0,0 +1,381 @@
+use std::{
+ path::PathBuf,
+ sync::Arc,
+ time::{SystemTime, UNIX_EPOCH},
+};
+
+use cap_media::{
+ encoders::{H264Encoder, MP3Encoder, Output},
+ feeds::{AudioInputFeed, CameraFeed},
+ filters::VideoFilter,
+ pipeline::{builder::PipelineBuilder, Pipeline, RealTimeClock},
+ sources::{AudioInputSource, CameraSource, ScreenCaptureSource},
+ MediaError,
+};
+use thiserror::Error;
+use tokio::sync::{oneshot, Mutex};
+
+use crate::RecordingOptions;
+
+enum ActorState {
+ Recording {
+ pipeline: Pipeline<RealTimeClock<()>>,
+ index: u32,
+ segment_start_time: f64,
+ },
+ Paused {
+ next_index: u32,
+ },
+ Stopped,
+}
+
+pub enum ActorControlMessage {
+ Pause(oneshot::Sender<Result<(), RecordingError>>),
+ Resume(oneshot::Sender<Result<(), RecordingError>>),
+ Stop(oneshot::Sender<Result<(), RecordingError>>),
+}
+
+pub struct Actor {
+ recording_dir: PathBuf,
+ options: RecordingOptions,
+ segments: Vec<(f64, f64)>,
+}
+
+pub struct ActorHandle {
+ ctrl_tx: flume::Sender<ActorControlMessage>,
+ pub options: RecordingOptions,
+}
+
+#[derive(Error, Debug)]
+pub enum ActorError {
+ #[error("Actor has stopped")]
+ ActorStopped,
+
+ #[error("Failed to send to actor")]
+ SendFailed(#[from] flume::SendError<ActorControlMessage>),
+}
+
+#[derive(Error, Debug)]
+pub enum RecordingError {
+ #[error("Media error: {0}")]
+ Media(#[from] MediaError),
+
+ #[error("Actor error: {0}")]
+ Actor(#[from] ActorError),
+}
+
+macro_rules! send_message {
+ ($ctrl_tx:expr, $variant:path) => {{
+ let (tx, rx) = oneshot::channel();
+ $ctrl_tx.send($variant(tx)).map_err(ActorError::from)?;
+ rx.await.map_err(|_| ActorError::ActorStopped)?
+ }};
+}
+
+impl ActorHandle {
+ pub async fn stop(&self) -> Result<(), RecordingError> {
+ send_message!(self.ctrl_tx, ActorControlMessage::Stop)
+ }
+
+ pub async fn pause(&self) -> Result<(), RecordingError> {
+ send_message!(self.ctrl_tx, ActorControlMessage::Pause)
+ }
+
+ pub async fn resume(&self) -> Result<(), RecordingError> {
+ send_message!(self.ctrl_tx, ActorControlMessage::Resume)
+ }
+}
+
+pub async fn start_recording_actor(
+ recording_dir: impl Into<PathBuf>,
+ options: RecordingOptions,
+ camera_feed: Option<Arc<Mutex<CameraFeed>>>,
+ audio_input_feed: Option<AudioInputFeed>,
+) -> Result<ActorHandle, RecordingError> {
+ let recording_dir = recording_dir.into();
+
+ let content_dir = ensure_dir(recording_dir.join("content"))?;
+
+ let segments_dir = ensure_dir(content_dir.join("segments"))?;
+ let cursors_dir = ensure_dir(content_dir.join("cursors"))?;
+
+ let screen_source = create_screen_capture(&options);
+
+ let index = 0;
+ let pipeline = create_segment_pipeline(
+ &segments_dir,
+ index,
+ screen_source.clone(),
+ camera_feed.as_deref(),
+ audio_input_feed.as_ref(),
+ )
+ .await?;
+
+ let segment_start_time = current_time_f64();
+
+ let (ctrl_tx, ctrl_rx) = flume::bounded(1);
+
+ tokio::spawn({
+ let options = options.clone();
+ async move {
+ let mut actor = Actor {
+ recording_dir,
+ options,
+ segments: Vec::new(),
+ };
+
+ let mut state = ActorState::Recording {
+ pipeline,
+ index,
+ segment_start_time,
+ };
+
+ loop {
+ state = match state {
+ ActorState::Recording {
+ mut pipeline,
+ index,
+ segment_start_time,
+ } => loop {
+ let Ok(msg) = ctrl_rx.recv_async().await else {
+ return;
+ };
+
+ if matches!(
+ &msg,
+ ActorControlMessage::Pause(_) | ActorControlMessage::Stop(_)
+ ) {
+ let segment_stop_time = current_time_f64();
+ actor.segments.push((segment_start_time, segment_stop_time));
+ }
+
+ break match msg {
+ ActorControlMessage::Pause(tx) => {
+ let res = pipeline.shutdown().await;
+ tx.send(res.map_err(Into::into)).ok();
+ ActorState::Paused {
+ next_index: index + 1,
+ }
+ }
+ ActorControlMessage::Stop(tx) => {
+ tx.send(stop_recording(Some(pipeline)).await).ok();
+ return;
+ }
+ _ => continue,
+ };
+ },
+ ActorState::Paused { next_index } => loop {
+ let Ok(msg) = ctrl_rx.recv_async().await else {
+ return;
+ };
+
+ break match msg {
+ ActorControlMessage::Stop(tx) => {
+ tx.send(stop_recording(None).await).ok();
+ ActorState::Stopped
+ }
+ ActorControlMessage::Resume(tx) => {
+ let (state, res) = match create_segment_pipeline(
+ &segments_dir,
+ next_index,
+ screen_source.clone(),
+ camera_feed.as_deref(),
+ audio_input_feed.as_ref(),
+ )
+ .await
+ {
+ Ok(pipeline) => (
+ ActorState::Recording {
+ pipeline,
+ index: next_index,
+ segment_start_time: current_time_f64(),
+ },
+ Ok(()),
+ ),
+ Err(e) => (ActorState::Stopped, Err(e.into())),
+ };
+
+ tx.send(res).ok();
+
+ state
+ }
+ _ => continue,
+ };
+ },
+ ActorState::Stopped => return,
+ };
+ }
+ }
+ });
+
+ Ok(ActorHandle { ctrl_tx, options })
+}
+
+async fn stop_recording(
+ pipeline: Option<Pipeline<RealTimeClock<()>>>,
+) -> Result<(), RecordingError> {
+ if let Some(mut pipeline) = pipeline {
+ pipeline.shutdown().await?;
+ }
+
+ Ok(())
+}
+
+fn create_screen_capture(
+ recording_options: &RecordingOptions,
+) -> ScreenCaptureSource<impl MakeCapturePipeline> {
+ #[cfg(target_os = "macos")]
+ {
+ ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(
+ dbg!(&recording_options.capture_target),
+ None,
+ None,
+ )
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ ScreenCaptureSource::<AVFrameCapture>::init(
+ dbg!(&recording_options.capture_target),
+ None,
+ None,
+ )
+ }
+}
+
+async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
+ segments_dir: &PathBuf,
+ index: u32,
+ screen_source: ScreenCaptureSource<TCaptureFormat>,
+ camera_feed: Option<&Mutex<CameraFeed>>,
+ audio_input_feed: Option<&AudioInputFeed>,
+) -> Result<Pipeline<RealTimeClock<()>>, MediaError> {
+ let camera_feed = match camera_feed.as_ref() {
+ Some(camera_feed) => Some(camera_feed.lock().await),
+ None => None,
+ };
+ let camera_feed = camera_feed.as_deref();
+
+ let dir = ensure_dir(segments_dir.join(format!("segment-{index}")))?;
+
+ let clock = RealTimeClock::<()>::new();
+ let mut pipeline_builder = Pipeline::builder(clock);
+
+ let display_output_path = dir.join("display.mp4");
+ let mut audio_output_path = None;
+ let mut camera_output_path = None;
+
+ pipeline_builder = TCaptureFormat::make_capture_pipeline(
+ pipeline_builder,
+ screen_source,
+ display_output_path,
+ )?;
+
+ if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {
+ let mic_config = mic_source.info();
+ audio_output_path = Some(dir.join("audio-input.mp3"));
+
+ // let mic_filter = AudioFilter::init("microphone", mic_config, "aresample=async=1:min_hard_comp=0.100000:first_pts=0")?;
+ let mic_encoder = MP3Encoder::init(
+ "microphone",
+ mic_config,
+ Output::File(audio_output_path.clone().unwrap()),
+ )?;
+
+ pipeline_builder = pipeline_builder
+ .source("microphone_capture", mic_source)
+ // .pipe("microphone_filter", mic_filter)
+ .sink("microphone_encoder", mic_encoder);
+ }
+
+ if let Some(camera_source) = camera_feed.map(CameraSource::init) {
+ let camera_config = camera_source.info();
+ let output_config = camera_config.scaled(1920, 30);
+ camera_output_path = Some(dir.join("camera.mp4"));
+
+ let camera_filter = VideoFilter::init("camera", camera_config, output_config)?;
+ let camera_encoder = H264Encoder::init(
+ "camera",
+ output_config,
+ Output::File(camera_output_path.clone().unwrap()),
+ )?;
+
+ pipeline_builder = pipeline_builder
+ .source("camera_capture", camera_source)
+ .pipe("camera_filter", camera_filter)
+ .sink("camera_encoder", camera_encoder);
+ }
+
+ let mut pipeline = pipeline_builder.build().await?;
+
+ pipeline.play().await?;
+
+ Ok(pipeline)
+}
+
+fn ensure_dir(path: PathBuf) -> Result<PathBuf, MediaError> {
+ std::fs::create_dir_all(&path)?;
+ Ok(path)
+}
+
+type CapturePipelineBuilder = PipelineBuilder<RealTimeClock<()>>;
+
+trait MakeCapturePipeline: 'static {
+ fn make_capture_pipeline(
+ builder: CapturePipelineBuilder,
+ source: ScreenCaptureSource<Self>,
+ output_path: impl Into<PathBuf>,
+ ) -> Result<CapturePipelineBuilder, MediaError>
+ where
+ Self: Sized;
+}
+
+impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
+ fn make_capture_pipeline(
+ builder: CapturePipelineBuilder,
+ source: ScreenCaptureSource<Self>,
+ output_path: impl Into<PathBuf>,
+ ) -> Result<CapturePipelineBuilder, MediaError> {
+ let screen_config = source.info();
+
+ let output_config = screen_config.scaled(1920, 30);
+ let screen_encoder = cap_media::encoders::H264AVAssetWriterEncoder::init(
+ "screen",
+ output_config,
+ Output::File(output_path.into()),
+ )?;
+
+ Ok(builder
+ .source("screen_capture", source)
+ .sink("screen_capture_encoder", screen_encoder))
+ }
+}
+
+impl MakeCapturePipeline for cap_media::sources::AVFrameCapture {
+ fn make_capture_pipeline(
+ builder: CapturePipelineBuilder,
+ source: ScreenCaptureSource<Self>,
+ output_path: impl Into<PathBuf>,
+ ) -> Result<CapturePipelineBuilder, MediaError>
+ where
+ Self: Sized,
+ {
+ let screen_config = source.info();
+ // let screen_bounds = screen_source.bounds;
+
+ let output_config = screen_config.scaled(1920, 30);
+ let screen_filter = VideoFilter::init("screen", screen_config, output_config)?;
+ let screen_encoder =
+ H264Encoder::init("screen", output_config, Output::File(output_path.into()))?;
+ Ok(builder
+ .source("screen_capture", source)
+ .pipe("screen_capture_filter", screen_filter)
+ .sink("screen_capture_encoder", screen_encoder))
+ }
+}
+
+fn current_time_f64() -> f64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64()
+}
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index b0c66b46a..6e5ec953c 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -11,16 +11,12 @@ serde = "1.0.209"
specta.workspace = true
wgpu.workspace = true
image = "0.25.2"
-
-cap-ffmpeg-cli = { path = "../ffmpeg-cli" }
cap-project = { path = "../project" }
cap-flags = { path = "../flags" }
ffmpeg-hw-device = { path = "../ffmpeg-hw-device" }
tokio.workspace = true
-serde_json = "1.0.127"
ffmpeg.workspace = true
ffmpeg-sys-next.workspace = true
-lru = "0.12.4"
futures = "0.3.30"
[target.'cfg(unix)'.dependencies]
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index c3d0793cb..978386591 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -57,4 +57,6 @@ declare global {
const IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw.jsx')['default']
const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default']
const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default']
+ const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default']
+ const IconLucideVolumeX: typeof import('~icons/lucide/volume-x.jsx')['default']
}