Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

more preparation for dynamic fps values

Brendan Allan2cb3f7f42c38
diff --git a/Cargo.lock b/Cargo.lock
index b50c761cf..63912ddc1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -825,6 +825,99 @@ dependencies = [
"serde",
]
+[[package]]
+name = "cap"
+version = "0.1.0"
+dependencies = [
+ "cap-editor",
+ "cap-export",
+ "cap-flags",
+ "cap-media",
+ "cap-project",
+ "cap-recording",
+ "cap-rendering",
+ "cap-utils",
+ "clap 4.5.23",
+ "core-graphics 0.24.0",
+ "editor",
+ "scap",
+ "serde",
+ "serde_json",
+ "tokio",
+]
+
+[[package]]
+name = "cap-desktop"
+version = "0.3.10"
+dependencies = [
+ "anyhow",
+ "axum",
+ "base64 0.22.1",
+ "cap-editor",
+ "cap-export",
+ "cap-flags",
+ "cap-media",
+ "cap-project",
+ "cap-recording",
+ "cap-rendering",
+ "cap-utils",
+ "chrono",
+ "clipboard-rs",
+ "cocoa 0.26.0",
+ "core-foundation 0.10.0",
+ "core-graphics 0.24.0",
+ "cpal 0.15.3 (git+https://github.com/RustAudio/cpal?rev=f43d36e55494993bbbde3299af0c53e5cdf4d4cf)",
+ "device_query",
+ "dotenvy_macro",
+ "ffmpeg-next",
+ "flume 0.11.0",
+ "futures",
+ "futures-intrusive",
+ "global-hotkey",
+ "image 0.25.5",
+ "keyed_priority_queue",
+ "mp4",
+ "nix 0.29.0",
+ "objc",
+ "objc2-app-kit",
+ "png",
+ "rand 0.8.5",
+ "reqwest",
+ "rodio",
+ "scap",
+ "sentry",
+ "serde",
+ "serde_json",
+ "specta",
+ "specta-typescript",
+ "swift-rs",
+ "tauri",
+ "tauri-build",
+ "tauri-nspanel",
+ "tauri-plugin-deep-link",
+ "tauri-plugin-dialog",
+ "tauri-plugin-fs",
+ "tauri-plugin-global-shortcut",
+ "tauri-plugin-http",
+ "tauri-plugin-notification",
+ "tauri-plugin-oauth",
+ "tauri-plugin-os",
+ "tauri-plugin-positioner",
+ "tauri-plugin-process",
+ "tauri-plugin-shell",
+ "tauri-plugin-single-instance",
+ "tauri-plugin-store",
+ "tauri-plugin-updater",
+ "tauri-plugin-window-state",
+ "tauri-specta",
+ "tempfile",
+ "tokio",
+ "tracing",
+ "uuid",
+ "windows 0.58.0",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "cap-editor"
version = "0.1.0"
@@ -858,22 +951,11 @@ dependencies = [
"futures",
"image 0.25.5",
"mp4",
- "tauri",
"tempfile",
"thiserror 1.0.63",
"tokio",
]
-[[package]]
-name = "cap-ffmpeg-cli"
-version = "0.1.0"
-dependencies = [
- "nix 0.29.0",
- "tauri",
- "tauri-plugin-shell",
- "tokio",
-]
-
[[package]]
name = "cap-flags"
version = "0.1.0"
@@ -934,8 +1016,6 @@ dependencies = [
"serde",
"serde_json",
"specta",
- "tauri",
- "tauri-plugin-store",
]
[[package]]
@@ -1217,26 +1297,6 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bfbf56724aa9eca8afa4fcfadeb479e722935bb2a0900c2d37e0cc477af0688"
-[[package]]
-name = "cli"
-version = "0.1.0"
-dependencies = [
- "cap-editor",
- "cap-export",
- "cap-ffmpeg-cli",
- "cap-flags",
- "cap-media",
- "cap-project",
- "cap-recording",
- "cap-rendering",
- "cap-utils",
- "clap 4.5.23",
- "editor",
- "serde",
- "serde_json",
- "tokio",
-]
-
[[package]]
name = "clipboard-rs"
version = "0.2.2"
@@ -1934,79 +1994,6 @@ dependencies = [
"syn 2.0.90",
]
-[[package]]
-name = "desktop"
-version = "0.3.10"
-dependencies = [
- "anyhow",
- "axum",
- "base64 0.22.1",
- "cap-editor",
- "cap-export",
- "cap-ffmpeg-cli",
- "cap-flags",
- "cap-media",
- "cap-project",
- "cap-recording",
- "cap-rendering",
- "cap-utils",
- "chrono",
- "clipboard-rs",
- "cocoa 0.26.0",
- "core-foundation 0.10.0",
- "core-graphics 0.24.0",
- "cpal 0.15.3 (git+https://github.com/RustAudio/cpal?rev=f43d36e55494993bbbde3299af0c53e5cdf4d4cf)",
- "device_query",
- "dotenvy_macro",
- "ffmpeg-next",
- "flume 0.11.0",
- "futures",
- "futures-intrusive",
- "global-hotkey",
- "image 0.25.5",
- "keyed_priority_queue",
- "mp4",
- "nix 0.29.0",
- "objc",
- "objc2-app-kit",
- "png",
- "rand 0.8.5",
- "reqwest",
- "rodio",
- "scap",
- "sentry",
- "serde",
- "serde_json",
- "specta",
- "specta-typescript",
- "swift-rs",
- "tauri",
- "tauri-build",
- "tauri-nspanel",
- "tauri-plugin-deep-link",
- "tauri-plugin-dialog",
- "tauri-plugin-fs",
- "tauri-plugin-global-shortcut",
- "tauri-plugin-http",
- "tauri-plugin-notification",
- "tauri-plugin-oauth",
- "tauri-plugin-os",
- "tauri-plugin-positioner",
- "tauri-plugin-process",
- "tauri-plugin-shell",
- "tauri-plugin-single-instance",
- "tauri-plugin-store",
- "tauri-plugin-updater",
- "tauri-plugin-window-state",
- "tauri-specta",
- "tempfile",
- "tokio",
- "tracing",
- "uuid",
- "windows 0.58.0",
- "windows-sys 0.59.0",
-]
-
[[package]]
name = "device_query"
version = "2.1.0"
diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.toml
index f7051142d..9bdb13d06 100644
--- a/apps/cli/Cargo.toml
+++ b/apps/cli/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "cli"
+name = "cap"
version = "0.1.0"
edition = "2021"
@@ -8,7 +8,6 @@ clap = { version = "4.5.23", features = ["derive"] }
cap-utils = { path = "../../crates/utils" }
cap-project = { path = "../../crates/project" }
cap-rendering = { path = "../../crates/rendering" }
-cap-ffmpeg-cli = { path = "../../crates/ffmpeg-cli" }
cap-editor = { path = "../../crates/editor" }
cap-media = { path = "../../crates/media" }
cap-flags = { path = "../../crates/flags" }
@@ -18,3 +17,5 @@ serde = "1.0.216"
serde_json = "1.0.133"
tokio.workspace = true
editor = "0.1.1"
+scap.workspace = true
+core-graphics = "0.24.0"
diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs
index 0aae8f2ce..d5e60176c 100644
--- a/apps/cli/src/main.rs
+++ b/apps/cli/src/main.rs
@@ -1,6 +1,7 @@
use std::{path::PathBuf, sync::Arc};
use cap_editor::create_segments;
+use cap_media::sources::get_target_fps;
use cap_project::{RecordingMeta, XY};
use cap_rendering::RenderVideoConstants;
use clap::{Parser, Subcommand};
@@ -17,6 +18,18 @@ enum Commands {
project_path: PathBuf,
output_path: Option<PathBuf>,
},
+ Record {
+ #[command(subcommand)]
+ command: Option<RecordCommands>,
+ },
+}
+
+#[derive(Subcommand)]
+enum RecordCommands {
+ Screens,
+ Windows,
+ Cameras,
+ Mics,
}
#[tokio::main]
@@ -54,6 +67,7 @@ async fn main() {
let segments = create_segments(&meta);
+ let fps = meta.content.max_fps();
let project_output_path = project_path.join("output/result.mp4");
let exporter = cap_export::Exporter::new(
project,
@@ -63,6 +77,7 @@ async fn main() {
meta,
render_constants,
&segments,
+ fps,
)
.unwrap();
@@ -77,5 +92,42 @@ async fn main() {
println!("Exported video to '{}'", output_path.display());
}
+ Commands::Record { command } => match command {
+ Some(RecordCommands::Screens) => {
+ let screens = cap_media::sources::list_screens();
+
+ for (i, (screen, target)) in screens.iter().enumerate() {
+ println!(
+ "
+screen {}:
+ id: {}
+ name: {}
+ fps: {}",
+ i,
+ screen.id,
+ screen.name,
+ get_target_fps(target).unwrap()
+ );
+ }
+ }
+ Some(RecordCommands::Windows) => {
+ let windows = cap_media::sources::list_windows();
+
+ for (i, (window, target)) in windows.iter().enumerate() {
+ println!(
+ "
+window {}:
+ id: {}
+ name: {}
+ fps: {}",
+ i,
+ window.id,
+ window.name,
+ get_target_fps(target).unwrap()
+ );
+ }
+ }
+ _ => {}
+ },
}
}
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index a06751cc0..166635dad 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "desktop"
+name = "cap-desktop"
version = "0.3.10"
description = "Beautiful screen recordings, owned by you."
authors = ["you"]
@@ -73,7 +73,6 @@ clipboard-rs = "0.2.2"
cap-utils = { path = "../../../crates/utils" }
cap-project = { path = "../../../crates/project" }
cap-rendering = { path = "../../../crates/rendering" }
-cap-ffmpeg-cli = { path = "../../../crates/ffmpeg-cli" }
cap-editor = { path = "../../../crates/editor" }
cap-media = { path = "../../../crates/media" }
cap-flags = { path = "../../../crates/flags" }
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index 4fad366a7..4383cbc60 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -70,7 +70,6 @@ pub async fn export_video(
}
let exporter = cap_export::Exporter::new(
- &app,
modified_project,
output_path.clone(),
move |frame_index| {
@@ -84,6 +83,7 @@ pub async fn export_video(
editor_instance.meta(),
editor_instance.render_constants.clone(),
&editor_instance.segments,
+ 30,
)
.map_err(|e| {
sentry::capture_message(&e.to_string(), sentry::Level::Error);
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index d0cb1448e..e435c1704 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1441,6 +1441,7 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resul
segment: cap_project::SingleSegment {
display: Display {
path: screenshot_path.clone(),
+ fps: 0,
},
camera: None,
audio: None,
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 838a7dbee..385d18a8b 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -15,7 +15,7 @@ use crate::{
};
use cap_flags::FLAGS;
use cap_media::feeds::CameraFeed;
-use cap_media::sources::{AVFrameCapture, CaptureScreen, CaptureWindow, ScreenCaptureSource};
+use cap_media::sources::{CaptureScreen, CaptureWindow};
use cap_project::{
Content, ProjectConfiguration, TimelineConfiguration, TimelineSegment, ZoomSegment,
};
@@ -28,13 +28,19 @@ use tauri_specta::Event;
#[tauri::command(async)]
#[specta::specta]
pub fn list_capture_screens() -> Vec<CaptureScreen> {
- ScreenCaptureSource::<AVFrameCapture>::list_screens()
+ cap_media::sources::list_screens()
+ .into_iter()
+ .map(|(v, _)| v)
+ .collect()
}
#[tauri::command(async)]
#[specta::specta]
pub fn list_capture_windows() -> Vec<CaptureWindow> {
- ScreenCaptureSource::<AVFrameCapture>::list_windows()
+ cap_media::sources::list_windows()
+ .into_iter()
+ .map(|(v, _)| v)
+ .collect()
}
#[tauri::command(async)]
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 60232e6a7..4fc95c1fa 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -41,6 +41,9 @@ import { Header } from "./Header";
import { Player } from "./Player";
import { ConfigSidebar } from "./ConfigSidebar";
import { Timeline } from "./Timeline";
+import { JSX } from "solid-js/jsx-runtime";
+
+export const FPS = 30;
export function Editor() {
const [params] = useSearchParams<{ id: string }>();
@@ -78,13 +81,13 @@ function Inner() {
onMount(() => {
events.editorStateChanged.listen((e) => {
renderFrame.clear();
- setPlaybackTime(e.payload.playhead_position / 30);
+ setPlaybackTime(e.payload.playhead_position / FPS);
});
});
const renderFrame = throttle((time: number) => {
events.renderFrameEvent.emit({
- frame_number: Math.max(Math.floor(time * 30), 0),
+ frame_number: Math.max(Math.floor(time * FPS), 0),
});
}, 1000 / 60);
diff --git a/apps/desktop/src/routes/editor/Timeline.tsx b/apps/desktop/src/routes/editor/Timeline.tsx
index 2b0a9df23..2b7f04d03 100644
--- a/apps/desktop/src/routes/editor/Timeline.tsx
+++ b/apps/desktop/src/routes/editor/Timeline.tsx
@@ -26,6 +26,7 @@ import {
useTrackContext,
} from "./context";
import { formatTime } from "./utils";
+import { FPS } from "./Editor";
export function Timeline() {
const {
@@ -99,7 +100,7 @@ export function Timeline() {
commands.setPlayheadPosition(
videoId,
Math.round(
- 30 *
+ FPS *
editorInstance.recordingDuration *
((e.clientX - left!) / width!)
)
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index bc10c24a5..7c12c5e17 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -227,7 +227,7 @@ export type BackgroundConfiguration = { source: BackgroundSource; blur: number;
export type BackgroundSource = { type: "wallpaper"; id: number } | { 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 }
-export type CameraMeta = { path: string }
+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"
@@ -238,7 +238,7 @@ export type CurrentRecordingChanged = null
export type CursorAnimationStyle = "regular" | "slow" | "fast"
export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: CursorType; animationStyle: CursorAnimationStyle }
export type CursorType = "pointer" | "circle"
-export type Display = { path: string }
+export type Display = { path: string; fps?: number }
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; recordingConfig?: RecordingConfig | null }
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index f14e3f844..b6b1229bb 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -2,7 +2,6 @@ use std::{sync::Arc, time::Duration};
use cap_media::data::{AudioInfo, AudioInfoError, FromSampleBytes};
use cap_media::feeds::{AudioData, AudioPlaybackBuffer};
-use cap_media::MediaError;
use cap_project::ProjectConfiguration;
use cap_rendering::{ProjectUniforms, RenderVideoConstants};
use cpal::{
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
index 9074f4b45..d1e701c67 100644
--- a/crates/export/Cargo.toml
+++ b/crates/export/Cargo.toml
@@ -17,5 +17,5 @@ image = "0.25.2"
mp4 = "0.14.0"
thiserror.workspace = true
futures = "0.3.31"
-tauri = { workspace = true }
+# tauri = { workspace = true }
ffmpeg = { workspace = true }
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 15bb567d0..426d46253 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -5,7 +5,7 @@ use cap_media::{
feeds::{AudioData, AudioFrameBuffer},
MediaError,
};
-use cap_project::{GeneralSettingsStore, ProjectConfiguration, RecordingMeta};
+use cap_project::{ProjectConfiguration, RecordingMeta};
use cap_rendering::{
ProjectUniforms, RecordingSegmentDecoders, RenderSegment, RenderVideoConstants, RenderedFrame,
SegmentVideoPaths,
@@ -14,7 +14,6 @@ use ffmpeg::Rational;
use futures::FutureExt;
use image::{ImageBuffer, Rgba};
use std::{path::PathBuf, sync::Arc};
-use tauri::AppHandle;
const FPS: u32 = 30;
@@ -53,7 +52,6 @@ where
TOnProgress: Fn(u32) + Send + 'static,
{
pub fn new(
- app: &AppHandle,
project: ProjectConfiguration,
output_path: PathBuf,
on_progress: TOnProgress,
@@ -61,25 +59,8 @@ where
meta: RecordingMeta,
render_constants: Arc<RenderVideoConstants>,
segments: &[Segment],
+ fps: u32,
) -> 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)?;
@@ -318,184 +299,4 @@ where
Ok(output_path)
}
-
- pub async fn export_with_mp4_encoder(self) -> Result<PathBuf, ExportError> {
- struct AudioRender {
- buffer: AudioFrameBuffer,
- }
-
- let (tx_image_data, mut rx_image_data) = tokio::sync::mpsc::channel::<RenderedFrame>(4);
-
- let encoder_handle = tokio::spawn({
- let project = self.project.clone();
- let project_path = self.project_path.clone();
- async move {
- println!("Starting MP4 encoding process...");
-
- let audio_info = if let Some(audio_data) =
- self.audio_segments.get(0).and_then(|d| d.as_ref().as_ref())
- {
- Some(
- AudioInfo::new(
- audio_data.info.sample_format,
- audio_data.info.sample_rate,
- audio_data.info.channels as u16,
- )
- .map_err(Into::<MediaError>::into)?,
- )
- } else {
- None
- };
-
- let mut encoder = cap_media::encoders::MP4Encoder::init(
- "output",
- VideoInfo::from_raw(
- MP4Encoder::video_format(),
- self.output_size.0,
- self.output_size.1,
- 30,
- ),
- audio_info,
- cap_media::encoders::Output::File(self.output_path.clone()),
- )?;
-
- let mut audio =
- if let Some(_) = self.audio_segments.get(0).and_then(|d| d.as_ref().as_ref()) {
- Some(AudioRender {
- buffer: AudioFrameBuffer::new(
- self.audio_segments
- .iter()
- .map(|s| s.as_ref().as_ref().unwrap().clone())
- .collect(),
- ),
- })
- } else {
- None
- };
-
- let mut frame_count = 0;
- let mut first_frame = None;
-
- while let Some(frame) = rx_image_data.recv().await {
- (self.on_progress)(frame_count);
-
- if frame_count == 0 {
- first_frame = Some(frame.clone());
- }
-
- if let Some(audio) = &mut audio {
- if frame_count == 0 {
- audio.buffer.set_playhead(0., project.timeline());
- }
-
- let audio_info = audio.buffer.info();
- let estimated_samples_per_frame =
- f64::from(audio_info.sample_rate) / f64::from(FPS);
- let samples = estimated_samples_per_frame.ceil() as usize;
-
- if let Some((_, frame_data)) =
- audio.buffer.next_frame_data(samples, project.timeline())
- {
- let mut frame = audio_info.wrap_frame(
- &frame_data
- .to_vec()
- .chunks(8)
- .flat_map(|v| {
- (f64::from_le_bytes([
- v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7],
- ]) as f32)
- .to_le_bytes()
- })
- .collect::<Vec<_>>(),
- 0,
- );
- let pts = i64::from(frame_count) * i64::try_from(samples).unwrap();
- frame.set_pts(Some(pts));
- println!(
- "Export: Sending audio frame {} with PTS: {:?}, samples: {}",
- frame_count,
- frame.pts(),
- samples
- );
- encoder.queue_audio_frame(frame);
- }
- }
-
- println!(
- "Export: Processing frame {} (size: {}x{}, padded_bytes_per_row: {})",
- frame_count, frame.width, frame.height, frame.padded_bytes_per_row
- );
-
- let mut video_frame = VideoInfo::from_raw(
- RawVideoFormat::Rgba,
- self.output_size.0,
- self.output_size.1,
- 30,
- )
- .wrap_frame(
- &frame.data,
- 0,
- frame.padded_bytes_per_row as usize,
- );
- video_frame.set_pts(Some(frame_count as i64));
-
- println!(
- "Export: Sending frame {} to encoder (PTS: {:?})",
- frame_count,
- video_frame.pts()
- );
-
- encoder.queue_video_frame(video_frame);
- frame_count += 1;
- }
-
- encoder.finish();
-
- // Save the first frame as a screenshot and thumbnail
- if let Some(frame) = first_frame {
- let rgba_img: ImageBuffer<Rgba<u8>, Vec<u8>> =
- ImageBuffer::from_raw(frame.width, frame.height, frame.data)
- .expect("Failed to create image from frame data");
-
- // Convert RGBA to RGB
- let rgb_img: ImageBuffer<image::Rgb<u8>, Vec<u8>> =
- ImageBuffer::from_fn(frame.width, frame.height, |x, y| {
- let rgba = rgba_img.get_pixel(x, y);
- image::Rgb([rgba[0], rgba[1], rgba[2]])
- });
-
- let screenshots_dir = project_path.join("screenshots");
- std::fs::create_dir_all(&screenshots_dir).unwrap_or_else(|e| {
- eprintln!("Failed to create screenshots directory: {:?}", e);
- });
-
- // Save full-size screenshot
- let screenshot_path = screenshots_dir.join("display.jpg");
- rgb_img.save(&screenshot_path).unwrap_or_else(|e| {
- eprintln!("Failed to save screenshot: {:?}", e);
- });
- } else {
- eprintln!("No frames were processed, cannot save screenshot or thumbnail");
- }
-
- Ok::<_, ExportError>(self.output_path)
- }
- });
-
- println!("Rendering video to channel");
-
- cap_rendering::render_video_to_channel(
- self.render_constants.options,
- self.project,
- tx_image_data,
- &self.meta,
- self.render_segments,
- FPS,
- )
- .await?;
-
- let output_path = encoder_handle.await??;
-
- Ok(output_path)
- }
}
diff --git a/crates/ffmpeg-cli/Cargo.toml b/crates/ffmpeg-cli/Cargo.toml
deleted file mode 100644
index 4181231f9..000000000
--- a/crates/ffmpeg-cli/Cargo.toml
+++ /dev/null
@@ -1,12 +0,0 @@
-[package]
-name = "cap-ffmpeg-cli"
-version = "0.1.0"
-edition = "2021"
-
-[dependencies]
-tauri = { workspace = true }
-tauri-plugin-shell = "2.0.0"
-tokio.workspace = true
-
-[target.'cfg(unix)'.dependencies]
-nix = { version = "0.29.0", features = ["signal"] }
diff --git a/crates/ffmpeg-cli/src/lib.rs b/crates/ffmpeg-cli/src/lib.rs
deleted file mode 100644
index 686b07057..000000000
--- a/crates/ffmpeg-cli/src/lib.rs
+++ /dev/null
@@ -1,346 +0,0 @@
-use std::{
- ffi::OsString,
- io::{Read, Write},
- ops::Deref,
- path::{Path, PathBuf},
- process::Stdio,
-};
-use tauri::utils::platform;
-use tokio::{
- io::{AsyncReadExt, AsyncWriteExt},
- process::{Child, ChildStderr, ChildStdin, Command},
-};
-
-pub struct FFmpegProcess {
- pub ffmpeg_stdin: ChildStdin,
- // pub ffmpeg_stderr: ChildStderr,
- cmd: Child,
-}
-
-impl FFmpegProcess {
- pub fn spawn(mut command: Command) -> Self {
- #[cfg(target_os = "windows")]
- {
- use std::os::windows::process::CommandExt;
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- command.creation_flags(CREATE_NO_WINDOW);
- }
-
- let mut cmd = command
- .stdin(Stdio::piped())
- // .stderr(Stdio::piped())
- .spawn()
- .unwrap_or_else(|e| {
- println!("Failed to start FFmpeg: {}", e);
- println!("Command: {:?}", command);
- panic!("Failed to start FFmpeg");
- });
-
- let ffmpeg_stdin = cmd.stdin.take().unwrap_or_else(|| {
- println!("Failed to capture FFmpeg stdin");
- panic!("Failed to capture FFmpeg stdin");
- });
-
- // let ffmpeg_stderr = cmd.stderr.take().unwrap_or_else(|| {
- // println!("Failed to capture FFmpeg stderr");
- // panic!("Failed to capture FFmpeg stderr");
- // });
-
- Self {
- ffmpeg_stdin,
- // ffmpeg_stderr,
- cmd,
- }
- }
-
- pub async fn write(&mut self, data: &[u8]) -> std::io::Result<()> {
- self.ffmpeg_stdin.write_all(data).await
- }
-
- pub async fn stop(&mut self) {
- self.ffmpeg_stdin.write_all(b"q").await.ok();
- self.ffmpeg_stdin.flush().await.ok();
- println!("Sent stop command to FFmpeg");
- }
-
- pub async fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
- self.cmd.wait().await
- }
-
- pub async fn read_stderr(&mut self) -> std::io::Result<String> {
- let mut err = String::new();
- // self.ffmpeg_stderr.read_to_string(&mut err).await?;
- Ok(err)
- }
-
- pub fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
- self.cmd.try_wait()
- }
-
- pub fn kill(&mut self) {
- let _ = self.cmd.kill();
- }
-
- pub fn wait_with_timeout(
- &mut self,
- timeout: std::time::Duration,
- ) -> std::io::Result<Option<std::process::ExitStatus>> {
- let start = std::time::Instant::now();
- while start.elapsed() < timeout {
- match self.cmd.try_wait()? {
- Some(status) => {
- return Ok(Some(status));
- }
- None => std::thread::sleep(std::time::Duration::from_millis(100)),
- }
- }
- Ok(None)
- }
-
- pub async fn read_video_frame(
- &mut self,
- frame_size: usize,
- ) -> Result<Option<Vec<u8>>, std::io::Error> {
- let mut buffer = vec![0u8; frame_size];
- match self
- .cmd
- .stdout
- .as_mut()
- .unwrap()
- .read_exact(&mut buffer)
- .await
- {
- Ok(_) => {
- println!("Read video frame of size: {}", buffer.len());
- Ok(Some(buffer))
- }
- Err(ref e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(None),
- Err(e) => Err(e),
- }
- }
-
- pub async fn write_video_frame(&mut self, data: &[u8]) -> std::io::Result<()> {
- let mut remaining = data;
- while !remaining.is_empty() {
- match self.ffmpeg_stdin.write(remaining).await {
- Ok(0) => {
- return Err(std::io::Error::new(
- std::io::ErrorKind::WriteZero,
- "Failed to write data to FFmpeg",
- ));
- }
- Ok(n) => {
- remaining = &remaining[n..];
- }
- Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {
- continue;
- }
- Err(e) => {
- return Err(e);
- }
- }
- }
- self.ffmpeg_stdin.flush().await?;
- Ok(())
- }
-
- pub fn pause(&mut self) -> std::io::Result<()> {
- #[cfg(unix)]
- {
- use nix::sys::signal::{kill, Signal};
- use nix::unistd::Pid;
- kill(
- Pid::from_raw(self.cmd.id().unwrap() as i32),
- Signal::SIGSTOP,
- )?;
- println!("Sent SIGSTOP to FFmpeg");
- }
- Ok(())
- }
-
- pub fn resume(&mut self) -> std::io::Result<()> {
- #[cfg(unix)]
- {
- use nix::sys::signal::{kill, Signal};
- use nix::unistd::Pid;
- kill(
- Pid::from_raw(self.cmd.id().unwrap() as i32),
- Signal::SIGCONT,
- )?;
- println!("Sent SIGCONT to FFmpeg");
- }
- Ok(())
- }
-}
-
-pub struct FFmpegInput<T> {
- inner: T,
- pub index: u8,
-}
-
-pub enum FFmpegOutput {
- File {
- path: PathBuf,
- codec: String,
- preset: String,
- crf: u32,
- },
- RawVideo {
- format: String,
- width: u32,
- height: u32,
- },
-}
-
-impl<T> Deref for FFmpegInput<T> {
- type Target = T;
-
- fn deref(&self) -> &Self::Target {
- &self.inner
- }
-}
-
-pub trait ApplyFFmpegArgs {
- fn apply_ffmpeg_args(&self, command: &mut Command);
-}
-
-#[derive(Debug, Default)]
-pub struct FFmpegRawVideoInput {
- pub width: u32,
- pub height: u32,
- pub fps: u32,
- pub pix_fmt: &'static str,
- pub input: OsString,
- // pub offset: f64,
-}
-
-impl ApplyFFmpegArgs for FFmpegRawVideoInput {
- fn apply_ffmpeg_args(&self, command: &mut Command) {
- dbg!(&self);
- let size = format!("{}x{}", self.width, self.height);
-
- command
- .args(["-f", "rawvideo", "-pix_fmt", self.pix_fmt])
- .args(["-s", &size]);
-
- if self.fps == 0 {
- command.args(["-use_wallclock_as_timestamps", "1"]);
- } else {
- command.args(["-r", &self.fps.to_string()]);
- }
-
- // if self.offset != 0.0 {
- // command.args(["-itsoffset", &self.offset.to_string()]);
- // }
-
- command
- .args(["-thread_queue_size", "4096", "-i"])
- .arg(&self.input);
- }
-}
-
-#[derive(Debug, Default)]
-pub struct FFmpegRawAudioInput {
- pub sample_format: String,
- pub sample_rate: u32,
- pub channels: u16,
- pub input: OsString,
-}
-
-impl ApplyFFmpegArgs for FFmpegRawAudioInput {
- fn apply_ffmpeg_args(&self, command: &mut Command) {
- dbg!(&self);
- command
- .args(["-f", &self.sample_format])
- .args(["-ar", &self.sample_rate.to_string()])
- .args(["-ac", &self.channels.to_string()])
- .args(["-probesize", "32"]);
-
- // if self.offset != 0.0 {
- // command.args(["-itsoffset", &self.offset.to_string()]);
- // }
-
- command.args(["-thread_queue_size", "4096", "-i"]);
- command.arg(&self.input);
- }
-}
-
-pub struct FFmpeg {
- pub command: Command,
- source_index: u8,
-}
-
-impl Default for FFmpeg {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl FFmpeg {
- pub fn new() -> Self {
- let mut command = Command::new(relative_command_path("ffmpeg").unwrap());
- // command.arg("-hide_banner");
-
- Self {
- command,
- source_index: 0,
- }
- }
-
- pub fn add_input<S: ApplyFFmpegArgs>(&mut self, source: S) -> FFmpegInput<S> {
- let source_index = self.source_index;
- self.source_index += 1;
-
- source.apply_ffmpeg_args(&mut self.command);
-
- FFmpegInput {
- inner: source,
- index: source_index,
- }
- }
-
- pub fn add_output(&mut self, output: FFmpegOutput) {
- match output {
- FFmpegOutput::File {
- path,
- codec,
- preset,
- crf,
- } => {
- self.command
- .arg("-i")
- .arg("pipe:0")
- .args(["-c:v", &codec])
- .args(["-preset", &preset])
- .args(["-crf", &crf.to_string()])
- .arg(path);
- }
- FFmpegOutput::RawVideo {
- format,
- width,
- height,
- } => {
- self.command
- .arg("-i")
- .arg("pipe:0")
- .args(["-f", &format])
- .args(["-s", &format!("{}x{}", width, height)])
- .arg("pipe:1");
- }
- }
- }
-
- pub fn start(self) -> FFmpegProcess {
- FFmpegProcess::spawn(self.command)
- }
-}
-
-fn relative_command_path(command: impl AsRef<Path>) -> Result<PathBuf, tauri_plugin_shell::Error> {
- match platform::current_exe()?.parent() {
- #[cfg(windows)]
- Some(exe_dir) => Ok(exe_dir.join(command.as_ref()).with_extension("exe")),
- #[cfg(not(windows))]
- Some(exe_dir) => Ok(exe_dir.join(command.as_ref())),
- None => Err(tauri_plugin_shell::Error::CurrentExeHasNoParent),
- }
-}
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index d29cb84ed..b1d9359e9 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -84,12 +84,13 @@ impl<TCaptureFormat> Clone for ScreenCaptureSource<TCaptureFormat> {
}
}
+const MAX_FPS: u32 = 60;
+
impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
pub fn init(
target: &ScreenCaptureTarget,
output_resolution: Option<cap_project::Resolution>,
output_type: Option<FrameType>,
- fps: u32,
) -> Self {
let mut this = Self {
target: target.clone(),
@@ -110,14 +111,15 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
}
}),
output_type,
- fps,
- video_info: VideoInfo::from_raw(RawVideoFormat::Bgra, 0, 0, fps),
+ fps: MAX_FPS,
+ video_info: VideoInfo::from_raw(RawVideoFormat::Bgra, 0, 0, MAX_FPS),
_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.video_info =
+ VideoInfo::from_raw(RawVideoFormat::Bgra, frame_width, frame_height, MAX_FPS);
this
}
@@ -168,6 +170,10 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
.cloned(),
};
+ if let Some(Target::Display(d)) = &target {
+ dbg!(d.raw_handle.display_mode().unwrap().refresh_rate());
+ }
+
Options {
fps: self.fps,
show_cursor: FLAGS.record_mouse,
@@ -180,64 +186,6 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
}
}
- pub fn list_screens() -> Vec<CaptureScreen> {
- if !scap::has_permission() {
- return vec![];
- }
-
- let mut targets = vec![];
- let screens = scap::get_all_targets()
- .into_iter()
- .filter_map(|t| match t {
- Target::Display(screen) => Some(screen),
- _ => None,
- })
- .collect::<Vec<_>>();
-
- let names = crate::platform::display_names();
-
- for (idx, screen) in screens.into_iter().enumerate() {
- targets.push(CaptureScreen {
- id: screen.id,
- name: names
- .get(&screen.id)
- .cloned()
- .unwrap_or_else(|| format!("Screen {}", idx + 1)),
- });
- }
- targets
- }
-
- pub fn list_windows() -> Vec<CaptureWindow> {
- if !scap::has_permission() {
- return vec![];
- }
-
- let targets = scap::get_all_targets();
-
- let platform_windows: HashMap<u32, Window> = crate::platform::get_on_screen_windows()
- .into_iter()
- .map(|window| (window.window_id, window))
- .collect();
-
- targets
- .into_iter()
- .filter_map(|target| match target {
- Target::Window(window) => {
- platform_windows
- .get(&window.id)
- .map(|platform_window| CaptureWindow {
- id: window.id,
- owner_name: platform_window.owner_name.clone(),
- name: platform_window.name.clone(),
- bounds: platform_window.bounds,
- })
- }
- Target::Display(_) => None,
- })
- .collect()
- }
-
pub fn info(&self) -> VideoInfo {
self.video_info
}
@@ -471,3 +419,125 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
println!("Shutting down screen capture source thread.");
}
}
+
+pub fn list_screens() -> Vec<(CaptureScreen, Target)> {
+ if !scap::has_permission() {
+ return vec![];
+ }
+
+ let mut targets = vec![];
+ let screens = scap::get_all_targets()
+ .into_iter()
+ .filter_map(|t| match t {
+ Target::Display(screen) => Some(screen),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+
+ let names = crate::platform::display_names();
+
+ for (idx, screen) in screens.into_iter().enumerate() {
+ targets.push((
+ CaptureScreen {
+ id: screen.id,
+ name: names
+ .get(&screen.id)
+ .cloned()
+ .unwrap_or_else(|| format!("Screen {}", idx + 1)),
+ },
+ Target::Display(screen),
+ ));
+ }
+ targets
+}
+
+pub fn list_windows() -> Vec<(CaptureWindow, Target)> {
+ if !scap::has_permission() {
+ return vec![];
+ }
+
+ let targets = scap::get_all_targets();
+
+ let platform_windows: HashMap<u32, Window> = crate::platform::get_on_screen_windows()
+ .into_iter()
+ .map(|window| (window.window_id, window))
+ .collect();
+
+ targets
+ .into_iter()
+ .filter_map(|target| match &target {
+ Target::Window(window) => {
+ let id = window.id;
+ platform_windows.get(&id).map(|platform_window| {
+ (
+ CaptureWindow {
+ id,
+ owner_name: platform_window.owner_name.clone(),
+ name: platform_window.name.clone(),
+ bounds: platform_window.bounds,
+ },
+ target,
+ )
+ })
+ }
+ Target::Display(_) => None,
+ })
+ .collect()
+}
+
+pub fn get_target_fps(target: &scap::Target) -> Option<u32> {
+ #[cfg(target_os = "macos")]
+ {
+ match target {
+ scap::Target::Display(display) => refresh_rate_for_display(display.raw_handle.id),
+ scap::Target::Window(window) => {
+ refresh_rate_for_display(display_for_window(window.raw_handle)?.id)
+ }
+ }
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ todo!()
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn display_for_window(
+ window: core_graphics::window::CGWindowID,
+) -> Option<core_graphics::display::CGDisplay> {
+ use core_foundation::array::CFArray;
+ use core_graphics::{
+ display::{CFDictionary, CGDisplay, CGRect},
+ window::{create_description_from_array, kCGWindowBounds},
+ };
+
+ let descriptions = create_description_from_array(CFArray::from_copyable(&[window]))?;
+
+ let window_bounds = CGRect::from_dict_representation(
+ &descriptions
+ .get(0)?
+ .get(unsafe { kCGWindowBounds })
+ .downcast::<CFDictionary>()?,
+ )?;
+
+ for id in CGDisplay::active_displays().ok()? {
+ let display = CGDisplay::new(id);
+ if window_bounds.is_intersects(&display.bounds()) {
+ return Some(display);
+ }
+ }
+
+ None
+}
+
+#[cfg(target_os = "macos")]
+fn refresh_rate_for_display(display_id: core_graphics::display::CGDirectDisplayID) -> Option<u32> {
+ use core_graphics::display::CGDisplay;
+
+ Some(
+ CGDisplay::new(display_id)
+ .display_mode()?
+ .refresh_rate()
+ .round() as u32,
+ )
+}
diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml
index 1f1ec4627..eb3bb52a7 100644
--- a/crates/project/Cargo.toml
+++ b/crates/project/Cargo.toml
@@ -8,5 +8,5 @@ specta = { workspace = true, 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"
+# 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 1438e19d3..50d4e3a45 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -8,8 +8,6 @@ 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")]
@@ -35,35 +33,3 @@ impl Default for RecordingConfig {
}
}
}
-
-#[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/project/src/meta.rs b/crates/project/src/meta.rs
index 7a1da07cd..8eaa4c627 100644
--- a/crates/project/src/meta.rs
+++ b/crates/project/src/meta.rs
@@ -12,11 +12,19 @@ use crate::{CursorData, CursorEvents, CursorImages, ProjectConfiguration};
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct Display {
pub path: PathBuf,
+ #[serde(default = "legacy_static_video_fps")]
+ pub fps: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct CameraMeta {
pub path: PathBuf,
+ #[serde(default = "legacy_static_video_fps")]
+ pub fps: u32,
+}
+
+fn legacy_static_video_fps() -> u32 {
+ 30
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
@@ -92,6 +100,24 @@ impl Content {
.and_then(|s| s.camera.as_ref().map(|c| c.path.clone())),
}
}
+
+ pub fn min_fps(&self) -> u32 {
+ match self {
+ Content::SingleSegment { segment } => segment.display.fps,
+ Content::MultipleSegments { inner } => {
+ inner.segments.iter().map(|s| s.display.fps).min().unwrap()
+ }
+ }
+ }
+
+ pub fn max_fps(&self) -> u32 {
+ match self {
+ Content::SingleSegment { segment } => segment.display.fps,
+ Content::MultipleSegments { inner } => {
+ inner.segments.iter().map(|s| s.display.fps).max().unwrap()
+ }
+ }
+ }
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
diff --git a/crates/recording/src/segmented_actor.rs b/crates/recording/src/actor.rs
similarity index 99%
rename from crates/recording/src/segmented_actor.rs
rename to crates/recording/src/actor.rs
index 52df8d77a..33544aa22 100644
--- a/crates/recording/src/segmented_actor.rs
+++ b/crates/recording/src/actor.rs
@@ -342,6 +342,7 @@ async fn stop_recording(
.strip_prefix(&actor.recording_dir)
.unwrap()
.to_owned(),
+ fps: 60,
},
camera: s
.pipeline
@@ -352,6 +353,7 @@ async fn stop_recording(
.strip_prefix(&actor.recording_dir)
.unwrap()
.to_owned(),
+ fps: 30,
}),
audio: s.pipeline.audio_output_path.as_ref().map(|path| AudioMeta {
path: path.strip_prefix(&actor.recording_dir).unwrap().to_owned(),
@@ -400,7 +402,6 @@ fn create_screen_capture(
dbg!(&recording_options.capture_target),
recording_options.output_resolution.clone(),
None,
- recording_options.fps,
)
}
#[cfg(not(target_os = "macos"))]
@@ -409,7 +410,6 @@ fn create_screen_capture(
dbg!(&recording_options.capture_target),
recording_options.output_resolution.clone(),
None,
- recording_options.fps,
)
}
}
diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs
index 8ba0158a1..305134b28 100644
--- a/crates/recording/src/lib.rs
+++ b/crates/recording/src/lib.rs
@@ -1,7 +1,7 @@
+pub mod actor;
pub mod cursor;
-pub mod segmented_actor;
-pub use segmented_actor::{spawn_recording_actor, ActorHandle, CompletedRecording, RecordingError};
+pub use actor::{spawn_recording_actor, ActorHandle, CompletedRecording, RecordingError};
use cap_media::sources::*;
use cap_project::Resolution;
diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rs
index 6792ec0d7..f18724b93 100644
--- a/crates/rendering/src/decoder.rs
+++ b/crates/rendering/src/decoder.rs
@@ -1,7 +1,7 @@
use std::{
- collections::{HashMap, VecDeque},
+ collections::BTreeMap,
path::PathBuf,
- sync::{mpsc, Arc, Mutex},
+ sync::{mpsc, Arc},
};
use ffmpeg::{
@@ -11,33 +11,8 @@ use ffmpeg::{
software::{self, scaling},
Codec, Rational, Rescale,
};
-use ffmpeg_hw_device::CodecContextExt;
-use ffmpeg_sys_next::{
- av_buffer_unref, av_hwdevice_ctx_alloc, av_hwdevice_ctx_init, av_hwframe_transfer_data,
- avcodec_find_decoder, AVHWDeviceType,
-};
-use log;
-
-// Trait for hardware frame operations
-trait HwFrameExt {
- fn has_hw_context(&self) -> bool;
- fn transfer_to_cpu(&self, output: &mut frame::Video) -> Result<(), ffmpeg::Error>;
-}
-
-impl HwFrameExt for frame::Video {
- fn has_hw_context(&self) -> bool {
- unsafe { (*self.as_ptr()).hw_frames_ctx.is_null() == false }
- }
-
- fn transfer_to_cpu(&self, output: &mut frame::Video) -> Result<(), ffmpeg::Error> {
- let ret = unsafe { av_hwframe_transfer_data(output.as_mut_ptr(), self.as_ptr(), 0) };
- if ret < 0 {
- Err(ffmpeg::Error::from(ret))
- } else {
- Ok(())
- }
- }
-}
+use ffmpeg_hw_device::{CodecContextExt, HwDevice};
+use ffmpeg_sys_next::{avcodec_find_decoder, AVHWDeviceType};
pub type DecodedFrame = Arc<Vec<u8>>;
@@ -45,60 +20,17 @@ enum VideoDecoderMessage {
GetFrame(u32, tokio::sync::oneshot::Sender<Option<Arc<Vec<u8>>>>),
}
-fn pts_to_frame(pts: i64, time_base: Rational) -> u32 {
- (FPS as f64 * ((pts as f64 * time_base.numerator() as f64) / (time_base.denominator() as f64)))
+fn pts_to_frame(pts: i64, time_base: Rational, fps: u32) -> u32 {
+ (fps as f64 * ((pts as f64 * time_base.numerator() as f64) / (time_base.denominator() as f64)))
.round() as u32
}
const FRAME_CACHE_SIZE: usize = 100;
+// TODO: Allow dynamic FPS values by either passing it into `spawn`
+// or changing `get_frame` to take the requested time instead of frame number,
+// so that the lookup can be done by PTS instead of frame number.
const FPS: u32 = 30;
-pub struct FrameCache {
- capacity: usize,
- frames: HashMap<u32, CachedFrame>,
- usage_order: VecDeque<u32>,
-}
-
-impl FrameCache {
- pub fn new(capacity: usize) -> Self {
- Self {
- capacity,
- frames: HashMap::new(),
- usage_order: VecDeque::new(),
- }
- }
-
- pub fn get(&mut self, key: u32) -> Option<&mut CachedFrame> {
- if self.frames.contains_key(&key) {
- self.refresh_usage(key);
- return self.frames.get_mut(&key);
- }
- None
- }
-
- pub fn insert(&mut self, key: u32, cached_frame: CachedFrame) {
- if self.frames.contains_key(&key) {
- self.frames.insert(key, cached_frame);
- self.refresh_usage(key);
- } else {
- if self.frames.len() >= self.capacity {
- if let Some(oldest) = self.usage_order.pop_front() {
- self.frames.remove(&oldest);
- }
- }
- self.frames.insert(key, cached_frame);
- self.usage_order.push_back(key);
- }
- }
-
- fn refresh_usage(&mut self, key: u32) {
- if let Some(pos) = self.usage_order.iter().position(|x| *x == key) {
- self.usage_order.remove(pos);
- }
- self.usage_order.push_back(key);
- }
-}
-
#[derive(Clone)]
struct CachedFrame {
data: CachedFrameData,
@@ -108,101 +40,46 @@ impl CachedFrame {
fn process(
&mut self,
scaler_input_format: &mut format::Pixel,
- scaler_ctx: &mut ScalerContext,
+ scaler: &mut scaling::Context,
decoder: &codec::decoder::Video,
) -> Arc<Vec<u8>> {
match &mut self.data {
- CachedFrameData::Processed(data) => {
- // Already have RGBA data, return it immediately
- return data.clone();
- }
CachedFrameData::Raw(frame) => {
- let width = frame.width();
- let height = frame.height();
-
- // Check if dimensions changed and update scalers if needed
- scaler_ctx.check_dimensions(width, height);
-
- // Handle hardware frames by transferring to CPU memory if needed
- let frame = if frame.has_hw_context() {
- let mut sw_frame = frame::Video::new(format::Pixel::YUV420P, width, height);
- if let Err(e) = frame.transfer_to_cpu(&mut sw_frame) {
- log::error!("Failed to transfer hardware frame to CPU: {:?}", e);
- panic!("Failed to transfer hardware frame to CPU memory");
- }
- sw_frame
- } else {
- frame.clone()
- };
-
- // Now handle software format conversion if needed
- let frame = if frame.format() != format::Pixel::YUV420P {
- log::debug!(
- "Converting from {:?} to YUV420P as intermediate format",
- frame.format()
- );
-
- let mut yuv_frame = frame::Video::new(format::Pixel::YUV420P, width, height);
- scaler_ctx.ensure_yuv_scaler(frame.format());
-
- if let Some(yuv_scaler) = &mut scaler_ctx.yuv_scaler {
- if let Err(e) = yuv_scaler.run(&frame, &mut yuv_frame) {
- log::error!(
- "Failed to convert to YUV420P: {:?} (from format: {:?})",
- e,
- frame.format()
- );
- panic!("Failed to convert to intermediate format");
- }
- }
- yuv_frame
- } else {
- frame
- };
+ if frame.format() != *scaler_input_format {
+ // Reinitialize the scaler with the new input format
+ *scaler_input_format = frame.format();
+ *scaler = software::converter(
+ (decoder.width(), decoder.height()),
+ *scaler_input_format,
+ format::Pixel::RGBA,
+ )
+ .unwrap();
+ }
- *scaler_input_format = format::Pixel::YUV420P;
+ let mut rgb_frame = frame::Video::empty();
+ scaler.run(&frame, &mut rgb_frame).unwrap();
- // Create output frame
- let mut rgb_frame = frame::Video::new(format::Pixel::RGBA, width, height);
+ let width = rgb_frame.width() as usize;
+ let height = rgb_frame.height() as usize;
+ let stride = rgb_frame.stride(0);
+ let data = rgb_frame.data(0);
- // Convert to RGBA with retry on failure
- let mut conversion_successful = false;
- for _ in 0..3 {
- match scaler_ctx.rgba_scaler.run(&frame, &mut rgb_frame) {
- Ok(_) => {
- conversion_successful = true;
- break;
- }
- Err(e) => {
- log::warn!(
- "Failed to convert to RGBA, retrying with new scaler: {:?}",
- e
- );
- scaler_ctx.rgba_scaler = create_scaler(
- format::Pixel::YUV420P,
- width,
- height,
- format::Pixel::RGBA,
- );
- }
- }
- }
+ let expected_size = width * height * 4;
+
+ let mut frame_buffer = Vec::with_capacity(expected_size);
- if !conversion_successful {
- panic!("Failed to convert frame to RGBA after multiple attempts");
+ // account for stride > width
+ for line_data in data.chunks_exact(stride) {
+ frame_buffer.extend_from_slice(&line_data[0..width * 4]);
}
- // Convert to bytes and store in Arc<Vec<u8>>
- let size = (width as usize) * (height as usize) * 4;
- let mut rgb_data = Vec::with_capacity(size);
- rgb_data.extend_from_slice(rgb_frame.data(0));
- let rgb_data = Arc::new(rgb_data);
+ let data = Arc::new(frame_buffer);
- // Store the processed RGBA data for future use
- self.data = CachedFrameData::Processed(rgb_data.clone());
+ self.data = CachedFrameData::Processed(data.clone());
- rgb_data
+ data
}
+ CachedFrameData::Processed(data) => data.clone(),
}
}
}
@@ -221,6 +98,7 @@ impl AsyncVideoDecoder {
std::thread::spawn(move || {
let mut input = ffmpeg::format::input(&path).unwrap();
+
let input_stream = input
.streams()
.best(ffmpeg::media::Type::Video)
@@ -235,13 +113,16 @@ impl AsyncVideoDecoder {
let input_stream_index = input_stream.index();
let time_base = input_stream.time_base();
- let _frame_rate = input_stream.rate();
+ let frame_rate = input_stream.rate();
+ // Create a decoder for the video stream
let mut decoder = context.decoder().video().unwrap();
{
use codec::threading::{Config, Type};
+
let capabilities = decoder_codec.capabilities();
+
if capabilities.intersects(Capabilities::FRAME_THREADS) {
decoder.set_threading(Config::kind(Type::Frame));
} else if capabilities.intersects(Capabilities::SLICE_THREADS) {
@@ -251,158 +132,242 @@ impl AsyncVideoDecoder {
}
}
- // Try to enable hardware acceleration on macOS
- #[cfg(target_os = "macos")]
- {
- // First try NV12 as it's commonly supported by VideoToolbox
- let formats = [format::Pixel::NV12, format::Pixel::YUV420P];
-
- for &fmt in &formats {
- unsafe {
- let mut hw_device_ptr =
- av_hwdevice_ctx_alloc(AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX);
- if !hw_device_ptr.is_null() && av_hwdevice_ctx_init(hw_device_ptr) >= 0 {
- (*decoder.as_mut_ptr()).hw_device_ctx = hw_device_ptr;
- (*decoder.as_mut_ptr()).sw_pix_fmt = fmt.into();
- (*decoder.as_mut_ptr()).get_format = Some(get_hw_format);
- log::info!("Successfully enabled VideoToolbox hardware acceleration with format {:?}", fmt);
- break;
- }
- if !hw_device_ptr.is_null() {
- av_buffer_unref(&mut hw_device_ptr);
- }
- }
+ let hw_device: Option<HwDevice> = {
+ #[cfg(target_os = "macos")]
+ {
+ decoder
+ .try_use_hw_device(
+ AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
+ Pixel::NV12,
+ )
+ .ok()
}
- }
+
+ #[cfg(not(target_os = "macos"))]
+ None
+ };
use ffmpeg::format::Pixel;
- use ffmpeg::software::scaling::{context::Context, flag::Flags};
- // Set initial scaler format based on hardware acceleration
- let mut scaler_input_format = format::Pixel::YUV420P;
- let mut scaler_ctx = ScalerContext::new(decoder.width(), decoder.height());
+ let mut scaler_input_format = hw_device
+ .as_ref()
+ .map(|d| d.pix_fmt)
+ .unwrap_or(decoder.format());
+
+ let mut scaler = ffmpeg::software::converter(
+ (decoder.width(), decoder.height()),
+ scaler_input_format,
+ Pixel::RGBA,
+ )
+ .unwrap();
let mut temp_frame = ffmpeg::frame::Video::empty();
- let mut frame_cache = FrameCache::new(FRAME_CACHE_SIZE);
+
+ let mut cache = BTreeMap::<u32, CachedFrame>::new();
+ // active frame is a frame that triggered decode.
+ // frames that are within render_more_margin of this frame won't trigger decode.
+ let mut last_active_frame = None::<u32>;
+
+ let mut last_decoded_frame = None::<u32>;
let mut last_sent_frame = None::<(u32, DecodedFrame)>;
- let mut reached_end = false;
let mut peekable_requests = PeekableReceiver { rx, peeked: None };
+
let mut packets = input.packets();
while let Ok(r) = peekable_requests.recv() {
match r {
VideoDecoderMessage::GetFrame(requested_frame, sender) => {
- if reached_end {
- if let Some((_, last_frame)) = &last_sent_frame {
- sender.send(Some(last_frame.clone())).ok();
- continue;
- }
- }
-
- if let Some(cached) = frame_cache.get(requested_frame) {
+ let mut sender = if let Some(cached) = cache.get_mut(&requested_frame) {
let data =
- cached.process(&mut scaler_input_format, &mut scaler_ctx, &decoder);
+ cached.process(&mut scaler_input_format, &mut scaler, &decoder);
+
sender.send(Some(data.clone())).ok();
last_sent_frame = Some((requested_frame, data));
continue;
+ } else {
+ Some(sender)
+ };
+
+ let cache_min = requested_frame.saturating_sub(FRAME_CACHE_SIZE as u32 / 2);
+ let cache_max = requested_frame + FRAME_CACHE_SIZE as u32 / 2;
+
+ if requested_frame <= 0
+ || last_sent_frame
+ .as_ref()
+ .map(|last| {
+ requested_frame < last.0 ||
+ // seek forward for big jumps. this threshold is arbitrary but should be derived from i-frames in future
+ requested_frame - last.0 > FRAME_CACHE_SIZE as u32
+ })
+ .unwrap_or(true)
+ {
+ let timestamp_us =
+ ((requested_frame as f32 / frame_rate.numerator() as f32)
+ * 1_000_000.0) as i64;
+ let position = timestamp_us.rescale((1, 1_000_000), rescale::TIME_BASE);
+
+ println!("seeking to {position} for frame {requested_frame}, last sent frame: {:?}", last_sent_frame.map(|(f, _)| f));
+
+ decoder.flush();
+ input.seek(position, ..position).unwrap();
+ cache.clear();
+ last_decoded_frame = None;
+ last_sent_frame = None;
+
+ packets = input.packets();
}
- let mut sender = Some(sender);
-
- 'packet_loop: while let Some((stream, packet)) = packets.next() {
- if stream.index() != input_stream_index {
+ // handle when requested_frame == last_decoded_frame or last_decoded_frame > requested_frame.
+ // the latter can occur when there are skips in frame numbers.
+ // in future we should alleviate this by using time + pts values instead of frame numbers.
+ if let Some((_, last_sent_frame)) = last_decoded_frame
+ .zip(last_sent_frame.as_ref())
+ .filter(|(last_decoded_frame, last_sent_frame)| {
+ last_sent_frame.0 < requested_frame
+ && requested_frame < *last_decoded_frame
+ })
+ {
+ if let Some(sender) = sender.take() {
+ sender.send(Some(last_sent_frame.1.clone())).ok();
continue;
}
+ }
+
+ last_active_frame = Some(requested_frame);
- decoder.send_packet(&packet).unwrap();
-
- while decoder.receive_frame(&mut temp_frame).is_ok() {
- let frame_number =
- pts_to_frame(temp_frame.pts().unwrap(), time_base);
- let cached_frame = CachedFrame {
- data: CachedFrameData::Raw(temp_frame.clone()),
- };
-
- frame_cache.insert(frame_number, cached_frame);
-
- if frame_number == requested_frame {
- if let Some(cached) = frame_cache.get(requested_frame) {
- let data = cached.process(
- &mut scaler_input_format,
- &mut scaler_ctx,
- &decoder,
- );
- if let Some(s) = sender.take() {
- s.send(Some(data.clone())).ok();
+ loop {
+ if peekable_requests.peek().is_some() {
+ break;
+ }
+ let Some((stream, packet)) = packets.next() else {
+ sender
+ .take()
+ .map(|s| s.send(last_sent_frame.clone().map(|f| f.1)));
+ break;
+ };
+
+ if stream.index() == input_stream_index {
+ let start_offset = stream.start_time();
+
+ decoder.send_packet(&packet).ok(); // decode failures are ok, we just fail to return a frame
+
+ let mut exit = false;
+
+ while decoder.receive_frame(&mut temp_frame).is_ok() {
+ let current_frame = pts_to_frame(
+ temp_frame.pts().unwrap() - start_offset,
+ time_base,
+ FPS,
+ );
+
+ last_decoded_frame = Some(current_frame);
+
+ // we repeat the similar section as above to do the check per-frame instead of just per-request
+ if let Some((_, last_sent_frame)) = last_decoded_frame
+ .zip(last_sent_frame.as_ref())
+ .filter(|(last_decoded_frame, last_sent_frame)| {
+ last_sent_frame.0 <= requested_frame
+ && requested_frame < *last_decoded_frame
+ })
+ {
+ if let Some(sender) = sender.take() {
+ sender.send(Some(last_sent_frame.1.clone())).ok();
}
- last_sent_frame = Some((requested_frame, data));
- break 'packet_loop;
}
+
+ let exceeds_cache_bounds = current_frame > cache_max;
+ let too_small_for_cache_bounds = current_frame < cache_min;
+
+ let hw_frame =
+ hw_device.as_ref().and_then(|d| d.get_hwframe(&temp_frame));
+
+ let frame = hw_frame.unwrap_or(std::mem::replace(
+ &mut temp_frame,
+ frame::Video::empty(),
+ ));
+
+ if !too_small_for_cache_bounds {
+ let mut cache_frame = CachedFrame {
+ data: CachedFrameData::Raw(frame),
+ };
+
+ if current_frame == requested_frame {
+ if let Some(sender) = sender.take() {
+ let data = cache_frame.process(
+ &mut scaler_input_format,
+ &mut scaler,
+ &decoder,
+ );
+ last_sent_frame =
+ Some((current_frame, data.clone()));
+ sender.send(Some(data)).ok();
+
+ break;
+ }
+ }
+
+ if cache.len() >= FRAME_CACHE_SIZE {
+ if let Some(last_active_frame) = &last_active_frame {
+ let frame = if requested_frame > *last_active_frame
+ {
+ *cache.keys().next().unwrap()
+ } else if requested_frame < *last_active_frame {
+ *cache.keys().next_back().unwrap()
+ } else {
+ let min = *cache.keys().min().unwrap();
+ let max = *cache.keys().max().unwrap();
+
+ if current_frame > max {
+ min
+ } else {
+ max
+ }
+ };
+
+ cache.remove(&frame);
+ } else {
+ cache.clear()
+ }
+ }
+
+ cache.insert(current_frame, cache_frame);
+ }
+
+ exit = exit || exceeds_cache_bounds;
}
- }
- }
- if sender.is_some() {
- reached_end = true;
- if let Some(s) = sender.take() {
- if let Some((_, last_frame)) = &last_sent_frame {
- s.send(Some(last_frame.clone())).ok();
- } else {
- s.send(None).ok();
+ if exit {
+ break;
}
}
}
+
+ if let Some(s) = sender.take() {
+ s.send(None).ok();
+ }
}
}
}
});
- AsyncVideoDecoderHandle {
- sender: tx,
- last_valid_frame: Arc::new(Mutex::new(None)),
- reached_end: Arc::new(Mutex::new(false)),
- }
+ AsyncVideoDecoderHandle { sender: tx }
}
}
#[derive(Clone)]
pub struct AsyncVideoDecoderHandle {
sender: mpsc::Sender<VideoDecoderMessage>,
- last_valid_frame: Arc<Mutex<Option<DecodedFrame>>>,
- reached_end: Arc<Mutex<bool>>,
}
impl AsyncVideoDecoderHandle {
- pub async fn get_frame(&self, frame_number: u32) -> Option<DecodedFrame> {
- // If we've already reached the end of the video, just return the last valid frame
- if *self.reached_end.lock().unwrap() {
- return self.last_valid_frame.lock().unwrap().clone();
- }
-
+ pub async fn get_frame(&self, time: u32) -> Option<Arc<Vec<u8>>> {
let (tx, rx) = tokio::sync::oneshot::channel();
self.sender
- .send(VideoDecoderMessage::GetFrame(frame_number, tx))
- .ok()?;
-
- // Wait for response with a timeout
- match tokio::time::timeout(std::time::Duration::from_secs(5), rx).await {
- Ok(Ok(frame)) => {
- if let Some(frame) = &frame {
- // Store this as the last valid frame
- *self.last_valid_frame.lock().unwrap() = Some(frame.clone());
- } else {
- // If we got no frame, we've reached the end
- *self.reached_end.lock().unwrap() = true;
- }
- // If we got no frame but have a last valid frame, return that instead
- frame.or_else(|| self.last_valid_frame.lock().unwrap().clone())
- }
- _ => {
- // On timeout, return last valid frame if we have one
- self.last_valid_frame.lock().unwrap().clone()
- }
- }
+ .send(VideoDecoderMessage::GetFrame(time, tx))
+ .unwrap();
+ let res = rx.await.ok().flatten();
+ res
}
}
@@ -426,15 +391,6 @@ impl<T> PeekableReceiver<T> {
}
}
- fn try_recv(&mut self) -> Result<T, mpsc::TryRecvError> {
- println!("try_recv");
- if let Some(value) = self.peeked.take() {
- Ok(value)
- } else {
- self.rx.try_recv()
- }
- }
-
fn recv(&mut self) -> Result<T, mpsc::RecvError> {
if let Some(value) = self.peeked.take() {
Ok(value)
@@ -472,125 +428,3 @@ fn ff_find_decoder(
Some(Codec::wrap(found))
}
}
-
-fn create_scaler(
- input_format: format::Pixel,
- width: u32,
- height: u32,
- output_format: format::Pixel,
-) -> scaling::Context {
- // Try different input/output format combinations in order of preference
- let format_combinations = [
- (input_format, output_format),
- (format::Pixel::YUV420P, output_format),
- (format::Pixel::YUV420P, format::Pixel::RGBA),
- (format::Pixel::YUV420P, format::Pixel::RGB24),
- (format::Pixel::YUV420P, format::Pixel::BGR24),
- ];
-
- // Try different scaling flags in order of quality/performance
- let scaling_flags = [
- scaling::Flags::BILINEAR,
- scaling::Flags::BICUBIC,
- scaling::Flags::POINT,
- scaling::Flags::FAST_BILINEAR,
- scaling::Flags::AREA,
- ];
-
- for (in_fmt, out_fmt) in format_combinations.iter() {
- for flags in scaling_flags.iter() {
- match scaling::Context::get(*in_fmt, width, height, *out_fmt, width, height, *flags) {
- Ok(context) => {
- log::info!(
- "Created scaler: {:?} -> {:?} with flags {:?}",
- in_fmt,
- out_fmt,
- flags
- );
- return context;
- }
- Err(e) => {
- log::debug!(
- "Failed to create scaler: {:?} -> {:?} with flags {:?}: {:?}",
- in_fmt,
- out_fmt,
- flags,
- e
- );
- continue;
- }
- }
- }
- }
-
- // Last resort: try with absolute minimal settings
- match scaling::Context::get(
- format::Pixel::YUV420P,
- width,
- height,
- format::Pixel::RGB24,
- width,
- height,
- scaling::Flags::POINT,
- ) {
- Ok(context) => {
- log::warn!("Using fallback RGB24 scaler with minimal settings");
- context
- }
- Err(e) => {
- log::error!("All scaler creation attempts failed. Last error: {:?}", e);
- panic!("Could not create scaler with any configuration");
- }
- }
-}
-
-unsafe extern "C" fn get_hw_format(
- ctx: *mut ffmpeg_sys_next::AVCodecContext,
- _pix_fmts: *const ffmpeg_sys_next::AVPixelFormat,
-) -> ffmpeg_sys_next::AVPixelFormat {
- (*ctx).sw_pix_fmt
-}
-
-struct ScalerContext {
- yuv_scaler: Option<scaling::Context>,
- rgba_scaler: scaling::Context,
- width: u32,
- height: u32,
-}
-
-impl ScalerContext {
- fn new(width: u32, height: u32) -> Self {
- let rgba_scaler = create_scaler(format::Pixel::YUV420P, width, height, format::Pixel::RGBA);
-
- Self {
- yuv_scaler: None,
- rgba_scaler,
- width,
- height,
- }
- }
-
- fn ensure_yuv_scaler(&mut self, input_format: format::Pixel) {
- if input_format != format::Pixel::YUV420P {
- self.yuv_scaler = Some(create_scaler(
- input_format,
- self.width,
- self.height,
- format::Pixel::YUV420P,
- ));
- }
- }
-
- fn check_dimensions(&mut self, width: u32, height: u32) -> bool {
- if width != self.width || height != self.height {
- self.width = width;
- self.height = height;
- self.rgba_scaler =
- create_scaler(format::Pixel::YUV420P, width, height, format::Pixel::RGBA);
- self.yuv_scaler = None;
- true
- } else {
- false
- }
- }
-}