Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

rendering error handling

Brendan Allancf890e1b93bb
diff --git a/Cargo.lock b/Cargo.lock
index d2842af87..f1a9c7635 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -771,6 +771,7 @@ dependencies = [
"image 0.25.2",
"mp4",
"tempfile",
+ "thiserror",
"tokio",
]
@@ -781,6 +782,7 @@ dependencies = [
"nix 0.29.0",
"tauri",
"tauri-plugin-shell",
+ "tokio",
]
[[package]]
@@ -881,6 +883,7 @@ dependencies = [
"nix 0.29.0",
"serde",
"specta",
+ "thiserror",
"tokio",
"wgpu",
]
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index f826c53e1..13d252c9b 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -23,12 +23,11 @@ use cap_editor::{EditorState, ProjectRecordings};
use cap_media::feeds::{AudioInputFeed, AudioInputSamplesSender};
use cap_media::sources::CaptureScreen;
use cap_media::{
- feeds::{AudioFrameBuffer, CameraFeed, CameraFrameSender},
+ feeds::{CameraFeed, CameraFrameSender},
sources::ScreenCaptureTarget,
};
use cap_project::{ProjectConfiguration, RecordingMeta, SharingMeta};
use cap_recording::RecordingOptions;
-use cap_rendering::ProjectUniforms;
use fake_window::FakeWindowBounds;
// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use general_settings::GeneralSettingsStore;
@@ -48,6 +47,7 @@ use std::{
sync::Arc, time::Duration,
};
use tauri::{AppHandle, Emitter, Manager, Runtime, State, WindowEvent};
+use tauri_plugin_dialog::DialogExt;
use tauri_plugin_notification::{NotificationExt, PermissionState};
use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
@@ -102,10 +102,7 @@ struct PreCreatedVideo {
}
impl App {
- pub fn set_current_recording(
- &mut self,
- actor: cap_recording::ActorHandle, /* new_value: InProgressRecording */
- ) {
+ pub fn set_current_recording(&mut self, actor: cap_recording::ActorHandle) {
let current_recording = self.current_recording.insert(actor);
CurrentRecordingChanged.emit(&self.handle).ok();
@@ -317,7 +314,7 @@ async fn get_current_recording(
}
#[derive(Serialize, Type, tauri_specta::Event, Clone)]
-pub struct CurrentRecordingChanged; // (JsonValue<Option<InProgressRecording>>);
+pub struct CurrentRecordingChanged;
async fn create_screenshot(
input: PathBuf,
@@ -518,7 +515,8 @@ async fn get_rendered_video_impl(
editor_instance.render_constants.clone(),
editor_instance.cursor.clone(),
)
- .await?;
+ .await
+ .map_err(|e| e.to_string())?;
Ok(output_path)
}
@@ -751,30 +749,8 @@ async fn create_editor_instance(
#[tauri::command]
#[specta::specta]
-async fn copy_rendered_video_to_clipboard(
- app: AppHandle,
- video_id: String,
- project: ProjectConfiguration,
-) -> Result<(), String> {
+async fn copy_video_to_clipboard(app: AppHandle, path: String) -> Result<(), String> {
println!("copying");
- let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
-
- let output_path = match get_rendered_video_impl(editor_instance, project, false).await {
- Ok(path) => {
- println!("Successfully retrieved rendered video path: {:?}", path);
- path
- }
- Err(e) => {
- println!("Failed to get rendered video: {}", e);
- notifications::send_notification(
- &app,
- notifications::NotificationType::VideoCopyFailed,
- );
- return Err(format!("Failed to get rendered video: {}", e));
- }
- };
-
- let output_path_str = output_path.to_str().unwrap();
#[cfg(target_os = "macos")]
{
@@ -788,7 +764,7 @@ async fn copy_rendered_video_to_clipboard(
let pasteboard: id = NSPasteboard::generalPasteboard(nil);
NSPasteboard::clearContents(pasteboard);
- let url_str = NSString::alloc(nil).init_str(output_path_str);
+ let url_str = NSString::alloc(nil).init_str(&path);
let url = NSURL::fileURLWithPath_(nil, url_str);
if url == nil {
@@ -1052,11 +1028,10 @@ enum RenderProgress {
#[specta::specta]
async fn render_to_file(
app: AppHandle,
- output_path: PathBuf,
video_id: String,
project: ProjectConfiguration,
progress_channel: tauri::ipc::Channel<RenderProgress>,
-) {
+) -> Result<PathBuf, String> {
let (duration, _size) =
get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen))
.await
@@ -1067,9 +1042,14 @@ async fn render_to_file(
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
+ let output_path = editor_instance
+ .project_path
+ .join("output")
+ .join("result.mp4");
+
cap_export::export_video_to_file(
project,
- output_path,
+ output_path.clone(),
move |current_frame| {
if current_frame == 0 {
progress_channel
@@ -1087,9 +1067,11 @@ async fn render_to_file(
editor_instance.cursor.clone(),
)
.await
- .ok();
+ .map_err(|e| e.to_string())?;
ShowCapturesPanel.emit(&app).ok();
+
+ Ok(output_path)
}
#[tauri::command]
@@ -1825,7 +1807,7 @@ pub async fn run() {
render_to_file,
get_rendered_video,
copy_file_to_path,
- copy_rendered_video_to_clipboard,
+ copy_video_to_clipboard,
copy_screenshot_to_clipboard,
open_file_path,
get_video_metadata,
@@ -1858,6 +1840,7 @@ pub async fn run() {
send_feedback_request,
windows::position_traffic_lights,
reupload_rendered_video,
+ global_message_dialog
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
@@ -2370,3 +2353,9 @@ async fn reupload_rendered_video(
}
}
}
+
+#[tauri::command]
+#[specta::specta]
+fn global_message_dialog(app: AppHandle, message: String) {
+ app.dialog().message(message).show(|_| {});
+}
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index bbf36b5af..d62ca949e 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -287,7 +287,7 @@ impl ShowCapWindow {
.accept_first_mouse(true)
.content_protected(true)
.inner_size(
- 350.0,
+ (monitor.size().width as f64) / monitor.scale_factor(),
(monitor.size().height as f64) / monitor.scale_factor(),
)
.skip_taskbar(true)
diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx
index 31bb9f0f3..cbdb5987c 100644
--- a/apps/desktop/src/App.tsx
+++ b/apps/desktop/src/App.tsx
@@ -2,16 +2,19 @@ import { Router, useCurrentMatches } from "@solidjs/router";
import { FileRoutes } from "@solidjs/start/router";
import { ErrorBoundary, onMount, Suspense } from "solid-js";
import { QueryClient, QueryClientProvider } from "@tanstack/solid-query";
+import { getCurrentWindow } from "@tauri-apps/api/window";
+import { message } from "@tauri-apps/plugin-dialog";
import "@cap/ui-solid/main.css";
import "unfonts.css";
-import { getCurrentWindow } from "@tauri-apps/api/window";
+import { commands } from "./utils/tauri";
const queryClient = new QueryClient({
defaultOptions: {
mutations: {
- onError: (e) =>
- alert("An error occured, here are the details:\n" + e.toString()),
+ onError: (e) => {
+ message(`An error occured, here are the details:\n${e}`);
+ },
},
},
});
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index 262b6854a..5a3cc2ff0 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -195,70 +195,63 @@ import { initializeTitlebar, setTitlebar } from "~/utils/titlebar-state";
function ExportButton() {
const { videoId, project, prettyName } = useEditorContext();
- return (
- <>
- <Button
- variant="primary"
- size="md"
- onClick={() => {
- save({
- filters: [{ name: "mp4 filter", extensions: ["mp4"] }],
- defaultPath: `~/Desktop/${prettyName()}.mp4`,
- }).then((p) => {
- if (!p) return;
-
- setProgressState({
- type: "saving",
- progress: 0,
- renderProgress: 0,
- totalFrames: 0,
- message: "Preparing to render...",
- mediaPath: p,
- stage: "rendering",
- });
-
- const progress = new Channel<RenderProgress>();
- progress.onmessage = (p) => {
- if (
- p.type === "FrameRendered" &&
- progressState.type === "saving"
- ) {
- setProgressState({
- ...progressState,
- renderProgress: p.current_frame,
- });
- }
- if (
- p.type === "EstimatedTotalFrames" &&
- progressState.type === "saving"
- ) {
- setProgressState({
- ...progressState,
- totalFrames: p.total_frames,
- });
- }
- };
-
- return commands
- .renderToFile(p, videoId, project, progress)
- .then(() => {
- setProgressState({
- type: "saving",
- progress: 100,
- message: "Saved successfully!",
- mediaPath: p,
- });
-
- setTimeout(() => {
- setProgressState({ type: "idle" });
- }, 1500);
- });
+ const exportVideo = createMutation(() => ({
+ mutationFn: async () => {
+ const path = await save({
+ filters: [{ name: "mp4 filter", extensions: ["mp4"] }],
+ defaultPath: `~/Desktop/${prettyName()}.mp4`,
+ });
+ if (!path) return;
+
+ setProgressState({
+ type: "saving",
+ progress: 0,
+ renderProgress: 0,
+ totalFrames: 0,
+ message: "Preparing to render...",
+ mediaPath: p,
+ stage: "rendering",
+ });
+
+ const progress = new Channel<RenderProgress>();
+ progress.onmessage = (p) => {
+ if (p.type === "FrameRendered" && progressState.type === "saving") {
+ setProgressState({
+ ...progressState,
+ renderProgress: p.current_frame,
});
- }}
- >
- Export
- </Button>
- </>
+ }
+ if (
+ p.type === "EstimatedTotalFrames" &&
+ progressState.type === "saving"
+ ) {
+ setProgressState({
+ ...progressState,
+ totalFrames: p.total_frames,
+ });
+ }
+ };
+
+ const videoPath = await commands.renderToFile(videoId, project, progress);
+ await commands.copyFileToPath(videoPath, path);
+
+ setProgressState({
+ type: "saving",
+ progress: 100,
+ message: "Saved successfully!",
+ mediaPath: path,
+ });
+
+ setTimeout(() => {
+ setProgressState({ type: "idle" });
+ }, 1500);
+ },
+ }));
+
+ return (
+ <Button variant="primary" size="md" onClick={() => exportVideo.mutate()}>
+ Export
+ </Button>
);
}
diff --git a/apps/desktop/src/routes/prev-recordings.tsx b/apps/desktop/src/routes/prev-recordings.tsx
index c634e4ef1..6345d250f 100644
--- a/apps/desktop/src/routes/prev-recordings.tsx
+++ b/apps/desktop/src/routes/prev-recordings.tsx
@@ -27,7 +27,6 @@ import { Channel } from "@tauri-apps/api/core";
import {
commands,
events,
- Result,
UploadResult,
type RenderProgress,
} from "~/utils/tauri";
@@ -132,7 +131,7 @@ export default function () {
return (
<div
- class="w-screen h-[100vh] bg-transparent relative"
+ class="w-screen h-[100vh] bg-transparent relative overflow-y-hidden"
style={{
"scrollbar-color": "auto transparent",
}}
@@ -147,7 +146,7 @@ export default function () {
exitActiveClass="absolute"
>
<For each={allMedia()}>
- {(media) => {
+ {(media, i) => {
const [ref, setRef] = createSignal<HTMLElement | null>(null);
const normalizedPath = media.path.replace(/\\/g, "/");
const mediaId = normalizedPath.split("/").pop()?.split(".")[0]!;
@@ -186,66 +185,49 @@ export default function () {
try {
if (isRecording) {
- const output_path = await commands.getRenderedVideo(
+ console.log("Setting up render progress channel");
+ const progress = new Channel<RenderProgress>();
+ progress.onmessage = (p) => {
+ console.log("Progress channel message:", p);
+ if (
+ p.type === "FrameRendered" &&
+ progressState.type === "copying"
+ ) {
+ console.log(
+ "Frame rendered in copy:",
+ p.current_frame,
+ "Current state:",
+ progressState
+ );
+ setProgressState({
+ ...progressState,
+ renderProgress: p.current_frame,
+ });
+ }
+ if (
+ p.type === "EstimatedTotalFrames" &&
+ progressState.type === "copying"
+ ) {
+ console.log(
+ "Got total frames in copy:",
+ p.total_frames
+ );
+ setProgressState({
+ ...progressState,
+ totalFrames: p.total_frames,
+ });
+ }
+ };
+
+ console.log("Starting render to file");
+ const outputPath = await commands.renderToFile(
mediaId,
- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,
+ progress
);
+ console.log("Render to file completed");
- if (output_path) {
- await commands.copyRenderedVideoToClipboard(
- mediaId,
- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
- );
- } else {
- console.log("Setting up render progress channel");
- const progress = new Channel<RenderProgress>();
- progress.onmessage = (p) => {
- console.log("Progress channel message:", p);
- if (
- p.type === "FrameRendered" &&
- progressState.type === "copying"
- ) {
- console.log(
- "Frame rendered in copy:",
- p.current_frame,
- "Current state:",
- progressState
- );
- setProgressState({
- ...progressState,
- renderProgress: p.current_frame,
- });
- }
- if (
- p.type === "EstimatedTotalFrames" &&
- progressState.type === "copying"
- ) {
- console.log(
- "Got total frames in copy:",
- p.total_frames
- );
- setProgressState({
- ...progressState,
- totalFrames: p.total_frames,
- });
- }
- };
-
- console.log("Starting render to file");
- await commands.renderToFile(
- output_path,
- mediaId,
- presets.getDefaultConfig() ??
- DEFAULT_PROJECT_CONFIG,
- progress
- );
- console.log("Render to file completed");
-
- await commands.copyRenderedVideoToClipboard(
- mediaId,
- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
- );
- }
+ await commands.copyVideoToClipboard(outputPath);
} else {
await commands.copyScreenshotToClipboard(media.path);
}
@@ -332,13 +314,7 @@ export default function () {
}
};
- const output_path = await commands.getRenderedVideo(
- mediaId,
- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
- );
-
- await commands.renderToFile(
- output_path,
+ const output_path = await commands.renderToFile(
mediaId,
presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,
progress
@@ -433,13 +409,7 @@ export default function () {
}
};
- const output_path = await commands.getRenderedVideo(
- mediaId,
- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
- );
-
await commands.renderToFile(
- output_path,
mediaId,
presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,
progress
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index ede99e8a3..6d5290341 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -56,8 +56,8 @@ async focusCapturesPanel() : Promise<void> {
async getCurrentRecording() : Promise<JsonValue<RecordingInfo | null>> {
return await TAURI_INVOKE("get_current_recording");
},
-async renderToFile(outputPath: string, videoId: string, project: ProjectConfiguration, progressChannel: TAURI_CHANNEL<RenderProgress>) : Promise<void> {
- await TAURI_INVOKE("render_to_file", { outputPath, videoId, project, progressChannel });
+async renderToFile(videoId: string, project: ProjectConfiguration, progressChannel: TAURI_CHANNEL<RenderProgress>) : Promise<string> {
+ return await TAURI_INVOKE("render_to_file", { videoId, project, progressChannel });
},
async getRenderedVideo(videoId: string, project: ProjectConfiguration) : Promise<string> {
return await TAURI_INVOKE("get_rendered_video", { videoId, project });
@@ -65,8 +65,8 @@ async getRenderedVideo(videoId: string, project: ProjectConfiguration) : Promise
async copyFileToPath(src: string, dst: string) : Promise<null> {
return await TAURI_INVOKE("copy_file_to_path", { src, dst });
},
-async copyRenderedVideoToClipboard(videoId: string, project: ProjectConfiguration) : Promise<null> {
- return await TAURI_INVOKE("copy_rendered_video_to_clipboard", { videoId, project });
+async copyVideoToClipboard(path: string) : Promise<null> {
+ return await TAURI_INVOKE("copy_video_to_clipboard", { path });
},
async copyScreenshotToClipboard(path: string) : Promise<null> {
return await TAURI_INVOKE("copy_screenshot_to_clipboard", { path });
@@ -163,6 +163,9 @@ async positionTrafficLights(controlsInset: [number, number] | null) : Promise<vo
},
async reuploadRenderedVideo(videoId: string, project: ProjectConfiguration) : Promise<UploadResult> {
return await TAURI_INVOKE("reupload_rendered_video", { videoId, project });
+},
+async globalMessageDialog(message: string) : Promise<void> {
+ await TAURI_INVOKE("global_message_dialog", { message });
}
}
diff --git a/crates/editor/Cargo.toml b/crates/editor/Cargo.toml
index f512a7a6b..581d39748 100644
--- a/crates/editor/Cargo.toml
+++ b/crates/editor/Cargo.toml
@@ -9,7 +9,7 @@ cap-media = { path = "../media" }
cap-project = { path = "../project" }
cap-rendering = { path = "../rendering" }
-tokio = { version = "1.39.2", features = ["macros", "process", "fs"] }
+tokio = { workspace = true, features = ["macros", "process", "fs"] }
cpal.workspace = true
axum = { version = "0.7.5", features = ["ws"] }
ffmpeg.workspace = true
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
index 2b18bd36e..05e66a54c 100644
--- a/crates/export/Cargo.toml
+++ b/crates/export/Cargo.toml
@@ -16,3 +16,4 @@ tokio.workspace = true
tempfile = "3.12.0"
image = "0.25.2"
mp4 = "0.14.0"
+thiserror.workspace = true
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index f6b40935a..f4b41cc8c 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -13,6 +13,21 @@ struct AudioRender {
const FPS: u32 = 30;
+#[derive(thiserror::Error, Debug)]
+pub enum ExportError {
+ #[error("FFmpeg: {0}")]
+ FFmpeg(String),
+
+ #[error("IO: {0}")]
+ IO(#[from] std::io::Error),
+
+ #[error("FFmpeg Task: {0}")]
+ FFmpegTask(#[from] tokio::task::JoinError),
+
+ #[error("Rendering: {0}")]
+ Rendering(#[from] cap_rendering::RenderingError),
+}
+
pub async fn export_video_to_file(
project: ProjectConfiguration,
output_path: PathBuf,
@@ -22,18 +37,16 @@ pub async fn export_video_to_file(
meta: RecordingMeta,
render_constants: Arc<RenderVideoConstants>,
cursor: Arc<CursorData>,
-) -> Result<PathBuf, String> {
+) -> Result<PathBuf, ExportError> {
let (tx_image_data, mut rx_image_data) = tokio::sync::mpsc::channel::<Vec<u8>>(4);
let output_folder = output_path.parent().unwrap();
- std::fs::create_dir_all(output_folder)
- .map_err(|e| format!("Failed to create output directory: {:?}", e))?;
+ std::fs::create_dir_all(output_folder)?;
let output_size = ProjectUniforms::get_output_size(&render_constants.options, &project);
let ffmpeg_handle = tokio::spawn({
let project = project.clone();
- let output_path = output_path.clone();
let project_path = project_path.clone();
async move {
println!("Starting FFmpeg output process...");
@@ -95,44 +108,65 @@ pub async fn export_video_to_file(
let mut first_frame = None;
loop {
- match rx_image_data.recv().await {
- Some(frame) => {
- 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());
+ tokio::select! {
+ result = ffmpeg_process.wait() => {
+ match result {
+ Err(e) => Err(ExportError::FFmpeg(e.to_string())),
+ Ok(status) => {
+ if status.success() {
+ Ok(())
+ } else {
+ Err(ExportError::FFmpeg(
+ ffmpeg_process
+ .read_stderr()
+ .await
+ .unwrap_or_else(|_| "Failed to read FFmpegg error".to_string())
+ ))
+ }
}
-
- 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 frame_samples = frame_data.to_vec();
- audio.pipe_tx.send(frame_samples).await.unwrap();
+ }?;
+ }
+ frame = rx_image_data.recv() => {
+ match frame {
+ Some(frame) => {
+ 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 frame_samples = frame_data.to_vec();
+ audio.pipe_tx.send(frame_samples).await.unwrap();
+ }
+ }
+
+ video_tx.send(frame).await.unwrap();
+
+ frame_count += 1;
+ }
+ None => {
+ println!("All frames sent to FFmpeg");
+ break;
}
}
-
- video_tx.send(frame).await.unwrap();
-
- frame_count += 1;
- }
- None => {
- println!("All frames sent to FFmpeg");
- break;
}
}
}
- ffmpeg_process.stop();
+ ffmpeg_process.stop().await;
// Save the first frame as a screenshot and thumbnail
if let Some(frame_data) = first_frame {
@@ -174,6 +208,8 @@ pub async fn export_video_to_file(
} else {
eprintln!("No frames were processed, cannot save screenshot or thumbnail");
}
+
+ Ok::<_, ExportError>(output_path)
}
});
@@ -191,7 +227,7 @@ pub async fn export_video_to_file(
)
.await?;
- ffmpeg_handle.await.ok();
+ let output_path = ffmpeg_handle.await??;
println!("Copying file to {:?}", project_path);
let result_path = project_path.join("output").join("result.mp4");
diff --git a/crates/ffmpeg-cli/Cargo.toml b/crates/ffmpeg-cli/Cargo.toml
index 6a92cf9d5..4181231f9 100644
--- a/crates/ffmpeg-cli/Cargo.toml
+++ b/crates/ffmpeg-cli/Cargo.toml
@@ -6,6 +6,7 @@ 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
index e47a86e74..6a8bc532e 100644
--- a/crates/ffmpeg-cli/src/lib.rs
+++ b/crates/ffmpeg-cli/src/lib.rs
@@ -3,12 +3,17 @@ use std::{
io::{Read, Write},
ops::Deref,
path::{Path, PathBuf},
- process::{Child, ChildStdin, Command, Stdio},
+ 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,
}
@@ -21,32 +26,55 @@ impl FFmpegProcess {
command.creation_flags(CREATE_NO_WINDOW);
}
- let mut cmd = command.stdin(Stdio::piped()).spawn().unwrap_or_else(|e| {
- println!("Failed to start FFmpeg: {}", e);
- println!("Command: {:?}", command);
- panic!("Failed to start FFmpeg");
- });
+ 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");
});
- Self { ffmpeg_stdin, cmd }
+ 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 fn write(&mut self, data: &[u8]) -> std::io::Result<()> {
- self.ffmpeg_stdin.write_all(data)
+ pub async fn write(&mut self, data: &[u8]) -> std::io::Result<()> {
+ self.ffmpeg_stdin.write_all(data).await
}
- pub fn stop(&mut self) {
- self.ffmpeg_stdin.write_all(b"q").ok();
- self.ffmpeg_stdin.flush().ok();
+ 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 fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
- self.cmd.wait()
+ 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) {
@@ -69,12 +97,19 @@ impl FFmpegProcess {
Ok(None)
}
- pub fn read_video_frame(
+ 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) {
+ match self
+ .cmd
+ .stdout
+ .as_mut()
+ .unwrap()
+ .read_exact(&mut buffer)
+ .await
+ {
Ok(_) => {
println!("Read video frame of size: {}", buffer.len());
Ok(Some(buffer))
@@ -84,10 +119,10 @@ impl FFmpegProcess {
}
}
- pub fn write_video_frame(&mut self, data: &[u8]) -> std::io::Result<()> {
+ 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) {
+ match self.ffmpeg_stdin.write(remaining).await {
Ok(0) => {
return Err(std::io::Error::new(
std::io::ErrorKind::WriteZero,
@@ -105,7 +140,7 @@ impl FFmpegProcess {
}
}
}
- self.ffmpeg_stdin.flush()?;
+ self.ffmpeg_stdin.flush().await?;
Ok(())
}
@@ -114,7 +149,10 @@ impl FFmpegProcess {
{
use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;
- kill(Pid::from_raw(self.cmd.id() as i32), Signal::SIGSTOP)?;
+ kill(
+ Pid::from_raw(self.cmd.id().unwrap() as i32),
+ Signal::SIGSTOP,
+ )?;
println!("Sent SIGSTOP to FFmpeg");
}
Ok(())
@@ -125,7 +163,10 @@ impl FFmpegProcess {
{
use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;
- kill(Pid::from_raw(self.cmd.id() as i32), Signal::SIGCONT)?;
+ kill(
+ Pid::from_raw(self.cmd.id().unwrap() as i32),
+ Signal::SIGCONT,
+ )?;
println!("Sent SIGCONT to FFmpeg");
}
Ok(())
@@ -237,8 +278,11 @@ impl Default for FFmpeg {
impl FFmpeg {
pub fn new() -> Self {
+ let mut command = Command::new(relative_command_path("ffmpeg").unwrap());
+ command.arg("-hide_banner");
+
Self {
- command: Command::new(relative_command_path("ffmpeg").unwrap()),
+ command,
source_index: 0,
}
}
diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs
index a11b47591..da36d9d13 100644
--- a/crates/recording/src/lib.rs
+++ b/crates/recording/src/lib.rs
@@ -4,17 +4,8 @@ mod segmented_actor;
pub use actor::{spawn_recording_actor, ActorHandle, RecordingError};
-use cap_media::{pipeline::*, sources::*};
-use cap_project::{CursorClickEvent, CursorMoveEvent};
+use cap_media::sources::*;
use serde::{Deserialize, Serialize};
-use specta::Type;
-use std::path::PathBuf;
-use std::sync::atomic::AtomicBool;
-use std::sync::Arc;
-use tokio::sync::oneshot;
-
-// TODO: Hacky, please fix
-pub const FPS: u32 = 30;
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
@@ -33,50 +24,3 @@ impl RecordingOptions {
self.audio_input_name.as_deref()
}
}
-
-#[derive(Type, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct InProgressRecording {
- pub id: String,
- pub recording_dir: PathBuf,
- #[serde(skip)]
- pub pipeline: Pipeline<RealTimeClock<()>>,
- #[serde(skip)]
- pub display_output_path: PathBuf,
- #[serde(skip)]
- pub camera_output_path: Option<PathBuf>,
- #[serde(skip)]
- pub audio_output_path: Option<PathBuf>,
- pub display_source: ScreenCaptureTarget,
- pub segments: Vec<f64>,
- #[serde(skip)]
- pub cursor_moves: oneshot::Receiver<Vec<CursorMoveEvent>>,
- #[serde(skip)]
- pub cursor_clicks: oneshot::Receiver<Vec<CursorClickEvent>>,
- #[serde(skip)]
- pub stop_signal: Arc<AtomicBool>,
-}
-
-impl InProgressRecording {
- pub async fn stop_and_discard(&mut self) {
- // Signal the mouse event tracking to stop
- if let Err(error) = self.pipeline.shutdown().await {
- eprintln!("Error while stopping recording: {error}");
- }
-
- // Delete all recorded files
- if let Err(e) = std::fs::remove_dir_all(&self.recording_dir) {
- eprintln!("Failed to delete recording directory: {:?}", e);
- }
- }
-
- // pub async fn pause(&mut self) -> Result<(), String> {
- // let _ = self.pipeline.pause().await;
- // Ok(())
- // }
-
- pub async fn play(&mut self) -> Result<(), String> {
- let _ = self.pipeline.play().await;
- Ok(())
- }
-}
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 6e5ec953c..383bc8be3 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -18,6 +18,7 @@ tokio.workspace = true
ffmpeg.workspace = true
ffmpeg-sys-next.workspace = true
futures = "0.3.30"
+thiserror.workspace = true
[target.'cfg(unix)'.dependencies]
nix = { version = "0.29.0", features = ["fs"] }
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index d3e3083d0..8a61d1c70 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -8,6 +8,7 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::ops::{Add, Deref, Mul, Sub};
use std::{collections::HashMap, sync::Arc};
+use tokio::sync::mpsc;
use wgpu::util::DeviceExt;
use wgpu::{CommandEncoder, COPY_BYTES_PER_ROW_ALIGNMENT};
@@ -121,6 +122,20 @@ impl RecordingDecoders {
}
}
+#[derive(thiserror::Error, Debug)]
+pub enum RenderingError {
+ #[error("No GPU adapter found")]
+ NoAdapter,
+ #[error(transparent)]
+ RequestDeviceFailed(#[from] wgpu::RequestDeviceError),
+ #[error("Failed to wait for buffer mapping")]
+ BufferMapWaitingFailed,
+ #[error(transparent)]
+ BufferMapFailed(#[from] wgpu::BufferAsyncError),
+ #[error("Sending frame to channel failed")]
+ ChannelSendFrameFailed(#[from] mpsc::error::SendError<Vec<u8>>),
+}
+
pub async fn render_video_to_channel(
options: RenderOptions,
project: ProjectConfiguration,
@@ -128,7 +143,7 @@ pub async fn render_video_to_channel(
decoders: RecordingDecoders,
cursor: Arc<CursorData>,
project_path: PathBuf, // Add project_path parameter
-) -> Result<(), String> {
+) -> Result<(), RenderingError> {
let constants = RenderVideoConstants::new(options, cursor, project_path).await?;
println!("Setting up FFmpeg input for screen recording...");
@@ -139,72 +154,59 @@ pub async fn render_video_to_channel(
let duration = project.timeline().map(|t| t.duration()).unwrap_or(f64::MAX);
- let render_handle: tokio::task::JoinHandle<Result<u32, String>> = tokio::spawn(async move {
- let mut frame_number = 0;
+ let mut frame_number = 0;
- let background = Background::from(project.background.source.clone());
+ let background = Background::from(project.background.source.clone());
- loop {
- if frame_number as f64 > 30_f64 * duration {
- break;
- };
+ Err(RenderingError::NoAdapter)?;
- let time = if let Some(timeline) = project.timeline() {
- match timeline.get_recording_time(frame_number as f64 / 30_f64) {
- Some(time) => time,
- None => break,
- }
- } else {
- frame_number as f64 / 30_f64
- };
+ loop {
+ if frame_number as f64 > 30_f64 * duration {
+ break;
+ };
- let uniforms = ProjectUniforms::new(&constants, &project, time as f32);
+ let time = if let Some(timeline) = project.timeline() {
+ match timeline.get_recording_time(frame_number as f64 / 30_f64) {
+ Some(time) => time,
+ None => break,
+ }
+ } else {
+ frame_number as f64 / 30_f64
+ };
- let Some((screen_frame, camera_frame)) =
- decoders.get_frames((time * 30.0) as u32).await
- else {
- break;
- };
+ let uniforms = ProjectUniforms::new(&constants, &project, time as f32);
- let frame = match produce_frame(
- &constants,
- &screen_frame,
- &camera_frame,
- background,
- &uniforms,
- time as f32,
- )
- .await
- {
- Ok(frame) => frame,
- Err(e) => {
- eprintln!("{e}");
- break;
- }
- };
+ let Some((screen_frame, camera_frame)) = decoders.get_frames((time * 30.0) as u32).await
+ else {
+ break;
+ };
- if sender.send(frame).await.is_err() {
- eprintln!("Failed to send processed frame to channel");
- break;
- }
+ let frame = produce_frame(
+ &constants,
+ &screen_frame,
+ &camera_frame,
+ background,
+ &uniforms,
+ time as f32,
+ )
+ .await?;
- frame_number += 1;
- if frame_number % 60 == 0 {
- let elapsed = start_time.elapsed();
- println!(
- "Rendered {} frames in {:?} seconds",
- frame_number,
- elapsed.as_secs_f32()
- );
- }
- }
+ sender.send(frame).await?;
- println!("Render loop exited");
+ frame_number += 1;
+ if frame_number % 60 == 0 {
+ let elapsed = start_time.elapsed();
+ println!(
+ "Rendered {} frames in {:?} seconds",
+ frame_number,
+ elapsed.as_secs_f32()
+ );
+ }
+ }
- Ok(frame_number)
- });
+ println!("Render loop exited");
- let total_frames = render_handle.await.map_err(|e| e.to_string())??;
+ let total_frames = frame_number;
let total_time = start_time.elapsed();
println!(
@@ -234,20 +236,19 @@ impl RenderVideoConstants {
options: RenderOptions,
cursor: Arc<CursorData>,
project_path: PathBuf, // Add project_path parameter
- ) -> Result<Self, String> {
+ ) -> Result<Self, RenderingError> {
println!("Initializing wgpu...");
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions::default())
.await
- .unwrap();
+ .ok_or(RenderingError::NoAdapter)?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor::default(), None)
- .await
- .map_err(|e| e.to_string())?;
+ .await?;
// Pass project_path to load_cursor_textures
- let cursor_textures = Self::load_cursor_textures(&device, &queue, &cursor, &project_path)?;
+ let cursor_textures = Self::load_cursor_textures(&device, &queue, &cursor, &project_path);
let cursor_pipeline = CursorPipeline::new(&device);
@@ -270,7 +271,7 @@ impl RenderVideoConstants {
queue: &wgpu::Queue,
cursor: &CursorData,
project_path: &PathBuf, // Add project_path parameter
- ) -> Result<HashMap<String, wgpu::Texture>, String> {
+ ) -> HashMap<String, wgpu::Texture> {
println!("Starting to load cursor textures");
println!("Project path: {:?}", project_path);
println!("Cursor images to load: {:?}", cursor.cursor_images);
@@ -353,7 +354,7 @@ impl RenderVideoConstants {
"Completed loading cursor textures. Total loaded: {}",
textures.len()
);
- Ok(textures)
+ textures
}
}
@@ -767,7 +768,7 @@ pub async fn produce_frame(
background: Background,
uniforms: &ProjectUniforms,
time: f32,
-) -> Result<Vec<u8>, String> {
+) -> Result<Vec<u8>, RenderingError> {
let mut encoder = constants.device.create_command_encoder(
&(wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
@@ -1026,13 +1027,9 @@ pub async fn produce_frame(
});
constants.device.poll(wgpu::Maintain::Wait);
- let Some(frame_result) = rx.receive().await else {
- return Err("2: Channel closed unexpectedly".to_string());
- };
-
- if let Err(e) = frame_result {
- return Err(format!("Failed to map buffer: {:?}", e));
- }
+ rx.receive()
+ .await
+ .ok_or(RenderingError::BufferMapWaitingFailed)??;
let data = buffer_slice.get_mapped_range();
let padded_data: Vec<u8> = data.to_vec(); // Ensure the type is Vec<u8>
diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs
index 42de8d9be..567b04fd5 100644
--- a/crates/utils/src/lib.rs
+++ b/crates/utils/src/lib.rs
@@ -1,4 +1,4 @@
-use std::{ffi::OsString, path::PathBuf};
+use std::{ffi::OsString, fs::OpenOptions, path::PathBuf};
#[cfg(windows)]
pub fn get_last_win32_error_formatted() -> String {
@@ -52,14 +52,19 @@ pub fn create_channel_named_pipe(
let path = unix_path.clone();
tokio::spawn(async move {
- let mut file = std::fs::File::create(&path).unwrap();
+ let mut file = OpenOptions::new()
+ .write(true)
+ .create(false)
+ .truncate(true)
+ .open(&path)?;
println!("video pipe opened");
while let Some(bytes) = rx.recv().await {
- file.write_all(&bytes).unwrap();
+ file.write_all(&bytes)?;
}
println!("done writing to video pipe");
+ Ok::<(), std::io::Error>(())
});
unix_path.into_os_string()