Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

almost public api

Brendan Allan027875fa6df9
diff --git a/Cargo.lock b/Cargo.lock
index 4a7f16a09..eb4d049d5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1117,6 +1117,7 @@ dependencies = [
"device_query",
"either",
"flume 0.11.0",
+ "futures",
"image 0.25.5",
"objc",
"relative-path",
diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs
index a45aa4571..a7e380fb4 100644
--- a/apps/cli/src/main.rs
+++ b/apps/cli/src/main.rs
@@ -147,7 +147,7 @@ impl Export {
let recording_meta = RecordingMeta::load_for_project(&self.project_path).unwrap();
let meta = recording_meta.studio_meta().unwrap();
- let recordings = cap_rendering::ProjectRecordings::new(&recording_meta, meta);
+ let recordings = cap_rendering::ProjectRecordings::new(&recording_meta.project_path, meta);
let render_options = cap_rendering::RenderOptions {
screen_size: XY::new(
diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rs
index 40ecbc5dc..93ae534cb 100644
--- a/apps/cli/src/record.rs
+++ b/apps/cli/src/record.rs
@@ -1,7 +1,7 @@
use std::{env::current_dir, hash::Hash, path::PathBuf, sync::Arc};
use cap_media::{feeds::CameraFeed, sources::ScreenCaptureTarget};
-use cap_recording::RecordingOptions;
+use cap_recording::{RecordingMode, RecordingOptions};
use clap::Args;
use nokhwa::utils::{ApiBackend, CameraIndex};
use tokio::{io::AsyncBufReadExt, sync::Mutex};
@@ -69,13 +69,14 @@ impl RecordStart {
.path
.unwrap_or_else(|| current_dir().unwrap().join(format!("{id}.cap")));
- let actor = cap_recording::spawn_recording_actor(
+ let actor = cap_recording::spawn_studio_recording_actor(
id,
path,
RecordingOptions {
capture_target: target_info,
camera_label: camera.as_ref().map(|c| c.camera_info.human_name()),
audio_input_name: None,
+ mode: RecordingMode::Studio,
},
camera.map(|c| Arc::new(Mutex::new(c))),
None,
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index b265b1696..82f6272f4 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -36,7 +36,10 @@ use cap_project::XY;
use cap_project::{
ProjectConfiguration, RecordingMeta, Resolution, SharingMeta, StudioRecordingMeta,
};
+use cap_recording::instant_recording::InstantRecordingHandle;
+use cap_recording::RecordingMode;
use cap_recording::RecordingOptions;
+use cap_recording::StudioRecordingHandle;
use cap_rendering::ProjectRecordings;
use clipboard_rs::common::RustImage;
use clipboard_rs::{Clipboard, ClipboardContext};
@@ -48,6 +51,7 @@ use mp4::Mp4Reader;
use notifications::NotificationType;
use png::{ColorType, Encoder};
use presets::PresetsStore;
+use recording::RecordingActor;
use relative_path::RelativePathBuf;
use scap::capturer::Capturer;
use scap::frame::Frame;
@@ -96,7 +100,7 @@ pub struct App {
#[serde(skip)]
handle: AppHandle,
#[serde(skip)]
- current_recording: Option<cap_recording::ActorHandle>,
+ current_recording: Option<RecordingActor>,
#[serde(skip)]
pre_created_video: Option<PreCreatedVideo>,
}
@@ -131,13 +135,13 @@ pub struct PreCreatedVideo {
}
impl App {
- pub fn set_current_recording(&mut self, actor: cap_recording::ActorHandle) {
+ pub fn set_current_recording(&mut self, actor: RecordingActor) {
let current_recording = self.current_recording.insert(actor);
CurrentRecordingChanged.emit(&self.handle).ok();
if matches!(
- current_recording.options.capture_target,
+ current_recording.capture_target(),
ScreenCaptureTarget::Window(_) | ScreenCaptureTarget::Area(_)
) {
let _ = ShowCapWindow::WindowCaptureOccluder.show(&self.handle);
@@ -146,7 +150,7 @@ impl App {
}
}
- pub fn clear_current_recording(&mut self) -> Option<cap_recording::ActorHandle> {
+ pub fn clear_current_recording(&mut self) -> Option<RecordingActor> {
self.close_occluder_window();
self.current_recording.take()
@@ -483,7 +487,7 @@ async fn get_current_recording(
let state = state.read().await;
Ok(JsonValue::new(&state.current_recording.as_ref().map(|r| {
RecordingInfo {
- capture_target: r.options.capture_target.clone(),
+ capture_target: r.capture_target().clone(),
}
})))
}
@@ -2113,6 +2117,7 @@ pub async fn run() {
}),
camera_label: None,
audio_input_name: None,
+ mode: RecordingMode::Studio,
},
current_recording: None,
pre_created_video: None,
@@ -2182,8 +2187,6 @@ pub async fn run() {
.ok();
recording.stop().await.ok();
-
- // recording.stop_and_discard();
}
}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index dfceb5538..e48aed7b8 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1,9 +1,8 @@
-use std::{path::PathBuf, sync::Arc, time::Instant};
+use std::{path::PathBuf, sync::Arc};
use crate::{
audio::AppSounds,
auth::AuthStore,
- create_screenshot,
export::export_video,
general_settings::GeneralSettingsStore,
notifications, open_editor, open_external_link,
@@ -15,20 +14,78 @@ use crate::{
RecordingStarted, RecordingStopped, UploadMode,
};
use cap_fail::fail;
-use cap_flags::FLAGS;
use cap_media::sources::{CaptureScreen, CaptureWindow};
use cap_media::{feeds::CameraFeed, sources::ScreenCaptureTarget};
use cap_project::{
- ProjectConfiguration, StudioRecordingMeta, TimelineConfiguration, TimelineSegment, ZoomSegment,
- XY,
+ ProjectConfiguration, RecordingMeta, RecordingMetaInner, TimelineConfiguration,
+ TimelineSegment, ZoomSegment, XY,
+};
+use cap_recording::{
+ instant_recording::{CompletedInstantRecording, InstantRecordingHandle},
+ CompletedStudioRecording, RecordingError, RecordingMode, StudioRecordingHandle,
};
-use cap_recording::CompletedRecording;
use cap_rendering::ProjectRecordings;
use cap_utils::spawn_actor;
use clipboard_rs::{Clipboard, ClipboardContext};
use tauri::{AppHandle, Manager};
use tauri_specta::Event;
+pub enum RecordingActor {
+ Instant(InstantRecordingHandle),
+ Studio(StudioRecordingHandle),
+}
+
+impl RecordingActor {
+ pub fn capture_target(&self) -> &ScreenCaptureTarget {
+ match self {
+ Self::Instant(a) => &a.options.capture_target,
+ Self::Studio(a) => &a.options.capture_target,
+ }
+ }
+
+ pub async fn pause(&self) -> Result<(), RecordingError> {
+ match self {
+ Self::Instant(a) => a.pause().await,
+ Self::Studio(a) => a.pause().await,
+ }
+ }
+
+ pub async fn resume(&self) -> Result<(), RecordingError> {
+ match self {
+ Self::Instant(a) => a.resume().await,
+ Self::Studio(a) => a.resume().await,
+ }
+ }
+
+ pub async fn stop(&self) -> Result<CompletedRecording, RecordingError> {
+ Ok(match self {
+ Self::Instant(a) => CompletedRecording::Instant(a.stop().await?),
+ Self::Studio(a) => CompletedRecording::Studio(a.stop().await?),
+ })
+ }
+}
+
+pub enum CompletedRecording {
+ Instant(CompletedInstantRecording),
+ Studio(CompletedStudioRecording),
+}
+
+impl CompletedRecording {
+ pub fn id(&self) -> &String {
+ match self {
+ Self::Instant(a) => &a.id,
+ Self::Studio(a) => &a.id,
+ }
+ }
+
+ pub fn project_path(&self) -> &PathBuf {
+ match self {
+ Self::Instant(a) => &a.project_path,
+ Self::Studio(a) => &a.project_path,
+ }
+ }
+}
+
#[tauri::command(async)]
#[specta::specta]
pub fn list_capture_screens() -> Vec<CaptureScreen> {
@@ -59,7 +116,9 @@ pub async fn start_recording(
app: AppHandle,
state_mtx: MutableState<'_, App>,
) -> Result<(), String> {
+ println!("start_recording");
let mut state = state_mtx.write().await;
+ println!("state lock acquired");
let id = uuid::Uuid::new_v4().to_string();
@@ -100,29 +159,67 @@ pub async fn start_recording(
let _ = ShowCapWindow::WindowCaptureOccluder.show(&app);
}
- let (actor, actor_done_rx) = cap_recording::spawn_recording_actor(
- id,
- recording_dir,
- state.start_recording_options.clone(),
- state.camera_feed.clone(),
- state.audio_input_feed.clone(),
- )
+ drop(state);
+
+ println!("spawning actor");
+
+ // done in spawn to catch panics just in case
+ let actor_done_rx = spawn_actor({
+ let state_mtx = Arc::clone(&state_mtx);
+ async move {
+ fail!("recording::spawn_actor");
+ let mut state = state_mtx.write().await;
+
+ let (actor, actor_done_rx) = match state.start_recording_options.mode {
+ RecordingMode::Studio => {
+ let (actor, actor_done_rx) = cap_recording::spawn_studio_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())?;
+
+ (RecordingActor::Studio(actor), actor_done_rx)
+ }
+ RecordingMode::Instant => {
+ let (actor, actor_done_rx) =
+ cap_recording::instant_recording::spawn_instant_recording_actor(
+ id,
+ recording_dir,
+ state.start_recording_options.clone(),
+ state.audio_input_feed.clone(),
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+
+ (RecordingActor::Instant(actor), actor_done_rx)
+ }
+ };
+
+ state.set_current_recording(actor);
+
+ Ok::<_, String>(actor_done_rx)
+ }
+ })
.await
- .map_err(|e| e.to_string())?;
+ .map_err(|e| format!("Failed to spawn recording actor: {}", e))??;
- state.set_current_recording(actor);
- drop(state);
+ println!("spawning actor");
spawn_actor({
let app = app.clone();
let state_mtx = Arc::clone(&state_mtx);
async move {
+ fail!("recording::wait_actor_done");
actor_done_rx.await.ok();
let mut state = state_mtx.write().await;
// this clears the current recording for us
- handle_recording_finished(app, None, &mut state).await.ok();
+ handle_recording_end(app, None, &mut state).await.ok();
}
});
@@ -179,14 +276,15 @@ pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Res
let completed_recording = current_recording.stop().await.map_err(|e| e.to_string())?;
- handle_recording_finished(app, Some(completed_recording), &mut state).await?;
+ handle_recording_end(app, Some(completed_recording), &mut state).await?;
Ok(())
}
-async fn handle_recording_finished(
+// runs when a recording ends, whether from success or failure
+async fn handle_recording_end(
app: AppHandle,
- completed_recording: Option<cap_recording::CompletedRecording>,
+ completed_recording: Option<CompletedRecording>,
state: &mut App,
) -> Result<(), String> {
// Clear current recording, just in case :)
@@ -201,170 +299,164 @@ async fn handle_recording_finished(
}
if let Some(completed_recording) = completed_recording {
- let screenshots_dir = completed_recording.recording_dir.join("screenshots");
- std::fs::create_dir_all(&screenshots_dir).ok();
-
- let recording_meta = &completed_recording.meta;
-
- let recording_dir = completed_recording.recording_dir.clone();
-
- let fire_events = || {
- ShowCapWindow::PrevRecordings.show(&app).ok();
-
- NewRecordingAdded {
- path: recording_dir.clone(),
- }
- .emit(&app)
- .ok();
-
- RecordingStopped {
- path: recording_dir,
- }
- .emit(&app)
- .ok();
- };
-
- match &recording_meta.inner {
- cap_project::RecordingMetaInner::Studio(meta) => {
- let display_output_path = match &meta {
- StudioRecordingMeta::SingleSegment { segment } => {
- recording_meta.path(&segment.display.path)
- }
- StudioRecordingMeta::MultipleSegments { inner } => {
- recording_meta.path(&inner.segments[0].display.path)
- }
- };
-
- let display_screenshot = screenshots_dir.join("display.jpg");
- create_screenshot(display_output_path, display_screenshot.clone(), None).await?;
-
- fire_events();
-
- let recordings = ProjectRecordings::new(&completed_recording.meta, meta);
-
- let config = project_config_from_recording(
- &completed_recording,
- &recordings,
- PresetsStore::get_default_preset(&app)?.map(|p| p.config),
- );
-
- config
- .write(&completed_recording.recording_dir)
- .map_err(|e| e.to_string())?;
-
- if let Some(pre_created_video) = state.pre_created_video.take() {
- let max_fps = meta.max_fps();
- spawn_actor({
- let app = app.clone();
- async move {
- 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 {
- // Copy link to clipboard
- let _ = app
- .state::<MutableState<'_, ClipboardContext>>()
- .write()
- .await
- .set_text(pre_created_video.link.clone());
-
- // Send notification for shareable link
- notifications::send_notification(
- &app,
- notifications::NotificationType::ShareableLinkCopied,
- );
+ handle_recording_finish(&app, completed_recording, state).await?;
+ };
- // Open the pre-created shareable link
- open_external_link(app.clone(), pre_created_video.link.clone())
- .ok();
+ AppSounds::StopRecording.play();
- // Start the upload process in the background with retry mechanism
- let app = app.clone();
+ CurrentRecordingChanged.emit(&app).ok();
- tauri::async_runtime::spawn(async move {
- let max_retries = 3;
- let mut retry_count = 0;
+ Ok(())
+}
- export_video(
+// runs when a recording successfully finishes
+async fn handle_recording_finish(
+ app: &AppHandle,
+ completed_recording: CompletedRecording,
+ state: &mut App,
+) -> Result<(), String> {
+ let recording_dir = completed_recording.project_path().clone();
+ let id = completed_recording.id().clone();
+
+ let meta_inner = match completed_recording {
+ CompletedRecording::Studio(recording) => {
+ let recordings = ProjectRecordings::new(&recording_dir, &recording.meta);
+
+ let config = project_config_from_recording(
+ &recording,
+ &recordings,
+ PresetsStore::get_default_preset(&app)?.map(|p| p.config),
+ );
+
+ config.write(&recording_dir).map_err(|e| e.to_string())?;
+
+ if let Some(pre_created_video) = state.pre_created_video.take() {
+ let max_fps = recording.meta.max_fps();
+ spawn_actor({
+ let app = app.clone();
+ async move {
+ 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 {
+ // Copy link to clipboard
+ let _ = app
+ .state::<MutableState<'_, ClipboardContext>>()
+ .write()
+ .await
+ .set_text(pre_created_video.link.clone());
+
+ // 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 = app.clone();
+
+ tauri::async_runtime::spawn(async move {
+ let max_retries = 3;
+ let mut retry_count = 0;
+
+ export_video(
+ app.clone(),
+ id.clone(),
+ tauri::ipc::Channel::new(|_| Ok(())),
+ true,
+ max_fps,
+ XY::new(1920, 1080),
+ )
+ .await
+ .ok();
+
+ while retry_count < max_retries {
+ match upload_exported_video(
app.clone(),
- completed_recording.id.clone(),
- tauri::ipc::Channel::new(|_| Ok(())),
- true,
- max_fps,
- XY::new(1920, 1080),
+ id.clone(),
+ UploadMode::Initial {
+ pre_created_video: Some(pre_created_video.clone()),
+ },
)
.await
- .ok();
-
- while retry_count < max_retries {
- match upload_exported_video(
- app.clone(),
- completed_recording.id.clone(),
- UploadMode::Initial {
- pre_created_video: 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(
+ {
+ 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,
notifications::NotificationType::UploadFailed,
);
- }
}
}
}
- });
- } else if settings.open_editor_after_recording {
- open_editor(app.clone(), completed_recording.id);
- }
+ }
+ });
+ } else if settings.open_editor_after_recording {
+ open_editor(app.clone(), id);
}
}
- });
- }
+ }
+ });
}
- cap_project::RecordingMetaInner::Instant(meta) => {
- fire_events();
- dbg!(meta);
- }
+ RecordingMetaInner::Studio(recording.meta)
}
+ CompletedRecording::Instant(recording) => RecordingMetaInner::Instant(recording.meta),
};
- AppSounds::StopRecording.play();
+ ShowCapWindow::PrevRecordings.show(&app).ok();
- CurrentRecordingChanged.emit(&app).ok();
+ let _ = NewRecordingAdded {
+ path: recording_dir.clone(),
+ }
+ .emit(app);
+
+ let _ = RecordingStopped {
+ path: recording_dir.clone(),
+ }
+ .emit(app);
+
+ let meta = RecordingMeta {
+ project_path: recording_dir,
+ sharing: None,
+ pretty_name: format!(
+ "Cap {}",
+ chrono::Local::now().format("%Y-%m-%d at %H.%M.%S")
+ ),
+ inner: meta_inner,
+ };
+
+ meta.save_for_project()
+ .map_err(|e| format!("Failed to save recording meta: {e}"))?;
Ok(())
}
fn generate_zoom_segments_from_clicks(
- recording: &CompletedRecording,
+ recording: &CompletedStudioRecording,
recordings: &ProjectRecordings,
) -> Vec<ZoomSegment> {
let mut segments = vec![];
@@ -408,7 +500,7 @@ fn generate_zoom_segments_from_clicks(
}
fn project_config_from_recording(
- completed_recording: &CompletedRecording,
+ completed_recording: &CompletedStudioRecording,
recordings: &ProjectRecordings,
default_config: Option<ProjectConfiguration>,
) -> ProjectConfiguration {
diff --git a/apps/desktop/src/routes/recordings-overlay.tsx b/apps/desktop/src/routes/recordings-overlay.tsx
index 1e757ab68..1b8147dd6 100644
--- a/apps/desktop/src/routes/recordings-overlay.tsx
+++ b/apps/desktop/src/routes/recordings-overlay.tsx
@@ -189,7 +189,7 @@ export default function () {
alt="media preview"
src={`${convertFileSrc(
isRecording
- ? `${media.path}/screenshots/display.jpg`
+ ? `${media.path}/content/segments/segment-0/display.mp4`
: `${media.path}`
)}?t=${Date.now()}`}
onError={() => setImageExists(false)}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 719a81b5c..2e9ff7cf3 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -281,7 +281,8 @@ export type ProjectRecordings = { segments: SegmentRecordings[] }
export type RecordingInfo = { captureTarget: ScreenCaptureTarget }
export type RecordingMeta = (StudioRecordingMeta | InstantRecordingMeta) & { pretty_name: string; sharing?: SharingMeta | null }
export type RecordingMetaChanged = { id: string }
-export type RecordingOptions = { captureTarget: ScreenCaptureTarget; cameraLabel: string | null; audioInputName: string | null }
+export type RecordingMode = "studio" | "instant"
+export type RecordingOptions = { captureTarget: ScreenCaptureTarget; audioInputName: string | null; cameraLabel: string | null; mode: RecordingMode }
export type RecordingOptionsChanged = null
export type RecordingStarted = null
export type RecordingStopped = { path: string }
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 5450d6767..f177fba60 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -43,7 +43,7 @@ impl Renderer {
recording_meta: &RecordingMeta,
meta: &StudioRecordingMeta,
) -> RendererHandle {
- let recordings = ProjectRecordings::new(recording_meta, meta);
+ let recordings = ProjectRecordings::new(&recording_meta.project_path, meta);
let mut max_duration = recordings.duration();
// Check camera duration if it exists
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index b7d91c5a4..4d0c69bb4 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -79,7 +79,7 @@ impl EditorInstance {
return Err("Cannot edit non-studio recordings".to_string());
};
let project = recording_meta.project_config();
- let recordings = ProjectRecordings::new(&recording_meta, meta);
+ let recordings = ProjectRecordings::new(&recording_meta.project_path, meta);
let render_options = RenderOptions {
screen_size: XY::new(
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 848916e4a..c9f38eb1a 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -9,8 +9,8 @@ use scap::{
};
use serde::{Deserialize, Serialize};
use specta::Type;
-use std::{collections::HashMap, ops::ControlFlow};
-use tracing::{error, info, trace, warn};
+use std::{collections::HashMap, ops::ControlFlow, sync::Arc};
+use tracing::{debug, error, info, trace, warn};
use crate::{
data::{FFVideo, RawVideoFormat, VideoInfo},
@@ -93,6 +93,7 @@ pub struct ScreenCaptureSource<TCaptureFormat> {
output_type: Option<FrameType>,
fps: u32,
video_info: VideoInfo,
+ options: Arc<Options>,
_phantom: std::marker::PhantomData<TCaptureFormat>,
}
@@ -104,6 +105,7 @@ impl<TCaptureFormat> Clone for ScreenCaptureSource<TCaptureFormat> {
output_type: self.output_type,
fps: self.fps,
video_info: self.video_info.clone(),
+ options: self.options.clone(),
_phantom: std::marker::PhantomData,
}
}
@@ -112,23 +114,29 @@ impl<TCaptureFormat> Clone for ScreenCaptureSource<TCaptureFormat> {
const MAX_FPS: u32 = 60;
impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
- pub fn init(target: &ScreenCaptureTarget, output_type: Option<FrameType>) -> Self {
+ pub fn init(
+ target: &ScreenCaptureTarget,
+ output_type: Option<FrameType>,
+ ) -> Result<Self, String> {
+ cap_fail::fail!("media::screen_capture::init");
+
let mut this = Self {
target: target.clone(),
output_resolution: None,
output_type,
fps: target.recording_fps(),
video_info: VideoInfo::from_raw(RawVideoFormat::Bgra, 0, 0, MAX_FPS),
+ options: Arc::new(Options::default()),
_phantom: std::marker::PhantomData,
};
- let options = this.create_options();
+ let options = this.create_options()?;
let [frame_width, frame_height] = get_output_frame_size(&options);
this.video_info =
VideoInfo::from_raw(RawVideoFormat::Bgra, frame_width, frame_height, MAX_FPS);
- this
+ Ok(this)
}
pub fn get_bounds(&self) -> Bounds {
@@ -141,7 +149,7 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
}
}
- fn create_options(&self) -> Options {
+ fn create_options(&self) -> Result<Options, String> {
let targets = scap::get_all_targets();
let excluded_targets: Vec<scap::Target> = targets
@@ -177,6 +185,8 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
}),
};
+ debug!("configured target: {:#?}", self.target);
+
let target = match &self.target {
ScreenCaptureTarget::Window(w) => {
let window_target = targets
@@ -223,9 +233,9 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
})
.cloned(),
}
- .expect("Capture target not found");
+ .ok_or_else(|| format!("Capture target not found"))?;
- Options {
+ Ok(Options {
fps: self.fps,
show_cursor: !FLAGS.record_mouse_state,
show_highlight: true,
@@ -233,9 +243,8 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
crop_area,
output_type: self.output_type.unwrap_or(FrameType::BGRAFrame),
output_resolution: self.output_resolution.unwrap_or(ScapResolution::Captured),
- excluded_targets: None,
- // excluded_targets: Some(excluded_targets),
- }
+ excluded_targets: Some(excluded_targets),
+ })
}
pub fn info(&self) -> VideoInfo {
@@ -351,7 +360,7 @@ fn inner<T>(
ScreenCaptureTarget::Window(window) => Some(window.id),
_ => None,
};
- let mut capturer = match Capturer::build(source.create_options()) {
+ let mut capturer = match Capturer::build(source.options.as_ref().clone()) {
Ok(capturer) => capturer,
Err(e) => {
error!("Failed to build capturer: {e}");
@@ -370,6 +379,7 @@ fn inner<T>(
let t = std::time::Instant::now();
loop {
+ println!("plz");
match control_signal.last() {
Some(Control::Shutdown) | None => {
trace!("Received shutdown signal");
@@ -421,12 +431,11 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
control_signal: crate::pipeline::control::PipelineControlSignal,
output: Sender<Self::Output>,
) {
- inner(
- self,
- ready_signal,
- control_signal,
- |capturer| match capturer.raw().get_next_pixel_buffer() {
+ inner(self, ready_signal, control_signal, |capturer| {
+ println!("pixel buffer");
+ match capturer.raw().get_next_pixel_buffer() {
Ok(pixel_buffer) => {
+ println!("got pixel buffer");
if pixel_buffer.height() == 0 || pixel_buffer.width() == 0 {
return Some(ControlFlow::Continue(()));
}
@@ -442,8 +451,8 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
eprintln!("Capture error: {error}");
Some(ControlFlow::Break(()))
}
- },
- )
+ }
+ })
}
}
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
index f162bc8a2..6911cd7e2 100644
--- a/crates/recording/Cargo.toml
+++ b/crates/recording/Cargo.toml
@@ -24,6 +24,7 @@ either = "1.13.0"
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
relative-path = "1.9.3"
screencapturekit = "0.2.8"
+futures = "0.3.31"
[target.'cfg(target_os = "macos")'.dependencies]
cocoa = "0.26.0"
diff --git a/crates/recording/src/actor.rs b/crates/recording/src/actor.rs
index 2d5be7667..061d4c29b 100644
--- a/crates/recording/src/actor.rs
+++ b/crates/recording/src/actor.rs
@@ -32,9 +32,9 @@ use crate::{
RecordingOptions,
};
-enum ActorState {
+enum StudioRecordingActorState {
Recording {
- pipeline: RecordingPipeline,
+ pipeline: StudioRecordingPipeline,
pipeline_done_rx: oneshot::Receiver<()>,
index: u32,
segment_start_time: f64,
@@ -47,26 +47,26 @@ enum ActorState {
Stopped,
}
-pub enum ActorControlMessage {
+pub enum StudioRecordingActorControlMessage {
Pause(oneshot::Sender<Result<(), RecordingError>>),
Resume(oneshot::Sender<Result<(), RecordingError>>),
- Stop(oneshot::Sender<Result<CompletedRecording, RecordingError>>),
+ Stop(oneshot::Sender<Result<CompletedStudioRecording, RecordingError>>),
}
-pub struct Actor {
+pub struct StudioRecordingActor {
id: String,
recording_dir: PathBuf,
options: RecordingOptions,
- segments: Vec<RecordingSegment>,
+ segments: Vec<StudioRecordingSegment>,
}
-pub struct RecordingSegment {
+pub struct StudioRecordingSegment {
pub start: f64,
pub end: f64,
- pipeline: RecordingPipeline,
+ pipeline: StudioRecordingPipeline,
}
-struct RecordingPipeline {
+struct StudioRecordingPipeline {
pub inner: Pipeline<RealTimeClock<()>>,
pub display_output_path: PathBuf,
pub audio_output_path: Option<PathBuf>,
@@ -80,8 +80,8 @@ struct CursorPipeline {
}
#[derive(Clone)]
-pub struct ActorHandle {
- ctrl_tx: flume::Sender<ActorControlMessage>,
+pub struct StudioRecordingHandle {
+ ctrl_tx: flume::Sender<StudioRecordingActorControlMessage>,
pub options: RecordingOptions,
}
@@ -91,7 +91,7 @@ pub enum ActorError {
ActorStopped,
#[error("Failed to send to actor")]
- SendFailed(#[from] flume::SendError<ActorControlMessage>),
+ SendFailed(#[from] flume::SendError<StudioRecordingActorControlMessage>),
}
#[derive(Error, Debug)]
@@ -117,27 +117,27 @@ macro_rules! send_message {
}};
}
-impl ActorHandle {
- pub async fn stop(&self) -> Result<CompletedRecording, RecordingError> {
- send_message!(self.ctrl_tx, ActorControlMessage::Stop)
+impl StudioRecordingHandle {
+ pub async fn stop(&self) -> Result<CompletedStudioRecording, RecordingError> {
+ send_message!(self.ctrl_tx, StudioRecordingActorControlMessage::Stop)
}
pub async fn pause(&self) -> Result<(), RecordingError> {
- send_message!(self.ctrl_tx, ActorControlMessage::Pause)
+ send_message!(self.ctrl_tx, StudioRecordingActorControlMessage::Pause)
}
pub async fn resume(&self) -> Result<(), RecordingError> {
- send_message!(self.ctrl_tx, ActorControlMessage::Resume)
+ send_message!(self.ctrl_tx, StudioRecordingActorControlMessage::Resume)
}
}
-pub async fn spawn_recording_actor(
+pub async fn spawn_stuido_recording_actor(
id: String,
recording_dir: PathBuf,
options: RecordingOptions,
camera_feed: Option<Arc<Mutex<CameraFeed>>>,
audio_input_feed: Option<AudioInputFeed>,
-) -> Result<(ActorHandle, tokio::sync::oneshot::Receiver<()>), RecordingError> {
+) -> Result<(StudioRecordingHandle, tokio::sync::oneshot::Receiver<()>), RecordingError> {
ensure_dir(&recording_dir)?;
let logfile = File::create(recording_dir.join("recording-logs.log"))?;
@@ -211,14 +211,14 @@ pub async fn spawn_recording_actor(
spawn_actor({
let options = options.clone();
async move {
- let mut actor = Actor {
+ let mut actor = StudioRecordingActor {
id,
recording_dir,
options,
segments: Vec::new(),
};
- let mut state = ActorState::Recording {
+ let mut state = StudioRecordingActorState::Recording {
pipeline,
pipeline_done_rx,
index,
@@ -227,7 +227,7 @@ pub async fn spawn_recording_actor(
'outer: loop {
state = match state {
- ActorState::Recording {
+ StudioRecordingActorState::Recording {
mut pipeline,
mut pipeline_done_rx,
index,
@@ -255,8 +255,8 @@ pub async fn spawn_recording_actor(
};
async fn shutdown(
- mut pipeline: RecordingPipeline,
- actor: &mut Actor,
+ mut pipeline: StudioRecordingPipeline,
+ actor: &mut StudioRecordingActor,
segment_start_time: f64,
) -> Result<(Cursors, u32), RecordingError>
{
@@ -284,7 +284,7 @@ pub async fn spawn_recording_actor(
Default::default()
};
- actor.segments.push(RecordingSegment {
+ actor.segments.push(StudioRecordingSegment {
start: segment_start_time,
end: segment_stop_time,
pipeline,
@@ -294,7 +294,7 @@ pub async fn spawn_recording_actor(
}
break match msg {
- ActorControlMessage::Pause(tx) => {
+ StudioRecordingActorControlMessage::Pause(tx) => {
let (res, cursors, next_cursor_id) = match shutdown(
pipeline,
&mut actor,
@@ -309,13 +309,13 @@ pub async fn spawn_recording_actor(
};
tx.send(res.map_err(Into::into)).ok();
- ActorState::Paused {
+ StudioRecordingActorState::Paused {
next_index: index + 1,
cursors,
next_cursor_id,
}
}
- ActorControlMessage::Stop(tx) => {
+ StudioRecordingActorControlMessage::Stop(tx) => {
let res =
shutdown(pipeline, &mut actor, segment_start_time)
.await;
@@ -334,7 +334,7 @@ pub async fn spawn_recording_actor(
};
}
}
- ActorState::Paused {
+ StudioRecordingActorState::Paused {
next_index,
cursors,
next_cursor_id,
@@ -346,11 +346,11 @@ pub async fn spawn_recording_actor(
};
break match msg {
- ActorControlMessage::Stop(tx) => {
+ StudioRecordingActorControlMessage::Stop(tx) => {
tx.send(stop_recording(actor, cursors).await).ok();
break 'outer;
}
- ActorControlMessage::Resume(tx) => {
+ StudioRecordingActorControlMessage::Resume(tx) => {
let (state, res) = match create_segment_pipeline(
&segments_dir,
&cursors_dir,
@@ -364,7 +364,7 @@ pub async fn spawn_recording_actor(
.await
{
Ok((pipeline, pipeline_done_rx)) => (
- ActorState::Recording {
+ StudioRecordingActorState::Recording {
pipeline,
pipeline_done_rx,
index: next_index,
@@ -372,7 +372,10 @@ pub async fn spawn_recording_actor(
},
Ok(()),
),
- Err(e) => (ActorState::Stopped, Err(e.into())),
+ Err(e) => (
+ StudioRecordingActorState::Stopped,
+ Err(e.into()),
+ ),
};
tx.send(res).ok();
@@ -383,7 +386,7 @@ pub async fn spawn_recording_actor(
};
}
}
- ActorState::Stopped => {
+ StudioRecordingActorState::Stopped => {
info!("recording actor paused");
break;
}
@@ -397,7 +400,7 @@ pub async fn spawn_recording_actor(
.in_current_span()
});
- Ok(ActorHandle { ctrl_tx, options })
+ Ok(StudioRecordingHandle { ctrl_tx, options })
}
.instrument(tracing::info_span!("recording"))
.await
@@ -407,19 +410,19 @@ pub async fn spawn_recording_actor(
.map(|a| (a, done_rx))
}
-pub struct CompletedRecording {
+pub struct CompletedStudioRecording {
pub id: String,
pub recording_dir: PathBuf,
pub display_source: ScreenCaptureTarget,
pub meta: RecordingMeta,
pub cursor_data: cap_project::CursorImages,
- pub segments: Vec<RecordingSegment>,
+ pub segments: Vec<StudioRecordingSegment>,
}
async fn stop_recording(
- actor: Actor,
+ actor: StudioRecordingActor,
cursors: Cursors,
-) -> Result<CompletedRecording, RecordingError> {
+) -> Result<CompletedStudioRecording, RecordingError> {
use cap_project::*;
let meta = RecordingMeta {
@@ -507,7 +510,7 @@ async fn stop_recording(
.write(&actor.recording_dir)
.map_err(RecordingError::from)?;
- Ok(CompletedRecording {
+ Ok(CompletedStudioRecording {
id: actor.id,
meta,
cursor_data: Default::default(),
@@ -546,7 +549,7 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
audio_input_feed: Option<&AudioInputFeed>,
prev_cursors: Cursors,
next_cursors_id: u32,
-) -> Result<(RecordingPipeline, oneshot::Receiver<()>), MediaError> {
+) -> Result<(StudioRecordingPipeline, oneshot::Receiver<()>), MediaError> {
let camera_feed = match camera_feed.as_ref() {
Some(camera_feed) => Some(camera_feed.lock().await),
None => None,
@@ -558,132 +561,105 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
let clock = RealTimeClock::<()>::new();
let mut pipeline_builder = Pipeline::builder(clock);
- let instant_mode = true;
- if instant_mode {
- let output_path = segments_dir.join("./recording.mp4");
- let pipeline_builder = TCaptureFormat::make_instant_mode_pipeline(
- pipeline_builder,
- screen_source,
- audio_input_feed.map(AudioInputSource::init),
+ let display_output_path = dir.join("display.mp4");
+
+ trace!("preparing segment pipeline {index}");
+
+ let screen_bounds = screen_source.get_bounds();
+ pipeline_builder = TCaptureFormat::make_capture_pipeline(
+ pipeline_builder,
+ screen_source,
+ &display_output_path,
+ )?;
+
+ info!(
+ r#"screen pipeline prepared, will output to "{}""#,
+ display_output_path
+ .strip_prefix(&segments_dir)
+ .unwrap()
+ .display()
+ );
+ let audio_output_path = if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {
+ let mic_config = mic_source.info();
+ let output_path = dir.join("audio-input.ogg");
+
+ let mic_encoder = OggFile::init(
output_path.clone(),
+ OpusEncoder::factory("microphone", mic_config),
)?;
- let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;
+ pipeline_builder = pipeline_builder
+ .source("microphone_capture", mic_source)
+ .sink("microphone_encoder", mic_encoder);
- pipeline.play().await?;
+ info!(
+ "mic pipeline prepared, will output to {}",
+ output_path.strip_prefix(&segments_dir).unwrap().display()
+ );
- Ok((
- RecordingPipeline {
- inner: pipeline,
- display_output_path: output_path,
- audio_output_path: None,
- camera: None,
- cursor: None,
- },
- pipeline_done_rx,
- ))
+ Some(output_path)
} else {
- let display_output_path = dir.join("display.mp4");
+ None
+ };
- trace!("preparing segment pipeline {index}");
+ let camera = if let Some(camera_source) = camera_feed.map(CameraSource::init) {
+ let camera_config = camera_source.info();
+ let output_path = dir.join("camera.mp4");
- let screen_bounds = screen_source.get_bounds();
- pipeline_builder = TCaptureFormat::make_capture_pipeline(
- pipeline_builder,
- screen_source,
- &display_output_path,
+ let camera_encoder = MP4File::init(
+ "camera",
+ output_path.clone(),
+ H264Encoder::factory("camera", camera_config),
+ |_| None,
)?;
+ pipeline_builder = pipeline_builder
+ .source("camera_capture", camera_source)
+ .sink("camera_encoder", camera_encoder);
+
info!(
- r#"screen pipeline prepared, will output to "{}""#,
- display_output_path
- .strip_prefix(&segments_dir)
- .unwrap()
- .display()
+ "camera pipeline prepared, will output to {}",
+ output_path.strip_prefix(&segments_dir).unwrap().display()
);
- let audio_output_path =
- if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {
- let mic_config = mic_source.info();
- let output_path = dir.join("audio-input.ogg");
-
- let mic_encoder = OggFile::init(
- output_path.clone(),
- OpusEncoder::factory("microphone", mic_config),
- )?;
-
- pipeline_builder = pipeline_builder
- .source("microphone_capture", mic_source)
- .sink("microphone_encoder", mic_encoder);
-
- info!(
- "mic pipeline prepared, will output to {}",
- output_path.strip_prefix(&segments_dir).unwrap().display()
- );
-
- Some(output_path)
- } else {
- None
- };
-
- let camera = if let Some(camera_source) = camera_feed.map(CameraSource::init) {
- let camera_config = camera_source.info();
- let output_path = dir.join("camera.mp4");
-
- let camera_encoder = MP4File::init(
- "camera",
- output_path.clone(),
- H264Encoder::factory("camera", camera_config),
- |_| None,
- )?;
-
- pipeline_builder = pipeline_builder
- .source("camera_capture", camera_source)
- .sink("camera_encoder", camera_encoder);
-
- info!(
- "camera pipeline prepared, will output to {}",
- output_path.strip_prefix(&segments_dir).unwrap().display()
- );
-
- Some(CameraPipelineInfo {
- output_path,
- fps: (camera_config.frame_rate.0 / camera_config.frame_rate.1) as u32,
- })
- } else {
- None
- };
-
- let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;
-
- let cursor = FLAGS.record_mouse_state.then(|| {
- let cursor = spawn_cursor_recorder(
- screen_bounds,
- cursors_dir.clone(),
- prev_cursors,
- next_cursors_id,
- );
-
- CursorPipeline {
- output_path: dir.join("cursor.json"),
- actor: Some(cursor),
- }
- });
-
- pipeline.play().await?;
-
- info!("pipeline playing");
-
- Ok((
- RecordingPipeline {
- inner: pipeline,
- display_output_path,
- audio_output_path,
- camera,
- cursor,
- },
- pipeline_done_rx,
- ))
- }
+
+ Some(CameraPipelineInfo {
+ output_path,
+ fps: (camera_config.frame_rate.0 / camera_config.frame_rate.1) as u32,
+ })
+ } else {
+ None
+ };
+
+ let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;
+
+ let cursor = FLAGS.record_mouse_state.then(|| {
+ let cursor = spawn_cursor_recorder(
+ screen_bounds,
+ cursors_dir.clone(),
+ prev_cursors,
+ next_cursors_id,
+ );
+
+ CursorPipeline {
+ output_path: dir.join("cursor.json"),
+ actor: Some(cursor),
+ }
+ });
+
+ pipeline.play().await?;
+
+ info!("pipeline playing");
+
+ Ok((
+ StudioRecordingPipeline {
+ inner: pipeline,
+ display_output_path,
+ audio_output_path,
+ camera,
+ cursor,
+ },
+ pipeline_done_rx,
+ ))
}
struct CameraPipelineInfo {
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs
new file mode 100644
index 000000000..56c9bc330
--- /dev/null
+++ b/crates/recording/src/capture_pipeline.rs
@@ -0,0 +1,152 @@
+use std::{
+ fs::File,
+ path::PathBuf,
+ sync::Arc,
+ time::{SystemTime, UNIX_EPOCH},
+};
+
+use cap_flags::FLAGS;
+use cap_media::{
+ data::Pixel,
+ encoders::{H264Encoder, MP4AVAssetWriterEncoder, MP4File, OggFile, OpusEncoder},
+ feeds::{AudioInputFeed, CameraFeed},
+ pipeline::{builder::PipelineBuilder, Pipeline, RealTimeClock},
+ sources::{AudioInputSource, CameraSource, ScreenCaptureSource, ScreenCaptureTarget},
+ MediaError,
+};
+use cap_project::{CursorEvents, RecordingMeta};
+use cap_utils::spawn_actor;
+use either::Either;
+use futures::future;
+use relative_path::{RelativePath, RelativePathBuf};
+use thiserror::Error;
+use tokio::sync::{oneshot, Mutex};
+use tracing::{
+ debug, info,
+ instrument::{self, WithSubscriber},
+ trace, Instrument,
+};
+use tracing_subscriber::{fmt::FormatFields, layer::SubscriberExt, Layer};
+
+use crate::{
+ cursor::{spawn_cursor_recorder, CursorActor, Cursors},
+ RecordingError, RecordingOptions,
+};
+
+pub type CapturePipelineBuilder = PipelineBuilder<RealTimeClock<()>>;
+
+pub trait MakeCapturePipeline: std::fmt::Debug + 'static {
+ fn make_capture_pipeline(
+ builder: CapturePipelineBuilder,
+ source: ScreenCaptureSource<Self>,
+ output_path: impl Into<PathBuf>,
+ ) -> Result<CapturePipelineBuilder, MediaError>
+ where
+ Self: Sized;
+
+ fn make_instant_mode_pipeline(
+ builder: CapturePipelineBuilder,
+ source: ScreenCaptureSource<Self>,
+ audio: Option<AudioInputSource>,
+ output_path: impl Into<PathBuf>,
+ ) -> Result<CapturePipelineBuilder, MediaError>
+ where
+ Self: Sized;
+}
+
+#[cfg(target_os = "macos")]
+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 screen_encoder = cap_media::encoders::MP4AVAssetWriterEncoder::init(
+ "screen",
+ screen_config,
+ None,
+ output_path.into(),
+ None,
+ )?;
+
+ Ok(builder
+ .source("screen_capture", source)
+ .sink("screen_capture_encoder", screen_encoder))
+ }
+
+ fn make_instant_mode_pipeline(
+ builder: CapturePipelineBuilder,
+ source: ScreenCaptureSource<Self>,
+ audio: Option<AudioInputSource>,
+ output_path: impl Into<PathBuf>,
+ ) -> Result<CapturePipelineBuilder, MediaError> {
+ let mp4 = Arc::new(std::sync::Mutex::new(MP4AVAssetWriterEncoder::init(
+ "mp4",
+ source.info(),
+ audio.as_ref().map(|f| f.info()),
+ output_path.into(),
+ Some(1080),
+ )?));
+
+ let mut builder = builder
+ .source("screen_capture", source)
+ .sink("screen_encoder", mp4.clone());
+
+ if let Some(audio) = audio {
+ builder = builder
+ .source("microphone_capture", audio)
+ .sink("mic_encoder", mp4.clone());
+ }
+
+ Ok(builder)
+ }
+}
+
+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_encoder = MP4File::init(
+ "screen",
+ output_path.into(),
+ H264Encoder::factory("screen", screen_config),
+ |_| None,
+ )?;
+ Ok(builder
+ .source("screen_capture", source)
+ .sink("screen_capture_encoder", screen_encoder))
+ }
+
+ fn make_instant_mode_pipeline(
+ builder: CapturePipelineBuilder,
+ source: ScreenCaptureSource<Self>,
+ audio: Option<AudioInputSource>,
+ output_path: impl Into<PathBuf>,
+ ) -> Result<CapturePipelineBuilder, MediaError>
+ where
+ Self: Sized,
+ {
+ todo!()
+ }
+}
+
+pub fn create_screen_capture(
+ capture_target: &ScreenCaptureTarget,
+) -> Result<ScreenCaptureSource<impl MakeCapturePipeline>, RecordingError> {
+ #[cfg(target_os = "macos")]
+ {
+ ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(capture_target, None)
+ .map_err(|e| RecordingError::Media(MediaError::TaskLaunch(e)))
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ ScreenCaptureSource::<cap_media::sources::AVFrameCapture>::init(capture_target, None)
+ }
+}
diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs
index 8357e091e..9e802f7ad 100644
--- a/crates/recording/src/cursor.rs
+++ b/crates/recording/src/cursor.rs
@@ -166,7 +166,6 @@ pub fn spawn_cursor_recorder(
#[cfg(target_os = "macos")]
let (mouse_x, mouse_y) = {
let primary_bounds = cap_media::platform::primary_monitor_bounds();
- dbg!(primary_bounds);
let mouse_x = mouse_x - screen_bounds.x as i32;
let mouse_y = mouse_y
@@ -213,8 +212,6 @@ pub fn spawn_cursor_recorder(
y.max(0.0).min(1.0)
};
- debug!("Normalized coords: ({}, {})", x, y);
-
let mouse_event = CursorMoveEvent {
active_modifiers: vec![],
cursor_id: cursor_id.clone(),
diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rs
new file mode 100644
index 000000000..38ab776f9
--- /dev/null
+++ b/crates/recording/src/instant_recording.rs
@@ -0,0 +1,392 @@
+use std::{
+ fs::File,
+ path::PathBuf,
+ sync::Arc,
+ time::{SystemTime, UNIX_EPOCH},
+};
+
+use cap_flags::FLAGS;
+use cap_media::{
+ data::Pixel,
+ encoders::{H264Encoder, MP4AVAssetWriterEncoder, MP4File, OggFile, OpusEncoder},
+ feeds::{AudioInputFeed, CameraFeed},
+ pipeline::{builder::PipelineBuilder, Pipeline, RealTimeClock},
+ sources::{AudioInputSource, CameraSource, ScreenCaptureSource, ScreenCaptureTarget},
+ MediaError,
+};
+use cap_project::{CursorEvents, InstantRecordingMeta, RecordingMeta};
+use cap_utils::spawn_actor;
+use either::Either;
+use futures::{future, FutureExt};
+use relative_path::{RelativePath, RelativePathBuf};
+use thiserror::Error;
+use tokio::sync::{oneshot, Mutex};
+use tracing::{
+ debug, error, info,
+ instrument::{self, WithSubscriber},
+ trace, Instrument,
+};
+use tracing_subscriber::{fmt::FormatFields, layer::SubscriberExt, Layer};
+
+use crate::{
+ capture_pipeline::{create_screen_capture, MakeCapturePipeline},
+ ActorError, RecordingError, RecordingOptions,
+};
+
+struct InstantRecordingPipeline {
+ pub inner: Pipeline<RealTimeClock<()>>,
+ pub output_path: PathBuf,
+}
+
+enum InstantRecordingActorState {
+ Recording {
+ pipeline: InstantRecordingPipeline,
+ pipeline_done_rx: oneshot::Receiver<()>,
+ segment_start_time: f64,
+ },
+ Paused,
+ Stopped,
+}
+
+#[derive(Clone)]
+pub struct InstantRecordingHandle {
+ ctrl_tx: flume::Sender<InstantRecordingActorControlMessage>,
+ pub options: RecordingOptions,
+}
+
+macro_rules! send_message {
+ ($ctrl_tx:expr, $variant:path) => {{
+ let (tx, rx) = oneshot::channel();
+ $ctrl_tx
+ .send($variant(tx))
+ .map_err(|_| flume::SendError(()))
+ .map_err(ActorError::from)?;
+ rx.await.map_err(|_| ActorError::ActorStopped)?
+ }};
+}
+
+impl InstantRecordingHandle {
+ pub async fn stop(&self) -> Result<CompletedInstantRecording, RecordingError> {
+ send_message!(self.ctrl_tx, InstantRecordingActorControlMessage::Stop)
+ }
+
+ pub async fn pause(&self) -> Result<(), RecordingError> {
+ send_message!(self.ctrl_tx, InstantRecordingActorControlMessage::Pause)
+ }
+
+ pub async fn resume(&self) -> Result<(), RecordingError> {
+ send_message!(self.ctrl_tx, InstantRecordingActorControlMessage::Resume)
+ }
+}
+
+pub enum InstantRecordingActorControlMessage {
+ Pause(oneshot::Sender<Result<(), RecordingError>>),
+ Resume(oneshot::Sender<Result<(), RecordingError>>),
+ Stop(oneshot::Sender<Result<CompletedInstantRecording, RecordingError>>),
+}
+
+impl std::fmt::Debug for InstantRecordingActorControlMessage {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Pause(_) => write!(f, "Pause"),
+ Self::Resume(_) => write!(f, "Resume"),
+ Self::Stop(_) => write!(f, "Stop"),
+ }
+ }
+}
+
+pub struct InstantRecordingActor {
+ id: String,
+ recording_dir: PathBuf,
+ capture_target: ScreenCaptureTarget,
+ audio_input_name: Option<String>,
+}
+
+pub struct CompletedInstantRecording {
+ pub id: String,
+ pub project_path: PathBuf,
+ pub display_source: ScreenCaptureTarget,
+ pub meta: InstantRecordingMeta,
+}
+
+#[tracing::instrument(skip_all, name = "standalone")]
+async fn create_pipeline<TCaptureFormat: MakeCapturePipeline>(
+ output_path: PathBuf,
+ screen_source: ScreenCaptureSource<TCaptureFormat>,
+ audio_input_feed: Option<&AudioInputFeed>,
+) -> Result<(InstantRecordingPipeline, oneshot::Receiver<()>), MediaError> {
+ let clock = RealTimeClock::<()>::new();
+ let pipeline_builder = Pipeline::builder(clock);
+
+ let pipeline_builder = TCaptureFormat::make_instant_mode_pipeline(
+ pipeline_builder,
+ screen_source,
+ audio_input_feed.map(AudioInputSource::init),
+ output_path.clone(),
+ )?;
+
+ let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;
+
+ pipeline.play().await?;
+
+ Ok((
+ InstantRecordingPipeline {
+ inner: pipeline,
+ output_path,
+ },
+ pipeline_done_rx,
+ ))
+}
+
+pub async fn spawn_instant_recording_actor(
+ id: String,
+ recording_dir: PathBuf,
+ options: RecordingOptions,
+ audio_input_feed: Option<AudioInputFeed>,
+) -> Result<(InstantRecordingHandle, tokio::sync::oneshot::Receiver<()>), RecordingError> {
+ ensure_dir(&recording_dir)?;
+ let logfile = File::create(recording_dir.join("recording-logs.log"))?;
+
+ let collector = tracing_subscriber::registry()
+ .with(
+ tracing_subscriber::fmt::layer()
+ .with_ansi(false)
+ .with_target(false)
+ .with_writer(logfile)
+ .with_filter(
+ tracing_subscriber::filter::EnvFilter::builder()
+ .with_default_directive(tracing::level_filters::LevelFilter::TRACE.into())
+ .from_env_lossy(),
+ ),
+ )
+ .with(
+ tracing_subscriber::fmt::layer()
+ .with_ansi(true)
+ .with_target(false)
+ .with_filter(
+ tracing_subscriber::filter::EnvFilter::builder()
+ .with_default_directive(tracing::level_filters::LevelFilter::TRACE.into())
+ .from_env_lossy(),
+ ),
+ );
+
+ let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
+
+ async {
+ async {
+ let run = async || {
+ trace!("creating recording actor");
+
+ let content_dir = ensure_dir(&recording_dir.join("content"))?;
+
+ let screen_source = create_screen_capture(&options.capture_target)?;
+
+ debug!("screen capture: {screen_source:#?}");
+
+ if let Some(audio_feed) = &audio_input_feed {
+ debug!("mic audio info: {:#?}", audio_feed.audio_info())
+ }
+
+ let (pipeline, pipeline_done_rx) = create_pipeline(
+ content_dir.join("output.mp4"),
+ screen_source.clone(),
+ audio_input_feed.as_ref(),
+ )
+ .await?;
+
+ let segment_start_time = current_time_f64();
+
+ let (ctrl_tx, ctrl_rx) = flume::bounded(1);
+
+ trace!("spawning recording actor");
+
+ spawn_actor({
+ let options = options.clone();
+ async move {
+ let mut actor = InstantRecordingActor {
+ id,
+ recording_dir,
+ capture_target: options.capture_target,
+ audio_input_name: options.audio_input_name,
+ };
+
+ let mut state = InstantRecordingActorState::Recording {
+ pipeline,
+ pipeline_done_rx,
+ segment_start_time,
+ };
+
+ 'outer: loop {
+ state = match state {
+ InstantRecordingActorState::Recording {
+ mut pipeline,
+ mut pipeline_done_rx,
+ segment_start_time,
+ } => {
+ info!("recording actor recording");
+ loop {
+ let msg = tokio::select! {
+ _ = &mut pipeline_done_rx => {
+ break 'outer;
+ }
+ msg = ctrl_rx.recv_async() => {
+ let Ok(msg) = msg else {
+ break 'outer;
+ };
+
+ info!("received control message: {msg:?}");
+
+ msg
+ }
+ };
+
+ async fn shutdown(
+ mut pipeline: InstantRecordingPipeline,
+ actor: &mut InstantRecordingActor,
+ segment_start_time: f64,
+ ) -> Result<(), RecordingError>
+ {
+ pipeline.inner.shutdown().await?;
+ Ok(())
+ }
+
+ break match msg {
+ InstantRecordingActorControlMessage::Pause(tx) => {
+ let res = shutdown(
+ pipeline,
+ &mut actor,
+ segment_start_time,
+ )
+ .await;
+
+ tx.send(res.map_err(Into::into)).ok();
+ InstantRecordingActorState::Paused
+ }
+ InstantRecordingActorControlMessage::Stop(tx) => {
+ let res = shutdown(
+ pipeline,
+ &mut actor,
+ segment_start_time,
+ )
+ .await;
+ let res = match res {
+ Ok(_) => stop_recording(actor).await,
+ Err(e) => Err(e),
+ };
+
+ tx.send(res).ok();
+
+ break 'outer;
+ }
+ _ => continue,
+ };
+ }
+ }
+ InstantRecordingActorState::Paused => {
+ info!("recording actor paused");
+ loop {
+ let Ok(msg) = ctrl_rx.recv_async().await else {
+ break 'outer;
+ };
+
+ break match msg {
+ InstantRecordingActorControlMessage::Stop(tx) => {
+ tx.send(stop_recording(actor).await).ok();
+ break 'outer;
+ }
+ InstantRecordingActorControlMessage::Resume(tx) => {
+ // let (state, res) = match create_pipeline(
+ // &segments_dir,
+ // &cursors_dir,
+ // next_index,
+ // screen_source.clone(),
+ // camera_feed.as_deref(),
+ // audio_input_feed.as_ref(),
+ // cursors,
+ // next_cursor_id,
+ // )
+ // .await
+ // {
+ // Ok((pipeline, pipeline_done_rx)) => (
+ // InstantRecordingActorState::Recording {
+ // pipeline,
+ // pipeline_done_rx,
+ // index: next_index,
+ // segment_start_time: current_time_f64(),
+ // },
+ // Ok(()),
+ // ),
+ // Err(e) => (
+ // InstantRecordingActorState::Stopped,
+ // Err(e.into()),
+ // ),
+ // };
+
+ // tx.send(res).ok();
+
+ state
+ }
+ _ => continue,
+ };
+ }
+ }
+ InstantRecordingActorState::Stopped => {
+ info!("recording actor paused");
+ break;
+ }
+ };
+ }
+
+ info!("recording actor finished");
+
+ done_tx.send(()).ok();
+ }
+ .in_current_span()
+ });
+
+ Ok(InstantRecordingHandle { ctrl_tx, options })
+ };
+
+ match run().await {
+ Ok(a) => Ok(a),
+ Err(e) => {
+ error!("Failed to start recording actor: {}", e);
+ Err(e)
+ }
+ }
+ }
+ .instrument(tracing::info_span!("recording"))
+ .await
+ }
+ .with_subscriber(collector)
+ .await
+ .map(|a| (a, done_rx))
+}
+
+async fn stop_recording(
+ actor: InstantRecordingActor,
+) -> Result<CompletedInstantRecording, RecordingError> {
+ use cap_project::*;
+
+ Ok(CompletedInstantRecording {
+ id: actor.id,
+ project_path: actor.recording_dir.clone(),
+ meta: InstantRecordingMeta {
+ fps: actor.capture_target.recording_fps(),
+ sample_rate: None,
+ },
+ display_source: actor.capture_target,
+ })
+}
+
+fn ensure_dir(path: &PathBuf) -> Result<PathBuf, MediaError> {
+ std::fs::create_dir_all(&path)?;
+ Ok(path.clone())
+}
+
+fn current_time_f64() -> f64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64()
+}
diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs
index 1bb618745..58cad1419 100644
--- a/crates/recording/src/lib.rs
+++ b/crates/recording/src/lib.rs
@@ -1,17 +1,30 @@
-pub mod actor;
+mod capture_pipeline;
pub mod cursor;
+pub mod instant_recording;
+pub mod studio_recording;
-pub use actor::{spawn_recording_actor, ActorHandle, CompletedRecording, RecordingError};
+pub use studio_recording::{
+ spawn_studio_recording_actor, CompletedStudioRecording, StudioRecordingHandle,
+};
-use cap_media::sources::*;
+use cap_media::{sources::*, MediaError};
use serde::{Deserialize, Serialize};
+use thiserror::Error;
+
+#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub enum RecordingMode {
+ Studio,
+ Instant,
+}
#[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>,
+ pub camera_label: Option<String>,
+ pub mode: RecordingMode,
}
impl Default for RecordingOptions {
@@ -24,6 +37,7 @@ impl Default for RecordingOptions {
}),
camera_label: None,
audio_input_name: None,
+ mode: RecordingMode::Studio,
}
}
}
@@ -37,3 +51,27 @@ impl RecordingOptions {
self.audio_input_name.as_deref()
}
}
+
+#[derive(Error, Debug)]
+pub enum ActorError {
+ #[error("Actor has stopped")]
+ ActorStopped,
+
+ #[error("Failed to send to actor")]
+ SendFailed(#[from] flume::SendError<()>),
+}
+
+#[derive(Error, Debug)]
+pub enum RecordingError {
+ #[error("Media error: {0}")]
+ Media(#[from] MediaError),
+
+ #[error("Actor error: {0}")]
+ Actor(#[from] ActorError),
+
+ #[error("Serde/{0}")]
+ Serde(#[from] serde_json::Error),
+
+ #[error("IO/{0}")]
+ Io(#[from] std::io::Error),
+}
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
new file mode 100644
index 000000000..ecbd2317b
--- /dev/null
+++ b/crates/recording/src/studio_recording.rs
@@ -0,0 +1,626 @@
+use std::{
+ fs::File,
+ path::PathBuf,
+ sync::Arc,
+ time::{SystemTime, UNIX_EPOCH},
+};
+
+use cap_flags::FLAGS;
+use cap_media::{
+ encoders::{H264Encoder, MP4File, OggFile, OpusEncoder},
+ feeds::{AudioInputFeed, CameraFeed},
+ pipeline::{Pipeline, RealTimeClock},
+ sources::{AudioInputSource, CameraSource, ScreenCaptureSource, ScreenCaptureTarget},
+ MediaError,
+};
+use cap_project::{CursorEvents, StudioRecordingMeta};
+use cap_utils::spawn_actor;
+use relative_path::RelativePathBuf;
+use tokio::sync::{oneshot, Mutex};
+use tracing::{debug, error, info, instrument::WithSubscriber, trace, Instrument};
+use tracing_subscriber::{layer::SubscriberExt, Layer};
+
+use crate::{
+ capture_pipeline::{create_screen_capture, MakeCapturePipeline},
+ cursor::{spawn_cursor_recorder, CursorActor, Cursors},
+ ActorError, RecordingError, RecordingOptions,
+};
+
+enum StudioRecordingActorState {
+ Recording {
+ pipeline: StudioRecordingPipeline,
+ pipeline_done_rx: oneshot::Receiver<()>,
+ index: u32,
+ segment_start_time: f64,
+ },
+ Paused {
+ next_index: u32,
+ cursors: Cursors,
+ next_cursor_id: u32,
+ },
+ Stopped,
+}
+
+pub enum StudioRecordingActorControlMessage {
+ Pause(oneshot::Sender<Result<(), RecordingError>>),
+ Resume(oneshot::Sender<Result<(), RecordingError>>),
+ Stop(oneshot::Sender<Result<CompletedStudioRecording, RecordingError>>),
+}
+
+pub struct StudioRecordingActor {
+ id: String,
+ recording_dir: PathBuf,
+ options: RecordingOptions,
+ segments: Vec<StudioRecordingSegment>,
+}
+
+pub struct StudioRecordingSegment {
+ pub start: f64,
+ pub end: f64,
+ pipeline: StudioRecordingPipeline,
+}
+
+struct StudioRecordingPipeline {
+ pub inner: Pipeline<RealTimeClock<()>>,
+ pub display_output_path: PathBuf,
+ pub audio_output_path: Option<PathBuf>,
+ pub camera: Option<CameraPipelineInfo>,
+ pub cursor: Option<CursorPipeline>,
+}
+
+struct CursorPipeline {
+ output_path: PathBuf,
+ actor: Option<CursorActor>,
+}
+
+#[derive(Clone)]
+pub struct StudioRecordingHandle {
+ ctrl_tx: flume::Sender<StudioRecordingActorControlMessage>,
+ pub options: RecordingOptions,
+}
+
+macro_rules! send_message {
+ ($ctrl_tx:expr, $variant:path) => {{
+ let (tx, rx) = oneshot::channel();
+ $ctrl_tx
+ .send($variant(tx))
+ .map_err(|_| flume::SendError(()))
+ .map_err(ActorError::from)?;
+ rx.await.map_err(|_| ActorError::ActorStopped)?
+ }};
+}
+
+impl StudioRecordingHandle {
+ pub async fn stop(&self) -> Result<CompletedStudioRecording, RecordingError> {
+ send_message!(self.ctrl_tx, StudioRecordingActorControlMessage::Stop)
+ }
+
+ pub async fn pause(&self) -> Result<(), RecordingError> {
+ send_message!(self.ctrl_tx, StudioRecordingActorControlMessage::Pause)
+ }
+
+ pub async fn resume(&self) -> Result<(), RecordingError> {
+ send_message!(self.ctrl_tx, StudioRecordingActorControlMessage::Resume)
+ }
+}
+
+pub async fn spawn_studio_recording_actor(
+ id: String,
+ recording_dir: PathBuf,
+ options: RecordingOptions,
+ camera_feed: Option<Arc<Mutex<CameraFeed>>>,
+ audio_input_feed: Option<AudioInputFeed>,
+) -> Result<(StudioRecordingHandle, tokio::sync::oneshot::Receiver<()>), RecordingError> {
+ ensure_dir(&recording_dir)?;
+ let logfile = File::create(recording_dir.join("recording-logs.log"))?;
+
+ let collector = tracing_subscriber::registry()
+ .with(
+ tracing_subscriber::fmt::layer()
+ .with_ansi(false)
+ .with_target(false)
+ .with_writer(logfile)
+ .with_filter(
+ tracing_subscriber::filter::EnvFilter::builder()
+ .with_default_directive(tracing::level_filters::LevelFilter::TRACE.into())
+ .from_env_lossy(),
+ ),
+ )
+ .with(
+ tracing_subscriber::fmt::layer()
+ .with_ansi(true)
+ .with_target(false)
+ .with_filter(
+ tracing_subscriber::filter::EnvFilter::builder()
+ .with_default_directive(tracing::level_filters::LevelFilter::TRACE.into())
+ .from_env_lossy(),
+ ),
+ );
+
+ let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
+
+ async {
+ let run = async || {
+ trace!("creating recording actor");
+
+ 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.capture_target)?;
+
+ debug!("screen capture: {screen_source:#?}");
+
+ if let Some(camera_feed) = &camera_feed {
+ let camera_feed = camera_feed.lock().await;
+ debug!("camera device info: {:#?}", camera_feed.camera_info());
+ debug!("camera video info: {:#?}", camera_feed.video_info());
+ }
+
+ if let Some(audio_feed) = &audio_input_feed {
+ debug!("mic audio info: {:#?}", audio_feed.audio_info())
+ }
+
+ let index = 0;
+ let (pipeline, pipeline_done_rx) = create_segment_pipeline(
+ &segments_dir,
+ &cursors_dir,
+ index,
+ screen_source.clone(),
+ camera_feed.as_deref(),
+ audio_input_feed.as_ref(),
+ Default::default(),
+ index,
+ )
+ .await?;
+
+ let segment_start_time = current_time_f64();
+
+ let (ctrl_tx, ctrl_rx) = flume::bounded(1);
+
+ trace!("spawning recording actor");
+
+ spawn_actor({
+ let options = options.clone();
+ async move {
+ let mut actor = StudioRecordingActor {
+ id,
+ recording_dir,
+ options,
+ segments: Vec::new(),
+ };
+
+ let mut state = StudioRecordingActorState::Recording {
+ pipeline,
+ pipeline_done_rx,
+ index,
+ segment_start_time,
+ };
+
+ 'outer: loop {
+ state = match state {
+ StudioRecordingActorState::Recording {
+ mut pipeline,
+ mut pipeline_done_rx,
+ index,
+ segment_start_time,
+ } => {
+ info!("recording actor recording");
+ loop {
+ let msg = tokio::select! {
+ _ = &mut pipeline_done_rx => {
+ if let Some(cursor) = &mut pipeline.cursor {
+ if let Some(actor) = cursor.actor.take() {
+ actor.stop().await;
+ }
+ }
+
+ break 'outer;
+ }
+ msg = ctrl_rx.recv_async() => {
+ let Ok(msg) = msg else {
+ break 'outer;
+ };
+
+ msg
+ }
+ };
+
+ async fn shutdown(
+ mut pipeline: StudioRecordingPipeline,
+ actor: &mut StudioRecordingActor,
+ segment_start_time: f64,
+ ) -> Result<(Cursors, u32), RecordingError>
+ {
+ pipeline.inner.shutdown().await?;
+
+ let segment_stop_time = current_time_f64();
+
+ let cursors = if let Some(cursor) = &mut pipeline.cursor {
+ if let Some(actor) = cursor.actor.take() {
+ let res = actor.stop().await;
+
+ std::fs::write(
+ &cursor.output_path,
+ serde_json::to_string_pretty(&CursorEvents {
+ clicks: res.clicks,
+ moves: res.moves,
+ })?,
+ )?;
+
+ (res.cursors, res.next_cursor_id)
+ } else {
+ Default::default()
+ }
+ } else {
+ Default::default()
+ };
+
+ actor.segments.push(StudioRecordingSegment {
+ start: segment_start_time,
+ end: segment_stop_time,
+ pipeline,
+ });
+
+ Ok(cursors)
+ }
+
+ break match msg {
+ StudioRecordingActorControlMessage::Pause(tx) => {
+ let (res, cursors, next_cursor_id) = match shutdown(
+ pipeline,
+ &mut actor,
+ segment_start_time,
+ )
+ .await
+ {
+ Ok((cursors, next_cursor_id)) => {
+ (Ok(()), cursors, next_cursor_id)
+ }
+ Err(e) => (Err(e), Default::default(), 0),
+ };
+
+ tx.send(res.map_err(Into::into)).ok();
+ StudioRecordingActorState::Paused {
+ next_index: index + 1,
+ cursors,
+ next_cursor_id,
+ }
+ }
+ StudioRecordingActorControlMessage::Stop(tx) => {
+ let res =
+ shutdown(pipeline, &mut actor, segment_start_time)
+ .await;
+ let res = match res {
+ Ok((cursors, _)) => {
+ stop_recording(actor, cursors).await
+ }
+ Err(e) => Err(e),
+ };
+
+ tx.send(res).ok();
+
+ break 'outer;
+ }
+ _ => continue,
+ };
+ }
+ }
+ StudioRecordingActorState::Paused {
+ next_index,
+ cursors,
+ next_cursor_id,
+ } => {
+ info!("recording actor paused");
+ loop {
+ let Ok(msg) = ctrl_rx.recv_async().await else {
+ break 'outer;
+ };
+
+ break match msg {
+ StudioRecordingActorControlMessage::Stop(tx) => {
+ tx.send(stop_recording(actor, cursors).await).ok();
+ break 'outer;
+ }
+ StudioRecordingActorControlMessage::Resume(tx) => {
+ let (state, res) = match create_segment_pipeline(
+ &segments_dir,
+ &cursors_dir,
+ next_index,
+ screen_source.clone(),
+ camera_feed.as_deref(),
+ audio_input_feed.as_ref(),
+ cursors,
+ next_cursor_id,
+ )
+ .await
+ {
+ Ok((pipeline, pipeline_done_rx)) => (
+ StudioRecordingActorState::Recording {
+ pipeline,
+ pipeline_done_rx,
+ index: next_index,
+ segment_start_time: current_time_f64(),
+ },
+ Ok(()),
+ ),
+ Err(e) => (
+ StudioRecordingActorState::Stopped,
+ Err(e.into()),
+ ),
+ };
+
+ tx.send(res).ok();
+
+ state
+ }
+ _ => continue,
+ };
+ }
+ }
+ StudioRecordingActorState::Stopped => {
+ info!("recording actor paused");
+ break;
+ }
+ };
+ }
+
+ info!("recording actor finished");
+
+ done_tx.send(()).ok();
+ }
+ .in_current_span()
+ });
+
+ Ok(StudioRecordingHandle { ctrl_tx, options })
+ };
+
+ match run().await {
+ Ok(a) => Ok(a),
+ Err(e) => {
+ error!("Failed to start recording actor: {}", e);
+ Err(e)
+ }
+ }
+ }
+ .instrument(tracing::info_span!("recording"))
+ .with_subscriber(collector)
+ .await
+ .map(|a| (a, done_rx))
+}
+
+pub struct CompletedStudioRecording {
+ pub id: String,
+ pub project_path: PathBuf,
+ pub display_source: ScreenCaptureTarget,
+ pub meta: StudioRecordingMeta,
+ pub cursor_data: cap_project::CursorImages,
+ pub segments: Vec<StudioRecordingSegment>,
+}
+
+async fn stop_recording(
+ actor: StudioRecordingActor,
+ cursors: Cursors,
+) -> Result<CompletedStudioRecording, RecordingError> {
+ use cap_project::*;
+
+ let meta = StudioRecordingMeta::MultipleSegments {
+ inner: MultipleSegments {
+ segments: {
+ actor
+ .segments
+ .iter()
+ .map(|s| MultipleSegment {
+ display: Display {
+ path: RelativePathBuf::from_path(
+ s.pipeline
+ .display_output_path
+ .strip_prefix(&actor.recording_dir)
+ .unwrap(),
+ )
+ .unwrap(),
+ fps: actor.options.capture_target.recording_fps(),
+ },
+ camera: s.pipeline.camera.as_ref().map(|camera| CameraMeta {
+ path: RelativePathBuf::from_path(
+ camera
+ .output_path
+ .strip_prefix(&actor.recording_dir)
+ .unwrap()
+ .to_owned(),
+ )
+ .unwrap(),
+ fps: camera.fps,
+ }),
+ audio: s.pipeline.audio_output_path.as_ref().map(|path| AudioMeta {
+ path: RelativePathBuf::from_path(
+ path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),
+ )
+ .unwrap(),
+ }),
+ cursor: s.pipeline.cursor.as_ref().map(|cursor| {
+ RelativePathBuf::from_path(
+ cursor
+ .output_path
+ .strip_prefix(&actor.recording_dir)
+ .unwrap()
+ .to_owned(),
+ )
+ .unwrap()
+ }),
+ })
+ .collect()
+ },
+ cursors: cap_project::Cursors::Correct(
+ cursors
+ .into_values()
+ .map(|cursor| {
+ (
+ cursor.id.to_string(),
+ CursorMeta {
+ image_path: RelativePathBuf::from("content/cursors")
+ .join(&cursor.file_name),
+ hotspot: cursor.hotspot,
+ },
+ )
+ })
+ .collect(),
+ ),
+ },
+ };
+
+ let project_config = cap_project::ProjectConfiguration::default();
+ project_config
+ .write(&actor.recording_dir)
+ .map_err(RecordingError::from)?;
+
+ Ok(CompletedStudioRecording {
+ id: actor.id,
+ project_path: actor.recording_dir.clone(),
+ meta,
+ cursor_data: Default::default(),
+ display_source: actor.options.capture_target,
+ segments: actor.segments,
+ })
+}
+
+#[tracing::instrument(skip_all, name = "segment", fields(index = index))]
+async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
+ segments_dir: &PathBuf,
+ cursors_dir: &PathBuf,
+ index: u32,
+ screen_source: ScreenCaptureSource<TCaptureFormat>,
+ camera_feed: Option<&Mutex<CameraFeed>>,
+ audio_input_feed: Option<&AudioInputFeed>,
+ prev_cursors: Cursors,
+ next_cursors_id: u32,
+) -> Result<(StudioRecordingPipeline, oneshot::Receiver<()>), 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");
+
+ trace!("preparing segment pipeline {index}");
+
+ let screen_bounds = screen_source.get_bounds();
+ pipeline_builder = TCaptureFormat::make_capture_pipeline(
+ pipeline_builder,
+ screen_source,
+ &display_output_path,
+ )?;
+
+ info!(
+ r#"screen pipeline prepared, will output to "{}""#,
+ display_output_path
+ .strip_prefix(&segments_dir)
+ .unwrap()
+ .display()
+ );
+ let audio_output_path = if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {
+ let mic_config = mic_source.info();
+ let output_path = dir.join("audio-input.ogg");
+
+ let mic_encoder = OggFile::init(
+ output_path.clone(),
+ OpusEncoder::factory("microphone", mic_config),
+ )?;
+
+ pipeline_builder = pipeline_builder
+ .source("microphone_capture", mic_source)
+ .sink("microphone_encoder", mic_encoder);
+
+ info!(
+ "mic pipeline prepared, will output to {}",
+ output_path.strip_prefix(&segments_dir).unwrap().display()
+ );
+
+ Some(output_path)
+ } else {
+ None
+ };
+
+ let camera = if let Some(camera_source) = camera_feed.map(CameraSource::init) {
+ let camera_config = camera_source.info();
+ let output_path = dir.join("camera.mp4");
+
+ let camera_encoder = MP4File::init(
+ "camera",
+ output_path.clone(),
+ H264Encoder::factory("camera", camera_config),
+ |_| None,
+ )?;
+
+ pipeline_builder = pipeline_builder
+ .source("camera_capture", camera_source)
+ .sink("camera_encoder", camera_encoder);
+
+ info!(
+ "camera pipeline prepared, will output to {}",
+ output_path.strip_prefix(&segments_dir).unwrap().display()
+ );
+
+ Some(CameraPipelineInfo {
+ output_path,
+ fps: (camera_config.frame_rate.0 / camera_config.frame_rate.1) as u32,
+ })
+ } else {
+ None
+ };
+
+ let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;
+
+ let cursor = FLAGS.record_mouse_state.then(|| {
+ let cursor = spawn_cursor_recorder(
+ screen_bounds,
+ cursors_dir.clone(),
+ prev_cursors,
+ next_cursors_id,
+ );
+
+ CursorPipeline {
+ output_path: dir.join("cursor.json"),
+ actor: Some(cursor),
+ }
+ });
+
+ pipeline.play().await?;
+
+ info!("pipeline playing");
+
+ Ok((
+ StudioRecordingPipeline {
+ inner: pipeline,
+ display_output_path,
+ audio_output_path,
+ camera,
+ cursor,
+ },
+ pipeline_done_rx,
+ ))
+}
+
+struct CameraPipelineInfo {
+ output_path: PathBuf,
+ fps: u32,
+}
+
+fn ensure_dir(path: &PathBuf) -> Result<PathBuf, MediaError> {
+ std::fs::create_dir_all(&path)?;
+ Ok(path.clone())
+}
+
+fn current_time_f64() -> f64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64()
+}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 38e1eb04d..3e89b11c4 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -146,7 +146,7 @@ pub async fn render_video_to_channel(
is_upgraded: bool,
) -> Result<(), RenderingError> {
let constants = RenderVideoConstants::new(options, recording_meta, meta).await?;
- let recordings = ProjectRecordings::new(recording_meta, meta);
+ let recordings = ProjectRecordings::new(&recording_meta.project_path, meta);
ffmpeg::init().unwrap();
diff --git a/crates/rendering/src/project_recordings.rs b/crates/rendering/src/project_recordings.rs
index d898f8f56..149d70eb1 100644
--- a/crates/rendering/src/project_recordings.rs
+++ b/crates/rendering/src/project_recordings.rs
@@ -1,4 +1,4 @@
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use crate::RecordingMeta;
use cap_project::StudioRecordingMeta;
@@ -14,29 +14,33 @@ pub struct Video {
}
impl Video {
- pub fn new(path: &PathBuf) -> Result<Self, String> {
- let input =
- ffmpeg::format::input(path).map_err(|e| format!("Failed to open video: {}", e))?;
- let stream = input
- .streams()
- .best(ffmpeg::media::Type::Video)
- .ok_or_else(|| "No video stream found".to_string())?;
-
- let video_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters())
- .map_err(|e| format!("Failed to create decoder: {}", e))?
- .decoder()
- .video()
- .map_err(|e| format!("Failed to get video decoder: {}", e))?;
-
- let rate = stream.avg_frame_rate();
- let fps = rate.numerator() as f64 / rate.denominator() as f64;
-
- Ok(Video {
- width: video_decoder.width(),
- height: video_decoder.height(),
- duration: input.duration() as f64 / 1_000_000.0,
- fps: fps.round() as u32,
- })
+ pub fn new(path: impl AsRef<Path>) -> Result<Self, String> {
+ fn inner(path: &Path) -> Result<Video, String> {
+ let input =
+ ffmpeg::format::input(path).map_err(|e| format!("Failed to open video: {}", e))?;
+ let stream = input
+ .streams()
+ .best(ffmpeg::media::Type::Video)
+ .ok_or_else(|| "No video stream found".to_string())?;
+
+ let video_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters())
+ .map_err(|e| format!("Failed to create decoder: {}", e))?
+ .decoder()
+ .video()
+ .map_err(|e| format!("Failed to get video decoder: {}", e))?;
+
+ let rate = stream.avg_frame_rate();
+ let fps = rate.numerator() as f64 / rate.denominator() as f64;
+
+ Ok(Video {
+ width: video_decoder.width(),
+ height: video_decoder.height(),
+ duration: input.duration() as f64 / 1_000_000.0,
+ fps: fps.round() as u32,
+ })
+ }
+
+ inner(path.as_ref())
}
pub fn fps(&self) -> u32 {
@@ -52,21 +56,29 @@ pub struct Audio {
}
impl Audio {
- pub fn new(path: &PathBuf) -> Self {
- let input = ffmpeg::format::input(path).unwrap();
- let stream = input.streams().best(ffmpeg::media::Type::Audio).unwrap();
-
- let audio_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters())
- .unwrap()
- .decoder()
- .audio()
- .unwrap();
-
- Audio {
- duration: input.duration() as f64 / 1_000_000.0,
- sample_rate: audio_decoder.rate(),
- channels: audio_decoder.channels(),
+ pub fn new(path: impl AsRef<Path>) -> Result<Self, String> {
+ fn inner(path: &Path) -> Result<Audio, String> {
+ let input =
+ ffmpeg::format::input(path).map_err(|e| format!("Failed to open audio: {}", e))?;
+ let stream = input
+ .streams()
+ .best(ffmpeg::media::Type::Audio)
+ .ok_or_else(|| "No audio stream found".to_string())?;
+
+ let audio_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters())
+ .map_err(|e| format!("Failed to create decoder: {}", e))?
+ .decoder()
+ .audio()
+ .map_err(|e| format!("Failed to get audio decoder: {}", e))?;
+
+ Ok(Audio {
+ duration: input.duration() as f64 / 1_000_000.0,
+ sample_rate: audio_decoder.rate(),
+ channels: audio_decoder.channels(),
+ })
}
+
+ inner(path.as_ref())
}
}
@@ -76,19 +88,21 @@ pub struct ProjectRecordings {
}
impl ProjectRecordings {
- pub fn new(recording_meta: &RecordingMeta, meta: &StudioRecordingMeta) -> Self {
+ pub fn new(recording_path: &PathBuf, meta: &StudioRecordingMeta) -> Self {
let segments = match &meta {
StudioRecordingMeta::SingleSegment { segment } => {
- let display = Video::new(&recording_meta.path(&segment.display.path))
+ let display = Video::new(segment.display.path.to_path(recording_path))
.expect("Failed to read display video");
let camera = segment.camera.as_ref().map(|camera| {
- Video::new(&recording_meta.path(&camera.path))
+ Video::new(&camera.path.to_path(recording_path))
.expect("Failed to read camera video")
});
let audio = segment
.audio
.as_ref()
- .map(|audio| Audio::new(&recording_meta.path(&audio.path)));
+ .map(|audio| Audio::new(audio.path.to_path(recording_path)))
+ .transpose()
+ .expect("Failed to read audio");
vec![SegmentRecordings {
display,
@@ -100,16 +114,18 @@ impl ProjectRecordings {
.segments
.iter()
.map(|s| {
- let display = Video::new(&recording_meta.path(&s.display.path))
+ let display = Video::new(s.display.path.to_path(recording_path))
.expect("Failed to read display video");
let camera = s.camera.as_ref().map(|camera| {
- Video::new(&recording_meta.path(&camera.path))
+ Video::new(&camera.path.to_path(recording_path))
.expect("Failed to read camera video")
});
let audio = s
.audio
.as_ref()
- .map(|audio| Audio::new(&recording_meta.path(&audio.path)));
+ .map(|audio| Audio::new(audio.path.to_path(recording_path)))
+ .transpose()
+ .expect("Failed to read audio");
SegmentRecordings {
display,