Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
182 changes: 181 additions & 1 deletion apps/cli/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{
path::{Path, PathBuf},
sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicU32, Ordering},
atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering},
},
};

Expand Down Expand Up @@ -87,6 +87,12 @@ pub struct Export {
/// Emit a final JSON completion event to stdout ({"type":"Completed","path":"..."}). Implied by --json
#[arg(long)]
completion_json: bool,
/// Export the recorded tracks as separate files instead of one video: a comma-separated list of
/// screen, camera, microphone, system-audio, or `all`. They follow the edited timeline and are
/// written to the --output folder (default '<project>/output/tracks') as Screen.mp4, Camera.mp4,
/// Microphone.wav and System audio.wav. Takes --fps (default 60); one project at a time
#[arg(long, value_name = "TRACKS")]
tracks: Option<String>,
}

#[derive(Default)]
Expand Down Expand Up @@ -453,6 +459,11 @@ impl Export {
completion_json: bool,
stdout: &Arc<Mutex<std::io::Stdout>>,
) -> Result<(), String> {
if let Some(tracks) = self.tracks.clone() {
return self
.run_tracks(&tracks, progress_json, completion_json, stdout)
.await;
}
let settings = self.resolve_settings()?;
let (projects, output) = split_projects_and_output(self.project_paths, self.output)?;

Expand Down Expand Up @@ -659,6 +670,150 @@ impl Export {
}
}

impl Export {
fn tracks_conflicts(&self) -> Option<&'static str> {
if self.settings_json.is_some() {
Some("--settings-json")
} else if self.format.is_some() {
Some("--format")
} else if self.resolution.is_some() {
Some("--resolution")
} else if self.quality.is_some() {
Some("--quality")
} else if self.optimize_filesize {
Some("--optimize-filesize")
} else {
None
}
}

async fn run_tracks(
self,
tracks: &str,
progress_json: bool,
completion_json: bool,
stdout: &Arc<Mutex<std::io::Stdout>>,
) -> Result<(), String> {
if let Some(flag) = self.tracks_conflicts() {
return Err(format!(
"--tracks cannot be combined with {flag}; tracks keep their recorded size and only take --fps"
));
}
let fps = self.fps.unwrap_or_else(|| default_fps(ExportFormat::Mp4));
if fps == 0 {
return Err("--fps must be greater than zero".to_string());
}
let (projects, output) = split_projects_and_output(self.project_paths, self.output)?;
let [project_path] = projects.as_slice() else {
return Err("--tracks exports one project at a time".to_string());
};

ensure_remuxed(project_path.clone()).await?;
let meta = RecordingMeta::load_for_project(project_path)
.map_err(|e| format!("Failed to load recording meta: {e}"))?;
let Some(studio) = meta.studio_meta() else {
return Err(cap_export::tracks::TrackExportError::NotStudio.to_string());
};
let selection = parse_tracks(tracks, || {
let recordings = cap_rendering::ProjectRecordingsMeta::new(&meta.project_path, studio)?;
Ok(cap_export::tracks::available_tracks(
&recordings,
&meta.project_config(),
))
})?;
let output = output.unwrap_or_else(|| project_path.join("output").join("tracks"));

let total = Arc::new(AtomicU64::new(0));
let done = Arc::new(AtomicU64::new(0));
let progress_stdout = Arc::clone(stdout);
let progress_done = Arc::clone(&done);
let progress_total = Arc::clone(&total);
let files = cap_export::tracks::export_tracks(
project_path.clone(),
None,
cap_export::tracks::TrackExportSettings {
tracks: selection,
fps,
force_ffmpeg_decoder: self.force_ffmpeg_decoder,
},
output.clone(),
Arc::new(AtomicBool::new(false)),
move |progress| {
progress_done.store(progress.done, Ordering::Relaxed);
progress_total.store(progress.total, Ordering::Relaxed);
if progress_json {
let _ = emit_export_message(
&progress_stdout,
&ExportProgressMessage::Progress {
rendered_count: progress.done.min(u64::from(u32::MAX)) as u32,
total_frames: progress.total.min(u64::from(u32::MAX)) as u32,
},
);
}
},
)
.await
.map_err(|error| error.to_string())?;

if progress_json || completion_json {
emit_export_message(stdout, &ExportProgressMessage::Completed { path: &output })?;
} else {
println!("Exported {} tracks to {}", files.len(), output.display());
for file in &files {
if let Some(name) = file.file_name() {
println!(" {}", name.to_string_lossy());
}
}
}
info!(
"Exported {} tracks to '{}' ({}/{} steps)",
files.len(),
output.display(),
done.load(Ordering::Relaxed),
total.load(Ordering::Relaxed)
);
Ok(())
}
}

