Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Redering fixes (#378)

Brendan Allan490344ed0340
diff --git a/Cargo.lock b/Cargo.lock
index 0562777a1..a4d4f353d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -912,7 +912,7 @@ dependencies = [
name = "cap-audio"
version = "0.1.0"
dependencies = [
- "cidre 0.7.0",
+ "cidre",
"cpal 0.15.3 (git+https://github.com/RustAudio/cpal?rev=f43d36e55494993bbbde3299af0c53e5cdf4d4cf)",
"ffmpeg-next",
"tokio",
@@ -978,6 +978,7 @@ dependencies = [
"tauri-plugin-http",
"tauri-plugin-notification",
"tauri-plugin-oauth",
+ "tauri-plugin-opener",
"tauri-plugin-os",
"tauri-plugin-positioner",
"tauri-plugin-process",
@@ -1069,7 +1070,7 @@ dependencies = [
"cap-flags",
"cap-gpu-converters",
"cap-project",
- "cidre 0.6.0",
+ "cidre",
"cocoa 0.26.0",
"core-foundation 0.10.0",
"core-graphics 0.24.0",
@@ -1118,6 +1119,7 @@ dependencies = [
"cap-project",
"cap-utils",
"chrono",
+ "cidre",
"cocoa 0.26.0",
"device_query",
"either",
@@ -1148,7 +1150,7 @@ dependencies = [
"bytemuck",
"cap-flags",
"cap-project",
- "cidre 0.6.0",
+ "cidre",
"ffmpeg-hw-device",
"ffmpeg-next",
"ffmpeg-sys-next",
@@ -1162,6 +1164,7 @@ dependencies = [
"specta",
"thiserror 1.0.69",
"tokio",
+ "tracing",
"wgpu",
]
@@ -1331,26 +1334,11 @@ name = "cidre"
version = "0.6.0"
source = "git+https://github.com/yury/cidre?rev=ef04aaabe14ffbbce4a330973a74b6d797d073ff#ef04aaabe14ffbbce4a330973a74b6d797d073ff"
dependencies = [
- "cidre-macros 0.1.0 (git+https://github.com/yury/cidre?rev=ef04aaabe14ffbbce4a330973a74b6d797d073ff)",
- "parking_lot",
- "tokio",
-]
-
-[[package]]
-name = "cidre"
-version = "0.7.0"
-source = "git+https://github.com/yury/cidre?rev=b525fce737310f524e0159488f8a4e29685680bf#b525fce737310f524e0159488f8a4e29685680bf"
-dependencies = [
- "cidre-macros 0.1.0 (git+https://github.com/yury/cidre?rev=b525fce737310f524e0159488f8a4e29685680bf)",
+ "cidre-macros",
"parking_lot",
"tokio",
]
-[[package]]
-name = "cidre-macros"
-version = "0.1.0"
-source = "git+https://github.com/yury/cidre?rev=b525fce737310f524e0159488f8a4e29685680bf#b525fce737310f524e0159488f8a4e29685680bf"
-
[[package]]
name = "cidre-macros"
version = "0.1.0"
@@ -7640,6 +7628,28 @@ dependencies = [
"url",
]
+[[package]]
+name = "tauri-plugin-opener"
+version = "2.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2fdc6cb608e04b7d2b6d1f21e9444ad49245f6d03465ba53323d692d1ceb1a30"
+dependencies = [
+ "dunce",
+ "glob",
+ "objc2-app-kit 0.3.0",
+ "objc2-foundation 0.3.0",
+ "open",
+ "schemars",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.6",
+ "url",
+ "windows 0.60.0",
+ "zbus 5.3.0",
+]
+
[[package]]
name = "tauri-plugin-os"
version = "2.2.0"
diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs
index 47bfa65c4..db1fdf59b 100644
--- a/apps/cli/src/main.rs
+++ b/apps/cli/src/main.rs
@@ -10,6 +10,7 @@ use clap::{Args, Parser, Subcommand};
use record::RecordStart;
use serde_json::json;
use tracing::*;
+use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[derive(Parser)]
struct Cli {
@@ -49,6 +50,21 @@ enum RecordCommands {
#[tokio::main]
async fn main() -> Result<(), String> {
+ // let (layer, handle) = tracing_subscriber::reload::Layer::new(None::<DynLoggingLayer>);
+
+ let registry = tracing_subscriber::registry().with(tracing_subscriber::filter::filter_fn(
+ (|v| v.target().starts_with("cap_")) as fn(&tracing::Metadata) -> bool,
+ ));
+
+ registry
+ // .with(layer)
+ .with(
+ tracing_subscriber::fmt::layer()
+ .with_ansi(true)
+ .with_target(true),
+ )
+ .init();
+
let cli = Cli::parse();
match cli.command {
@@ -177,7 +193,7 @@ impl Export {
recording_meta,
render_constants,
&segments,
- fps,
+ 60,
XY::new(1920, 1080),
)
.await
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 06c929483..fdbc9c435 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -41,6 +41,7 @@
"@tauri-apps/plugin-fs": "2.2.0",
"@tauri-apps/plugin-http": "^2.0.1",
"@tauri-apps/plugin-notification": "2.0.0",
+ "@tauri-apps/plugin-opener": "^2.2.6",
"@tauri-apps/plugin-os": "2.0.0",
"@tauri-apps/plugin-process": "2.0.0",
"@tauri-apps/plugin-shell": ">=2.0.1",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 77c0763f2..adfbb9539 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -89,6 +89,7 @@ relative-path = "1.9.3"
cap-fail = { version = "0.1.0", path = "../../../crates/fail" }
tokio-stream = { version = "0.1.17", features = ["sync"] }
md5 = "0.7.0"
+tauri-plugin-opener = "2.2.6"
[target.'cfg(target_os = "macos")'.dependencies]
core-graphics = "0.24.0"
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json
index 5ff40afc1..7751dbe8a 100644
--- a/apps/desktop/src-tauri/capabilities/default.json
+++ b/apps/desktop/src-tauri/capabilities/default.json
@@ -60,6 +60,7 @@
{ "url": "http://localhost:*" }
]
},
- "clipboard-manager:allow-write-text"
+ "clipboard-manager:allow-write-text",
+ "opener:allow-reveal-item-in-dir"
]
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index dd4f0dffa..2e79441d9 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1453,12 +1453,13 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resul
pretty_name: screenshot_name,
inner: RecordingMetaInner::Studio(cap_project::StudioRecordingMeta::SingleSegment {
segment: cap_project::SingleSegment {
- display: Display {
+ display: VideoMeta {
path: RelativePathBuf::from_path(
&screenshot_path.strip_prefix(&recording_dir).unwrap(),
)
.unwrap(),
fps: 0,
+ start_time: None,
},
camera: None,
audio: None,
@@ -2159,6 +2160,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
.plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_fs::init())
+ .plugin(tauri_plugin_opener::init())
.plugin(
tauri_plugin_window_state::Builder::new()
.with_state_flags({
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
index 8f2293128..b8d8cfd5c 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
@@ -16,9 +16,10 @@ import {
ParentProps,
Show,
} from "solid-js";
+import { revealItemInDir } from "@tauri-apps/plugin-opener";
import { ask } from "@tauri-apps/plugin-dialog";
-import { open } from "@tauri-apps/plugin-shell";
+import * as shell from "@tauri-apps/plugin-shell";
import { trackEvent } from "~/utils/analytics";
import { commands, events, RecordingMetaWithType } from "~/utils/tauri";
@@ -117,7 +118,9 @@ export default function Recordings() {
<Show
when={recordings.data && recordings.data.length > 0}
fallback={
- <p class="text-center text-[--text-tertiary] absolute flex items-center justify-center w-full h-full">No recordings found</p>
+ <p class="text-center text-[--text-tertiary] absolute flex items-center justify-center w-full h-full">
+ No recordings found
+ </p>
}
>
<div class="p-4 border-b border-gray-300 border-dashed">
@@ -176,21 +179,6 @@ function RecordingItem(props: {
const queryClient = useQueryClient();
- const deleteButton = () => (
- <TooltipIconButton
- tooltipText="Delete"
- onClick={async () => {
- if (!(await ask("Are you sure you want to delete this recording?")))
- return;
- await remove(props.recording.path, { recursive: true });
-
- queryClient.refetchQueries(recordingsQuery);
- }}
- >
- <IconCapTrash class="size-4" />
- </TooltipIconButton>
- );
-
return (
<li class="flex flex-row justify-between items-center px-4 py-3 w-full rounded-xl transition-colors duration-200 hover:bg-gray-100">
<div class="flex gap-5 items-center">
@@ -225,7 +213,7 @@ function RecordingItem(props: {
</div>
</div>
</div>
- <div class="flex items-center">
+ <div class="flex items-center gap-2">
<Show when={type() === "studio"}>
<TooltipIconButton
tooltipText="Edit"
@@ -243,13 +231,12 @@ function RecordingItem(props: {
{(sharing) => (
<TooltipIconButton
tooltipText="Open link"
- onClick={() => open(sharing().link)}
+ onClick={() => shell.open(sharing().link)}
>
<IconCapLink class="size-4" />
</TooltipIconButton>
)}
</Show>
- {deleteButton()}
</Show>
<Show when={type() === "instant"}>
{(_) => {
@@ -260,34 +247,49 @@ function RecordingItem(props: {
}));
return (
- <>
- <Show when={props.recording.meta.sharing}>
- {(sharing) => (
- <>
- <TooltipIconButton
- tooltipText="Reupload"
- onClick={() => reupload.mutate()}
- >
- {reupload.isPending ? (
- <IconLucideLoaderCircle class="animate-spin" />
- ) : (
- <IconLucideRotateCcw class="size-4" />
- )}
- </TooltipIconButton>
- <TooltipIconButton
- tooltipText="Open link"
- onClick={() => open(sharing().link)}
- >
- <IconCapLink class="size-4" />
- </TooltipIconButton>
- </>
- )}
- </Show>
- {deleteButton()}
- </>
+ <Show when={props.recording.meta.sharing}>
+ {(sharing) => (
+ <>
+ <TooltipIconButton
+ tooltipText="Reupload"
+ onClick={() => reupload.mutate()}
+ >
+ {reupload.isPending ? (
+ <IconLucideLoaderCircle class="animate-spin" />
+ ) : (
+ <IconLucideRotateCcw class="size-4" />
+ )}
+ </TooltipIconButton>
+ <TooltipIconButton
+ tooltipText="Open link"
+ onClick={() => shell.open(sharing().link)}
+ >
+ <IconCapLink class="size-4" />
+ </TooltipIconButton>
+ </>
+ )}
+ </Show>
);
}}
</Show>
+ <TooltipIconButton
+ tooltipText="Open recording bundle"
+ onClick={() => revealItemInDir(`${props.recording.path}/`)}
+ >
+ <IconLucideFolder class="size-4" />
+ </TooltipIconButton>
+ <TooltipIconButton
+ tooltipText="Delete"
+ onClick={async () => {
+ if (!(await ask("Are you sure you want to delete this recording?")))
+ return;
+ await remove(props.recording.path, { recursive: true });
+
+ queryClient.refetchQueries(recordingsQuery);
+ }}
+ >
+ <IconCapTrash class="size-4" />
+ </TooltipIconButton>
</div>
</li>
);
@@ -308,7 +310,7 @@ function TooltipIconButton(
props.onClick();
}}
disabled={props.disabled}
- class="p-2.5 mr-2 opacity-70 will-change-transform hover:opacity-100 rounded-full transition-all duration-200 hover:bg-gray-200 dark:hover:bg-gray-300"
+ class="p-2.5 opacity-70 will-change-transform hover:opacity-100 rounded-full transition-all duration-200 hover:bg-gray-200 dark:hover:bg-gray-300"
>
{props.children}
</Tooltip.Trigger>
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 0020907d2..a8f95c022 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -229,14 +229,13 @@ export type AspectRatio = "wide" | "vertical" | "square" | "classic" | "tall"
export type Audio = { duration: number; sample_rate: number; channels: number }
export type AudioConfiguration = { mute: boolean; improve: boolean }
export type AudioInputLevelChange = number
-export type AudioMeta = { path: string }
+export type AudioMeta = { path: string; start_time?: number | null }
export type AuthStore = { token: string; user_id: string | null; expires: number; plan: Plan | null; intercom_hash: string | null }
export type AuthenticationInvalid = null
export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; inset: number; crop: Crop | null; shadow?: number; advancedShadow?: ShadowConfiguration | null }
export type BackgroundSource = { type: "wallpaper"; path: string | null } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number] } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number }
export type Bounds = { x: number; y: number; width: number; height: number }
export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition; size: number; zoom_size: number | null; rounding?: number; shadow?: number; advanced_shadow?: ShadowConfiguration | null }
-export type CameraMeta = { path: string; fps?: number }
export type CameraPosition = { x: CameraXPosition; y: CameraYPosition }
export type CameraXPosition = "left" | "center" | "right"
export type CameraYPosition = "top" | "bottom"
@@ -251,7 +250,6 @@ export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: C
export type CursorMeta = { imagePath: string; hotspot: XY<number> }
export type CursorType = "pointer" | "circle"
export type Cursors = { [key in string]: string } | { [key in string]: CursorMeta }
-export type Display = { path: string; fps?: number }
export type EditorStateChanged = { playhead_position: number }
export type ExportEstimates = { duration_seconds: number; estimated_time_seconds: number; estimated_size_mb: number }
export type Flags = { recordMouseState: boolean; systemAudioRecording: boolean; split: boolean }
@@ -264,7 +262,7 @@ 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; system_audio?: AudioMeta | null; cursor?: string | null }
+export type MultipleSegment = { display: VideoMeta; camera?: VideoMeta | null; audio?: AudioMeta | null; system_audio?: AudioMeta | null; cursor?: string | null }
export type MultipleSegments = { segments: MultipleSegment[]; cursors: Cursors }
export type NewNotification = { title: string; body: string; is_error: boolean }
export type NewScreenshotAdded = { path: string }
@@ -300,7 +298,7 @@ export type SerializedEditorInstance = { framesSocketUrl: string; recordingDurat
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 } } | "RecordingsOverlay" | "WindowCaptureOccluder" | { CaptureArea: { screen_id: number } } | { Camera: { ws_port: number } } | { InProgressRecording: { position: [number, number] | null } } | "Upgrade" | "SignIn" | "ModeSelect"
-export type SingleSegment = { display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null; cursor?: string | null }
+export type SingleSegment = { display: VideoMeta; camera?: VideoMeta | 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 }
@@ -308,6 +306,11 @@ export type UploadMode = { Initial: { pre_created_video: VideoUploadInfo | null
export type UploadProgress = { progress: number; message: string }
export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"
export type Video = { duration: number; width: number; height: number; fps: number }
+export type VideoMeta = { path: string; fps?: number;
+/**
+ * unix time of the first frame
+ */
+start_time?: number | null }
export type VideoRecordingMetadata = { duration: number; size: number }
export type VideoType = "screen" | "output" | "camera"
export type VideoUploadInfo = { id: string; link: string; config: S3UploadMeta }
diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml
index 9fcc9f12c..825981272 100644
--- a/crates/audio/Cargo.toml
+++ b/crates/audio/Cargo.toml
@@ -10,4 +10,4 @@ cpal = { workspace = true }
tokio.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
-cidre = { git = "https://github.com/yury/cidre", rev = "b525fce737310f524e0159488f8a4e29685680bf" }
+cidre = { workspace = true }
diff --git a/crates/media/src/encoders/mp4_avassetwriter.rs b/crates/media/src/encoders/mp4_avassetwriter.rs
index 5c90bd80d..5249a5734 100644
--- a/crates/media/src/encoders/mp4_avassetwriter.rs
+++ b/crates/media/src/encoders/mp4_avassetwriter.rs
@@ -149,18 +149,12 @@ impl MP4AVAssetWriterEncoder {
})
}
- pub fn queue_video_frame(&mut self, frame: screencapturekit::output::CMSampleBuffer) {
+ pub fn queue_video_frame(&mut self, frame: &cidre::cm::SampleBuf) {
if !self.video_input.is_ready_for_more_media_data() {
return;
}
- let sample_buf = unsafe {
- use core_foundation::base::TCFType;
- let ptr = &*frame.as_concrete_TypeRef() as *const _ as *const cm::SampleBuf;
- &*ptr
- };
-
- let time = sample_buf.pts();
+ let time = frame.pts();
if self.first_timestamp.is_none() {
self.asset_writer.start_session_at_src_time(time);
@@ -169,7 +163,7 @@ impl MP4AVAssetWriterEncoder {
self.last_timestamp = Some(time);
- self.video_input.append_sample_buf(sample_buf).ok();
+ self.video_input.append_sample_buf(frame).ok();
}
pub fn queue_audio_frame(&mut self, frame: FFAudio) -> Result<(), MediaError> {
@@ -267,20 +261,19 @@ impl MP4AVAssetWriterEncoder {
}
}
-use flume::Receiver;
use screencapturekit::output::CMSampleBuffer;
use tracing::{debug, info};
-impl PipelineSinkTask<CMSampleBuffer> for MP4AVAssetWriterEncoder {
+impl PipelineSinkTask<cidre::arc::R<cidre::cm::SampleBuf>> for MP4AVAssetWriterEncoder {
fn run(
&mut self,
ready_signal: crate::pipeline::task::PipelineReadySignal,
- input: &flume::Receiver<CMSampleBuffer>,
+ input: &flume::Receiver<cidre::arc::R<cidre::cm::SampleBuf>>,
) {
ready_signal.send(Ok(())).ok();
while let Ok(frame) = input.recv() {
- self.queue_video_frame(frame);
+ self.queue_video_frame(&frame);
self.process_frame();
}
}
@@ -310,26 +303,6 @@ impl PipelineSinkTask<FFAudio> for Arc<Mutex<MP4AVAssetWriterEncoder>> {
}
}
-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;
diff --git a/crates/media/src/pipeline/builder.rs b/crates/media/src/pipeline/builder.rs
index 095da5a63..dbcb7332c 100644
--- a/crates/media/src/pipeline/builder.rs
+++ b/crates/media/src/pipeline/builder.rs
@@ -11,7 +11,7 @@ use tracing::{info, trace};
use crate::pipeline::{
clock::CloneFrom,
control::ControlBroadcast,
- task::{PipelinePipeTask, PipelineReadySignal, PipelineSinkTask, PipelineSourceTask},
+ task::{PipelineReadySignal, PipelineSinkTask, PipelineSourceTask},
MediaError, Pipeline, PipelineClock,
};
@@ -39,7 +39,7 @@ impl<T> PipelineBuilder<T> {
pub fn source<O: Send + 'static, C: CloneFrom<T> + Send + 'static>(
mut self,
name: impl Into<String>,
- mut task: impl PipelineSourceTask<Output = O, Clock = C> + 'static,
+ mut task: impl PipelineSourceTask<Clock = C> + 'static,
) -> PipelinePathBuilder<T, O> {
let name = name.into();
let (output, next_input) = flume::bounded(task.queue_size());
@@ -56,10 +56,10 @@ impl<T> PipelineBuilder<T> {
}
}
- pub fn spawn_source<O: Send + 'static, C: CloneFrom<T> + Send + 'static>(
+ pub fn spawn_source<C: CloneFrom<T> + Send + 'static>(
&mut self,
name: impl Into<String>,
- mut task: impl PipelineSourceTask<Output = O, Clock = C> + 'static,
+ mut task: impl PipelineSourceTask<Clock = C> + 'static,
) {
let name = name.into();
let clock = C::clone_from(&self.clock);
@@ -176,50 +176,3 @@ pub struct PipelinePathBuilder<Clock, PreviousOutput: Send> {
pipeline: PipelineBuilder<Clock>,
next_input: Receiver<PreviousOutput>,
}
-
-impl<Clock, PreviousOutput: Send + 'static> PipelinePathBuilder<Clock, PreviousOutput> {
- pub fn pipe<Output: Send + 'static>(
- self,
- name: impl Into<String>,
- mut task: impl PipelinePipeTask<Input = PreviousOutput, Output = Output> + 'static,
- ) -> PipelinePathBuilder<Clock, Output> {
- let Self {
- mut pipeline,
- next_input: input,
- } = self;
-
- let (output, next_input) = flume::bounded(task.queue_size());
-
- pipeline.spawn_task(name.into(), move |ready_signal| {
- trace!("Pipe starting");
- task.run(ready_signal, input, output);
- info!("Pipe stopped");
- });
-
- PipelinePathBuilder {
- pipeline,
- next_input,
- }
- }
-
- pub fn sink(
- self,
- name: impl Into<String>,
- mut task: impl PipelineSinkTask<PreviousOutput> + 'static,
- ) -> PipelineBuilder<Clock> {
- let Self {
- mut pipeline,
- next_input: input,
- } = self;
-
- pipeline.spawn_task(name.into(), move |ready_signal| {
- trace!("Sink starting");
- task.run(ready_signal, &input);
- info!("Sink stopped running");
- task.finish();
- info!("Sink stopped");
- });
-
- pipeline
- }
-}
diff --git a/crates/media/src/pipeline/task.rs b/crates/media/src/pipeline/task.rs
index 0d19d0224..ab123fc2b 100644
--- a/crates/media/src/pipeline/task.rs
+++ b/crates/media/src/pipeline/task.rs
@@ -1,5 +1,3 @@
-use std::marker::PhantomData;
-
use flume::{Receiver, Sender};
use crate::pipeline::{MediaError, PipelineControlSignal};
@@ -9,7 +7,6 @@ const DEFAULT_QUEUE_SIZE: usize = 2048;
pub type PipelineReadySignal = Sender<Result<(), MediaError>>;
pub trait PipelineSourceTask: Send {
- type Output;
type Clock;
fn run(
@@ -24,22 +21,6 @@ pub trait PipelineSourceTask: Send {
}
}
-pub trait PipelinePipeTask: Send {
- type Input;
- type Output;
-
- fn run(
- &mut self,
- ready_signal: PipelineReadySignal,
- input: Receiver<Self::Input>,
- output: Sender<Self::Output>,
- );
-
- fn queue_size(&self) -> usize {
- DEFAULT_QUEUE_SIZE
- }
-}
-
pub trait PipelineSinkTask<Input>: Send {
fn run(&mut self, ready_signal: PipelineReadySignal, input: &Receiver<Input>);
diff --git a/crates/media/src/sources/audio_input.rs b/crates/media/src/sources/audio_input.rs
index 8648bb0fb..6c5d4479f 100644
--- a/crates/media/src/sources/audio_input.rs
+++ b/crates/media/src/sources/audio_input.rs
@@ -26,11 +26,11 @@ impl LocalTimestamp for StreamInstant {
pub struct AudioInputSource {
feed_connection: AudioInputConnection,
audio_info: AudioInfo,
- tx: Sender<FFAudio>,
+ tx: Sender<(FFAudio, f64)>,
}
impl AudioInputSource {
- pub fn init(feed: &AudioInputFeed, tx: Sender<FFAudio>) -> Self {
+ pub fn init(feed: &AudioInputFeed, tx: Sender<(FFAudio, f64)>) -> Self {
Self {
feed_connection: feed.create_connection(),
audio_info: feed.audio_info(),
@@ -53,7 +53,7 @@ impl AudioInputSource {
}
Some(timestamp) => {
let frame = self.audio_info.wrap_frame(&samples.data, timestamp);
- if let Err(_) = self.tx.send(frame) {
+ if let Err(_) = self.tx.send((frame, 0.0 /* TODO: correct this */)) {
return Err(MediaError::Any("Pipeline is unreachable! Stopping capture"));
}
}
@@ -79,8 +79,6 @@ impl AudioInputSource {
}
impl PipelineSourceTask for AudioInputSource {
- type Output = FFAudio;
-
type Clock = RealTimeClock<StreamInstant>;
fn run(
diff --git a/crates/media/src/sources/audio_mixer.rs b/crates/media/src/sources/audio_mixer.rs
index 440e15861..d6484b373 100644
--- a/crates/media/src/sources/audio_mixer.rs
+++ b/crates/media/src/sources/audio_mixer.rs
@@ -33,7 +33,7 @@ impl AudioMixer {
AudioMixerSink { tx }
}
- pub fn add_source(&mut self, info: AudioInfo, rx: Receiver<FFAudio>) {
+ pub fn add_source(&mut self, info: AudioInfo, rx: Receiver<(FFAudio, f64)>) {
self.sources.push(AudioMixerSource { rx, info })
}
@@ -131,7 +131,7 @@ impl AudioMixer {
Err(flume::TryRecvError::Empty) => break,
};
- abuffers[i].source().add(&value).unwrap();
+ abuffers[i].source().add(&value.0).unwrap();
}
}
@@ -149,32 +149,31 @@ impl AudioMixer {
}
pub struct AudioMixerSink {
- pub tx: flume::Sender<FFAudio>,
+ pub tx: flume::Sender<(FFAudio, f64)>,
}
pub struct AudioMixerSource {
- rx: flume::Receiver<FFAudio>,
+ rx: flume::Receiver<(FFAudio, f64)>,
info: AudioInfo,
}
-impl PipelineSinkTask<FFAudio> for AudioMixerSink {
- fn run(
- &mut self,
- ready_signal: crate::pipeline::task::PipelineReadySignal,
- input: &flume::Receiver<FFAudio>,
- ) {
- let _ = ready_signal.send(Ok(()));
+// impl PipelineSinkTask<(FFAudio, f64)> for AudioMixerSink {
+// fn run(
+// &mut self,
+// ready_signal: crate::pipeline::task::PipelineReadySignal,
+// input: &flume::Receiver<(FFAudio, f64)>,
+// ) {
+// let _ = ready_signal.send(Ok(()));
- while let Ok(input) = input.recv() {
- let _ = self.tx.send(input);
- }
- }
+// while let Ok(input) = input.recv() {
+// let _ = self.tx.send(input);
+// }
+// }
- fn finish(&mut self) {}
-}
+// fn finish(&mut self) {}
+// }
impl PipelineSourceTask for AudioMixer {
- type Output = FFAudio;
type Clock = RealTimeClock<RawNanoseconds>;
fn run(
diff --git a/crates/media/src/sources/camera.rs b/crates/media/src/sources/camera.rs
index 6d145b36e..d71751fe0 100644
--- a/crates/media/src/sources/camera.rs
+++ b/crates/media/src/sources/camera.rs
@@ -70,8 +70,6 @@ impl CameraSource {
}
impl PipelineSourceTask for CameraSource {
- type Output = FFVideo;
-
type Clock = RealTimeClock<Instant>;
// #[tracing::instrument(skip_all)]
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 6e52ba14f..1fdbc46fb 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -1,6 +1,7 @@
use cap_flags::FLAGS;
use cpal::traits::{DeviceTrait, HostTrait};
use ffmpeg::{format::Sample, frame::Audio, ChannelLayout};
+use ffmpeg_sys_next::AV_TIME_BASE_Q;
use flume::Sender;
use scap::{
capturer::{
@@ -130,8 +131,8 @@ pub struct ScreenCaptureSource<TCaptureFormat: ScreenCaptureFormat> {
show_camera: bool,
force_show_cursor: bool,
bounds: Bounds,
- video_tx: Sender<TCaptureFormat::VideoFormat>,
- audio_tx: Option<Sender<ffmpeg::frame::Audio>>,
+ video_tx: Sender<(TCaptureFormat::VideoFormat, f64)>,
+ audio_tx: Option<Sender<(ffmpeg::frame::Audio, f64)>>,
_phantom: std::marker::PhantomData<TCaptureFormat>,
}
@@ -205,8 +206,8 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
show_camera: bool,
force_show_cursor: bool,
max_fps: u32,
- video_tx: Sender<TCaptureFormat::VideoFormat>,
- audio_tx: Option<Sender<ffmpeg::frame::Audio>>,
+ video_tx: Sender<(TCaptureFormat::VideoFormat, f64)>,
+ audio_tx: Option<Sender<(ffmpeg::frame::Audio, f64)>>,
) -> Result<Self, String> {
cap_fail::fail!("media::screen_capture::init");
@@ -366,7 +367,6 @@ pub struct AVFrameCapture;
impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {
type Clock = RealTimeClock<RawNanoseconds>;
- type Output = (FFVideo, Option<ffmpeg::frame::Audio>);
// #[instrument(skip_all)]
fn run(
@@ -440,7 +440,9 @@ impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {
}
}
- if let Err(_) = video_tx.send(buffer) {
+ if let Err(_) =
+ video_tx.send((buffer, 0.0 /* TODO: correct this */))
+ {
error!("Pipeline is unreachable. Shutting down recording.");
return Some(ControlFlow::Break(()));
}
@@ -451,7 +453,10 @@ impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {
}
Ok(Frame::Audio(frame)) => {
if let Some(audio_tx) = &audio_tx {
- let _ = audio_tx.send(scap_audio_to_ffmpeg(frame));
+ let _ = audio_tx.send((
+ scap_audio_to_ffmpeg(frame),
+ 0.0, /* TODO: correct this */
+ ));
}
None
}
@@ -540,7 +545,7 @@ pub struct CMSampleBufferCapture;
#[cfg(target_os = "macos")]
impl ScreenCaptureFormat for CMSampleBufferCapture {
- type VideoFormat = screencapturekit::output::CMSampleBuffer;
+ type VideoFormat = cidre::arc::R<cidre::cm::SampleBuf>;
fn audio_info() -> AudioInfo {
AudioInfo::new(
@@ -555,7 +560,6 @@ impl ScreenCaptureFormat for CMSampleBufferCapture {
#[cfg(target_os = "macos")]
impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
type Clock = RealTimeClock<RawNanoseconds>;
- type Output = screencapturekit::output::CMSampleBuffer;
fn run(
&mut self,
@@ -567,7 +571,14 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
let video_tx = self.video_tx.clone();
let audio_tx = self.audio_tx.clone();
- let audio_info = self.audio_info();
+
+ let start = std::time::SystemTime::now();
+ let start_time_unix = start
+ .duration_since(std::time::UNIX_EPOCH)
+ .expect("Time went backwards")
+ .as_secs_f64();
+ let start_cmtime = cidre::cm::Clock::host_time_clock().time();
+ let start_cmtime = start_cmtime.value as f64 / start_cmtime.scale as f64;
inner(
self,
@@ -575,17 +586,25 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
control_signal,
|capturer| match capturer.raw().get_next_sample_buffer() {
Ok((sample_buffer, typ)) => {
+ let sample_buffer = unsafe {
+ std::mem::transmute::<_, cidre::arc::R<cidre::cm::SampleBuf>>(sample_buffer)
+ };
+
+ let frame_time =
+ sample_buffer.pts().value as f64 / sample_buffer.pts().scale as f64;
+ let unix_timestamp = start_time_unix + frame_time - start_cmtime;
+
match typ {
SCStreamOutputType::Screen => {
- let Ok(pixel_buffer) = sample_buffer.get_pixel_buffer() else {
+ let Some(pixel_buffer) = sample_buffer.image_buf() else {
return Some(ControlFlow::Continue(()));
};
- if pixel_buffer.get_height() == 0 || pixel_buffer.get_width() == 0 {
+ if pixel_buffer.height() == 0 || pixel_buffer.width() == 0 {
return Some(ControlFlow::Continue(()));
}
- if let Err(_) = video_tx.send(sample_buffer) {
+ if let Err(_) = video_tx.send((sample_buffer, unix_timestamp)) {
eprintln!("Pipeline is unreachable. Shutting down recording.");
return Some(ControlFlow::Continue(()));
}
@@ -595,22 +614,6 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
return Some(ControlFlow::Continue(()));
};
- // let list = sample_buffer.get_audio_buffer_list().unwrap();
- // let mut bytes = Vec::<u8>::new();
-
- // // dbg!(list.buffers().len());
-
- // for buffer in list.buffers() {
- // bytes.extend(buffer.data());
- // }
-
- use core_foundation::base::TCFType;
- let sample_buffer = unsafe {
- let s = sample_buffer.as_concrete_TypeRef();
- let b = s as *const _ as *const cidre::cm::SampleBuf;
- &*b
- };
-
let buf_list = sample_buffer.audio_buf_list::<2>().unwrap();
let slice = buf_list.block().as_slice().unwrap();
@@ -628,13 +631,14 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
);
}
- frame.set_pts(Some(sample_buffer.pts().value));
-
- // dbg!(&audio_info);
+ frame.set_pts(Some(
+ (sample_buffer.pts().value as f64
+ / sample_buffer.pts().scale as f64
+ * AV_TIME_BASE_Q.den as f64)
+ as i64,
+ ));
- let _ = audio_tx.send(
- frame, // audio_info.wrap_frame(&bytes, sample_buffer.output_pts().value),
- );
+ let _ = audio_tx.send((frame, unix_timestamp));
}
}
diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rs
index b92b0ead6..d0c76556f 100644
--- a/crates/project/src/meta.rs
+++ b/crates/project/src/meta.rs
@@ -1,29 +1,23 @@
use either::Either;
-use relative_path::{RelativePath, RelativePathBuf};
+use relative_path::RelativePathBuf;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::{
collections::HashMap,
- fs::File,
path::{Path, PathBuf},
};
use crate::{CursorEvents, CursorImage, CursorImages, ProjectConfiguration, XY};
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
-pub struct Display {
- #[specta(type = String)]
- pub path: RelativePathBuf,
- #[serde(default = "legacy_static_video_fps")]
- pub fps: u32,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, Type)]
-pub struct CameraMeta {
+pub struct VideoMeta {
#[specta(type = String)]
pub path: RelativePathBuf,
#[serde(default = "legacy_static_video_fps")]
pub fps: u32,
+ /// unix time of the first frame
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub start_time: Option<f64>,
}
fn legacy_static_video_fps() -> u32 {
@@ -34,6 +28,9 @@ fn legacy_static_video_fps() -> u32 {
pub struct AudioMeta {
#[specta(type = String)]
pub path: RelativePathBuf,
+ /// unix time of the first frame
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub start_time: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
@@ -157,9 +154,9 @@ impl StudioRecordingMeta {
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SingleSegment {
- pub display: Display,
+ pub display: VideoMeta,
#[serde(default, skip_serializing_if = "Option::is_none")]
- pub camera: Option<CameraMeta>,
+ pub camera: Option<VideoMeta>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub audio: Option<AudioMeta>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -232,9 +229,9 @@ impl MultipleSegments {
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct MultipleSegment {
- pub display: Display,
+ pub display: VideoMeta,
#[serde(default, skip_serializing_if = "Option::is_none")]
- pub camera: Option<CameraMeta>,
+ pub camera: Option<VideoMeta>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub audio: Option<AudioMeta>,
#[serde(default, skip_serializing_if = "Option::is_none")]
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
index 3e29284c3..73ccc5f5f 100644
--- a/crates/recording/Cargo.toml
+++ b/crates/recording/Cargo.toml
@@ -30,6 +30,7 @@ futures = "0.3.31"
screencapturekit = "0.3.5"
cocoa = "0.26.0"
objc = "0.2.7"
+cidre = { workspace = true }
[target.'cfg(target_os = "windows")'.dependencies]
windows = { workspace = true, features = [
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs
index 3c3134940..49b3ef342 100644
--- a/crates/recording/src/capture_pipeline.rs
+++ b/crates/recording/src/capture_pipeline.rs
@@ -11,6 +11,7 @@ use cap_media::{
},
MediaError,
};
+use ffmpeg::ffi::AV_TIME_BASE_Q;
use flume::{Receiver, Sender};
use tracing::error;
@@ -23,10 +24,10 @@ pub trait MakeCapturePipeline: ScreenCaptureFormat + std::fmt::Debug + 'static {
builder: CapturePipelineBuilder,
source: (
ScreenCaptureSource<Self>,
- flume::Receiver<Self::VideoFormat>,
+ flume::Receiver<(Self::VideoFormat, f64)>,
),
output_path: PathBuf,
- ) -> Result<CapturePipelineBuilder, MediaError>
+ ) -> Result<(CapturePipelineBuilder, flume::Receiver<f64>), MediaError>
where
Self: Sized;
@@ -34,10 +35,10 @@ pub trait MakeCapturePipeline: ScreenCaptureFormat + std::fmt::Debug + 'static {
builder: CapturePipelineBuilder,
source: (
ScreenCaptureSource<Self>,
- flume::Receiver<Self::VideoFormat>,
+ flume::Receiver<(Self::VideoFormat, f64)>,
),
audio: Option<&AudioInputFeed>,
- system_audio: Option<(Receiver<ffmpeg::frame::Audio>, AudioInfo)>,
+ system_audio: Option<(Receiver<(ffmpeg::frame::Audio, f64)>, AudioInfo)>,
output_path: PathBuf,
) -> impl Future<Output = Result<CapturePipelineBuilder, MediaError>> + Send
where
@@ -50,10 +51,10 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
mut builder: CapturePipelineBuilder,
source: (
ScreenCaptureSource<Self>,
- flume::Receiver<Self::VideoFormat>,
+ flume::Receiver<(Self::VideoFormat, f64)>,
),
output_path: PathBuf,
- ) -> Result<CapturePipelineBuilder, MediaError> {
+ ) -> Result<(CapturePipelineBuilder, flume::Receiver<f64>), MediaError> {
let screen_config = source.0.info();
let mut screen_encoder = cap_media::encoders::MP4AVAssetWriterEncoder::init(
"screen",
@@ -63,27 +64,43 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
None,
)?;
+ let (timestamp_tx, timestamp_rx) = flume::bounded(1);
+
builder.spawn_task("screen_capture_encoder", move |ready| {
+ let start = std::time::SystemTime::now();
+ let start_time_unix = start
+ .duration_since(std::time::UNIX_EPOCH)
+ .expect("Time went backwards")
+ .as_secs_f64();
+ let start_cmtime = cidre::cm::Clock::host_time_clock().time();
+ let start_cmtime = start_cmtime.value as f64 / start_cmtime.scale as f64;
+
+ let mut timestamp_tx = Some(timestamp_tx);
let _ = ready.send(Ok(()));
+
while let Ok(frame) = source.1.recv() {
- screen_encoder.queue_video_frame(frame);
+ if let Some(timestamp_tx) = timestamp_tx.take() {
+ let _ = timestamp_tx.send(frame.1);
+ }
+
+ screen_encoder.queue_video_frame(frame.0.as_ref());
}
screen_encoder.finish();
});
builder.spawn_source("screen_capture", source.0);
- Ok(builder)
+ Ok((builder, timestamp_rx))
}
async fn make_instant_mode_pipeline(
mut builder: CapturePipelineBuilder,
source: (
ScreenCaptureSource<Self>,
- flume::Receiver<Self::VideoFormat>,
+ flume::Receiver<(Self::VideoFormat, f64)>,
),
audio: Option<&AudioInputFeed>,
- system_audio: Option<(Receiver<ffmpeg::frame::Audio>, AudioInfo)>,
+ system_audio: Option<(Receiver<(ffmpeg::frame::Audio, f64)>, AudioInfo)>,
output_path: PathBuf,
) -> Result<CapturePipelineBuilder, MediaError> {
let (audio_tx, audio_rx) = flume::bounded(64);
@@ -131,9 +148,9 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
builder.spawn_task("screen_capture_encoder", move |ready| {
let _ = ready.send(Ok(()));
- while let Ok(frame) = source.1.recv() {
+ while let Ok((frame, unix_time)) = source.1.recv() {
if let Ok(mut mp4) = mp4.lock() {
- mp4.queue_video_frame(frame);
+ mp4.queue_video_frame(frame.as_ref());
}
}
if let Ok(mut mp4) = mp4.lock() {
@@ -152,10 +169,10 @@ impl MakeCapturePipeline for AVFrameCapture {
mut builder: CapturePipelineBuilder,
source: (
ScreenCaptureSource<Self>,
- flume::Receiver<Self::VideoFormat>,
+ flume::Receiver<(Self::VideoFormat, f64)>,
),
output_path: PathBuf,
- ) -> Result<CapturePipelineBuilder, MediaError>
+ ) -> Result<(CapturePipelineBuilder, flume::Receiver<f64>), MediaError>
where
Self: Sized,
{
@@ -169,25 +186,32 @@ impl MakeCapturePipeline for AVFrameCapture {
builder.spawn_source("screen_capture", source.0);
+ let (timestamp_tx, timestamp_rx) = flume::bounded(1);
+
builder.spawn_task("screen_capture_encoder", move |ready| {
+ let mut timestamp_tx = Some(timestamp_tx);
let _ = ready.send(Ok(()));
+
while let Ok(frame) = source.1.recv() {
- screen_encoder.queue_video_frame(frame);
+ if let Some(timestamp_tx) = timestamp_tx.take() {
+ timestamp_tx.send(frame.1).unwrap();
+ }
+ screen_encoder.queue_video_frame(frame.0);
}
screen_encoder.finish();
});
- Ok(builder)
+ Ok((builder, timestamp_rx))
}
async fn make_instant_mode_pipeline(
mut builder: CapturePipelineBuilder,
source: (
ScreenCaptureSource<Self>,
- flume::Receiver<Self::VideoFormat>,
+ flume::Receiver<(Self::VideoFormat, f64)>,
),
audio: Option<&AudioInputFeed>,
- system_audio: Option<(Receiver<ffmpeg::frame::Audio>, AudioInfo)>,
+ system_audio: Option<(Receiver<(ffmpeg::frame::Audio, f64)>, AudioInfo)>,
output_path: PathBuf,
) -> Result<CapturePipelineBuilder, MediaError>
where
@@ -235,7 +259,7 @@ impl MakeCapturePipeline for AVFrameCapture {
builder.spawn_task("screen_encoder", move |ready| {
let _ = ready.send(Ok(()));
- while let Ok(frame) = source.1.recv() {
+ while let Ok((frame, unix_time)) = source.1.recv() {
if let Ok(mut mp4) = mp4.lock() {
mp4.queue_video_frame(frame);
}
@@ -251,7 +275,7 @@ impl MakeCapturePipeline for AVFrameCapture {
type ScreenCaptureReturn<T> = (
ScreenCaptureSource<T>,
- Receiver<<T as ScreenCaptureFormat>::VideoFormat>,
+ Receiver<(<T as ScreenCaptureFormat>::VideoFormat, f64)>,
);
#[cfg(target_os = "macos")]
@@ -265,7 +289,7 @@ pub fn create_screen_capture(
show_camera: bool,
force_show_cursor: bool,
max_fps: u32,
- audio_tx: Option<Sender<ffmpeg::frame::Audio>>,
+ audio_tx: Option<Sender<(ffmpeg::frame::Audio, f64)>>,
) -> Result<ScreenCaptureReturn<ScreenCaptureMethod>, RecordingError> {
let (video_tx, video_rx) = flume::bounded(16);
diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rs
index 886b77908..f2841d810 100644
--- a/crates/recording/src/instant_recording.rs
+++ b/crates/recording/src/instant_recording.rs
@@ -108,10 +108,10 @@ async fn create_pipeline<TCaptureFormat: MakeCapturePipeline>(
output_path: PathBuf,
screen_source: (
ScreenCaptureSource<TCaptureFormat>,
- flume::Receiver<TCaptureFormat::VideoFormat>,
+ flume::Receiver<(TCaptureFormat::VideoFormat, f64)>,
),
audio_input_feed: Option<&AudioInputFeed>,
- system_audio: Option<Receiver<ffmpeg::frame::Audio>>,
+ system_audio: Option<Receiver<(ffmpeg::frame::Audio, f64)>>,
) -> Result<(InstantRecordingPipeline, oneshot::Receiver<()>), MediaError> {
let clock = RealTimeClock::<()>::new();
let pipeline_builder = Pipeline::builder(clock);
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index f6a52464c..05a1a5e04 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -19,7 +19,9 @@ use cap_media::{
};
use cap_project::{CursorEvents, StudioRecordingMeta};
use cap_utils::spawn_actor;
+use ffmpeg::ffi::AV_TIME_BASE_Q;
use flume::Receiver;
+use futures::{future::OptionFuture, StreamExt};
use relative_path::RelativePathBuf;
use tokio::sync::{oneshot, Mutex};
use tracing::{debug, info, trace, Instrument};
@@ -65,15 +67,24 @@ pub struct StudioRecordingSegment {
pipeline: StudioRecordingPipeline,
}
+pub struct PipelineOutput {
+ pub path: PathBuf,
+ pub first_timestamp_rx: flume::Receiver<f64>,
+}
+
+pub struct ScreenPipelineOutput {
+ pub inner: PipelineOutput,
+ pub bounds: Bounds,
+ pub video_info: VideoInfo,
+}
+
struct StudioRecordingPipeline {
pub inner: Pipeline<RealTimeClock<()>>,
- pub display_output_path: PathBuf,
- pub audio_output_path: Option<PathBuf>,
+ pub screen: ScreenPipelineOutput,
+ pub microphone: Option<PipelineOutput>,
pub camera: Option<CameraPipelineInfo>,
pub cursor: Option<CursorPipeline>,
- pub system_audio_path: Option<PathBuf>,
- pub screen_bounds: Bounds,
- pub screen_video_info: VideoInfo,
+ pub system_audio: Option<PipelineOutput>,
}
struct CursorPipeline {
@@ -164,11 +175,11 @@ pub async fn spawn_studio_recording_actor(
trace!("spawning recording actor");
- let bounds = pipeline.screen_bounds;
+ let bounds = pipeline.screen.bounds;
spawn_actor({
let options = options.clone();
- let fps = pipeline.screen_video_info.fps();
+ let fps = pipeline.screen.video_info.fps();
async move {
let mut actor = StudioRecordingActor {
id,
@@ -385,32 +396,51 @@ async fn stop_recording(
.segments
.iter()
.map(|s| MultipleSegment {
- display: Display {
+ display: VideoMeta {
path: RelativePathBuf::from_path(
s.pipeline
- .display_output_path
+ .screen
+ .inner
+ .path
.strip_prefix(&actor.recording_dir)
.unwrap(),
)
.unwrap(),
fps: actor.fps,
+ start_time: None,
+ // Some(
+ // s.pipeline
+ // .screen
+ // .inner
+ // .first_timestamp_rx
+ // .try_recv()
+ // .unwrap(),
+ // ),
},
- camera: s.pipeline.camera.as_ref().map(|camera| CameraMeta {
+ camera: s.pipeline.camera.as_ref().map(|camera| VideoMeta {
path: RelativePathBuf::from_path(
camera
- .output_path
+ .inner
+ .path
.strip_prefix(&actor.recording_dir)
.unwrap()
.to_owned(),
)
.unwrap(),
fps: camera.fps,
+ start_time: None,
+ // Some(camera.inner.first_timestamp_rx.try_recv().unwrap()),
}),
- audio: s.pipeline.audio_output_path.as_ref().map(|path| AudioMeta {
+ audio: s.pipeline.microphone.as_ref().map(|mic| AudioMeta {
path: RelativePathBuf::from_path(
- path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),
+ mic.path
+ .strip_prefix(&actor.recording_dir)
+ .unwrap()
+ .to_owned(),
)
.unwrap(),
+ start_time: None,
+ // Some(mic.first_timestamp_rx.try_recv().unwrap()),
}),
cursor: s.pipeline.cursor.as_ref().map(|cursor| {
RelativePathBuf::from_path(
@@ -422,11 +452,17 @@ async fn stop_recording(
)
.unwrap()
}),
- system_audio: s.pipeline.system_audio_path.as_ref().map(|path| AudioMeta {
+ system_audio: s.pipeline.system_audio.as_ref().map(|audio| AudioMeta {
path: RelativePathBuf::from_path(
- path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),
+ audio
+ .path
+ .strip_prefix(&actor.recording_dir)
+ .unwrap()
+ .to_owned(),
)
.unwrap(),
+ start_time: None,
+ // Some(audio.first_timestamp_rx.try_recv().unwrap()),
}),
})
.collect()
@@ -496,27 +532,41 @@ async fn create_segment_pipeline(
let clock = RealTimeClock::<()>::new();
let mut pipeline_builder = Pipeline::builder(clock);
- let display_output_path = dir.join("display.mp4");
+ let screen_output_path = dir.join("display.mp4");
trace!("preparing segment pipeline {index}");
- let screen_bounds = screen_source.get_bounds().clone();
- let screen_video_info = screen_source.info();
- pipeline_builder = ScreenCaptureMethod::make_studio_mode_pipeline(
- pipeline_builder,
- (screen_source, screen_rx),
- display_output_path.clone(),
- )?;
-
- 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) = mic_feed {
+ let screen = {
+ let bounds = screen_source.get_bounds().clone();
+ let video_info = screen_source.info();
+
+ let (pipeline_builder_, screen_timestamp_rx) =
+ ScreenCaptureMethod::make_studio_mode_pipeline(
+ pipeline_builder,
+ (screen_source, screen_rx),
+ screen_output_path.clone(),
+ )?;
+ pipeline_builder = pipeline_builder_;
+
+ info!(
+ r#"screen pipeline prepared, will output to "{}""#,
+ screen_output_path
+ .strip_prefix(&segments_dir)
+ .unwrap()
+ .display()
+ );
+
+ ScreenPipelineOutput {
+ inner: PipelineOutput {
+ path: screen_output_path,
+ first_timestamp_rx: screen_timestamp_rx,
+ },
+ bounds,
+ video_info,
+ }
+ };
+
+ let microphone = if let Some(mic_source) = mic_feed {
let (tx, rx) = flume::bounded(8);
let mic_source = AudioInputSource::init(mic_source, tx);
@@ -531,11 +581,20 @@ async fn create_segment_pipeline(
pipeline_builder.spawn_source("microphone_capture", mic_source);
+ let (timestamp_tx, timestamp_rx) = flume::bounded(1);
+
pipeline_builder.spawn_task("microphone_encoder", move |ready| {
+ let mut timestamp_tx = Some(timestamp_tx);
let _ = ready.send(Ok(()));
while let Ok(frame) = rx.recv() {
- mic_encoder.queue_frame(frame);
+ if let Some(timestamp_tx) = timestamp_tx.take() {
+ // timestamp_tx
+ // .send(frame.timestamp().unwrap_or(0) as f64 / AV_TIME_BASE_Q.den as f64)
+ // .unwrap();
+ }
+
+ mic_encoder.queue_frame(frame.0);
}
mic_encoder.finish();
});
@@ -545,12 +604,15 @@ async fn create_segment_pipeline(
output_path.strip_prefix(&segments_dir).unwrap().display()
);
- Some(output_path)
+ Some(PipelineOutput {
+ path: output_path,
+ first_timestamp_rx: timestamp_rx,
+ })
} else {
None
};
- let system_audio_path = if let Some((config, channel)) =
+ let system_audio = if let Some((config, channel)) =
Some(ScreenCaptureMethod::audio_info()).zip(system_audio.1.clone())
{
let output_path = dir.join("system_audio.ogg");
@@ -560,15 +622,26 @@ async fn create_segment_pipeline(
OpusEncoder::factory("system_audio", config),
)?;
+ let (timestamp_tx, timestamp_rx) = flume::bounded(1);
+
pipeline_builder.spawn_task("system_audio_encoder", move |ready| {
+ let mut timestamp_tx = Some(timestamp_tx);
let _ = ready.send(Ok(()));
+
while let Ok(frame) = channel.recv() {
- system_audio_encoder.queue_frame(frame);
+ if let Some(timestamp_tx) = timestamp_tx.take() {
+ timestamp_tx.send(frame.1).unwrap();
+ }
+
+ system_audio_encoder.queue_frame(frame.0);
}
system_audio_encoder.finish();
});
- Some(output_path)
+ Some(PipelineOutput {
+ path: output_path,
+ first_timestamp_rx: timestamp_rx,
+ })
} else {
None
};
@@ -589,9 +662,19 @@ async fn create_segment_pipeline(
pipeline_builder.spawn_source("camera_capture", camera_source);
+ let (timestamp_tx, timestamp_rx) = flume::bounded(1);
+
pipeline_builder.spawn_task("camera_encoder", move |ready| {
+ let mut timestamp_tx = Some(timestamp_tx);
let _ = ready.send(Ok(()));
+
while let Ok(frame) = rx.recv() {
+ if let Some(timestamp_tx) = timestamp_tx.take() {
+ timestamp_tx
+ .send(frame.timestamp().unwrap_or(0) as f64 / AV_TIME_BASE_Q.den as f64)
+ .unwrap();
+ }
+
camera_encoder.queue_video_frame(frame);
}
camera_encoder.finish();
@@ -603,7 +686,10 @@ async fn create_segment_pipeline(
);
Some(CameraPipelineInfo {
- output_path,
+ inner: PipelineOutput {
+ path: output_path,
+ first_timestamp_rx: timestamp_rx,
+ },
fps: (camera_config.frame_rate.0 / camera_config.frame_rate.1) as u32,
})
} else {
@@ -614,7 +700,7 @@ async fn create_segment_pipeline(
let cursor = FLAGS.record_mouse_state.then(|| {
let cursor = spawn_cursor_recorder(
- screen_bounds.clone(),
+ screen.bounds.clone(),
cursors_dir.clone(),
prev_cursors,
next_cursors_id,
@@ -633,20 +719,18 @@ async fn create_segment_pipeline(
Ok((
StudioRecordingPipeline {
inner: pipeline,
- display_output_path,
- audio_output_path,
+ screen,
+ microphone,
camera,
cursor,
- system_audio_path,
- screen_bounds,
- screen_video_info,
+ system_audio,
},
pipeline_done_rx,
))
}
struct CameraPipelineInfo {
- output_path: PathBuf,
+ inner: PipelineOutput,
fps: u32,
}
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index d922d2c4c..88d0ad437 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -22,6 +22,7 @@ thiserror.workspace = true
wgpu.workspace = true
bezier_easing = "0.1.1"
reactive_graph = "0.1.5"
+tracing = "0.1.41"
[target.'cfg(target_os = "macos")'.dependencies]
cidre.workspace = true
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8e7b5b406..5f508f30f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -130,6 +130,9 @@ importers:
'@tauri-apps/plugin-notification':
specifier: 2.0.0
version: 2.0.0
+ '@tauri-apps/plugin-opener':
+ specifier: ^2.2.6
+ version: 2.2.6
'@tauri-apps/plugin-os':
specifier: 2.0.0
version: 2.0.0
@@ -4655,10 +4658,10 @@ packages:
react-dom:
optional: true
- '@storybook/[email protected]':
- resolution: {integrity: sha512-TxCLKB+nHkoooKzcJN8QKM2D8l9A8t5/qPQkStkadP5xdkoMC9CHYuq0Anu55mtbzZQnuDtS09lT3laGqswRuw==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-X6cWPtBTaagi0+pIFZtJe8XjiuwjbfFks09PmSqZJMr1V/0jB/Odifa/XnKqyBHuaudnbClI1kqieBHfu4pu+g==}
peerDependencies:
- storybook: ^9.0.0-alpha.4
+ storybook: ^9.0.0-alpha.6
vite: ^4.0.0 || ^5.0.0 || ^6.0.0
'@storybook/[email protected]':
@@ -4669,10 +4672,10 @@ packages:
peerDependencies:
storybook: ^8.3.3
- '@storybook/[email protected]':
- resolution: {integrity: sha512-Zq65uk267XRMr/DeAoOj1Yom6tuMPAOJo+GRw6qglX3NPxjc5eheGkFbT74P4CGXxYX9D5jDe9hY4CGBLNkACw==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-7PjatRFh5dyYlNdwRWcauiitw71MhqXoWfj8/wU0CGWCTJr+Cn2ZYA9lgjX2GTKU3ctJDTX7gX45NpnZGXIcqw==}
peerDependencies:
- storybook: ^9.0.0-alpha.4
+ storybook: ^9.0.0-alpha.6
'@storybook/[email protected]':
resolution: {integrity: sha512-dHYFQH3mA+EtnCkHXzicbLgsvzYjcDJ1JWsogbItZogkPHgSJM/Wr71uMkcvw8v9mmCyP4NpXJuu6bPoVsOnzg==}
@@ -4945,6 +4948,9 @@ packages:
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-6qEDYJS7mgXZWLXA0EFL+DVCJh8sJlzSoyw6B50pxhLPVFjc5Vr5DVzl5W3mUHaYhod5wsC984eQnlCCGqxYDA==}
+ '@tauri-apps/[email protected]':
+ resolution: {integrity: sha512-bSdkuP71ZQRepPOn8BOEdBKYJQvl6+jb160QtJX/i2H9BF6ZySY/kYljh76N2Ne5fJMQRge7rlKoStYQY5Jq1w==}
+
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-M7hG/nNyQYTJxVG/UhTKhp9mpXriwWzrs9mqDreB8mIgqA3ek5nHLdwRZJWhkKjZrnDT4v9CpA9BhYeplTlAiA==}
@@ -15942,9 +15948,9 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
dependencies:
- '@storybook/csf-plugin': 9.0.0-alpha.4([email protected])
+ '@storybook/csf-plugin': 9.0.0-alpha.6([email protected])
browser-assert: 1.2.1
storybook: 8.3.3
ts-dedent: 2.2.0
@@ -15975,7 +15981,7 @@ snapshots:
storybook: 8.3.3
unplugin: 1.16.1
dependencies:
storybook: 8.3.3
unplugin: 1.16.1
@@ -16213,6 +16219,10 @@ snapshots:
dependencies:
'@tauri-apps/api': 2.1.1
+ '@tauri-apps/[email protected]':
+ dependencies:
+ '@tauri-apps/api': 2.1.1
+
'@tauri-apps/[email protected]':
dependencies:
'@tauri-apps/api': 2.1.1
@@ -18819,7 +18829,7 @@ snapshots:
'@typescript-eslint/parser': 5.62.0([email protected])([email protected])
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
+ eslint-import-resolver-typescript: 3.6.3(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])
transitivePeerDependencies:
- supports-color
@@ -23767,7 +23777,7 @@ snapshots:
dependencies:
- '@storybook/builder-vite': 9.0.0-alpha.4([email protected])([email protected](@types/[email protected])([email protected]))
+ '@storybook/builder-vite': 9.0.0-alpha.6([email protected])([email protected](@types/[email protected])([email protected]))
transitivePeerDependencies:
- storybook
- vite