Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

start instant mode

Brendan Allan658cedb82cfc
diff --git a/Cargo.lock b/Cargo.lock
index 9616d141c..2d45289b8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1110,6 +1110,7 @@ dependencies = [
"image 0.25.5",
"objc",
"relative-path",
+ "screencapturekit",
"serde",
"serde_json",
"specta",
@@ -1301,8 +1302,8 @@ dependencies = [
[[package]]
name = "cidre"
-version = "0.5.0"
-source = "git+https://github.com/yury/cidre?rev=3479c18b9ac81dbb15d0acb3a75edd6b42d044b1#3479c18b9ac81dbb15d0acb3a75edd6b42d044b1"
+version = "0.6.0"
+source = "git+https://github.com/yury/cidre?rev=ef04aaabe14ffbbce4a330973a74b6d797d073ff#ef04aaabe14ffbbce4a330973a74b6d797d073ff"
dependencies = [
"cidre-macros",
"parking_lot",
@@ -1312,7 +1313,7 @@ dependencies = [
[[package]]
name = "cidre-macros"
version = "0.1.0"
-source = "git+https://github.com/yury/cidre?rev=3479c18b9ac81dbb15d0acb3a75edd6b42d044b1#3479c18b9ac81dbb15d0acb3a75edd6b42d044b1"
+source = "git+https://github.com/yury/cidre?rev=ef04aaabe14ffbbce4a330973a74b6d797d073ff#ef04aaabe14ffbbce4a330973a74b6d797d073ff"
[[package]]
name = "clang-sys"
diff --git a/Cargo.toml b/Cargo.toml
index c932dd34e..09c95706f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -36,7 +36,7 @@ sentry = { version = "0.34.0", features = [
"debug-images",
] }
-cidre = { git = "https://github.com/yury/cidre", rev = "3479c18b9ac81dbb15d0acb3a75edd6b42d044b1" }
+cidre = { git = "https://github.com/yury/cidre", rev = "ef04aaabe14ffbbce4a330973a74b6d797d073ff" }
windows = "0.58.0"
windows-sys = "0.59.0"
diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs
index 6085dc621..a45aa4571 100644
--- a/apps/cli/src/main.rs
+++ b/apps/cli/src/main.rs
@@ -145,8 +145,9 @@ impl Export {
)
.unwrap();
- let meta = RecordingMeta::load_for_project(&self.project_path).unwrap();
- let recordings = cap_rendering::ProjectRecordings::new(&meta);
+ 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 render_options = cap_rendering::RenderOptions {
screen_size: XY::new(
@@ -159,21 +160,21 @@ impl Export {
.map(|c| XY::new(c.width, c.height)),
};
let render_constants = Arc::new(
- RenderVideoConstants::new(render_options, &meta)
+ RenderVideoConstants::new(render_options, &recording_meta, meta)
.await
.unwrap(),
);
- let segments = create_segments(&meta).await.unwrap();
+ let segments = create_segments(&recording_meta, meta).await.unwrap();
- let fps = meta.content.max_fps();
+ let fps = meta.max_fps();
let project_output_path = self.project_path.join("output/result.mp4");
let exporter = cap_export::Exporter::new(
project,
project_output_path.clone(),
|_| {},
self.project_path.clone(),
- meta,
+ recording_meta,
render_constants,
&segments,
fps,
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 2bf46711a..fa4f41bac 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -29,8 +29,11 @@ use cap_media::feeds::{AudioInputFeed, AudioInputSamplesSender};
use cap_media::frame_ws::WSFrame;
use cap_media::sources::CaptureScreen;
use cap_media::{feeds::CameraFeed, sources::ScreenCaptureTarget};
+use cap_project::RecordingMetaInner;
use cap_project::XY;
-use cap_project::{Content, ProjectConfiguration, RecordingMeta, Resolution, SharingMeta};
+use cap_project::{
+ ProjectConfiguration, RecordingMeta, Resolution, SharingMeta, StudioRecordingMeta,
+};
use cap_recording::RecordingOptions;
use cap_rendering::ProjectRecordings;
use clipboard_rs::common::RustImage;
@@ -958,7 +961,10 @@ async fn get_video_metadata(
.join("recordings")
.join(format!("{}.cap", video_id));
- let meta = RecordingMeta::load_for_project(&project_path)?;
+ let recording_meta = RecordingMeta::load_for_project(&project_path)?;
+ let meta = recording_meta
+ .studio_meta()
+ .ok_or_else(|| "Not a studio recording".to_string())?;
fn get_duration_for_path(path: PathBuf) -> Result<f64, String> {
let reader = BufReader::new(
@@ -983,14 +989,14 @@ async fn get_video_metadata(
Ok(current_duration)
}
- let display_paths = match &meta.content {
- Content::SingleSegment { segment } => {
- vec![meta.path(&segment.display.path)]
+ let display_paths = match &meta {
+ StudioRecordingMeta::SingleSegment { segment } => {
+ vec![recording_meta.path(&segment.display.path)]
}
- Content::MultipleSegments { inner } => inner
+ StudioRecordingMeta::MultipleSegments { inner } => inner
.segments
.iter()
- .map(|s| meta.path(&s.display.path))
+ .map(|s| recording_meta.path(&s.display.path))
.collect(),
};
@@ -1413,7 +1419,7 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resul
project_path: recording_dir.clone(),
sharing: None,
pretty_name: screenshot_name,
- content: cap_project::Content::SingleSegment {
+ inner: RecordingMetaInner::Studio(cap_project::StudioRecordingMeta::SingleSegment {
segment: cap_project::SingleSegment {
display: Display {
path: RelativePathBuf::from_path(
@@ -1426,7 +1432,7 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resul
audio: None,
cursor: None,
},
- },
+ }),
}
.save_for_project()
.unwrap();
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 58b577634..f4131ba01 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1,4 +1,4 @@
-use std::{sync::Arc, time::Instant};
+use std::{path::PathBuf, sync::Arc, time::Instant};
use crate::{
audio::AppSounds,
@@ -18,7 +18,8 @@ use cap_flags::FLAGS;
use cap_media::sources::{CaptureScreen, CaptureWindow};
use cap_media::{feeds::CameraFeed, sources::ScreenCaptureTarget};
use cap_project::{
- Content, ProjectConfiguration, TimelineConfiguration, TimelineSegment, ZoomSegment, XY,
+ ProjectConfiguration, StudioRecordingMeta, TimelineConfiguration, TimelineSegment, ZoomSegment,
+ XY,
};
use cap_recording::CompletedRecording;
use cap_rendering::ProjectRecordings;
@@ -208,131 +209,155 @@ async fn handle_recording_finished(
let screenshots_dir = completed_recording.recording_dir.join("screenshots");
std::fs::create_dir_all(&screenshots_dir).ok();
- let meta = &completed_recording.meta;
- let display_output_path = match &meta.content {
- Content::SingleSegment { segment } => meta.path(&segment.display.path),
- Content::MultipleSegments { inner } => 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?;
+ let recording_meta = &completed_recording.meta;
let recording_dir = completed_recording.recording_dir.clone();
- ShowCapWindow::PrevRecordings.show(&app).ok();
+ let fire_events = || {
+ ShowCapWindow::PrevRecordings.show(&app).ok();
- NewRecordingAdded {
- path: recording_dir.clone(),
- }
- .emit(&app)
- .ok();
+ NewRecordingAdded {
+ path: recording_dir.clone(),
+ }
+ .emit(&app)
+ .ok();
- RecordingStopped {
- path: recording_dir,
- }
- .emit(&app)
- .ok();
-
- let recordings = ProjectRecordings::new(&completed_recording.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() {
- 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(),
- completed_recording.id.clone(),
- tauri::ipc::Channel::new(|_| Ok(())),
- true,
- completed_recording.meta.content.max_fps(),
- XY::new(1920, 1080),
- )
- .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(
- &app,
- notifications::NotificationType::UploadFailed,
- );
+ 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,
+ );
+
+ // 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(),
+ completed_recording.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(),
+ 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(
+ &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(), completed_recording.id);
+ }
}
- }
+ });
}
- });
+ }
+ cap_project::RecordingMetaInner::Instant(meta) => {
+ fire_events();
+
+ dbg!(meta);
+ }
}
};
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index 488fefb4c..fea5fe17b 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -224,7 +224,7 @@ impl ShowCapWindow {
.shadow(false)
.fullscreen(false)
.always_on_top(true)
- .content_protected(true)
+ // .content_protected(true)
.visible_on_all_workspaces(true)
.skip_taskbar(true)
.position(
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index fe2a1c72d..9282304fb 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -256,6 +256,7 @@ 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 InstantRecordingMeta = { fps: number; sample_rate: number | null }
export type JsonValue<T> = [T]
export type MultipleSegment = { display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null; cursor?: string | null }
export type MultipleSegments = { segments: MultipleSegment[]; cursors: Cursors }
@@ -272,7 +273,7 @@ export type PresetsStore = { presets: Preset[]; default: number | null }
export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null }
export type ProjectRecordings = { segments: SegmentRecordings[] }
export type RecordingInfo = { captureTarget: ScreenCaptureTarget }
-export type RecordingMeta = ({ segment: SingleSegment } | { inner: MultipleSegments }) & { pretty_name: string; sharing?: SharingMeta | null }
+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 RecordingOptionsChanged = null
@@ -293,6 +294,7 @@ export type ShadowConfiguration = { size: number; opacity: number; blur: number
export type SharingMeta = { id: string; link: string }
export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_id: string } } | "PrevRecordings" | "WindowCaptureOccluder" | { CaptureArea: { screen: CaptureScreen } } | { Camera: { ws_port: number } } | { InProgressRecording: { position: [number, number] | null } } | "Upgrade" | "SignIn"
export type SingleSegment = { display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null; cursor?: string | null }
+export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }
export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[] }
export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number }
export type UploadMode = { Initial: { pre_created_video: PreCreatedVideo | null } } | "Reupload"
diff --git a/apps/desktop/test.mp4 b/apps/desktop/test.mp4
new file mode 100644
index 000000000..e58813c4b
Binary files /dev/null and b/apps/desktop/test.mp4 differ
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index c1c74f95e..5450d6767 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -1,7 +1,7 @@
use std::{sync::Arc, time::Instant};
use cap_media::{feeds::RawCameraFrame, frame_ws::WSFrame};
-use cap_project::{BackgroundSource, CursorEvents, RecordingMeta, XY};
+use cap_project::{BackgroundSource, CursorEvents, RecordingMeta, StudioRecordingMeta, XY};
use cap_rendering::{
decoder::DecodedFrame, DecodedSegmentFrames, FrameRenderer, ProjectRecordings, ProjectUniforms,
RenderVideoConstants,
@@ -40,14 +40,17 @@ impl Renderer {
pub fn spawn(
render_constants: Arc<RenderVideoConstants>,
frame_tx: flume::Sender<WSFrame>,
- meta: &RecordingMeta,
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
) -> RendererHandle {
- let recordings = ProjectRecordings::new(meta);
+ let recordings = ProjectRecordings::new(recording_meta, meta);
let mut max_duration = recordings.duration();
// Check camera duration if it exists
- if let Some(camera_path) = meta.content.camera_path() {
- if let Ok(camera_duration) = recordings.get_source_duration(&meta.path(&camera_path)) {
+ if let Some(camera_path) = meta.camera_path() {
+ if let Ok(camera_duration) =
+ recordings.get_source_duration(&recording_meta.path(&camera_path))
+ {
max_duration = max_duration.max(camera_duration);
}
}
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index ab2937a18..b7d91c5a4 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -4,8 +4,8 @@ use cap_media::data::RawVideoFormat;
use cap_media::data::VideoInfo;
use cap_media::feeds::AudioData;
use cap_media::frame_ws::create_frame_ws;
-use cap_project::RecordingConfig;
-use cap_project::{CursorEvents, ProjectConfiguration, RecordingMeta, XY};
+use cap_project::{CursorEvents, ProjectConfiguration, RecordingMeta, RecordingMetaInner, XY};
+use cap_project::{RecordingConfig, StudioRecordingMeta};
use cap_rendering::{
get_duration, DecodedSegmentFrames, ProjectRecordings, ProjectUniforms,
RecordingSegmentDecoders, RenderOptions, RenderVideoConstants, SegmentVideoPaths,
@@ -74,9 +74,12 @@ impl EditorInstance {
panic!("Video path {} not found!", project_path.display());
}
- let meta = cap_project::RecordingMeta::load_for_project(&project_path).unwrap();
- let project = meta.project_config();
- let recordings = ProjectRecordings::new(&meta);
+ let recording_meta = cap_project::RecordingMeta::load_for_project(&project_path).unwrap();
+ let RecordingMetaInner::Studio(meta) = &recording_meta.inner else {
+ return Err("Cannot edit non-studio recordings".to_string());
+ };
+ let project = recording_meta.project_config();
+ let recordings = ProjectRecordings::new(&recording_meta, meta);
let render_options = RenderOptions {
screen_size: XY::new(
@@ -89,14 +92,14 @@ impl EditorInstance {
.map(|c| XY::new(c.width, c.height)),
};
- let segments = create_segments(&meta).await?;
+ let segments = create_segments(&recording_meta, meta).await?;
let (frame_tx, frame_rx) = flume::bounded(4);
let (ws_port, ws_shutdown) = create_frame_ws(frame_rx).await;
let render_constants = Arc::new(
- RenderVideoConstants::new(render_options, &meta)
+ RenderVideoConstants::new(render_options, &recording_meta, meta)
.await
.unwrap(),
);
@@ -104,7 +107,8 @@ impl EditorInstance {
let renderer = Arc::new(editor::Renderer::spawn(
render_constants.clone(),
frame_tx,
- &meta,
+ &recording_meta,
+ meta,
));
let (preview_tx, preview_rx) = watch::channel(None);
@@ -126,7 +130,7 @@ impl EditorInstance {
project_config: watch::channel(project),
ws_shutdown: Arc::new(StdMutex::new(Some(ws_shutdown))),
segments: Arc::new(segments),
- meta,
+ meta: recording_meta,
});
this.state.lock().await.preview_task = Some(
@@ -138,7 +142,7 @@ impl EditorInstance {
}
pub fn meta(&self) -> RecordingMeta {
- RecordingMeta::load_for_project(&self.project_path).unwrap()
+ self.meta.clone()
}
pub async fn dispose(&self) {
@@ -293,11 +297,19 @@ impl EditorInstance {
})
}
+ fn get_studio_meta(&self) -> &StudioRecordingMeta {
+ match &self.meta.inner {
+ RecordingMetaInner::Studio(meta) => &meta,
+ _ => panic!("Not a studio recording"),
+ }
+ }
+
pub fn get_total_frames(&self, fps: u32) -> u32 {
// Calculate total frames based on actual video duration and fps
let duration = get_duration(
&self.recordings,
&self.meta,
+ self.get_studio_meta(),
&self.project_config.1.borrow(),
);
@@ -327,20 +339,22 @@ pub struct Segment {
pub decoders: RecordingSegmentDecoders,
}
-pub async fn create_segments(meta: &RecordingMeta) -> Result<Vec<Segment>, String> {
- match &meta.content {
- cap_project::Content::SingleSegment { segment: s } => {
- let audio = Arc::new(
- s.audio
- .as_ref()
- .map(|audio_meta| AudioData::from_file(meta.path(&audio_meta.path)).unwrap()),
- );
+pub async fn create_segments(
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
+) -> Result<Vec<Segment>, String> {
+ match &meta {
+ cap_project::StudioRecordingMeta::SingleSegment { segment: s } => {
+ let audio = Arc::new(s.audio.as_ref().map(|audio_meta| {
+ AudioData::from_file(recording_meta.path(&audio_meta.path)).unwrap()
+ }));
let decoders = RecordingSegmentDecoders::new(
- &meta,
+ &recording_meta,
+ meta,
SegmentVideoPaths {
- display: meta.path(&s.display.path),
- camera: s.camera.as_ref().map(|c| meta.path(&c.path)),
+ display: recording_meta.path(&s.display.path),
+ camera: s.camera.as_ref().map(|c| recording_meta.path(&c.path)),
},
)
.await
@@ -352,22 +366,22 @@ pub async fn create_segments(meta: &RecordingMeta) -> Result<Vec<Segment>, Strin
decoders,
}])
}
- cap_project::Content::MultipleSegments { inner } => {
+ cap_project::StudioRecordingMeta::MultipleSegments { inner } => {
let mut segments = vec![];
for (i, s) in inner.segments.iter().enumerate() {
- let audio =
- Arc::new(s.audio.as_ref().map(|audio_meta| {
- AudioData::from_file(meta.path(&audio_meta.path)).unwrap()
- }));
+ let audio = Arc::new(s.audio.as_ref().map(|audio_meta| {
+ AudioData::from_file(recording_meta.path(&audio_meta.path)).unwrap()
+ }));
- let cursor = Arc::new(s.cursor_events(&meta));
+ let cursor = Arc::new(s.cursor_events(&recording_meta));
let decoders = RecordingSegmentDecoders::new(
- &meta,
+ &recording_meta,
+ meta,
SegmentVideoPaths {
- display: meta.path(&s.display.path),
- camera: s.camera.as_ref().map(|c| meta.path(&c.path)),
+ display: recording_meta.path(&s.display.path),
+ camera: s.camera.as_ref().map(|c| recording_meta.path(&c.path)),
},
)
.await
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 50d58bbfc..adaa967ee 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -5,7 +5,9 @@ use cap_media::{
feeds::{AudioData, AudioFrameBuffer},
MediaError,
};
-use cap_project::{ProjectConfiguration, RecordingMeta, XY};
+use cap_project::{
+ ProjectConfiguration, RecordingMeta, RecordingMetaInner, StudioRecordingMeta, XY,
+};
use cap_rendering::{
ProjectUniforms, RecordingSegmentDecoders, RenderSegment, RenderVideoConstants, RenderedFrame,
SegmentVideoPaths,
@@ -46,7 +48,7 @@ pub struct Exporter<TOnProgress> {
project: ProjectConfiguration,
project_path: PathBuf,
on_progress: TOnProgress,
- meta: RecordingMeta,
+ recording_meta: RecordingMeta,
render_constants: Arc<RenderVideoConstants>,
fps: u32,
resolution_base: XY<u32>,
@@ -62,13 +64,19 @@ where
output_path: PathBuf,
on_progress: TOnProgress,
project_path: PathBuf,
- meta: RecordingMeta,
+ recording_meta: RecordingMeta,
render_constants: Arc<RenderVideoConstants>,
segments: &[Segment],
fps: u32,
resolution_base: XY<u32>,
is_upgraded: bool,
) -> Result<Self, ExportError> {
+ let RecordingMetaInner::Studio(meta) = &recording_meta.inner else {
+ return Err(ExportError::Other(
+ "Cannot export non-studio recordings".to_string(),
+ ));
+ };
+
let output_folder = output_path.parent().unwrap();
std::fs::create_dir_all(output_folder)?;
@@ -79,23 +87,25 @@ where
let mut audio_segments = vec![];
for (i, s) in segments.iter().enumerate() {
- let segment_paths = match &meta.content {
- cap_project::Content::SingleSegment { segment: s } => SegmentVideoPaths {
- display: meta.path(&s.display.path),
- camera: s.camera.as_ref().map(|c| meta.path(&c.path)),
- },
- cap_project::Content::MultipleSegments { inner } => {
+ let segment_paths = match &meta {
+ cap_project::StudioRecordingMeta::SingleSegment { segment: s } => {
+ SegmentVideoPaths {
+ display: recording_meta.path(&s.display.path),
+ camera: s.camera.as_ref().map(|c| recording_meta.path(&c.path)),
+ }
+ }
+ cap_project::StudioRecordingMeta::MultipleSegments { inner } => {
let s = &inner.segments[i];
SegmentVideoPaths {
- display: meta.path(&s.display.path),
- camera: s.camera.as_ref().map(|c| meta.path(&c.path)),
+ display: recording_meta.path(&s.display.path),
+ camera: s.camera.as_ref().map(|c| recording_meta.path(&c.path)),
}
}
};
render_segments.push(RenderSegment {
cursor: s.cursor.clone(),
- decoders: RecordingSegmentDecoders::new(&meta, segment_paths)
+ decoders: RecordingSegmentDecoders::new(&recording_meta, meta, segment_paths)
.await
.map_err(ExportError::Other)?,
});
@@ -107,7 +117,7 @@ where
output_path,
on_progress,
project_path,
- meta,
+ recording_meta,
render_constants,
render_segments,
audio_segments,
@@ -123,6 +133,11 @@ where
buffer: AudioFrameBuffer,
}
+ let meta = match &self.recording_meta.inner {
+ RecordingMetaInner::Studio(meta) => meta,
+ _ => panic!("Not a studio recording"),
+ };
+
println!("Exporting with custom muxer");
let (tx_image_data, mut rx_image_data) =
@@ -308,7 +323,8 @@ where
self.render_constants.options,
self.project,
tx_image_data,
- &self.meta,
+ &self.recording_meta,
+ meta,
self.render_segments,
self.fps,
self.resolution_base,
diff --git a/crates/media/src/encoders/h264_avassetwriter.rs b/crates/media/src/encoders/h264_avassetwriter.rs
deleted file mode 100644
index c12ec178e..000000000
--- a/crates/media/src/encoders/h264_avassetwriter.rs
+++ /dev/null
@@ -1,142 +0,0 @@
-use std::path::PathBuf;
-
-use crate::{data::VideoInfo, pipeline::task::PipelineSinkTask, MediaError};
-
-use arc::Retained;
-use cidre::{objc::Obj, *};
-use tracing::{info, trace};
-
-pub struct H264AVAssetWriterEncoder {
- tag: &'static str,
- last_pts: Option<i64>,
- config: VideoInfo,
- asset_writer: Retained<av::AssetWriter>,
- video_input: Retained<av::AssetWriterInput>,
- first_timestamp: Option<cm::Time>,
- last_timestamp: Option<cm::Time>,
-}
-
-impl H264AVAssetWriterEncoder {
- pub fn init(tag: &'static str, config: VideoInfo, output: PathBuf) -> Result<Self, MediaError> {
- let fps = config.frame_rate.0 as f32 / config.frame_rate.1 as f32;
-
- let mut asset_writer = av::AssetWriter::with_url_and_file_type(
- cf::Url::with_path(output.as_path(), false).unwrap().as_ns(),
- av::FileType::mp4(),
- )
- .map_err(|_| MediaError::Any("Failed to create AVAssetWriter"))?;
-
- let assistant =
- av::OutputSettingsAssistant::with_preset(av::OutputSettingsPreset::h264_3840x2160())
- .ok_or(MediaError::Any(
- "Failed to create output settings assistant",
- ))?;
-
- let mut output_settings = assistant
- .video_settings()
- .ok_or(MediaError::Any("No assistant video settings"))?
- .copy_mut();
-
- output_settings.insert(
- av::video_settings_keys::width(),
- ns::Number::with_u32(config.width).as_id_ref(),
- );
-
- output_settings.insert(
- av::video_settings_keys::height(),
- ns::Number::with_u32(config.height).as_id_ref(),
- );
-
- let bitrate = config.width as f32 * config.height as f32 / (1920.0 * 1080.0) * 14_000_000.0
- + fps / 30.0 * 6_000_000.0;
-
- output_settings.insert(
- av::video_settings_keys::compression_props(),
- ns::Dictionary::with_keys_values(
- &[unsafe { AVVideoAverageBitRateKey }],
- &[ns::Number::with_f32(bitrate).as_id_ref()],
- )
- .as_id_ref(),
- );
-
- let mut video_input = av::AssetWriterInput::with_media_type_and_output_settings(
- av::MediaType::video(),
- Some(output_settings.as_ref()),
- )
- .map_err(|_| MediaError::Any("Failed to create AVAssetWriterInput"))?;
- video_input.set_expects_media_data_in_real_time(true);
-
- asset_writer
- .add_input(&video_input)
- .map_err(|_| MediaError::Any("Failed to add asset writer input"))?;
-
- asset_writer.start_writing();
-
- Ok(Self {
- tag,
- last_pts: None,
- config,
- asset_writer,
- video_input,
- first_timestamp: None,
- last_timestamp: None,
- })
- }
-
- fn queue_frame(&mut self, frame: screencapturekit::cm_sample_buffer::CMSampleBuffer) {
- if !self.video_input.is_ready_for_more_media_data() {
- return;
- }
-
- let sample_buf = unsafe {
- let ptr = &*frame.sys_ref as *const _ as *const cm::SampleBuf;
- &*ptr
- };
-
- let time = sample_buf.pts();
-
- if self.first_timestamp.is_none() {
- self.asset_writer.start_session_at_src_time(time);
- self.first_timestamp = Some(time);
- }
-
- self.last_timestamp = Some(time);
-
- self.video_input.append_sample_buf(sample_buf).ok();
- }
-
- fn process_frame(&mut self) {}
-
- fn finish(&mut self) {
- self.asset_writer
- .end_session_at_src_time(self.last_timestamp.take().unwrap_or(cm::Time::zero()));
- self.video_input.mark_as_finished();
- self.asset_writer.finish_writing();
- }
-}
-
-use screencapturekit::cm_sample_buffer::CMSampleBuffer;
-
-impl PipelineSinkTask<CMSampleBuffer> for H264AVAssetWriterEncoder {
- fn run(
- &mut self,
- ready_signal: crate::pipeline::task::PipelineReadySignal,
- input: &flume::Receiver<CMSampleBuffer>,
- ) {
- ready_signal.send(Ok(())).ok();
-
- while let Ok(frame) = input.recv() {
- self.queue_frame(frame);
- self.process_frame();
- }
- }
-
- fn finish(&mut self) {
- self.finish();
- }
-}
-
-#[link(name = "AVFoundation", kind = "framework")]
-extern "C" {
- static AVVideoAverageBitRateKey: &'static cidre::ns::String;
-}
diff --git a/crates/media/src/encoders/mod.rs b/crates/media/src/encoders/mod.rs
index 965bbfce6..d5d54c236 100644
--- a/crates/media/src/encoders/mod.rs
+++ b/crates/media/src/encoders/mod.rs
@@ -1,13 +1,11 @@
-use std::path::PathBuf;
-
mod h264;
-#[cfg(target_os = "macos")]
-mod h264_avassetwriter;
mod mp4;
+#[cfg(target_os = "macos")]
+mod mp4_avassetwriter;
mod opus;
pub use h264::*;
-#[cfg(target_os = "macos")]
-pub use h264_avassetwriter::*;
pub use mp4::*;
+#[cfg(target_os = "macos")]
+pub use mp4_avassetwriter::*;
pub use opus::*;
diff --git a/crates/media/src/encoders/mp4_avassetwriter.rs b/crates/media/src/encoders/mp4_avassetwriter.rs
new file mode 100644
index 000000000..9c3561efe
--- /dev/null
+++ b/crates/media/src/encoders/mp4_avassetwriter.rs
@@ -0,0 +1,319 @@
+use std::{
+ path::PathBuf,
+ sync::{Arc, Mutex},
+};
+
+use crate::{
+ data::{AudioInfo, FFAudio, VideoInfo},
+ pipeline::task::PipelineSinkTask,
+ MediaError,
+};
+
+use arc::Retained;
+use cidre::{cm::FormatDesc, objc::Obj, *};
+
+pub struct MP4AVAssetWriterEncoder {
+ tag: &'static str,
+ last_pts: Option<i64>,
+ config: VideoInfo,
+ asset_writer: Retained<av::AssetWriter>,
+ video_input: Retained<av::AssetWriterInput>,
+ audio_input: Option<Retained<av::AssetWriterInput>>,
+ first_timestamp: Option<cm::Time>,
+ last_timestamp: Option<cm::Time>,
+}
+
+impl MP4AVAssetWriterEncoder {
+ pub fn init(
+ tag: &'static str,
+ video_config: VideoInfo,
+ audio_config: Option<AudioInfo>,
+ output: PathBuf,
+ output_height: Option<u32>,
+ ) -> Result<Self, MediaError> {
+ let fps = video_config.frame_rate.0 as f32 / video_config.frame_rate.1 as f32;
+
+ let mut asset_writer = av::AssetWriter::with_url_and_file_type(
+ cf::Url::with_path(output.as_path(), false).unwrap().as_ns(),
+ av::FileType::mp4(),
+ )
+ .map_err(|_| MediaError::Any("Failed to create AVAssetWriter"))?;
+
+ let video_input = {
+ let assistant = av::OutputSettingsAssistant::with_preset(
+ av::OutputSettingsPreset::h264_3840x2160(),
+ )
+ .ok_or(MediaError::Any(
+ "Failed to create output settings assistant",
+ ))?;
+
+ let mut output_settings = assistant
+ .video_settings()
+ .ok_or(MediaError::Any("No assistant video settings"))?
+ .copy_mut();
+
+ let downscale = output_height
+ .map(|h| h as f32 / video_config.height as f32)
+ .unwrap_or(1.0);
+
+ let output_width = (video_config.width as f32 * downscale) as u32;
+ let output_height = output_height.unwrap_or(video_config.height);
+
+ output_settings.insert(
+ av::video_settings_keys::width(),
+ ns::Number::with_u32(output_width).as_id_ref(),
+ );
+
+ output_settings.insert(
+ av::video_settings_keys::height(),
+ ns::Number::with_u32(output_height).as_id_ref(),
+ );
+
+ let bitrate = video_config.width as f32 * video_config.height as f32
+ / (1920.0 * 1080.0)
+ * 14_000_000.0
+ + fps / 30.0 * 6_000_000.0;
+
+ output_settings.insert(
+ av::video_settings_keys::compression_props(),
+ ns::Dictionary::with_keys_values(
+ &[unsafe { AVVideoAverageBitRateKey }],
+ &[ns::Number::with_f32(bitrate).as_id_ref()],
+ )
+ .as_id_ref(),
+ );
+
+ let mut video_input = av::AssetWriterInput::with_media_type_and_output_settings(
+ av::MediaType::video(),
+ Some(output_settings.as_ref()),
+ )
+ .map_err(|_| MediaError::Any("Failed to create AVAssetWriterInput"))?;
+ video_input.set_expects_media_data_in_real_time(true);
+
+ asset_writer
+ .add_input(&video_input)
+ .map_err(|_| MediaError::Any("Failed to add asset writer video input"))?;
+
+ video_input
+ };
+
+ let audio_input = audio_config
+ .as_ref()
+ .map(|config| {
+ debug!("{config:?}");
+
+ let output_settings = cidre::ns::Dictionary::with_keys_values(
+ &[
+ av::audio::all_formats_keys::id(),
+ av::audio::all_formats_keys::number_of_channels(),
+ av::audio::all_formats_keys::sample_rate(),
+ ],
+ &[
+ cat::AudioFormat::MPEG4_AAC.as_ref(),
+ (config.channels as u32).as_ref(),
+ (config.sample_rate).as_ref(),
+ ],
+ );
+
+ let mut audio_input = av::AssetWriterInput::with_media_type_and_output_settings(
+ av::MediaType::audio(),
+ Some(output_settings.as_ref()),
+ )
+ .map_err(|_| MediaError::Any("Failed to create AVAssetWriterInput"))?;
+
+ audio_input.set_expects_media_data_in_real_time(true);
+
+ asset_writer
+ .add_input(&audio_input)
+ .map_err(|_| MediaError::Any("Failed to add asset writer audio input"))?;
+
+ Ok::<_, MediaError>(audio_input)
+ })
+ .transpose()?;
+
+ asset_writer.start_writing();
+
+ Ok(Self {
+ tag,
+ last_pts: None,
+ config: video_config,
+ audio_input,
+ asset_writer,
+ video_input,
+ first_timestamp: None,
+ last_timestamp: None,
+ })
+ }
+
+ fn queue_video_frame(&mut self, frame: screencapturekit::cm_sample_buffer::CMSampleBuffer) {
+ if !self.video_input.is_ready_for_more_media_data() {
+ return;
+ }
+
+ let sample_buf = unsafe {
+ let ptr = &*frame.sys_ref as *const _ as *const cm::SampleBuf;
+ &*ptr
+ };
+
+ let time = sample_buf.pts();
+
+ if self.first_timestamp.is_none() {
+ self.asset_writer.start_session_at_src_time(time);
+ self.first_timestamp = Some(time);
+ }
+
+ self.last_timestamp = Some(time);
+
+ self.video_input.append_sample_buf(sample_buf).ok();
+ }
+
+ fn queue_audio_frame(&mut self, frame: FFAudio) -> Result<(), MediaError> {
+ let Some(audio_input) = &mut self.audio_input else {
+ return Err(MediaError::Any("No audio input"));
+ };
+
+ if !audio_input.is_ready_for_more_media_data() {
+ return Err(MediaError::Any("Not ready for more media data"));
+ }
+
+ if self.first_timestamp.is_none() {
+ return Ok(());
+ }
+
+ if frame.planes() != 1 {
+ return Err(MediaError::Any("Audio planes != 1"));
+ }
+
+ let audio_desc = cat::audio::StreamBasicDesc::common_f32(
+ frame.rate() as f64,
+ frame.channels() as u32,
+ frame.is_packed(),
+ );
+
+ let total_data = frame.data(0).len();
+
+ let mut block_buf = cm::BlockBuf::with_mem_block(total_data, None)
+ .map_err(|_| MediaError::Any("Failed to allocate block buffer"))?;
+
+ let block_buf_slice = block_buf
+ .as_mut_slice()
+ .map_err(|_| MediaError::Any("Failed to map block buffer"))?;
+
+ block_buf_slice.copy_from_slice(frame.data(0));
+
+ let format_desc = cm::AudioFormatDesc::with_asbd(&audio_desc)
+ .map_err(|_| MediaError::Any("Failed to create audio format desc"))?;
+
+ let buffer = unsafe {
+ result_unchecked(|res| {
+ cm::SampleBuf::create_in(
+ None,
+ Some(&block_buf),
+ true,
+ None,
+ std::ptr::null(),
+ Some(format_desc.as_ref()),
+ frame.samples() as isize,
+ 0,
+ std::ptr::null(),
+ 0,
+ std::ptr::null(),
+ res,
+ )
+ })
+ }
+ .map_err(|_| MediaError::Any("Failed to create sample buffer"))?;
+
+ audio_input.append_sample_buf(&buffer).map_err(|_| {
+ MediaError::Any("Failed to append audio sample buffer to asset writer input")
+ })?;
+
+ Ok(())
+ }
+
+ fn process_frame(&mut self) {}
+
+ fn finish(&mut self) {
+ self.asset_writer
+ .end_session_at_src_time(self.last_timestamp.take().unwrap_or(cm::Time::zero()));
+ self.video_input.mark_as_finished();
+ self.audio_input.as_mut().map(|i| i.mark_as_finished());
+ self.asset_writer.finish_writing();
+ }
+}
+
+use screencapturekit::cm_sample_buffer::CMSampleBuffer;
+use tracing::debug;
+
+impl PipelineSinkTask<CMSampleBuffer> for MP4AVAssetWriterEncoder {
+ fn run(
+ &mut self,
+ ready_signal: crate::pipeline::task::PipelineReadySignal,
+ input: &flume::Receiver<CMSampleBuffer>,
+ ) {
+ ready_signal.send(Ok(())).ok();
+
+ while let Ok(frame) = input.recv() {
+ self.queue_video_frame(frame);
+ self.process_frame();
+ }
+ }
+
+ fn finish(&mut self) {
+ self.finish();
+ }
+}
+
+impl PipelineSinkTask<FFAudio> for Arc<Mutex<MP4AVAssetWriterEncoder>> {
+ fn run(
+ &mut self,
+ ready_signal: crate::pipeline::task::PipelineReadySignal,
+ input: &flume::Receiver<FFAudio>,
+ ) {
+ ready_signal.send(Ok(())).ok();
+
+ while let Ok(frame) = input.recv() {
+ let mut this = self.lock().unwrap();
+ this.queue_audio_frame(frame).ok();
+ this.process_frame();
+ }
+ }
+
+ fn finish(&mut self) {
+ self.lock().unwrap().finish();
+ }
+}
+
+impl PipelineSinkTask<CMSampleBuffer> for Arc<Mutex<MP4AVAssetWriterEncoder>> {
+ fn run(
+ &mut self,
+ ready_signal: crate::pipeline::task::PipelineReadySignal,
+ input: &flume::Receiver<CMSampleBuffer>,
+ ) {
+ ready_signal.send(Ok(())).ok();
+
+ while let Ok(frame) = input.recv() {
+ let mut this = self.lock().unwrap();
+ this.queue_video_frame(frame);
+ this.process_frame();
+ }
+ }
+
+ fn finish(&mut self) {
+ self.lock().unwrap().finish();
+ }
+}
+
+#[link(name = "AVFoundation", kind = "framework")]
+extern "C" {
+ static AVVideoAverageBitRateKey: &'static cidre::ns::String;
+}
+
+unsafe fn result_unchecked<T, R>(op: impl FnOnce(&mut Option<T>) -> R) -> cidre::os::Result<T>
+where
+ R: Into<cidre::os::Result>,
+{
+ let mut option = None;
+ op(&mut option).into()?;
+ Ok(unsafe { option.unwrap_unchecked() })
+}
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 9207a6e69..848916e4a 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -233,7 +233,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: Some(excluded_targets),
+ excluded_targets: None,
+ // excluded_targets: Some(excluded_targets),
}
}
diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rs
index aa6e60db1..5fe40fb33 100644
--- a/crates/project/src/meta.rs
+++ b/crates/project/src/meta.rs
@@ -51,7 +51,22 @@ pub struct RecordingMeta {
#[serde(default)]
pub sharing: Option<SharingMeta>,
#[serde(flatten)]
- pub content: Content,
+ pub inner: RecordingMetaInner,
+}
+
+impl specta::Flatten for RecordingMetaInner {}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+#[serde(untagged, rename_all = "camelCase")]
+pub enum RecordingMetaInner {
+ Studio(StudioRecordingMeta),
+ Instant(InstantRecordingMeta),
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+pub struct InstantRecordingMeta {
+ pub fps: u32,
+ pub sample_rate: Option<u32>,
}
impl RecordingMeta {
@@ -82,11 +97,18 @@ impl RecordingMeta {
pub fn output_path(&self) -> PathBuf {
self.project_path.join("output").join("result.mp4")
}
+
+ pub fn studio_meta(&self) -> Option<&StudioRecordingMeta> {
+ match &self.inner {
+ RecordingMetaInner::Studio(meta) => Some(&meta),
+ _ => None,
+ }
+ }
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(untagged, rename_all = "camelCase")]
-pub enum Content {
+pub enum StudioRecordingMeta {
SingleSegment {
#[serde(flatten)]
segment: SingleSegment,
@@ -97,11 +119,13 @@ pub enum Content {
},
}
-impl Content {
+impl StudioRecordingMeta {
pub fn camera_path(&self) -> Option<RelativePathBuf> {
match self {
- Content::SingleSegment { segment } => segment.camera.as_ref().map(|c| c.path.clone()),
- Content::MultipleSegments { inner } => inner
+ StudioRecordingMeta::SingleSegment { segment } => {
+ segment.camera.as_ref().map(|c| c.path.clone())
+ }
+ StudioRecordingMeta::MultipleSegments { inner } => inner
.segments
.first()
.and_then(|s| s.camera.as_ref().map(|c| c.path.clone())),
@@ -110,8 +134,8 @@ impl Content {
pub fn min_fps(&self) -> u32 {
match self {
- Content::SingleSegment { segment } => segment.display.fps,
- Content::MultipleSegments { inner } => {
+ StudioRecordingMeta::SingleSegment { segment } => segment.display.fps,
+ StudioRecordingMeta::MultipleSegments { inner } => {
inner.segments.iter().map(|s| s.display.fps).min().unwrap()
}
}
@@ -119,8 +143,8 @@ impl Content {
pub fn max_fps(&self) -> u32 {
match self {
- Content::SingleSegment { segment } => segment.display.fps,
- Content::MultipleSegments { inner } => {
+ StudioRecordingMeta::SingleSegment { segment } => segment.display.fps,
+ StudioRecordingMeta::MultipleSegments { inner } => {
inner.segments.iter().map(|s| s.display.fps).max().unwrap()
}
}
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
index 02569d28b..f162bc8a2 100644
--- a/crates/recording/Cargo.toml
+++ b/crates/recording/Cargo.toml
@@ -23,6 +23,7 @@ image = "0.25.2"
either = "1.13.0"
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
relative-path = "1.9.3"
+screencapturekit = "0.2.8"
[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 70d03af1f..2d5be7667 100644
--- a/crates/recording/src/actor.rs
+++ b/crates/recording/src/actor.rs
@@ -8,7 +8,7 @@ use std::{
use cap_flags::FLAGS;
use cap_media::{
data::Pixel,
- encoders::{H264Encoder, MP4File, OggFile, OpusEncoder},
+ encoders::{H264Encoder, MP4AVAssetWriterEncoder, MP4File, OggFile, OpusEncoder},
feeds::{AudioInputFeed, CameraFeed},
pipeline::{builder::PipelineBuilder, Pipeline, RealTimeClock},
sources::{AudioInputSource, CameraSource, ScreenCaptureSource, ScreenCaptureTarget},
@@ -429,70 +429,74 @@ async fn stop_recording(
"Cap {}",
chrono::Local::now().format("%Y-%m-%d at %H.%M.%S")
),
- content: Content::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(),
- ),
- },
- },
+ inner: RecordingMetaInner::Instant(InstantRecordingMeta {
+ fps: actor.options.capture_target.recording_fps(),
+ sample_rate: None,
+ }),
+ // inner: RecordingMetaInner::Studio(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(),
+ // ),
+ // },
+ // }),
};
meta.save_for_project()
@@ -554,106 +558,132 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
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(
+ 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),
output_path.clone(),
- OpusEncoder::factory("microphone", mic_config),
)?;
- pipeline_builder = pipeline_builder
- .source("microphone_capture", mic_source)
- .sink("microphone_encoder", mic_encoder);
+ let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;
- info!(
- "mic pipeline prepared, will output to {}",
- output_path.strip_prefix(&segments_dir).unwrap().display()
- );
+ pipeline.play().await?;
- Some(output_path)
+ Ok((
+ RecordingPipeline {
+ inner: pipeline,
+ display_output_path: output_path,
+ audio_output_path: None,
+ camera: None,
+ cursor: None,
+ },
+ pipeline_done_rx,
+ ))
} else {
- None
- };
+ let display_output_path = dir.join("display.mp4");
- 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");
+ trace!("preparing segment pipeline {index}");
- let camera_encoder = MP4File::init(
- "camera",
- output_path.clone(),
- H264Encoder::factory("camera", camera_config),
- |_| None,
+ let screen_bounds = screen_source.get_bounds();
+ pipeline_builder = TCaptureFormat::make_capture_pipeline(
+ pipeline_builder,
+ screen_source,
+ &display_output_path,
)?;
- 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()
+ 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),
+ }
+ });
- 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?;
+ pipeline.play().await?;
- let cursor = FLAGS.record_mouse_state.then(|| {
- let cursor = spawn_cursor_recorder(
- screen_bounds,
- cursors_dir.clone(),
- prev_cursors,
- next_cursors_id,
- );
+ info!("pipeline playing");
- 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,
- ))
+ Ok((
+ RecordingPipeline {
+ inner: pipeline,
+ display_output_path,
+ audio_output_path,
+ camera,
+ cursor,
+ },
+ pipeline_done_rx,
+ ))
+ }
}
struct CameraPipelineInfo {
@@ -676,6 +706,15 @@ trait MakeCapturePipeline: std::fmt::Debug + 'static {
) -> 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")]
@@ -686,16 +725,45 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
output_path: impl Into<PathBuf>,
) -> Result<CapturePipelineBuilder, MediaError> {
let screen_config = source.info();
- let screen_encoder = cap_media::encoders::H264AVAssetWriterEncoder::init(
+ 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 {
@@ -718,6 +786,18 @@ impl MakeCapturePipeline for cap_media::sources::AVFrameCapture {
.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!()
+ }
}
fn current_time_f64() -> f64 {
diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rs
index 0f5b1cb5e..8548c1652 100644
--- a/crates/rendering/src/decoder/avassetreader.rs
+++ b/crates/rendering/src/decoder/avassetreader.rs
@@ -29,7 +29,12 @@ impl CachedFrame {
let format = pixel_format_to_pixel(image_buf.pixel_format());
let data = if matches!(format, format::Pixel::RGBA) {
- let _lock = image_buf.base_address_lock(LockFlags::READ_ONLY).unwrap();
+ let _lock = unsafe {
+ image_buf
+ .lock_base_addr(LockFlags::READ_ONLY)
+ .result()
+ .unwrap()
+ };
let bytes_per_row = image_buf.plane_bytes_per_row(0);
let width = image_buf.width() as usize;
@@ -53,6 +58,8 @@ impl CachedFrame {
)
}
+ unsafe { image_buf.unlock_lock_base_addr(LockFlags::READ_ONLY) };
+
bytes
} else {
let mut ffmpeg_frame = ffmpeg::frame::Video::new(
@@ -61,10 +68,15 @@ impl CachedFrame {
image_buf.height() as u32,
);
+ let _lock = unsafe {
+ image_buf
+ .lock_base_addr(LockFlags::READ_ONLY)
+ .result()
+ .unwrap()
+ };
+
match ffmpeg_frame.format() {
format::Pixel::NV12 => {
- let _lock = image_buf.base_address_lock(LockFlags::READ_ONLY).unwrap();
-
for plane_i in 0..image_buf.plane_count() {
let bytes_per_row = image_buf.plane_bytes_per_row(plane_i);
let height = image_buf.plane_height(plane_i);
@@ -90,8 +102,6 @@ impl CachedFrame {
}
}
format::Pixel::YUV420P => {
- let _lock = image_buf.base_address_lock(LockFlags::READ_ONLY).unwrap();
-
for plane_i in 0..image_buf.plane_count() {
let bytes_per_row = image_buf.plane_bytes_per_row(plane_i);
let height = image_buf.plane_height(plane_i);
@@ -119,6 +129,8 @@ impl CachedFrame {
format => todo!("implement {:?}", format),
}
+ unsafe { image_buf.unlock_lock_base_addr(LockFlags::READ_ONLY) };
+
let mut converter = ffmpeg::software::converter(
(ffmpeg_frame.width(), ffmpeg_frame.height()),
ffmpeg_frame.format(),
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 4b1d7a56b..38e1eb04d 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1,7 +1,7 @@
use anyhow::Result;
use cap_project::{
- AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Content, Crop, CursorEvents,
- ProjectConfiguration, RecordingMeta, XY,
+ AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, CursorEvents,
+ ProjectConfiguration, RecordingMeta, StudioRecordingMeta, XY,
};
use composite_frame::{CompositeVideoFramePipeline, CompositeVideoFrameUniforms};
use core::f64;
@@ -55,13 +55,17 @@ pub struct SegmentVideoPaths {
}
impl RecordingSegmentDecoders {
- pub async fn new(meta: &RecordingMeta, segment: SegmentVideoPaths) -> Result<Self, String> {
+ pub async fn new(
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
+ segment: SegmentVideoPaths,
+ ) -> Result<Self, String> {
let screen = spawn_decoder(
"screen",
- meta.project_path.join(segment.display),
- match &meta.content {
- Content::SingleSegment { segment } => segment.display.fps,
- Content::MultipleSegments { inner } => inner.segments[0].display.fps,
+ recording_meta.project_path.join(segment.display),
+ match &meta {
+ StudioRecordingMeta::SingleSegment { segment } => segment.display.fps,
+ StudioRecordingMeta::MultipleSegments { inner } => inner.segments[0].display.fps,
},
)
.await
@@ -69,10 +73,12 @@ impl RecordingSegmentDecoders {
let camera = OptionFuture::from(segment.camera.map(|camera| {
spawn_decoder(
"camera",
- meta.project_path.join(camera),
- match &meta.content {
- Content::SingleSegment { segment } => segment.camera.as_ref().unwrap().fps,
- Content::MultipleSegments { inner } => {
+ recording_meta.project_path.join(camera),
+ match &meta {
+ StudioRecordingMeta::SingleSegment { segment } => {
+ segment.camera.as_ref().unwrap().fps
+ }
+ StudioRecordingMeta::MultipleSegments { inner } => {
inner.segments[0].camera.as_ref().unwrap().fps
}
},
@@ -132,21 +138,22 @@ pub async fn render_video_to_channel(
options: RenderOptions,
project: ProjectConfiguration,
sender: mpsc::Sender<(RenderedFrame, u32)>,
- meta: &RecordingMeta,
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
segments: Vec<RenderSegment>,
fps: u32,
resolution_base: XY<u32>,
is_upgraded: bool,
) -> Result<(), RenderingError> {
- let constants = RenderVideoConstants::new(options, meta).await?;
- let recordings = ProjectRecordings::new(meta);
+ let constants = RenderVideoConstants::new(options, recording_meta, meta).await?;
+ let recordings = ProjectRecordings::new(recording_meta, meta);
ffmpeg::init().unwrap();
let start_time = Instant::now();
// Get the duration from the timeline if it exists, otherwise use the longest source duration
- let duration = get_duration(&recordings, meta, &project);
+ let duration = get_duration(&recordings, recording_meta, meta, &project);
let total_frames = (fps as f64 * duration).ceil() as u32;
println!(
@@ -221,16 +228,17 @@ pub async fn render_video_to_channel(
pub fn get_duration(
recordings: &ProjectRecordings,
- meta: &RecordingMeta,
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
project: &ProjectConfiguration,
) -> f64 {
let mut max_duration = recordings.duration();
println!("Initial screen recording duration: {}", max_duration);
// Check camera duration if it exists
- if let Some(camera_path) = meta.content.camera_path() {
+ if let Some(camera_path) = meta.camera_path() {
if let Ok(camera_duration) =
- recordings.get_source_duration(&camera_path.to_path(&meta.project_path))
+ recordings.get_source_duration(&recording_meta.path(&camera_path))
{
println!("Camera recording duration: {}", camera_duration);
max_duration = max_duration.max(camera_duration);
@@ -286,7 +294,11 @@ pub struct RenderVideoConstants {
}
impl RenderVideoConstants {
- pub async fn new(options: RenderOptions, meta: &RecordingMeta) -> Result<Self, RenderingError> {
+ pub async fn new(
+ options: RenderOptions,
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
+ ) -> Result<Self, RenderingError> {
println!("Initializing wgpu...");
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());
let adapter = instance
@@ -303,7 +315,7 @@ impl RenderVideoConstants {
)
.await?;
- let cursor_textures = Self::load_cursor_textures(&device, &queue, meta);
+ let cursor_textures = Self::load_cursor_textures(&device, &queue, recording_meta, meta);
let composite_video_frame_pipeline = CompositeVideoFramePipeline::new(&device);
let gradient_or_color_pipeline = GradientOrColorPipeline::new(&device);
@@ -383,21 +395,24 @@ impl RenderVideoConstants {
fn load_cursor_textures(
device: &wgpu::Device,
queue: &wgpu::Queue,
- meta: &RecordingMeta,
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
) -> HashMap<String, CursorTexture> {
println!("Starting to load cursor textures");
- println!("Project path: {:?}", meta.project_path);
+ println!("Project path: {:?}", recording_meta.project_path);
// println!("Cursor images to load: {:?}", cursor.cursor_images);
let mut textures = HashMap::new();
// Create the full path to the cursors directory
- let cursors_dir = meta.project_path.join("content").join("cursors");
+ let cursors_dir = recording_meta.project_path.join("content").join("cursors");
println!("Cursors directory: {:?}", cursors_dir);
- let cursor_images = match &meta.content {
- Content::SingleSegment { .. } => Default::default(),
- Content::MultipleSegments { inner } => inner.cursor_images(meta).unwrap_or_default(),
+ let cursor_images = match &meta {
+ StudioRecordingMeta::SingleSegment { .. } => Default::default(),
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ inner.cursor_images(recording_meta).unwrap_or_default()
+ }
};
for (cursor_id, cursor) in &cursor_images.0 {
diff --git a/crates/rendering/src/project_recordings.rs b/crates/rendering/src/project_recordings.rs
index 812f2b8bb..d898f8f56 100644
--- a/crates/rendering/src/project_recordings.rs
+++ b/crates/rendering/src/project_recordings.rs
@@ -1,6 +1,7 @@
use std::path::PathBuf;
use crate::RecordingMeta;
+use cap_project::StudioRecordingMeta;
use serde::Serialize;
use specta::Type;
@@ -75,18 +76,19 @@ pub struct ProjectRecordings {
}
impl ProjectRecordings {
- pub fn new(meta: &RecordingMeta) -> Self {
- let segments = match &meta.content {
- crate::Content::SingleSegment { segment } => {
- let display = Video::new(&meta.path(&segment.display.path))
+ pub fn new(recording_meta: &RecordingMeta, meta: &StudioRecordingMeta) -> Self {
+ let segments = match &meta {
+ StudioRecordingMeta::SingleSegment { segment } => {
+ let display = Video::new(&recording_meta.path(&segment.display.path))
.expect("Failed to read display video");
let camera = segment.camera.as_ref().map(|camera| {
- Video::new(&meta.path(&camera.path)).expect("Failed to read camera video")
+ Video::new(&recording_meta.path(&camera.path))
+ .expect("Failed to read camera video")
});
let audio = segment
.audio
.as_ref()
- .map(|audio| Audio::new(&meta.path(&audio.path)));
+ .map(|audio| Audio::new(&recording_meta.path(&audio.path)));
vec![SegmentRecordings {
display,
@@ -94,19 +96,20 @@ impl ProjectRecordings {
audio,
}]
}
- crate::Content::MultipleSegments { inner } => inner
+ StudioRecordingMeta::MultipleSegments { inner } => inner
.segments
.iter()
.map(|s| {
- let display = Video::new(&meta.path(&s.display.path))
+ let display = Video::new(&recording_meta.path(&s.display.path))
.expect("Failed to read display video");
let camera = s.camera.as_ref().map(|camera| {
- Video::new(&meta.path(&camera.path)).expect("Failed to read camera video")
+ Video::new(&recording_meta.path(&camera.path))
+ .expect("Failed to read camera video")
});
let audio = s
.audio
.as_ref()
- .map(|audio| Audio::new(&meta.path(&audio.path)));
+ .map(|audio| Audio::new(&recording_meta.path(&audio.path)));
SegmentRecordings {
display,