/// `all`, or a comma-separated list of track names, in a stable order.
fn parse_tracks(
value: &str,
available: impl FnOnce() -> Result<Vec<cap_export::tracks::TrackKind>, String>,
) -> Result<Vec<cap_export::tracks::TrackKind>, String> {
use cap_export::tracks::TrackKind;
let names = value
.split(',')
.map(str::trim)
.filter(|name| !name.is_empty())
.collect::<Vec<_>>();
if names.is_empty() {
return Err(
"--tracks needs at least one of screen, camera, microphone, system-audio, or all"
.to_string(),
);
}
if names.iter().any(|name| name.eq_ignore_ascii_case("all")) {
if names.len() > 1 {
return Err("--tracks all cannot be combined with other track names".to_string());
}
return available();
}
let mut tracks = names
.iter()
.map(|name| {
TrackKind::from_slug(name).ok_or_else(|| {
format!(
"Unknown track '{name}'; use screen, camera, microphone, system-audio, or all"
)
})
})
.collect::<Result<Vec<_>, _>>()?;
tracks.sort();
tracks.dedup();
Ok(tracks)
}

/// Remux a recording left as fragments (status `NeedsRemux`) into a progressive `display.mp4` before
/// export, reusing the shared `RecoveryManager`. A graceful `cap record` stop already remuxes in
/// `finalize`, so this only fires for recordings interrupted before that (e.g. a killed worker);
Expand Down Expand Up @@ -1021,6 +1176,31 @@ fn emit_export_message(
mod tests {
use super::*;

#[test]
fn track_lists_parse_in_a_stable_order() {
use cap_export::tracks::TrackKind;
let none = || -> Result<Vec<TrackKind>, String> { panic!("only `all` lists the project") };
assert_eq!(
parse_tracks("system-audio, mic,screen,mic", none).unwrap(),
[
TrackKind::Screen,
TrackKind::Microphone,
TrackKind::SystemAudio
]
);
assert_eq!(
parse_tracks("ALL", || Ok(vec![TrackKind::Screen, TrackKind::Camera])).unwrap(),
[TrackKind::Screen, TrackKind::Camera]
);
assert!(parse_tracks("all,screen", none).is_err());
assert!(parse_tracks(" , ", none).is_err());
assert!(
parse_tracks("screen,cursor", none)
.unwrap_err()
.contains("Unknown track 'cursor'")
);
}

fn playable_instant_project() -> tempfile::TempDir {
ffmpeg::init().unwrap();
let project = tempfile::tempdir().unwrap();
Expand Down
2 changes: 1 addition & 1 deletion apps/cli/src/guide.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ fn build() -> Guide {
notes: Some(
"EXCEPTION: export NDJSON uses PascalCase `type` tags and snake_case fields \
(rendered_count, total_frames) for desktop compatibility. --format selects the \
CONTAINER (mp4/gif/mov), NOT output mode; use --json for machine-readable output. Pass several projects to export them in one run; each is written to '<project name>.<ext>' inside the output directory.",
CONTAINER (mp4/gif/mov), NOT output mode; use --json for machine-readable output. Pass several projects to export them in one run; each is written to '<project name>.<ext>' inside the output directory. --tracks screen,camera,microphone,system-audio (or all) writes the recorded tracks as separate files that follow the edit into the --output folder; Completed.path is that folder.",
),
..cmd(
"export",
Expand Down
20 changes: 20 additions & 0 deletions apps/desktop-gpui/locales/de.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2532,6 +2532,7 @@ format = "Format"
frame_rate = "Bildrate"
quality = "Qualität"
resolution = "Auflösung"
tracks = "Spuren"

[editor.export.stats]
calculating = "Wird berechnet…"
Expand All @@ -2544,6 +2545,25 @@ refining_size = "Größe wird präzisiert…"
refining_time = "Dauer wird präzisiert…"
unavailable = "Nicht verfügbar"

[editor.export.tracks]
aligned = "Spuren folgen Ihren Schnitten und Ihrer Geschwindigkeit und passen in jedem Videoeditor zusammen. Video wird ohne Hintergrund und Effekte exportiert."
audio_detail = "WAV · 48 kHz"
camera = "Kamera"
choose_one = "Wählen Sie mindestens eine Spur zum Exportieren."
cta = "Spuren exportieren"
exported = "Spuren exportiert"
exporting = "Spuren werden exportiert"
file_count = { one = "{count} Datei", other = "{count} Dateien" }
file_only = "Spuren werden als einzelne Dateien in einem Ordner gespeichert."
files = "Dateien"
format = "Spuren"
microphone = "Mikrofon"
open_folder = "Ordner öffnen"
screen = "Bildschirm"
studio_only = "Separate Spuren werden nur im Studio-Modus aufgenommen."
system_audio = "Systemaudio"
video_detail = "MP4 · {width}×{height}"

[editor.export.turbo]
title = "Turbo-Export"
description = "Exportiert deutlich schneller mit allen CPU-Kernen und der GPU"
Expand Down
20 changes: 20 additions & 0 deletions apps/desktop-gpui/locales/en.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2534,6 +2534,7 @@ format = "Format"
frame_rate = "Frame rate"
quality = "Quality"
resolution = "Resolution"
tracks = "Tracks"

[editor.export.stats]
calculating = "Calculating…"
Expand All @@ -2546,6 +2547,25 @@ refining_size = "Refining size…"
refining_time = "Refining time…"
unavailable = "Unavailable"

[editor.export.tracks]
aligned = "Tracks follow your cuts and speed, so they line up in any video editor. Video comes out clean, without background or effects."
audio_detail = "WAV · 48 kHz"
camera = "Camera"
choose_one = "Choose at least one track to export."
cta = "Export Tracks"
exported = "Tracks exported"
exporting = "Exporting tracks"
file_count = { one = "{count} file", other = "{count} files", context = "How many files a tracks export writes." }
file_only = "Tracks are saved as separate files in a folder."
files = "Files"
format = { text = "Tracks", context = "Export format: separate screen, camera and audio files." }
microphone = "Microphone"
open_folder = "Open Folder"
screen = "Screen"
studio_only = "Separate tracks are only recorded in Studio Mode."
system_audio = "System audio"
video_detail = { text = "MP4 · {width}×{height}", context = "Video track file type and size, for example MP4 · 1920×1080." }

[editor.export.turbo]
title = "Turbo export"
description = "Exports much faster using every CPU core and the GPU"
Expand Down
20 changes: 20 additions & 0 deletions apps/desktop-gpui/locales/es.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2532,6 +2532,7 @@ format = "Formato"
frame_rate = "Velocidad de fotogramas"
quality = "Calidad"
resolution = "Resolución"
tracks = "Pistas"

[editor.export.stats]
calculating = "Calculando…"
Expand All @@ -2544,6 +2545,25 @@ refining_size = "Ajustando tamaño…"
refining_time = "Ajustando tiempo…"
unavailable = "No disponible"

[editor.export.tracks]
aligned = "Las pistas siguen tus cortes y tu velocidad, así que encajan en cualquier editor de vídeo. El vídeo sale limpio, sin fondo ni efectos."
audio_detail = "WAV · 48 kHz"
camera = "Cámara"
choose_one = "Elige al menos una pista para exportar."
cta = "Exportar pistas"
exported = "Pistas exportadas"
exporting = "Exportando pistas"
file_count = { one = "{count} archivo", other = "{count} archivos" }
file_only = "Las pistas se guardan como archivos separados en una carpeta."
files = "Archivos"
format = "Pistas"
microphone = "Micrófono"
open_folder = "Abrir carpeta"
screen = "Pantalla"
studio_only = "Las pistas separadas solo se graban en el modo Studio."
system_audio = "Audio del sistema"
video_detail = "MP4 · {width}×{height}"

[editor.export.turbo]
title = "Exportación turbo"
description = "Exporta mucho más rápido usando todos los núcleos de la CPU y la GPU"
Expand Down
20 changes: 20 additions & 0 deletions apps/desktop-gpui/locales/fr.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2532,6 +2532,7 @@ format = "Format"
frame_rate = "Fréquence d'images"
quality = "Qualité"
resolution = "Résolution"
tracks = "Pistes"

[editor.export.stats]
calculating = "Calcul…"
Expand All @@ -2544,6 +2545,25 @@ refining_size = "Affinage de la taille…"
refining_time = "Affinage de la durée…"
unavailable = "Indisponible"

[editor.export.tracks]
aligned = "Les pistes suivent vos coupes et votre vitesse, et s'alignent dans n'importe quel logiciel de montage. La vidéo sort propre, sans arrière-plan ni effets."
audio_detail = "WAV · 48 kHz"
camera = "Caméra"
choose_one = "Choisissez au moins une piste à exporter."
cta = "Exporter les pistes"
exported = "Pistes exportées"
exporting = "Exportation des pistes"
file_count = { one = "{count} fichier", other = "{count} fichiers" }
file_only = "Les pistes sont enregistrées dans un dossier, en fichiers séparés."
files = "Fichiers"
format = "Pistes"
microphone = "Micro"
open_folder = "Ouvrir le dossier"
screen = "Écran"
studio_only = "Les pistes séparées ne sont enregistrées qu'en mode Studio."
system_audio = "Audio système"
video_detail = "MP4 · {width}×{height}"

[editor.export.turbo]
title = "Exportation turbo"
description = "Exporte beaucoup plus vite en utilisant tous les cœurs du processeur et le GPU"
Expand Down
20 changes: 20 additions & 0 deletions apps/desktop-gpui/locales/hi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2532,6 +2532,7 @@ format = "फ़ॉर्मैट"
frame_rate = "फ़्रेम रेट"
quality = "क्वालिटी"
resolution = "रेज़ोल्यूशन"
tracks = "ट्रैक"

[editor.export.stats]
calculating = "गणना हो रही है…"
Expand All @@ -2544,6 +2545,25 @@ refining_size = "साइज़ सटीक किया जा रहा ह
refining_time = "समय सटीक किया जा रहा है…"
unavailable = "उपलब्ध नहीं"

[editor.export.tracks]
aligned = "ट्रैक आपके कट और स्पीड के हिसाब से चलते हैं, इसलिए किसी भी वीडियो एडिटर में एक साथ मेल खाते हैं। वीडियो बिना बैकग्राउंड या इफ़ेक्ट के साफ़ निकलता है।"
audio_detail = "WAV · 48 kHz"
camera = "कैमरा"
choose_one = "एक्सपोर्ट करने के लिए कम से कम एक ट्रैक चुनें।"
cta = "ट्रैक एक्सपोर्ट करें"
exported = "ट्रैक एक्सपोर्ट हो गए"
exporting = "ट्रैक एक्सपोर्ट हो रहे हैं"
file_count = { one = "{count} फ़ाइल", other = "{count} फ़ाइलें" }
file_only = "ट्रैक एक फ़ोल्डर में अलग-अलग फ़ाइलों के रूप में सेव होते हैं।"
files = "फ़ाइलें"
format = "ट्रैक"
microphone = "माइक्रोफ़ोन"
open_folder = "फ़ोल्डर खोलें"
screen = "स्क्रीन"
studio_only = "अलग-अलग ट्रैक सिर्फ़ Studio मोड में रिकॉर्ड होते हैं।"
system_audio = "सिस्टम ऑडियो"
video_detail = "MP4 · {width}×{height}"

[editor.export.turbo]
title = "टर्बो एक्सपोर्ट"
description = "हर CPU कोर और GPU का इस्तेमाल करके कहीं तेज़ी से एक्सपोर्ट करता है"
Expand Down
Loading
Loading