Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

isolate export crate + decoders

Brendan Allance3cf6a3653f
diff --git a/Cargo.lock b/Cargo.lock
index 2d6e36b91..17444bee2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -766,6 +766,23 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "cap-export"
+version = "0.1.0"
+dependencies = [
+ "cap-editor",
+ "cap-ffmpeg-cli",
+ "cap-flags",
+ "cap-media",
+ "cap-project",
+ "cap-rendering",
+ "cap-utils",
+ "image 0.25.2",
+ "mp4",
+ "tempfile",
+ "tokio",
+]
+
[[package]]
name = "cap-ffmpeg-cli"
version = "0.1.0"
@@ -1680,6 +1697,7 @@ dependencies = [
"base64 0.22.1",
"bytemuck",
"cap-editor",
+ "cap-export",
"cap-ffmpeg-cli",
"cap-flags",
"cap-media",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 9d0c5b0f7..d5ed00620 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -35,6 +35,7 @@ tauri-plugin-notification = "2.0.0-rc"
tauri-plugin-oauth = { git = "https://github.com/FabianLars/tauri-plugin-oauth", branch = "v2" }
tauri-plugin-global-shortcut = "2.0.0"
tauri-plugin-single-instance = "2.0.1"
+tauri-plugin-http = "2.0.0-rc.0"
tauri-specta = { version = "=2.0.0-rc.20", features = ["derive", "typescript"] }
serde = { version = "1", features = ["derive"] }
@@ -53,7 +54,6 @@ image = "0.25.2"
tauri-plugin-fs = "2.0.0-rc.0"
futures-intrusive = "0.5.0"
anyhow.workspace = true
-mp4 = "0.14.0"
futures = "0.3"
axum = { version = "0.7.5", features = ["ws"] }
tracing = "0.1.40"
@@ -67,6 +67,13 @@ fast_image_resize = "4.2.1"
png = "0.17.13"
device_query = "2.1.0"
base64 = "0.22.1"
+reqwest = { version = "0.12.7", features = ["json", "stream", "multipart"] }
+dotenvy_macro = "0.15.7"
+global-hotkey = "0.6.3"
+rand = "0.8.5"
+cpal.workspace = true
+keyed_priority_queue = "0.4.2"
+mp4 = "0.14.0"
cap-utils = { path = "../../../crates/utils" }
cap-project = { path = "../../../crates/project" }
@@ -75,13 +82,7 @@ cap-ffmpeg-cli = { path = "../../../crates/ffmpeg-cli" }
cap-editor = { path = "../../../crates/editor" }
cap-media = { path = "../../../crates/media" }
cap-flags = { path = "../../../crates/flags" }
-reqwest = { version = "0.12.7", features = ["json", "stream", "multipart"] }
-dotenvy_macro = "0.15.7"
-global-hotkey = "0.6.3"
-tauri-plugin-http = "2.0.0-rc.0"
-rand = "0.8.5"
-cpal.workspace = true
-keyed_priority_queue = "0.4.2"
+cap-export = { path = "../../../crates/export" }
[target.'cfg(target_os = "macos")'.dependencies]
core-graphics = "0.24.0"
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 74583cdab..6f7fbeb5b 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -23,7 +23,7 @@ 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},
platform::Bounds,
sources::ScreenCaptureTarget,
};
@@ -31,15 +31,11 @@ use cap_project::{
ProjectConfiguration, RecordingMeta, SharingMeta, TimelineConfiguration, TimelineSegment,
ZoomSegment,
};
-use cap_rendering::{ProjectUniforms, ZOOM_DURATION};
-// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
+use cap_rendering::ZOOM_DURATION;
use general_settings::GeneralSettingsStore;
-use image::{ImageBuffer, Rgba};
use mp4::Mp4Reader;
use png::{ColorType, Encoder};
-use recording::{
- list_cameras, list_capture_screens, list_capture_windows, InProgressRecording, FPS,
-};
+use recording::{list_cameras, list_capture_screens, list_capture_windows, InProgressRecording};
use scap::capturer::Capturer;
use scap::frame::Frame;
use serde::{Deserialize, Serialize};
@@ -53,7 +49,7 @@ use std::{
collections::HashMap, marker::PhantomData, path::PathBuf, process::Command, sync::Arc,
time::Duration,
};
-use tauri::{AppHandle, Manager, Runtime, State, WindowEvent};
+use tauri::{AppHandle, Emitter, Manager, Runtime, State, WindowEvent};
use tauri_plugin_notification::{NotificationExt, PermissionState};
use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
@@ -833,7 +829,17 @@ async fn get_rendered_video_impl(
return Ok(output_path);
}
- render_to_file_impl(&editor_instance, project, output_path.clone(), |_| {}).await?;
+ cap_export::export_video_to_file(
+ project,
+ output_path.clone(),
+ |_| {},
+ &editor_instance.project_path,
+ editor_instance.audio.clone(),
+ editor_instance.meta(),
+ editor_instance.render_constants.clone(),
+ editor_instance.cursor.clone(),
+ )
+ .await?;
Ok(output_path)
}
@@ -987,235 +993,6 @@ async fn open_file_path(_app: AppHandle, path: PathBuf) -> Result<(), String> {
Ok(())
}
-struct AudioRender {
- buffer: AudioFrameBuffer,
- pipe_tx: tokio::sync::mpsc::Sender<Vec<u8>>,
-}
-
-async fn render_to_file_impl(
- editor_instance: &Arc<EditorInstance>,
- project: ProjectConfiguration,
- output_path: PathBuf,
- on_progress: impl Fn(u32) + Send + 'static,
-) -> Result<PathBuf, String> {
- let recording_dir = &editor_instance.project_path;
- let audio = editor_instance.audio.clone();
- let decoders = editor_instance.decoders.clone();
- let options = editor_instance.render_constants.options.clone();
-
- let (tx_image_data, mut rx_image_data) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
-
- let output_folder = output_path.parent().unwrap();
- std::fs::create_dir_all(output_folder)
- .map_err(|e| format!("Failed to create output directory: {:?}", e))?;
-
- let output_size = ProjectUniforms::get_output_size(&options, &project);
-
- let ffmpeg_handle = tokio::spawn({
- let project = project.clone();
- let output_path = output_path.clone();
- let recording_dir = recording_dir.clone();
- async move {
- println!("Starting FFmpeg output process...");
- let mut ffmpeg = cap_ffmpeg_cli::FFmpeg::new();
-
- let audio_dir = tempfile::tempdir().unwrap();
- let video_dir = tempfile::tempdir().unwrap();
- let mut audio = if let Some(audio_data) = audio.lock().unwrap().as_ref() {
- let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(30);
-
- let pipe_path =
- cap_utils::create_channel_named_pipe(rx, audio_dir.path().join("audio.pipe"));
-
- ffmpeg.add_input(cap_ffmpeg_cli::FFmpegRawAudioInput {
- input: pipe_path,
- sample_format: "f64le".to_string(),
- sample_rate: audio_data.info.sample_rate,
- channels: audio_data.info.channels as u16,
- });
-
- let buffer = AudioFrameBuffer::new(audio_data.clone());
- Some(AudioRender {
- buffer,
- pipe_tx: tx,
- })
- } else {
- None
- };
-
- let video_tx = {
- let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(30);
-
- let pipe_path =
- cap_utils::create_channel_named_pipe(rx, video_dir.path().join("video.pipe"));
-
- ffmpeg.add_input(cap_ffmpeg_cli::FFmpegRawVideoInput {
- width: output_size.0,
- height: output_size.1,
- fps: 30,
- pix_fmt: "rgba",
- input: pipe_path,
- });
-
- tx
- };
-
- ffmpeg
- .command
- .args(["-f", "mp4"])
- .args(["-codec:v", "libx264", "-codec:a", "aac"])
- .args(["-preset", "ultrafast"])
- .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
- .arg("-y")
- .arg(&output_path);
-
- let mut ffmpeg_process = ffmpeg.start();
-
- let mut frame_count = 0;
- 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());
- }
-
- 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;
- }
- }
- }
-
- ffmpeg_process.stop();
-
- // Save the first frame as a screenshot and thumbnail
- if let Some(frame_data) = first_frame {
- let width = output_size.0;
- let height = output_size.1;
- let rgba_img: ImageBuffer<Rgba<u8>, Vec<u8>> =
- ImageBuffer::from_raw(width, 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(width, height, |x, y| {
- let rgba = rgba_img.get_pixel(x, y);
- image::Rgb([rgba[0], rgba[1], rgba[2]])
- });
-
- let screenshots_dir = recording_dir.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);
- });
-
- // // Create and save thumbnail
- // let thumbnail = image::imageops::resize(
- // &rgb_img,
- // 100,
- // 100,
- // image::imageops::FilterType::Lanczos3,
- // );
- // let thumbnail_path = screenshots_dir.join("thumbnail.png");
- // thumbnail.save(&thumbnail_path).unwrap_or_else(|e| {
- // eprintln!("Failed to save thumbnail: {:?}", e);
- // });
- } else {
- eprintln!("No frames were processed, cannot save screenshot or thumbnail");
- }
- }
- });
-
- println!("Rendering video to channel");
-
- cap_rendering::render_video_to_channel(
- options,
- project,
- tx_image_data,
- decoders,
- editor_instance.cursor.clone(),
- editor_instance.project_path.clone(),
- )
- .await?;
-
- ffmpeg_handle.await.ok();
-
- println!("Copying file to {:?}", recording_dir);
- let result_path = recording_dir.join("output").join("result.mp4");
- // Function to check if the file is a valid MP4
- fn is_valid_mp4(path: &std::path::Path) -> bool {
- if let Ok(file) = std::fs::File::open(path) {
- let file_size = match file.metadata() {
- Ok(metadata) => metadata.len(),
- Err(_) => return false,
- };
- let reader = std::io::BufReader::new(file);
- Mp4Reader::read_header(reader, file_size).is_ok()
- } else {
- false
- }
- }
-
- if output_path != result_path {
- println!("Waiting for valid MP4 file at {:?}", output_path);
- // Wait for the file to become a valid MP4
- let mut attempts = 0;
- while attempts < 10 {
- // Wait for up to 60 seconds
- if is_valid_mp4(&output_path) {
- println!("Valid MP4 file detected after {} seconds", attempts);
- match std::fs::copy(&output_path, &result_path) {
- Ok(bytes) => {
- println!("Successfully copied {} bytes to {:?}", bytes, result_path)
- }
- Err(e) => eprintln!("Failed to copy file: {:?}", e),
- }
- break;
- }
- println!("Attempt {}: File not yet valid, waiting...", attempts + 1);
- std::thread::sleep(std::time::Duration::from_secs(1));
- attempts += 1;
- }
-
- if attempts == 10 {
- eprintln!("Timeout: Failed to detect a valid MP4 file after 60 seconds");
- }
- }
-
- Ok(output_path)
-}
-
#[derive(Deserialize, specta::Type, tauri_specta::Event, Debug, Clone)]
struct RenderFrameEvent {
frame_number: u32,
@@ -1579,10 +1356,8 @@ fn show_previous_recordings_window(app: AppHandle) {
if !window.is_focused().unwrap_or(false) {
window.set_focus().ok();
}
- } else {
- if window.is_focused().unwrap_or(false) {
- window.set_ignore_cursor_events(true).ok();
- }
+ } else if window.is_focused().unwrap_or(false) {
+ window.set_ignore_cursor_events(true).ok();
}
}
});
@@ -1652,8 +1427,7 @@ async fn render_to_file(
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
- render_to_file_impl(
- &editor_instance,
+ cap_export::export_video_to_file(
project,
output_path,
move |current_frame| {
@@ -1666,6 +1440,11 @@ async fn render_to_file(
.send(RenderProgress::FrameRendered { current_frame })
.ok();
},
+ &editor_instance.project_path,
+ editor_instance.audio.clone(),
+ editor_instance.meta(),
+ editor_instance.render_constants.clone(),
+ editor_instance.cursor.clone(),
)
.await
.ok();
@@ -1822,7 +1601,7 @@ async fn upload_rendered_video(
get_s3_config(&app, false, None).await?
};
- let result = match upload_video(
+ match upload_video(
&app,
video_id.clone(),
output_path,
@@ -1862,9 +1641,7 @@ async fn upload_rendered_video(
notifications::send_notification(&app, notifications::NotificationType::UploadFailed);
Err(e)
}
- };
-
- result
+ }
}
#[tauri::command]
@@ -2499,7 +2276,7 @@ pub async fn run() {
builder
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
- let _ = CapWindow::Main.show(&app);
+ let _ = CapWindow::Main.show(app);
}))
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_dialog::init())
@@ -2926,9 +2703,7 @@ async fn reupload_rendered_video(
// Get S3 config with the existing video ID
let s3_config = get_s3_config(&app, false, Some(sharing.id)).await?;
- let result = match upload_video(&app, video_id.clone(), output_path, false, Some(s3_config))
- .await
- {
+ match upload_video(&app, video_id.clone(), output_path, false, Some(s3_config)).await {
Ok(uploaded_video) => {
// Emit upload complete
UploadProgress {
@@ -2953,7 +2728,5 @@ async fn reupload_rendered_video(
notifications::send_notification(&app, notifications::NotificationType::UploadFailed);
Err(e)
}
- };
-
- result
+ }
}
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rs
index 3ddecdbf3..6db055255 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -147,7 +147,7 @@ pub async fn upload_video(
},
)?;
- let (upload_url, mut form) = presigned_s3_url(app, body).await?;
+ let (upload_url, form) = presigned_s3_url(app, body).await?;
let file_bytes = tokio::fs::read(&file_path)
.await
@@ -196,7 +196,7 @@ pub async fn upload_video(
.map_err(|e| format!("Error setting MIME type: {}", e))?
};
- let mut form = form.part("file", file_part);
+ let form = form.part("file", file_part);
// Prepare screenshot upload
let screenshot_path = file_path
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index a35136f35..a744bc071 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -91,9 +91,11 @@ impl CapWindowId {
pub fn traffic_lights_position(&self) -> Option<Option<LogicalPosition<f64>>> {
match self {
- Self::Camera | Self::WindowCaptureOccluder | Self::PrevRecordings => None,
+ Self::Camera
+ | Self::WindowCaptureOccluder
+ | Self::PrevRecordings
+ | Self::InProgressRecording => None,
Self::Editor { .. } => Some(Some(LogicalPosition::new(20.0, 40.5))),
- Self::InProgressRecording => Some(Some(LogicalPosition::new(-100.0, -100.0))),
_ => Some(None),
}
}
@@ -190,7 +192,6 @@ impl CapWindow {
.resizable(false)
.shadow(false)
.fullscreen(false)
- .decorations(false)
.always_on_top(true)
.content_protected(true)
.visible_on_all_workspaces(true)
@@ -275,7 +276,6 @@ impl CapWindow {
.maximized(false)
.resizable(false)
.fullscreen(false)
- .decorations(false)
.shadow(false)
.always_on_top(true)
.visible_on_all_workspaces(true)
@@ -348,6 +348,8 @@ impl CapWindow {
builder = builder
.hidden_title(true)
.title_bar_style(tauri::TitleBarStyle::Overlay);
+ } else {
+ builder = builder.decorations(false)
}
}
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index f0b8a414c..03b6f3811 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -113,7 +113,7 @@ pub enum RendererMessage {
pub struct Renderer {
rx: mpsc::Receiver<RendererMessage>,
- frame_tx: mpsc::UnboundedSender<SocketMessage>,
+ frame_tx: mpsc::Sender<SocketMessage>,
render_constants: Arc<RenderVideoConstants>,
}
@@ -124,7 +124,7 @@ pub struct RendererHandle {
impl Renderer {
pub fn spawn(
render_constants: Arc<RenderVideoConstants>,
- frame_tx: mpsc::UnboundedSender<SocketMessage>,
+ frame_tx: mpsc::Sender<SocketMessage>,
) -> RendererHandle {
let (tx, rx) = mpsc::channel(4);
@@ -179,7 +179,7 @@ impl Renderer {
// println!("produced frame in {:?}", time_instant.elapsed());
frame_tx
- .send(SocketMessage::Frame {
+ .try_send(SocketMessage::Frame {
data: frame,
width: uniforms.output_size.0,
height: uniforms.output_size.1,
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index 16bb6987b..704ed66ef 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -3,7 +3,6 @@ use crate::playback::{self, PlaybackHandle};
use crate::project_recordings::ProjectRecordings;
use cap_media::feeds::AudioData;
use cap_project::{CursorData, ProjectConfiguration, RecordingMeta, XY};
-use cap_rendering::decoder::AsyncVideoDecoder;
use cap_rendering::{ProjectUniforms, RecordingDecoders, RenderOptions, RenderVideoConstants};
use std::ops::Deref;
use std::sync::Mutex as StdMutex;
@@ -15,7 +14,7 @@ const FPS: u32 = 30;
pub struct EditorInstance {
pub project_path: PathBuf,
pub id: String,
- pub audio: Arc<StdMutex<Option<AudioData>>>,
+ pub audio: Arc<Option<AudioData>>,
pub cursor: Arc<CursorData>,
pub ws_port: u16,
pub decoders: RecordingDecoders,
@@ -66,20 +65,13 @@ impl EditorInstance {
.map(|c| XY::new(c.width, c.height)),
};
- let screen_decoder =
- AsyncVideoDecoder::spawn(project_path.join(&meta.display.path).clone());
- let camera_decoder = meta
- .camera
- .as_ref()
- .map(|camera| AsyncVideoDecoder::spawn(project_path.join(&camera.path).clone()));
-
let audio = meta.audio.as_ref().map(|meta| {
let audio_path = project_path.join(&meta.path);
AudioData::from_file(audio_path).unwrap()
});
- let (frame_tx, frame_rx) = tokio::sync::mpsc::unbounded_channel();
+ let (frame_tx, frame_rx) = tokio::sync::mpsc::channel(4);
let (ws_port, ws_shutdown) = create_frames_ws(frame_rx).await;
@@ -102,12 +94,12 @@ impl EditorInstance {
let this = Arc::new(Self {
id: video_id,
project_path,
- decoders: RecordingDecoders::new(screen_decoder, camera_decoder),
+ decoders: RecordingDecoders::new(&meta),
recordings,
ws_port,
renderer,
render_constants,
- audio: Arc::new(StdMutex::new(audio)),
+ audio: Arc::new(audio),
cursor,
state: Arc::new(Mutex::new(EditorState {
playhead_position: 0,
@@ -162,11 +154,11 @@ impl EditorInstance {
println!("Stopping decoders");
self.decoders.stop().await;
- // Clear audio data
- if self.audio.lock().unwrap().is_some() {
- println!("Clearing audio data");
- *self.audio.lock().unwrap() = None; // Explicitly drop the audio data
- }
+ // // Clear audio data
+ // if self.audio.lock().unwrap().is_some() {
+ // println!("Clearing audio data");
+ // *self.audio.lock().unwrap() = None; // Explicitly drop the audio data
+ // }
// Cancel any remaining tasks
tokio::task::yield_now().await;
@@ -282,9 +274,7 @@ impl Drop for EditorInstance {
}
}
-async fn create_frames_ws(
- frame_rx: mpsc::UnboundedReceiver<SocketMessage>,
-) -> (u16, mpsc::Sender<()>) {
+async fn create_frames_ws(frame_rx: mpsc::Receiver<SocketMessage>) -> (u16, mpsc::Sender<()>) {
use axum::{
extract::{
ws::{Message, WebSocket, WebSocketUpgrade},
@@ -293,9 +283,9 @@ async fn create_frames_ws(
response::IntoResponse,
routing::get,
};
- use tokio::sync::{mpsc::UnboundedReceiver, Mutex};
+ use tokio::sync::{mpsc::Receiver, Mutex};
- type RouterState = Arc<Mutex<UnboundedReceiver<SocketMessage>>>;
+ type RouterState = Arc<Mutex<Receiver<SocketMessage>>>;
async fn ws_handler(
ws: WebSocketUpgrade,
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index 0298acd26..140117cb5 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -1,4 +1,4 @@
-use std::{sync::Arc, sync::Mutex as StdMutex, time::Duration};
+use std::{sync::Arc, time::Duration};
use cap_media::data::{AudioInfo, FromSampleBytes};
use cap_media::feeds::{AudioData, AudioPlaybackBuffer};
@@ -13,7 +13,7 @@ use tokio::{sync::watch, time::Instant};
use crate::{editor, project_recordings::ProjectRecordings};
pub struct Playback {
- pub audio: Arc<StdMutex<Option<AudioData>>>,
+ pub audio: Arc<Option<AudioData>>,
pub renderer: Arc<editor::RendererHandle>,
pub render_constants: Arc<RenderVideoConstants>,
pub decoders: RecordingDecoders,
@@ -63,7 +63,7 @@ impl Playback {
.unwrap_or(f64::MAX);
// Lock the mutex and check if audio data is available
- if let Some(audio_data) = self.audio.lock().unwrap().as_ref() {
+ if let Some(audio_data) = self.audio.as_ref() {
AudioPlayback {
audio: audio_data.clone(),
stop_rx: stop_rx.clone(),
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
new file mode 100644
index 000000000..2b18bd36e
--- /dev/null
+++ b/crates/export/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "cap-export"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+cap-utils = { path = "../utils" }
+cap-project = { path = "../project" }
+cap-rendering = { path = "../rendering" }
+cap-ffmpeg-cli = { path = "../ffmpeg-cli" }
+cap-editor = { path = "../editor" }
+cap-media = { path = "../media" }
+cap-flags = { path = "../flags" }
+
+tokio.workspace = true
+tempfile = "3.12.0"
+image = "0.25.2"
+mp4 = "0.14.0"
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
new file mode 100644
index 000000000..f6b40935a
--- /dev/null
+++ b/crates/export/src/lib.rs
@@ -0,0 +1,239 @@
+use image::{ImageBuffer, Rgba};
+use mp4::Mp4Reader;
+use std::{path::PathBuf, sync::Arc};
+
+use cap_media::feeds::{AudioData, AudioFrameBuffer};
+use cap_project::{CursorData, ProjectConfiguration, RecordingMeta};
+use cap_rendering::{ProjectUniforms, RecordingDecoders, RenderVideoConstants};
+
+struct AudioRender {
+ buffer: AudioFrameBuffer,
+ pipe_tx: tokio::sync::mpsc::Sender<Vec<u8>>,
+}
+
+const FPS: u32 = 30;
+
+pub async fn export_video_to_file(
+ project: ProjectConfiguration,
+ output_path: PathBuf,
+ on_progress: impl Fn(u32) + Send + 'static,
+ project_path: &PathBuf,
+ audio: Arc<Option<AudioData>>,
+ meta: RecordingMeta,
+ render_constants: Arc<RenderVideoConstants>,
+ cursor: Arc<CursorData>,
+) -> Result<PathBuf, String> {
+ 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))?;
+
+ 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...");
+ let mut ffmpeg = cap_ffmpeg_cli::FFmpeg::new();
+
+ let audio_dir = tempfile::tempdir().unwrap();
+ let video_dir = tempfile::tempdir().unwrap();
+ let mut audio = if let Some(audio_data) = audio.as_ref() {
+ let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(30);
+
+ let pipe_path =
+ cap_utils::create_channel_named_pipe(rx, audio_dir.path().join("audio.pipe"));
+
+ ffmpeg.add_input(cap_ffmpeg_cli::FFmpegRawAudioInput {
+ input: pipe_path,
+ sample_format: "f64le".to_string(),
+ sample_rate: audio_data.info.sample_rate,
+ channels: audio_data.info.channels as u16,
+ });
+
+ let buffer = AudioFrameBuffer::new(audio_data.clone());
+ Some(AudioRender {
+ buffer,
+ pipe_tx: tx,
+ })
+ } else {
+ None
+ };
+
+ let video_tx = {
+ let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(30);
+
+ let pipe_path =
+ cap_utils::create_channel_named_pipe(rx, video_dir.path().join("video.pipe"));
+
+ ffmpeg.add_input(cap_ffmpeg_cli::FFmpegRawVideoInput {
+ width: output_size.0,
+ height: output_size.1,
+ fps: 30,
+ pix_fmt: "rgba",
+ input: pipe_path,
+ });
+
+ tx
+ };
+
+ ffmpeg
+ .command
+ .args(["-f", "mp4"])
+ .args(["-codec:v", "libx264", "-codec:a", "aac"])
+ .args(["-preset", "ultrafast"])
+ .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
+ .arg("-y")
+ .arg(&output_path);
+
+ let mut ffmpeg_process = ffmpeg.start();
+
+ let mut frame_count = 0;
+ 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());
+ }
+
+ 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;
+ }
+ }
+ }
+
+ ffmpeg_process.stop();
+
+ // Save the first frame as a screenshot and thumbnail
+ if let Some(frame_data) = first_frame {
+ let width = output_size.0;
+ let height = output_size.1;
+ let rgba_img: ImageBuffer<Rgba<u8>, Vec<u8>> =
+ ImageBuffer::from_raw(width, 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(width, 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);
+ });
+
+ // // Create and save thumbnail
+ // let thumbnail = image::imageops::resize(
+ // &rgb_img,
+ // 100,
+ // 100,
+ // image::imageops::FilterType::Lanczos3,
+ // );
+ // let thumbnail_path = screenshots_dir.join("thumbnail.png");
+ // thumbnail.save(&thumbnail_path).unwrap_or_else(|e| {
+ // eprintln!("Failed to save thumbnail: {:?}", e);
+ // });
+ } else {
+ eprintln!("No frames were processed, cannot save screenshot or thumbnail");
+ }
+ }
+ });
+
+ println!("Rendering video to channel");
+
+ let decoders = RecordingDecoders::new(&meta);
+
+ cap_rendering::render_video_to_channel(
+ render_constants.options,
+ project,
+ tx_image_data,
+ decoders,
+ cursor.clone(),
+ project_path.clone(),
+ )
+ .await?;
+
+ ffmpeg_handle.await.ok();
+
+ println!("Copying file to {:?}", project_path);
+ let result_path = project_path.join("output").join("result.mp4");
+ // Function to check if the file is a valid MP4
+ fn is_valid_mp4(path: &std::path::Path) -> bool {
+ if let Ok(file) = std::fs::File::open(path) {
+ let file_size = match file.metadata() {
+ Ok(metadata) => metadata.len(),
+ Err(_) => return false,
+ };
+ let reader = std::io::BufReader::new(file);
+ Mp4Reader::read_header(reader, file_size).is_ok()
+ } else {
+ false
+ }
+ }
+
+ if output_path != result_path {
+ println!("Waiting for valid MP4 file at {:?}", output_path);
+ // Wait for the file to become a valid MP4
+ let mut attempts = 0;
+ while attempts < 10 {
+ // Wait for up to 60 seconds
+ if is_valid_mp4(&output_path) {
+ println!("Valid MP4 file detected after {} seconds", attempts);
+ match std::fs::copy(&output_path, &result_path) {
+ Ok(bytes) => {
+ println!("Successfully copied {} bytes to {:?}", bytes, result_path)
+ }
+ Err(e) => eprintln!("Failed to copy file: {:?}", e),
+ }
+ break;
+ }
+ println!("Attempt {}: File not yet valid, waiting...", attempts + 1);
+ std::thread::sleep(std::time::Duration::from_secs(1));
+ attempts += 1;
+ }
+
+ if attempts == 10 {
+ eprintln!("Timeout: Failed to detect a valid MP4 file after 60 seconds");
+ }
+ }
+
+ Ok(output_path)
+}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index bca08b72f..d3e3083d0 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1,7 +1,7 @@
use anyhow::Result;
use bytemuck::{Pod, Zeroable};
use cap_flags::FLAGS;
-use decoder::AsyncVideoDecoderHandle;
+use decoder::{AsyncVideoDecoder, AsyncVideoDecoderHandle};
use futures::future::OptionFuture;
use futures_intrusive::channel::shared::oneshot_channel;
use serde::{Deserialize, Serialize};
@@ -13,7 +13,7 @@ use wgpu::{CommandEncoder, COPY_BYTES_PER_ROW_ALIGNMENT};
use cap_project::{
AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, CursorAnimationStyle,
- CursorData, CursorMoveEvent, ProjectConfiguration, FAST_SMOOTHING_SAMPLES,
+ CursorData, CursorMoveEvent, ProjectConfiguration, RecordingMeta, FAST_SMOOTHING_SAMPLES,
FAST_VELOCITY_THRESHOLD, REGULAR_SMOOTHING_SAMPLES, REGULAR_VELOCITY_THRESHOLD,
SLOW_SMOOTHING_SAMPLES, SLOW_VELOCITY_THRESHOLD, XY,
};
@@ -27,7 +27,7 @@ pub use decoder::DecodedFrame;
const STANDARD_CURSOR_HEIGHT: f32 = 75.0;
-#[derive(Debug, Clone, Type)]
+#[derive(Debug, Clone, Copy, Type)]
pub struct RenderOptions {
pub camera_size: Option<XY<u32>>,
pub screen_size: XY<u32>,
@@ -87,9 +87,16 @@ pub struct RecordingDecoders {
}
impl RecordingDecoders {
- pub fn new(screen: AsyncVideoDecoderHandle, camera: Option<AsyncVideoDecoderHandle>) -> Self {
- RecordingDecoders { screen, camera }
+ pub fn new(meta: &RecordingMeta) -> Self {
+ let screen = AsyncVideoDecoder::spawn(meta.project_path.join(&meta.display.path).clone());
+ let camera = meta
+ .camera
+ .as_ref()
+ .map(|camera| AsyncVideoDecoder::spawn(meta.project_path.join(&camera.path).clone()));
+
+ Self { screen, camera }
}
+
pub async fn get_frames(
&self,
frame_number: u32,
@@ -117,7 +124,7 @@ impl RecordingDecoders {
pub async fn render_video_to_channel(
options: RenderOptions,
project: ProjectConfiguration,
- sender: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
+ sender: tokio::sync::mpsc::Sender<Vec<u8>>,
decoders: RecordingDecoders,
cursor: Arc<CursorData>,
project_path: PathBuf, // Add project_path parameter
@@ -176,7 +183,7 @@ pub async fn render_video_to_channel(
}
};
- if sender.send(frame).is_err() {
+ if sender.send(frame).await.is_err() {
eprintln!("Failed to send processed frame to channel");
break;
}
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index c458e30d6..c3d0793cb 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -6,6 +6,7 @@
// biome-ignore lint: disable
export {}
declare global {
+ const IconCapArrows: typeof import('~icons/cap/arrows.jsx')['default']
const IconCapAudioOn: typeof import('~icons/cap/audio-on.jsx')['default']
const IconCapBlur: typeof import('~icons/cap/blur.jsx')['default']
const IconCapCamera: typeof import('~icons/cap/camera.jsx')['default']
@@ -39,6 +40,7 @@ declare global {
const IconCapScissors: typeof import('~icons/cap/scissors.jsx')['default']
const IconCapSettings: typeof import('~icons/cap/settings.jsx')['default']
const IconCapShadow: typeof import('~icons/cap/shadow.jsx')['default']
+ const IconCapSquare: typeof import('~icons/cap/square.jsx')['default']
const IconCapStopCircle: typeof import('~icons/cap/stop-circle.jsx')['default']
const IconCapTrash: typeof import('~icons/cap/trash.jsx')['default']
const IconCapUndo: typeof import('~icons/cap/undo.jsx')['default']
@@ -46,8 +48,11 @@ declare global {
const IconLucideBell: typeof import('~icons/lucide/bell.jsx')['default']
const IconLucideCamera: typeof import('~icons/lucide/camera.jsx')['default']
const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default']
+ const IconLucideEdit: typeof import('~icons/lucide/edit.jsx')['default']
const IconLucideEye: typeof import('~icons/lucide/eye.jsx')['default']
+ const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default']
const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default']
+ const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default']
const IconLucideRabbit: typeof import('~icons/lucide/rabbit.jsx')['default']
const IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw.jsx')['default']
const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default']