Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Fix the 5 min studio export limit being enforced incorrectly (#1117)

Oscar Beaumontc1e481a12e70
diff --git a/Cargo.lock b/Cargo.lock
index 7f9753127..d8fe74ff7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1178,7 +1178,6 @@ dependencies = [
"lazy_static",
"log",
"md5",
- "mp4",
"nix 0.29.0",
"objc",
"objc2-app-kit",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 85046ece2..ee8edef69 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -53,7 +53,6 @@ specta-typescript = "0.0.7"
tokio.workspace = true
uuid = { version = "1.10.0", features = ["v4"] }
image = "0.25.2"
-mp4 = "0.14.0"
futures-intrusive = "0.5.0"
anyhow.workspace = true
futures = { workspace = true }
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 701242654..1d934bcc5 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -45,9 +45,9 @@ use cap_rendering::{ProjectRecordingsMeta, RenderedFrame};
use clipboard_rs::common::RustImage;
use clipboard_rs::{Clipboard, ClipboardContext};
use editor_window::{EditorInstances, WindowEditorInstance};
+use ffmpeg::ffi::AV_TIME_BASE;
use general_settings::GeneralSettingsStore;
use kameo::{Actor, actor::ActorRef};
-use mp4::Mp4Reader;
use notifications::NotificationType;
use png::{ColorType, Encoder};
use recording::InProgressRecording;
@@ -64,7 +64,7 @@ use std::{
collections::BTreeMap,
fs::File,
future::Future,
- io::{BufReader, BufWriter},
+ io::BufWriter,
marker::PhantomData,
path::{Path, PathBuf},
process::Command,
@@ -421,11 +421,6 @@ async fn create_screenshot(
println!("Creating screenshot: input={input:?}, output={output:?}, size={size:?}");
let result: Result<(), String> = tokio::task::spawn_blocking(move || -> Result<(), String> {
- ffmpeg::init().map_err(|e| {
- eprintln!("Failed to initialize ffmpeg: {e}");
- e.to_string()
- })?;
-
let mut ictx = ffmpeg::format::input(&input).map_err(|e| {
eprintln!("Failed to create input context: {e}");
e.to_string()
@@ -584,11 +579,11 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(
return Err(format!("Source file {src} does not exist"));
}
- if !is_screenshot && !is_gif && !is_valid_mp4(src_path) {
+ if !is_screenshot && !is_gif && !is_valid_video(src_path) {
let mut attempts = 0;
while attempts < 10 {
std::thread::sleep(std::time::Duration::from_secs(1));
- if is_valid_mp4(src_path) {
+ if is_valid_video(src_path) {
break;
}
attempts += 1;
@@ -631,8 +626,8 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(
continue;
}
- if !is_screenshot && !is_gif && !is_valid_mp4(std::path::Path::new(&dst)) {
- last_error = Some("Destination file is not a valid MP4".to_string());
+ if !is_screenshot && !is_gif && !is_valid_video(std::path::Path::new(&dst)) {
+ last_error = Some("Destination file is not a valid".to_string());
let _ = tokio::fs::remove_file(&dst).await;
attempts += 1;
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
@@ -682,16 +677,15 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(
Err(last_error.unwrap_or_else(|| "Maximum retry attempts exceeded".to_string()))
}
-pub 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
+pub fn is_valid_video(path: &std::path::Path) -> bool {
+ match ffmpeg::format::input(path) {
+ Ok(input_context) => {
+ // Check if we have at least one video stream
+ input_context
+ .streams()
+ .any(|stream| stream.parameters().medium() == ffmpeg::media::Type::Video)
+ }
+ Err(_) => false,
}
}
@@ -877,23 +871,19 @@ async fn get_video_metadata(path: PathBuf) -> Result<VideoRecordingMetadata, Str
let recording_meta = RecordingMeta::load_for_project(&path).map_err(|v| v.to_string())?;
fn get_duration_for_path(path: PathBuf) -> Result<f64, String> {
- let reader = BufReader::new(
- File::open(&path).map_err(|e| format!("Failed to open video file: {e}"))?,
- );
- let file_size = path
- .metadata()
- .map_err(|e| format!("Failed to get file metadata: {e}"))?
- .len();
-
- let current_duration = match Mp4Reader::read_header(reader, file_size) {
- Ok(mp4) => mp4.duration().as_secs_f64(),
- Err(e) => {
- println!("Failed to read MP4 header: {e}. Falling back to default duration.");
- 0.0_f64
- }
- };
+ let input =
+ ffmpeg::format::input(&path).map_err(|e| format!("Failed to open video file: {e}"))?;
+
+ let raw_duration = input.duration();
+ if raw_duration <= 0 {
+ return Err(format!(
+ "Unknown or invalid duration for video file: {:?}",
+ path
+ ));
+ }
- Ok(current_duration)
+ let duration = raw_duration as f64 / AV_TIME_BASE as f64;
+ Ok(duration)
}
let display_paths = match &recording_meta.inner {
@@ -915,7 +905,10 @@ async fn get_video_metadata(path: PathBuf) -> Result<VideoRecordingMetadata, Str
let duration = display_paths
.into_iter()
.map(get_duration_for_path)
- .sum::<Result<_, _>>()?;
+ .try_fold(0f64, |acc, item| -> Result<f64, String> {
+ let d = item?;
+ Ok(acc + d)
+ })?;
let (width, height) = (1920, 1080);
let fps = 30;
@@ -1841,6 +1834,12 @@ type LoggingHandle = tracing_subscriber::reload::Handle<Option<DynLoggingLayer>,
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub async fn run(recording_logging_handle: LoggingHandle) {
+ ffmpeg::init()
+ .map_err(|e| {
+ error!("Failed to initialize ffmpeg: {e}");
+ })
+ .ok();
+
let tauri_context = tauri::generate_context!();
let specta_builder = tauri_specta::Builder::new()
diff --git a/apps/desktop/src/routes/editor/ExportDialog.tsx b/apps/desktop/src/routes/editor/ExportDialog.tsx
index a41e7574d..40d6a75c6 100644
--- a/apps/desktop/src/routes/editor/ExportDialog.tsx
+++ b/apps/desktop/src/routes/editor/ExportDialog.tsx
@@ -47,6 +47,8 @@ import {
topSlideAnimateClasses,
} from "./ui";
+class SilentError extends Error {}
+
export const COMPRESSION_OPTIONS: Array<{
label: string;
value: ExportCompression;
@@ -319,9 +321,9 @@ export function ExportDialog() {
if (!canShare.allowed) {
if (canShare.reason === "upgrade_required") {
await commands.showWindow("Upgrade");
- throw new Error(
- "Upgrade required to share recordings longer than 5 minutes",
- );
+ // The window takes a little to show and this prevents the user seeing it glitch
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ throw new SilentError();
}
}
@@ -376,9 +378,11 @@ export function ExportDialog() {
},
onError: (error) => {
console.error(error);
- commands.globalMessageDialog(
- error instanceof Error ? error.message : "Failed to upload recording",
- );
+ if (!(error instanceof SilentError)) {
+ commands.globalMessageDialog(
+ error instanceof Error ? error.message : "Failed to upload recording",
+ );
+ }
setExportState(reconcile({ type: "idle" }));
},
diff --git a/crates/enc-avfoundation/src/mp4.rs b/crates/enc-avfoundation/src/mp4.rs
index c56b56b46..cee416d45 100644
--- a/crates/enc-avfoundation/src/mp4.rs
+++ b/crates/enc-avfoundation/src/mp4.rs
@@ -8,8 +8,6 @@ pub struct MP4Encoder {
#[allow(unused)]
tag: &'static str,
#[allow(unused)]
- last_pts: Option<i64>,
- #[allow(unused)]
config: VideoInfo,
asset_writer: arc::R<av::AssetWriter>,
video_input: arc::R<av::AssetWriterInput>,
@@ -17,7 +15,7 @@ pub struct MP4Encoder {
start_time: cm::Time,
first_timestamp: Option<cm::Time>,
segment_first_timestamp: Option<cm::Time>,
- last_timestamp: Option<cm::Time>,
+ last_pts: Option<cm::Time>,
is_writing: bool,
is_paused: bool,
elapsed_duration: cm::Time,
@@ -177,14 +175,13 @@ impl MP4Encoder {
Ok(Self {
tag,
- last_pts: None,
config: video_config,
audio_input,
asset_writer,
video_input,
first_timestamp: None,
segment_first_timestamp: None,
- last_timestamp: None,
+ last_pts: None,
is_writing: false,
is_paused: false,
start_time: cm::Time::zero(),
@@ -227,7 +224,7 @@ impl MP4Encoder {
self.first_timestamp.get_or_insert(time);
self.segment_first_timestamp.get_or_insert(time);
- self.last_timestamp = Some(time);
+ self.last_pts = Some(new_pts);
self.video_frames_appended += 1;
@@ -322,7 +319,7 @@ impl MP4Encoder {
.elapsed_duration
.add(time.sub(self.segment_first_timestamp.unwrap()));
self.segment_first_timestamp = None;
- self.last_timestamp = None;
+ self.last_pts = None;
self.is_paused = true;
}
@@ -342,7 +339,7 @@ impl MP4Encoder {
self.is_writing = false;
self.asset_writer
- .end_session_at_src_time(self.last_timestamp.unwrap_or(cm::Time::zero()));
+ .end_session_at_src_time(self.last_pts.unwrap_or(cm::Time::zero()));
self.video_input.mark_as_finished();
if let Some(i) = self.audio_input.as_mut() {
i.mark_as_finished()
@@ -354,7 +351,7 @@ impl MP4Encoder {
debug!("Appended {} audio frames", self.audio_frames_appended);
debug!("First video timestamp: {:?}", self.first_timestamp);
- debug!("Last video timestamp: {:?}", self.last_timestamp);
+ debug!("Last video timestamp: {:?}", self.last_pts);
info!("Finished writing");
}