Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

wip: Custom record options (60fps/4k resolution)

Richie McIlroyaf701f1442d4
diff --git a/Cargo.lock b/Cargo.lock
index abc0a2233..1bbf7d352 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -830,9 +830,11 @@ dependencies = [
"cap-project",
"cap-rendering",
"cap-utils",
+ "ffmpeg-next",
"futures",
"image 0.25.5",
"mp4",
+ "tauri",
"tempfile",
"thiserror 1.0.63",
"tokio",
@@ -907,6 +909,8 @@ dependencies = [
"serde",
"serde_json",
"specta",
+ "tauri",
+ "tauri-plugin-store",
]
[[package]]
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index fc022ef44..75d4d8c33 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -1,6 +1,6 @@
use crate::{
- get_video_metadata, upsert_editor_instance, windows::ShowCapWindow, RenderProgress,
- VideoRecordingMetadata, VideoType,
+ general_settings::GeneralSettingsStore, get_video_metadata, upsert_editor_instance,
+ windows::ShowCapWindow, RenderProgress, VideoRecordingMetadata, VideoType,
};
use cap_project::ProjectConfiguration;
use std::path::PathBuf;
@@ -21,8 +21,14 @@ pub async fn export_video(
.await
.unwrap();
- // 30 FPS (calculated for output video)
- let total_frames = (duration * 30.0).round() as u32;
+ // Get FPS from general settings
+ let fps = GeneralSettingsStore::get(&app)?
+ .and_then(|s| s.recording_config)
+ .unwrap_or_default()
+ .fps;
+
+ // Use configured FPS for output video
+ let total_frames = (duration * fps as f64).round() as u32;
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
@@ -38,6 +44,7 @@ pub async fn export_video(
.ok();
let exporter = cap_export::Exporter::new(
+ &app,
project,
output_path.clone(),
move |frame_index| {
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index 88c11db11..4f7d91db5 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -1,3 +1,4 @@
+use cap_project::Resolution;
use serde::{Deserialize, Serialize};
use serde_json::json;
use specta::Type;
@@ -25,6 +26,8 @@ pub struct GeneralSettingsStore {
pub has_completed_startup: bool,
#[serde(default)]
pub theme: AppTheme,
+ #[serde(default)]
+ pub recording_config: Option<RecordingConfig>,
}
#[derive(Default, Debug, Copy, Clone, Serialize, Deserialize, Type)]
@@ -36,6 +39,25 @@ pub enum AppTheme {
Dark,
}
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct RecordingConfig {
+ pub fps: u32,
+ pub resolution: Resolution,
+}
+
+impl Default for RecordingConfig {
+ fn default() -> Self {
+ Self {
+ fps: 30,
+ resolution: Resolution {
+ width: 1920,
+ height: 1080,
+ },
+ }
+ }
+}
+
fn true_b() -> bool {
true
}
@@ -78,3 +100,20 @@ pub fn init(app: &AppHandle) {
app.manage(GeneralSettingsState::new(store));
println!("GeneralSettingsState managed");
}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn get_recording_config(app: AppHandle) -> Result<RecordingConfig, String> {
+ let settings = GeneralSettingsStore::get(&app)?;
+ Ok(settings
+ .and_then(|s| s.recording_config)
+ .unwrap_or_default())
+}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn set_recording_config(app: AppHandle, config: RecordingConfig) -> Result<(), String> {
+ GeneralSettingsStore::update(&app, |settings| {
+ settings.recording_config = Some(config);
+ })
+}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index c2a8afae5..089ca3618 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -25,12 +25,12 @@ 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::{Content, ProjectConfiguration, RecordingMeta, SharingMeta};
+use cap_project::{Content, ProjectConfiguration, RecordingMeta, Resolution, SharingMeta};
use cap_recording::RecordingOptions;
use cap_rendering::ProjectRecordings;
use clipboard_rs::common::RustImage;
use clipboard_rs::{Clipboard, ClipboardContext};
-use general_settings::GeneralSettingsStore;
+use general_settings::{GeneralSettingsStore, RecordingConfig};
use mp4::Mp4Reader;
// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use notifications::NotificationType;
@@ -376,9 +376,20 @@ type MutableState<'a, T> = State<'a, Arc<RwLock<T>>>;
#[tauri::command]
#[specta::specta]
-async fn get_recording_options(state: MutableState<'_, App>) -> Result<RecordingOptions, ()> {
+async fn get_recording_options(
+ app: AppHandle,
+ state: MutableState<'_, App>,
+) -> Result<RecordingOptions, ()> {
let mut state = state.write().await;
+ // Load settings from disk if they exist
+ if let Ok(Some(settings)) = GeneralSettingsStore::get(&app) {
+ if let Some(config) = settings.recording_config {
+ state.start_recording_options.fps = config.fps;
+ state.start_recording_options.output_resolution = Some(config.resolution);
+ }
+ }
+
// If there's a saved audio input but no feed, initialize it
if let Some(audio_input_name) = state.start_recording_options.audio_input_name() {
if state.audio_input_feed.is_none() {
@@ -400,15 +411,28 @@ async fn get_recording_options(state: MutableState<'_, App>) -> Result<Recording
#[tauri::command]
#[specta::specta]
async fn set_recording_options(
+ app: AppHandle,
state: MutableState<'_, App>,
options: RecordingOptions,
) -> Result<(), String> {
+ // Update in-memory state
state
.write()
.await
- .set_start_recording_options(options)
+ .set_start_recording_options(options.clone())
.await?;
+ // Update persistent settings
+ GeneralSettingsStore::update(&app, |settings| {
+ settings.recording_config = Some(RecordingConfig {
+ fps: options.fps,
+ resolution: options.output_resolution.unwrap_or_else(|| Resolution {
+ width: 1920,
+ height: 1080,
+ }),
+ });
+ })?;
+
Ok(())
}
@@ -1977,11 +2001,13 @@ pub async fn run() {
audio_input_feed: None,
start_recording_options: RecordingOptions {
capture_target: ScreenCaptureTarget::Screen(CaptureScreen {
- id: 1,
- name: "Default".to_string(),
+ id: 0,
+ name: String::new(),
}),
camera_label: None,
audio_input_name: None,
+ fps: 30,
+ output_resolution: None,
},
current_recording: None,
pre_created_video: None,
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index f0d957b00..8beccdbe0 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -48,6 +48,14 @@ pub fn list_cameras() -> Vec<String> {
pub async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
let mut state = state.write().await;
+ // Get the recording config
+ let config = GeneralSettingsStore::get(&app)?
+ .and_then(|s| s.recording_config)
+ .unwrap_or_default();
+
+ // Update the recording options with the configured FPS
+ state.start_recording_options.fps = config.fps;
+
let id = uuid::Uuid::new_v4().to_string();
let recording_dir = app
diff --git a/apps/desktop/src/routes/(window-chrome)/settings.tsx b/apps/desktop/src/routes/(window-chrome)/settings.tsx
index 20f381a10..eab865b19 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings.tsx
@@ -20,6 +20,7 @@ export default function Settings(props: RouteSectionProps) {
<For
each={[
{ href: "general", name: "General", icon: IconCapSettings },
+ { href: "config", name: "Config", icon: IconLucideVideo },
{ href: "hotkeys", name: "Shortcuts", icon: IconCapHotkeys },
{
href: "recordings",
@@ -31,7 +32,7 @@ export default function Settings(props: RouteSectionProps) {
name: "Previous Screenshots",
icon: IconLucideCamera,
},
- window.FLAGS.customS3 && {
+ {
href: "apps",
name: "Cap Apps",
icon: IconLucideLayoutGrid,
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/config.tsx b/apps/desktop/src/routes/(window-chrome)/settings/config.tsx
new file mode 100644
index 000000000..a11e566d5
--- /dev/null
+++ b/apps/desktop/src/routes/(window-chrome)/settings/config.tsx
@@ -0,0 +1,89 @@
+import { createQuery } from "@tanstack/solid-query";
+import { For, Show } from "solid-js";
+import { commands } from "~/utils/tauri";
+
+const RESOLUTION_OPTIONS = [
+ { label: "720p (1280x720)", value: "720p", width: 1280, height: 720 },
+ { label: "1080p (1920x1080)", value: "1080p", width: 1920, height: 1080 },
+ { label: "4K (3840x2160)", value: "4k", width: 3840, height: 2160 },
+] as const;
+
+const FPS_OPTIONS = [
+ { label: "30 FPS", value: 30 },
+ { label: "60 FPS", value: 60 },
+] as const;
+
+export default function Config() {
+ const config = createQuery(() => ({
+ queryKey: ["recording-config"],
+ queryFn: () => commands.getRecordingOptions(),
+ }));
+
+ const updateConfig = async (updates: {
+ fps?: number;
+ outputResolution?: { width: number; height: number };
+ }) => {
+ if (!config.data) return;
+
+ await commands.setRecordingOptions({
+ ...config.data,
+ ...updates,
+ });
+
+ config.refetch();
+ };
+
+ return (
+ <div class="flex flex-col w-full h-full divide-y divide-[--gray-200] pt-1 pb-12">
+ <div class="p-4">
+ <div class="mb-6">
+ <label class="text-sm font-medium mb-2 block">
+ Output Resolution
+ </label>
+ <select
+ class="w-full p-2 border rounded"
+ value={
+ RESOLUTION_OPTIONS.find(
+ (opt) =>
+ opt.width === config.data?.outputResolution?.width &&
+ opt.height === config.data?.outputResolution?.height
+ )?.value
+ }
+ onChange={(e) => {
+ const option = RESOLUTION_OPTIONS.find(
+ (opt) => opt.value === e.currentTarget.value
+ );
+ if (option) {
+ updateConfig({
+ outputResolution: {
+ width: option.width,
+ height: option.height,
+ },
+ });
+ }
+ }}
+ >
+ <For each={RESOLUTION_OPTIONS}>
+ {(option) => <option value={option.value}>{option.label}</option>}
+ </For>
+ </select>
+ </div>
+
+ <div class="mb-6">
+ <label class="text-sm font-medium mb-2 block">Frame Rate</label>
+ <select
+ class="w-full p-2 border rounded"
+ value={config.data?.fps}
+ onChange={(e) => {
+ updateConfig({ fps: Number(e.currentTarget.value) });
+ }}
+ >
+ <For each={FPS_OPTIONS}>
+ {(option) => <option value={option.value}>{option.label}</option>}
+ </For>
+ </select>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index 4cecad665..7f1446268 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -541,71 +541,78 @@ export function ConfigSidebar() {
</Field>
</KTabs.Content>
<KTabs.Content value="cursor" class="flex flex-col gap-6">
- <Field name="Cursor" icon={<IconCapCursor />}>
- <ComingSoonTooltip>
- <Subfield name="Hide cursor when not moving">
- <Toggle disabled />
- </Subfield>
- </ComingSoonTooltip>
- </Field>
- <Field name="Size" icon={<IconCapEnlarge />}>
- <ComingSoonTooltip>
- <Slider
- disabled
- value={[project.cursor.size]}
- onChange={(v) => setProject("cursor", "size", v[0])}
- minValue={20}
- maxValue={300}
- step={1}
- />
- </ComingSoonTooltip>
- </Field>
- {window.FLAGS.zoom && (
- <Field name="Animation Style" icon={<IconLucideRabbit />}>
- <RadioGroup
- defaultValue="regular"
- value={project.cursor.animationStyle}
- onChange={(value) => {
- console.log("Changing animation style to:", value);
- setProject(
- "cursor",
- "animationStyle",
- value as CursorAnimationStyle
- );
- }}
- class="flex flex-col gap-2"
- >
- {(
- Object.entries(CURSOR_ANIMATION_STYLES) as [
- CursorAnimationStyle,
- string
- ][]
- ).map(([value, label]) => (
- <RadioGroup.Item value={value} class="flex items-center">
- <RadioGroup.ItemInput class="peer sr-only" />
- <RadioGroup.ItemControl
- class={cx(
- "w-4 h-4 rounded-full border border-gray-300 mr-2",
- "relative after:absolute after:inset-0 after:m-auto after:block after:w-2 after:h-2 after:rounded-full",
- "after:transition-colors after:duration-200",
- "peer-checked:border-blue-500 peer-checked:after:bg-blue-400",
- "peer-focus-visible:ring-2 peer-focus-visible:ring-blue-400/50",
- "peer-disabled:opacity-50"
- )}
- />
- <span
- class={cx(
- "text-gray-500",
- "peer-checked:text-gray-900",
- "peer-disabled:opacity-50"
- )}
- >
- {label}
- </span>
- </RadioGroup.Item>
- ))}
- </RadioGroup>
- </Field>
+ {window.FLAGS.recordMouse ? (
+ <>
+ <Field name="Cursor" icon={<IconCapCursor />}>
+ <Subfield name="Hide cursor when not moving">
+ <Toggle
+ checked={project.cursor.hideWhenIdle}
+ onChange={(v) => setProject("cursor", "hideWhenIdle", v)}
+ />
+ </Subfield>
+ </Field>
+ <Field name="Size" icon={<IconCapEnlarge />}>
+ <Slider
+ value={[project.cursor.size]}
+ onChange={(v) => setProject("cursor", "size", v[0])}
+ minValue={20}
+ maxValue={300}
+ step={1}
+ />
+ </Field>
+ {window.FLAGS.zoom && (
+ <Field name="Animation Style" icon={<IconLucideRabbit />}>
+ <RadioGroup
+ defaultValue="regular"
+ value={project.cursor.animationStyle}
+ onChange={(value) => {
+ console.log("Changing animation style to:", value);
+ setProject(
+ "cursor",
+ "animationStyle",
+ value as CursorAnimationStyle
+ );
+ }}
+ class="flex flex-col gap-2"
+ >
+ {(
+ Object.entries(CURSOR_ANIMATION_STYLES) as [
+ CursorAnimationStyle,
+ string
+ ][]
+ ).map(([value, label]) => (
+ <RadioGroup.Item value={value} class="flex items-center">
+ <RadioGroup.ItemInput class="peer sr-only" />
+ <RadioGroup.ItemControl
+ class={cx(
+ "w-4 h-4 rounded-full border border-gray-300 mr-2",
+ "relative after:absolute after:inset-0 after:m-auto after:block after:w-2 after:h-2 after:rounded-full",
+ "after:transition-colors after:duration-200",
+ "peer-checked:border-blue-500 peer-checked:after:bg-blue-400",
+ "peer-focus-visible:ring-2 peer-focus-visible:ring-blue-400/50",
+ "peer-disabled:opacity-50"
+ )}
+ />
+ <span
+ class={cx(
+ "text-gray-500",
+ "peer-checked:text-gray-900",
+ "peer-disabled:opacity-50"
+ )}
+ >
+ {label}
+ </span>
+ </RadioGroup.Item>
+ ))}
+ </RadioGroup>
+ </Field>
+ )}
+ </>
+ ) : (
+ <div class="flex flex-col items-center justify-center gap-2 text-gray-400 p-4">
+ <IconCapCursor class="size-6" />
+ <span>Cursor settings coming soon</span>
+ </div>
)}
</KTabs.Content>
<KTabs.Content value="hotkeys">
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index a8b14ca3f..6401791b9 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -238,7 +238,7 @@ export type CursorType = "pointer" | "circle"
export type Display = { path: string }
export type EditorStateChanged = { playhead_position: number }
export type Flags = { recordMouse: boolean; split: boolean; pauseResume: boolean; zoom: boolean }
-export type GeneralSettingsStore = { uploadIndividualFiles?: boolean; openEditorAfterRecording?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme }
+export type GeneralSettingsStore = { uploadIndividualFiles?: boolean; openEditorAfterRecording?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; recordingConfig?: RecordingConfig | null }
export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }
export type HotkeyAction = "startRecording" | "stopRecording" | "restartRecording" | "takeScreenshot"
export type HotkeysConfiguration = { show: boolean }
@@ -256,10 +256,11 @@ export type Plan = { upgraded: boolean; last_checked: number }
export type PreCreatedVideo = { id: string; link: string; config: S3UploadMeta }
export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null; motionBlur: number | null }
export type ProjectRecordings = { segments: SegmentRecordings[] }
+export type RecordingConfig = { fps: number; resolution: Resolution }
export type RecordingInfo = { captureTarget: ScreenCaptureTarget }
export type RecordingMeta = ({ segment: SingleSegment } | { inner: MultipleSegments }) & { pretty_name: string; sharing?: SharingMeta | null }
export type RecordingMetaChanged = { id: string }
-export type RecordingOptions = { captureTarget: ScreenCaptureTarget; cameraLabel: string | null; audioInputName: string | null }
+export type RecordingOptions = { captureTarget: ScreenCaptureTarget; cameraLabel: string | null; audioInputName: string | null; fps: number; outputResolution: Resolution | null }
export type RecordingOptionsChanged = null
export type RecordingStarted = null
export type RecordingStopped = { path: string }
@@ -270,6 +271,7 @@ export type RequestOpenSettings = { page: string }
export type RequestRestartRecording = null
export type RequestStartRecording = null
export type RequestStopRecording = null
+export type Resolution = { width: number; height: number }
export type S3UploadMeta = { id: string; user_id: string; aws_region?: string; aws_bucket?: string }
export type ScreenCaptureTarget = ({ variant: "window" } & CaptureWindow) | ({ variant: "screen" } & CaptureScreen)
export type SegmentRecordings = { display: Video; camera: Video | null; audio: Audio | null }
diff --git a/apps/storybook/vite.config.ts.timestamp-1734982723347-15965ce66b06c.mjs b/apps/storybook/vite.config.ts.timestamp-1734982723347-15965ce66b06c.mjs
new file mode 100644
index 000000000..2cc8ae255
--- /dev/null
+++ b/apps/storybook/vite.config.ts.timestamp-1734982723347-15965ce66b06c.mjs
@@ -0,0 +1,11 @@
+// vite.config.ts
+import { defineConfig } from "file:///Users/macbookuser/Documents/GitHub/cap/node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/vite/dist/node/index.js";
+import solid from "file:///Users/macbookuser/Documents/GitHub/cap/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected]_@[email protected][email protected]_/node_modules/vite-plugin-solid/dist/esm/index.mjs";
+import capUIPlugin from "file:///Users/macbookuser/Documents/GitHub/cap/packages/ui-solid/vite.js";
+var vite_config_default = defineConfig({
+ plugins: [solid(), capUIPlugin]
+});
+export {
+ vite_config_default as default
+};
+//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvbWFjYm9va3VzZXIvRG9jdW1lbnRzL0dpdEh1Yi9jYXAvYXBwcy9zdG9yeWJvb2tcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfZmlsZW5hbWUgPSBcIi9Vc2Vycy9tYWNib29rdXNlci9Eb2N1bWVudHMvR2l0SHViL2NhcC9hcHBzL3N0b3J5Ym9vay92aXRlLmNvbmZpZy50c1wiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9pbXBvcnRfbWV0YV91cmwgPSBcImZpbGU6Ly8vVXNlcnMvbWFjYm9va3VzZXIvRG9jdW1lbnRzL0dpdEh1Yi9jYXAvYXBwcy9zdG9yeWJvb2svdml0ZS5jb25maWcudHNcIjtpbXBvcnQgeyBkZWZpbmVDb25maWcgfSBmcm9tIFwidml0ZVwiO1xuaW1wb3J0IHNvbGlkIGZyb20gXCJ2aXRlLXBsdWdpbi1zb2xpZFwiO1xuaW1wb3J0IGNhcFVJUGx1Z2luIGZyb20gXCJAY2FwL3VpLXNvbGlkL3ZpdGVcIjtcblxuZXhwb3J0IGRlZmF1bHQgZGVmaW5lQ29uZmlnKHtcbiAgcGx1Z2luczogW3NvbGlkKCksIGNhcFVJUGx1Z2luXSxcbn0pO1xuIl0sCiAgIm1hcHBpbmdzIjogIjtBQUFvVixTQUFTLG9CQUFvQjtBQUNqWCxPQUFPLFdBQVc7QUFDbEIsT0FBTyxpQkFBaUI7QUFFeEIsSUFBTyxzQkFBUSxhQUFhO0FBQUEsRUFDMUIsU0FBUyxDQUFDLE1BQU0sR0FBRyxXQUFXO0FBQ2hDLENBQUM7IiwKICAibmFtZXMiOiBbXQp9Cg==
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index e45084ba8..7a3d97b48 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -1,12 +1,16 @@
use crate::editor;
use crate::playback::{self, PlaybackHandle};
+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_rendering::{
ProjectRecordings, ProjectUniforms, RecordingSegmentDecoders, RenderOptions,
RenderVideoConstants, SegmentVideoPaths,
};
+use ffmpeg::Rational;
use std::ops::Deref;
use std::sync::Mutex as StdMutex;
use std::time::Instant;
@@ -339,3 +343,16 @@ pub fn create_segments(meta: &RecordingMeta) -> Vec<Segment> {
}
}
}
+
+fn create_preview_config(recording_config: &RecordingConfig, meta: &RecordingMeta) -> VideoInfo {
+ let (width, height) = if recording_config.resolution.width > 1280 {
+ (1280, 720)
+ } else {
+ (
+ recording_config.resolution.width,
+ recording_config.resolution.height,
+ )
+ };
+
+ VideoInfo::from_raw(RawVideoFormat::Rgba, width, height, 30)
+}
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
index 1711b488f..d11afccf9 100644
--- a/crates/export/Cargo.toml
+++ b/crates/export/Cargo.toml
@@ -18,3 +18,5 @@ image = "0.25.2"
mp4 = "0.14.0"
thiserror.workspace = true
futures = "0.3.31"
+tauri = { workspace = true }
+ffmpeg = { workspace = true }
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 8f9247de4..758fcb0c6 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -5,14 +5,16 @@ use cap_media::{
feeds::{AudioData, AudioFrameBuffer},
MediaError,
};
-use cap_project::{ProjectConfiguration, RecordingMeta};
+use cap_project::{GeneralSettingsStore, ProjectConfiguration, RecordingMeta};
use cap_rendering::{
ProjectUniforms, RecordingSegmentDecoders, RenderSegment, RenderVideoConstants, RenderedFrame,
SegmentVideoPaths,
};
+use ffmpeg::Rational;
use futures::FutureExt;
use image::{ImageBuffer, Rgba};
use std::{path::PathBuf, sync::Arc};
+use tauri::AppHandle;
const FPS: u32 = 30;
@@ -51,6 +53,7 @@ where
TOnProgress: Fn(u32) + Send + 'static,
{
pub fn new(
+ app: &AppHandle,
project: ProjectConfiguration,
output_path: PathBuf,
on_progress: TOnProgress,
@@ -59,6 +62,24 @@ where
render_constants: Arc<RenderVideoConstants>,
segments: &[Segment],
) -> Result<Self, ExportError> {
+ let recording_config = GeneralSettingsStore::get(app)
+ .map_err(|e| ExportError::FFmpeg(e))?
+ .and_then(|s| Some(s.recording_config))
+ .flatten()
+ .unwrap_or_default();
+
+ let display_info = match &meta.content {
+ cap_project::Content::SingleSegment { segment } => &segment.display,
+ cap_project::Content::MultipleSegments { inner } => &inner.segments[0].display,
+ };
+
+ let output_config = VideoInfo::from_raw(
+ RawVideoFormat::Rgba,
+ recording_config.resolution.width,
+ recording_config.resolution.height,
+ recording_config.fps,
+ );
+
let output_folder = output_path.parent().unwrap();
std::fs::create_dir_all(output_folder)?;
diff --git a/crates/flags/src/lib.rs b/crates/flags/src/lib.rs
index 1d3980908..da74f9a80 100644
--- a/crates/flags/src/lib.rs
+++ b/crates/flags/src/lib.rs
@@ -8,7 +8,7 @@ pub struct Flags {
}
pub const FLAGS: Flags = Flags {
- record_mouse: false, // cfg!(debug_assertions),
+ record_mouse: cfg!(debug_assertions),
split: false, // cfg!(debug_assertions),
pause_resume: false, // cfg!(debug_assertions),
zoom: cfg!(debug_assertions),
diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rs
index b479e9c9c..979a0f162 100644
--- a/crates/media/src/feeds/camera.rs
+++ b/crates/media/src/feeds/camera.rs
@@ -151,7 +151,7 @@ fn create_camera(info: &CameraInfo) -> Result<Camera, MediaError> {
},
frame_rate: 30,
},
- &[FrameFormat::NV12],
+ &[FrameFormat::NV12, FrameFormat::MJPEG, FrameFormat::YUYV],
);
let index = info.index().clone();
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index d3d5f8ab2..d29cb84ed 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -1,7 +1,9 @@
use cap_flags::FLAGS;
use flume::Sender;
use scap::{
- capturer::{get_output_frame_size, Area, Capturer, Options, Point, Resolution, Size},
+ capturer::{
+ get_output_frame_size, Area, Capturer, Options, Point, Resolution as ScapResolution, Size,
+ },
frame::{Frame, FrameType},
Target,
};
@@ -13,6 +15,7 @@ use crate::{
data::{FFVideo, RawVideoFormat, VideoInfo},
pipeline::{clock::*, control::Control, task::PipelineSourceTask},
platform::{self, Bounds, Window},
+ MediaError,
};
static EXCLUDED_WINDOWS: [&str; 4] = [
@@ -58,52 +61,62 @@ impl PartialEq<Target> for ScreenCaptureTarget {
}
}
-pub struct ScreenCaptureSource<T> {
+#[derive(Debug)]
+pub struct ScreenCaptureSource<TCaptureFormat> {
target: ScreenCaptureTarget,
+ output_resolution: Option<ScapResolution>,
+ output_type: Option<FrameType>,
fps: u32,
- resolution: Resolution,
video_info: VideoInfo,
- phantom: std::marker::PhantomData<T>,
+ _phantom: std::marker::PhantomData<TCaptureFormat>,
}
-impl<T> Clone for ScreenCaptureSource<T> {
+impl<TCaptureFormat> Clone for ScreenCaptureSource<TCaptureFormat> {
fn clone(&self) -> Self {
Self {
target: self.target.clone(),
+ output_resolution: self.output_resolution,
+ output_type: self.output_type,
fps: self.fps,
- resolution: self.resolution,
- video_info: self.video_info,
- phantom: Default::default(),
+ video_info: self.video_info.clone(),
+ _phantom: std::marker::PhantomData,
}
}
}
-unsafe impl<T> Send for ScreenCaptureSource<T> {}
-unsafe impl<T> Sync for ScreenCaptureSource<T> {}
-
-impl<T> ScreenCaptureSource<T> {
- pub const DEFAULT_FPS: u32 = 30;
-
+impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
pub fn init(
- capture_target: &ScreenCaptureTarget,
- fps: Option<u32>,
- resolution: Option<Resolution>,
+ target: &ScreenCaptureTarget,
+ output_resolution: Option<cap_project::Resolution>,
+ output_type: Option<FrameType>,
+ fps: u32,
) -> Self {
- let output_resolution = resolution.unwrap_or(Resolution::Captured);
- let fps = fps.unwrap_or(Self::DEFAULT_FPS);
-
let mut this = Self {
- target: capture_target.clone(),
+ target: target.clone(),
+ output_resolution: output_resolution.map(|r| {
+ // Choose the closest resolution based on height
+ if r.height <= 480 {
+ ScapResolution::_480p
+ } else if r.height <= 720 {
+ ScapResolution::_720p
+ } else if r.height <= 1080 {
+ ScapResolution::_1080p
+ } else if r.height <= 1440 {
+ ScapResolution::_1440p
+ } else if r.height <= 2160 {
+ ScapResolution::_2160p
+ } else {
+ ScapResolution::_4320p
+ }
+ }),
+ output_type,
fps,
- resolution: output_resolution,
video_info: VideoInfo::from_raw(RawVideoFormat::Bgra, 0, 0, fps),
- phantom: Default::default(),
+ _phantom: std::marker::PhantomData,
};
let options = this.create_options();
-
let [frame_width, frame_height] = get_output_frame_size(&options);
-
this.video_info = VideoInfo::from_raw(RawVideoFormat::Bgra, frame_width, frame_height, fps);
this
@@ -145,7 +158,7 @@ impl<T> ScreenCaptureSource<T> {
};
let target = match &self.target {
- ScreenCaptureTarget::Window(w) => None,
+ ScreenCaptureTarget::Window(_) => None,
ScreenCaptureTarget::Screen(capture_screen) => targets
.iter()
.find(|t| match t {
@@ -157,18 +170,13 @@ impl<T> ScreenCaptureSource<T> {
Options {
fps: self.fps,
- show_cursor: !FLAGS.record_mouse,
+ show_cursor: FLAGS.record_mouse,
show_highlight: true,
- excluded_targets: Some(excluded_targets),
- output_type: if cfg!(windows) {
- FrameType::BGRAFrame
- } else {
- FrameType::YUVFrame
- },
- output_resolution: self.resolution,
- crop_area,
target,
- ..Default::default()
+ crop_area,
+ output_type: self.output_type.unwrap_or(FrameType::YUVFrame),
+ output_resolution: self.output_resolution.unwrap_or(ScapResolution::Captured),
+ excluded_targets: Some(excluded_targets),
}
}
@@ -256,7 +264,17 @@ impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {
ScreenCaptureTarget::Window(window) => Some(window.id),
_ => None,
};
- let mut capturer = Capturer::new(dbg!(options));
+ let mut capturer = match Capturer::build(dbg!(options)) {
+ Ok(capturer) => capturer,
+ Err(e) => {
+ let error = format!("Failed to build capturer: {e}");
+ eprintln!("{}", error);
+ ready_signal
+ .send(Err(MediaError::Any("Failed to build capturer")))
+ .unwrap();
+ return;
+ }
+ };
let mut capturing = false;
ready_signal.send(Ok(())).unwrap();
@@ -389,7 +407,17 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
ScreenCaptureTarget::Window(window) => Some(window.id),
_ => None,
};
- let mut capturer = Capturer::new(dbg!(self.create_options()));
+ let mut capturer = match Capturer::build(dbg!(self.create_options())) {
+ Ok(capturer) => capturer,
+ Err(e) => {
+ let error = format!("Failed to build capturer: {e}");
+ eprintln!("{}", error);
+ ready_signal
+ .send(Err(MediaError::Any("Failed to build capturer")))
+ .unwrap();
+ return;
+ }
+ };
let mut capturing = false;
ready_signal.send(Ok(())).ok();
diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml
index 125233e42..1f1ec4627 100644
--- a/crates/project/Cargo.toml
+++ b/crates/project/Cargo.toml
@@ -5,6 +5,8 @@ edition = "2021"
[dependencies]
specta = { workspace = true, features = ["derive"] }
-serde = { version = "1.0.209", features = ["derive"] }
+serde = { version = "1", features = ["derive"] }
serde_json = "1.0.127"
either = "1.13.0"
+tauri = { workspace = true }
+tauri-plugin-store = "2.0.0-rc.4"
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
index b87168f0d..1438e19d3 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -5,3 +5,65 @@ mod meta;
pub use configuration::*;
pub use cursor::*;
pub use meta::*;
+
+use serde::{Deserialize, Serialize};
+use specta::Type;
+use tauri::AppHandle;
+use tauri_plugin_store::StoreExt;
+
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct RecordingConfig {
+ pub fps: u32,
+ pub resolution: Resolution,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+pub struct Resolution {
+ pub width: u32,
+ pub height: u32,
+}
+
+impl Default for RecordingConfig {
+ fn default() -> Self {
+ Self {
+ fps: 30,
+ resolution: Resolution {
+ width: 1920,
+ height: 1080,
+ },
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+pub struct GeneralSettingsStore {
+ #[serde(default)]
+ pub recording_config: Option<RecordingConfig>,
+}
+
+impl GeneralSettingsStore {
+ pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {
+ match app.get_store("store").map(|s| s.get("general_settings")) {
+ Some(Some(store)) => match serde_json::from_value(store) {
+ Ok(settings) => Ok(Some(settings)),
+ Err(_) => Ok(Some(GeneralSettingsStore::default())),
+ },
+ _ => Ok(None),
+ }
+ }
+
+ pub fn save(&self, app: &AppHandle) -> Result<(), String> {
+ let store = app.get_store("store").ok_or("Store not found")?;
+ store.set("general_settings", serde_json::json!(self));
+ store.save().map_err(|e| e.to_string())
+ }
+}
+
+impl Default for GeneralSettingsStore {
+ fn default() -> Self {
+ Self {
+ recording_config: Some(RecordingConfig::default()),
+ }
+ }
+}
diff --git a/crates/recording/src/actor.rs b/crates/recording/src/actor.rs
index f49bbf2dd..bfa4bc4a0 100644
--- a/crates/recording/src/actor.rs
+++ b/crates/recording/src/actor.rs
@@ -1,3 +1,9 @@
+use std::{
+ path::{Path, PathBuf},
+ sync::{atomic::AtomicBool, Arc},
+ time::{SystemTime, UNIX_EPOCH},
+};
+
use cap_flags::FLAGS;
use cap_media::{
encoders::{H264Encoder, MP3Encoder, Output},
@@ -7,262 +13,25 @@ use cap_media::{
sources::{AudioInputSource, CameraSource, ScreenCaptureSource, ScreenCaptureTarget},
MediaError,
};
-use cap_project::RecordingMeta;
+use cap_project::{CameraMeta, CursorEvents, RecordingMeta};
use either::Either;
-use std::{
- path::PathBuf,
- sync::{atomic::AtomicBool, Arc},
- time::{SystemTime, UNIX_EPOCH},
-};
use thiserror::Error;
use tokio::sync::{oneshot, Mutex};
use crate::{
- cursor::{spawn_cursor_recorder, CursorActor},
+ cursor::{spawn_cursor_recorder, CursorActor, Cursors},
RecordingOptions,
};
-pub enum ActorControlMessage {
- Stop(oneshot::Sender<Result<CompletedRecording, RecordingError>>),
-}
-
-pub struct Actor {
- id: String,
- recording_dir: PathBuf,
- options: RecordingOptions,
- pipeline: RecordingPipeline,
- start_time: f64,
- stop_signal: Arc<AtomicBool>,
- cursor: Option<CursorActor>,
-}
-
-pub struct ActorHandle {
- ctrl_tx: flume::Sender<ActorControlMessage>,
- pub options: RecordingOptions,
-}
-
-#[derive(Error, Debug)]
-pub enum ActorError {
- #[error("Actor has stopped")]
- ActorStopped,
-
- #[error("Failed to send to actor")]
- SendFailed(#[from] flume::SendError<ActorControlMessage>),
-}
-
-#[derive(Error, Debug)]
-pub enum RecordingError {
- #[error("Media/{0}")]
- Media(#[from] MediaError),
-
- #[error("Actor/{0}")]
- Actor(#[from] ActorError),
-
- #[error("Serde/{0}")]
- Serde(#[from] serde_json::Error),
-
- #[error("IO/{0}")]
- Io(#[from] std::io::Error),
-}
-
-macro_rules! send_message {
- ($ctrl_tx:expr, $variant:path) => {{
- let (tx, rx) = oneshot::channel();
- $ctrl_tx.send($variant(tx)).map_err(ActorError::from)?;
- rx.await.map_err(|_| ActorError::ActorStopped)?
- }};
-}
-
-impl ActorHandle {
- pub async fn stop(&self) -> Result<CompletedRecording, RecordingError> {
- send_message!(self.ctrl_tx, ActorControlMessage::Stop)
- }
-
- pub async fn pause(&self) -> Result<(), RecordingError> {
- Ok(())
- }
-
- pub async fn resume(&self) -> Result<(), RecordingError> {
- Ok(())
- }
-}
-
-pub async fn spawn_recording_actor(
- id: String,
- recording_dir: impl Into<PathBuf>,
- options: RecordingOptions,
- camera_feed: Option<Arc<Mutex<CameraFeed>>>,
- audio_input_feed: Option<AudioInputFeed>,
-) -> Result<ActorHandle, RecordingError> {
- let recording_dir = recording_dir.into();
-
- let content_dir = ensure_dir(recording_dir.join("content"))?;
- let cursors_dir = ensure_dir(content_dir.join("cursors"))?;
-
- let screen_source = create_screen_capture(&options);
-
- let pipeline = create_pipeline(
- &content_dir,
- screen_source.clone(),
- camera_feed.as_deref(),
- audio_input_feed.as_ref(),
- )
- .await?;
-
- let start_time = current_time_f64();
-
- let (ctrl_tx, ctrl_rx) = flume::bounded(1);
-
- let stop_signal = Arc::new(AtomicBool::new(false));
-
- // Initialize default values for cursor channels
- let cursor = FLAGS.record_mouse.then(|| {
- spawn_cursor_recorder(
- screen_source.get_bounds(),
- cursors_dir,
- Default::default(),
- 0,
- )
- });
-
- tokio::spawn({
- let options = options.clone();
- async move {
- let actor = Actor {
- recording_dir,
- options,
- pipeline,
- start_time,
- cursor,
- stop_signal,
- id,
- };
-
- loop {
- let Ok(ActorControlMessage::Stop(tx)) = ctrl_rx.recv_async().await else {
- return;
- };
-
- let resp = stop_recording(actor).await;
-
- tx.send(resp).ok();
- return;
- }
- }
- });
-
- Ok(ActorHandle { ctrl_tx, options })
+struct CursorPipeline {
+ pub output_path: PathBuf,
+ pub actor: CursorActor,
}
-pub struct CompletedRecording {
- pub id: String,
- pub recording_dir: PathBuf,
- pub display_source: ScreenCaptureTarget,
- pub meta: RecordingMeta,
- pub cursor_data: cap_project::CursorData,
- pub segments: Vec<f64>,
-}
-
-async fn stop_recording(mut actor: Actor) -> Result<CompletedRecording, RecordingError> {
- let segment = (actor.start_time, current_time_f64());
-
- use cap_project::*;
-
- let meta = RecordingMeta {
- project_path: actor.recording_dir.clone(),
- sharing: None,
- pretty_name: format!(
- "Cap {}",
- chrono::Local::now().format("%Y-%m-%d at %H.%M.%S")
- ),
- content: Content::SingleSegment {
- segment: SingleSegment {
- display: Display {
- path: actor
- .pipeline
- .display_output_path
- .strip_prefix(&actor.recording_dir)
- .unwrap()
- .to_owned(),
- },
- camera: actor
- .pipeline
- .camera_output_path
- .as_ref()
- .map(|path| CameraMeta {
- path: path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),
- }),
- audio: actor
- .pipeline
- .audio_output_path
- .as_ref()
- .map(|path| AudioMeta {
- path: path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),
- }),
- cursor: Some(PathBuf::from("content/cursor.json")),
- },
- },
- };
-
- actor.pipeline.inner.shutdown().await?;
-
- actor
- .stop_signal
- .store(true, std::sync::atomic::Ordering::Relaxed);
-
- let cursor_data = if let Some(cursor) = actor.cursor {
- let resp = cursor.stop().await;
- cap_project::CursorData {
- clicks: resp.clicks,
- moves: resp.moves,
- cursor_images: CursorImages(
- resp.cursors
- .into_values()
- .map(|(filename, id)| (id.to_string(), filename))
- .collect(),
- ),
- }
- } else {
- Default::default()
- };
-
- std::fs::write(
- actor.recording_dir.join("content/cursor.json"),
- serde_json::to_string_pretty(&cursor_data)?,
- )?;
-
- meta.save_for_project()
- .map_err(Either::either_into::<RecordingError>)?;
-
- Ok(CompletedRecording {
- id: actor.id,
- meta,
- cursor_data,
- recording_dir: actor.recording_dir,
- display_source: actor.options.capture_target,
- segments: vec![segment.0, segment.1],
- })
-}
-
-fn create_screen_capture(
- recording_options: &RecordingOptions,
-) -> ScreenCaptureSource<impl MakeCapturePipeline> {
- #[cfg(target_os = "macos")]
- {
- ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(
- dbg!(&recording_options.capture_target),
- None,
- None,
- )
- }
- #[cfg(not(target_os = "macos"))]
- {
- ScreenCaptureSource::<cap_media::sources::AVFrameCapture>::init(
- dbg!(&recording_options.capture_target),
- None,
- None,
- )
- }
+pub struct RecordingSegment {
+ pub start: f64,
+ pub end: f64,
+ pub pipeline: RecordingPipeline,
}
struct RecordingPipeline {
@@ -270,149 +39,16 @@ struct RecordingPipeline {
pub display_output_path: PathBuf,
pub audio_output_path: Option<PathBuf>,
pub camera_output_path: Option<PathBuf>,
+ pub cursor: Option<CursorPipeline>,
}
-async fn create_pipeline<TCaptureFormat: MakeCapturePipeline>(
- content_dir: &PathBuf,
- screen_source: ScreenCaptureSource<TCaptureFormat>,
- camera_feed: Option<&Mutex<CameraFeed>>,
- audio_input_feed: Option<&AudioInputFeed>,
-) -> Result<RecordingPipeline, MediaError> {
- let camera_feed = match camera_feed.as_ref() {
- Some(camera_feed) => Some(camera_feed.lock().await),
- None => None,
- };
- let camera_feed = camera_feed.as_deref();
-
- let clock = RealTimeClock::<()>::new();
- let mut pipeline_builder = Pipeline::builder(clock);
-
- let display_output_path = content_dir.join("display.mp4");
- let mut audio_output_path = None;
- let mut camera_output_path = None;
-
- if let Some(camera_source) = camera_feed.map(CameraSource::init) {
- let camera_config = camera_source.info();
- let output_config = camera_config.scaled(1920, 30);
- camera_output_path = Some(content_dir.join("camera.mp4"));
-
- let camera_filter = VideoFilter::init("camera", camera_config, output_config)?;
- let camera_encoder = H264Encoder::init(
- "camera",
- output_config,
- Output::File(camera_output_path.clone().unwrap()),
- )?;
-
- pipeline_builder = pipeline_builder
- .source("camera_capture", camera_source)
- .pipe("camera_filter", camera_filter)
- .sink("camera_encoder", camera_encoder);
- }
-
- if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {
- let mic_config = mic_source.info();
- audio_output_path = Some(content_dir.join("audio-input.mp3"));
-
- // let mic_filter = AudioFilter::init("microphone", mic_config, "aresample=async=1:min_hard_comp=0.100000:first_pts=0")?;
- let mic_encoder = MP3Encoder::init(
- "microphone",
- mic_config,
- Output::File(audio_output_path.clone().unwrap()),
- )?;
-
- pipeline_builder = pipeline_builder
- .source("microphone_capture", mic_source)
- // .pipe("microphone_filter", mic_filter)
- .sink("microphone_encoder", mic_encoder);
- }
-
- // we do this last to frontload the majority of errors,
- // as the screen pipeline crashes the app if an error occurs afterwards for some reason
- pipeline_builder = TCaptureFormat::make_capture_pipeline(
- pipeline_builder,
- screen_source,
- &display_output_path,
- )?;
-
- //
-
- let mut pipeline = pipeline_builder.build().await?;
-
- pipeline.play().await?;
-
- Ok(RecordingPipeline {
- inner: pipeline,
- display_output_path,
- audio_output_path,
- camera_output_path,
- })
-}
-
-fn ensure_dir(path: PathBuf) -> Result<PathBuf, MediaError> {
- std::fs::create_dir_all(&path)?;
- Ok(path)
-}
-
-type CapturePipelineBuilder = PipelineBuilder<RealTimeClock<()>>;
-
-trait MakeCapturePipeline: 'static {
- fn make_capture_pipeline(
- builder: CapturePipelineBuilder,
- source: ScreenCaptureSource<Self>,
- output_path: impl Into<PathBuf>,
- ) -> Result<CapturePipelineBuilder, MediaError>
- where
- Self: Sized;
-}
-
-#[cfg(target_os = "macos")]
-impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
- fn make_capture_pipeline(
- builder: CapturePipelineBuilder,
- source: ScreenCaptureSource<Self>,
- output_path: impl Into<PathBuf>,
- ) -> Result<CapturePipelineBuilder, MediaError> {
- let screen_config = source.info();
-
- let output_config = screen_config.scaled(1920, 30);
- let screen_encoder = cap_media::encoders::H264AVAssetWriterEncoder::init(
- "screen",
- output_config,
- Output::File(output_path.into()),
- )?;
-
- Ok(builder
- .source("screen_capture", source)
- .sink("screen_capture_encoder", screen_encoder))
+impl RecordingSegment {
+ pub fn camera_meta(&self, base_path: &Path) -> Option<CameraMeta> {
+ self.pipeline
+ .camera_output_path
+ .as_ref()
+ .map(|path| CameraMeta {
+ path: path.strip_prefix(base_path).unwrap().to_owned(),
+ })
}
}
-
-impl MakeCapturePipeline for cap_media::sources::AVFrameCapture {
- fn make_capture_pipeline(
- builder: CapturePipelineBuilder,
- source: ScreenCaptureSource<Self>,
- output_path: impl Into<PathBuf>,
- ) -> Result<CapturePipelineBuilder, MediaError>
- where
- Self: Sized,
- {
- let screen_config = source.info();
- // let screen_bounds = screen_source.bounds;
-
- let output_config = screen_config.scaled(1920, 30);
- let screen_filter = VideoFilter::init("screen", screen_config, output_config)?;
- let screen_encoder =
- H264Encoder::init("screen", output_config, Output::File(output_path.into()))?;
- Ok(builder
- .source("screen_capture", source)
- .pipe("screen_capture_filter", screen_filter)
- .sink("screen_capture_encoder", screen_encoder))
- }
-}
-
-fn current_time_f64() -> f64 {
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap()
- .as_secs_f64()
-}
diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs
index 486896bd5..c3f1fed1b 100644
--- a/crates/recording/src/lib.rs
+++ b/crates/recording/src/lib.rs
@@ -5,6 +5,7 @@ pub mod segmented_actor;
pub use segmented_actor::{spawn_recording_actor, ActorHandle, CompletedRecording, RecordingError};
use cap_media::sources::*;
+use cap_project::Resolution;
use serde::{Deserialize, Serialize};
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
@@ -13,6 +14,23 @@ pub struct RecordingOptions {
pub capture_target: ScreenCaptureTarget,
pub camera_label: Option<String>,
pub audio_input_name: Option<String>,
+ pub fps: u32,
+ pub output_resolution: Option<Resolution>,
+}
+
+impl Default for RecordingOptions {
+ fn default() -> Self {
+ Self {
+ capture_target: ScreenCaptureTarget::Screen(CaptureScreen {
+ id: 0,
+ name: String::new(),
+ }),
+ camera_label: None,
+ audio_input_name: None,
+ fps: 30,
+ output_resolution: None,
+ }
+ }
}
impl RecordingOptions {
diff --git a/crates/recording/src/segmented_actor.rs b/crates/recording/src/segmented_actor.rs
index 395d396bb..e54f87a07 100644
--- a/crates/recording/src/segmented_actor.rs
+++ b/crates/recording/src/segmented_actor.rs
@@ -393,16 +393,18 @@ fn create_screen_capture(
{
ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(
dbg!(&recording_options.capture_target),
+ recording_options.output_resolution.clone(),
None,
- None,
+ recording_options.fps,
)
}
#[cfg(not(target_os = "macos"))]
{
ScreenCaptureSource::<cap_media::sources::AVFrameCapture>::init(
dbg!(&recording_options.capture_target),
+ recording_options.output_resolution.clone(),
None,
- None,
+ recording_options.fps,
)
}
}
@@ -443,7 +445,6 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
let mic_config = mic_source.info();
audio_output_path = Some(dir.join("audio-input.mp3"));
- // let mic_filter = AudioFilter::init("microphone", mic_config, "aresample=async=1:min_hard_comp=0.100000:first_pts=0")?;
let mic_encoder = MP3Encoder::init(
"microphone",
mic_config,
@@ -452,13 +453,12 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
pipeline_builder = pipeline_builder
.source("microphone_capture", mic_source)
- // .pipe("microphone_filter", mic_filter)
.sink("microphone_encoder", mic_encoder);
}
if let Some(camera_source) = camera_feed.map(CameraSource::init) {
let camera_config = camera_source.info();
- let output_config = camera_config.scaled(1920, 30);
+ let output_config = camera_config.scaled(1280_u32, 30_u32);
camera_output_path = Some(dir.join("camera.mp4"));
let camera_filter = VideoFilter::init("camera", camera_config, output_config)?;
@@ -526,11 +526,9 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
output_path: impl Into<PathBuf>,
) -> Result<CapturePipelineBuilder, MediaError> {
let screen_config = source.info();
-
- let output_config = screen_config.scaled(1920, 30);
let screen_encoder = cap_media::encoders::H264AVAssetWriterEncoder::init(
"screen",
- output_config,
+ screen_config,
Output::File(output_path.into()),
)?;
@@ -550,12 +548,9 @@ impl MakeCapturePipeline for cap_media::sources::AVFrameCapture {
Self: Sized,
{
let screen_config = source.info();
- // let screen_bounds = screen_source.bounds;
-
- let output_config = screen_config.scaled(1920, 30);
- let screen_filter = VideoFilter::init("screen", screen_config, output_config)?;
+ let screen_filter = VideoFilter::init("screen", screen_config, screen_config)?;
let screen_encoder =
- H264Encoder::init("screen", output_config, Output::File(output_path.into()))?;
+ H264Encoder::init("screen", screen_config, Output::File(output_path.into()))?;
Ok(builder
.source("screen_capture", source)
.pipe("screen_capture_filter", screen_filter)
diff --git a/package.json b/package.json
index 3c43939cb..33c09c857 100644
--- a/package.json
+++ b/package.json
@@ -2,8 +2,8 @@
"type": "module",
"scripts": {
"build": "dotenv -e .env -- turbo run build",
- "dev": "(cd apps/web && docker compose up -d && cd ../..) && dotenv -e .env -- pnpm --dir packages/database db:generate && dotenv -e .env -- pnpm --dir packages/database db:push && dotenv -e .env -- turbo run dev --no-cache --concurrency 12",
- "dev:manual": "dotenv -e .env -- turbo run dev --no-cache --concurrency 1",
+ "dev": "(cd apps/web && docker compose up -d && cd ../..) && dotenv -e .env -- pnpm --dir packages/database db:generate && dotenv -e .env -- pnpm --dir packages/database db:push && dotenv -e .env -- turbo run dev --filter=!@cap/storybook --no-cache --concurrency 12",
+ "dev:manual": "dotenv -e .env -- turbo run dev --filter=!@cap/storybook --no-cache --concurrency 1",
"lint": "turbo run lint",
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
"db:push": "dotenv -e .env -- pnpm --dir packages/database db:push",
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index 1a8c60b25..891872317 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -61,6 +61,7 @@ declare global {
const IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw.jsx')['default']
const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default']
const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default']
+ const IconLucideVideo: typeof import('~icons/lucide/video.jsx')['default']
const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default']
const IconLucideVolumeX: typeof import('~icons/lucide/volume-x.jsx')['default']
}