Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: isolate desktop exports in sidecar

Richie McIlroy72fb5b6a1f97
diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs
index 79d9eedfe..c57822b71 100644
--- a/apps/cli/src/main.rs
+++ b/apps/cli/src/main.rs
@@ -1,14 +1,17 @@
mod record;
use std::{
- io::{Write, stdout},
+ io::{Write, stderr, stdout},
path::PathBuf,
+ sync::{Arc, Mutex},
};
-use cap_export::ExporterBase;
+use cap_export::{ExporterBase, make_cursor_only_project};
+use cap_project::RecordingMeta;
use cap_project::XY;
use clap::{Args, Parser, Subcommand};
use record::RecordStart;
+use serde::{Deserialize, Serialize};
use serde_json::json;
use tracing::*;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
@@ -62,7 +65,8 @@ async fn main() -> Result<(), String> {
.with(
tracing_subscriber::fmt::layer()
.with_ansi(true)
- .with_target(true),
+ .with_target(true)
+ .with_writer(stderr),
)
.init();
@@ -70,9 +74,7 @@ async fn main() -> Result<(), String> {
match cli.command {
Commands::Export(e) => {
- if let Err(e) = e.run().await {
- eprint!("Export failed: {e}")
- }
+ e.run().await?;
}
Commands::Record(RecordArgs { command, args }) => match command {
Some(RecordCommands::Screens) => {
@@ -152,47 +154,160 @@ window {}:
struct Export {
project_path: PathBuf,
output_path: Option<PathBuf>,
+ #[arg(long)]
+ settings_json: Option<String>,
+ #[arg(long)]
+ force_ffmpeg_decoder: bool,
+ #[arg(long)]
+ progress_json: bool,
}
-impl Export {
- async fn run(self) -> Result<(), String> {
- let exporter_base = ExporterBase::builder(self.project_path)
- .build()
- .await
- .map_err(|v| format!("Exporter build error: {v}"))?;
-
- let mut stdout = stdout();
+#[derive(Deserialize)]
+#[serde(tag = "format")]
+enum CliExportSettings {
+ Mp4(cap_export::mp4::Mp4ExportSettings),
+ Gif(cap_export::gif::GifExportSettings),
+ Mov(cap_export::mov::MovExportSettings),
+}
- let exporter_output_path = cap_export::mp4::Mp4ExportSettings {
+impl CliExportSettings {
+ fn default_mp4() -> Self {
+ Self::Mp4(cap_export::mp4::Mp4ExportSettings {
fps: 60,
resolution_base: XY::new(1920, 1080),
compression: cap_export::mp4::ExportCompression::Maximum,
custom_bpp: None,
force_ffmpeg_decoder: false,
optimize_filesize: false,
+ })
+ }
+
+ fn fps(&self) -> u32 {
+ match self {
+ Self::Mp4(settings) => settings.fps,
+ Self::Gif(settings) => settings.fps,
+ Self::Mov(settings) => settings.fps,
}
- .export(exporter_base, move |_f| {
- // print!("\rrendered frame {f}");
+ }
- stdout.flush().unwrap();
- true
- })
- .await
- .map_err(|v| format!("Exporter error: {v}"))?;
+ fn force_ffmpeg_decoder(&self) -> bool {
+ match self {
+ Self::Mp4(settings) => settings.force_ffmpeg_decoder,
+ Self::Gif(_) | Self::Mov(_) => false,
+ }
+ }
+
+ fn cursor_only(&self) -> bool {
+ match self {
+ Self::Mov(settings) => settings.cursor_only,
+ Self::Mp4(_) | Self::Gif(_) => false,
+ }
+ }
+}
+
+#[derive(Serialize)]
+#[serde(tag = "type")]
+enum ExportProgressMessage<'a> {
+ Progress {
+ rendered_count: u32,
+ total_frames: u32,
+ },
+ Completed {
+ path: &'a std::path::Path,
+ },
+}
+
+impl Export {
+ async fn run(self) -> Result<(), String> {
+ let settings = self
+ .settings_json
+ .as_deref()
+ .map(serde_json::from_str)
+ .transpose()
+ .map_err(|e| format!("Invalid export settings JSON: {e}"))?
+ .unwrap_or_else(CliExportSettings::default_mp4);
+
+ let force_ffmpeg_decoder = self.force_ffmpeg_decoder || settings.force_ffmpeg_decoder();
+ let mut builder = ExporterBase::builder(self.project_path.clone())
+ .with_force_ffmpeg_decoder(force_ffmpeg_decoder);
+
+ if let Some(output_path) = self.output_path {
+ builder = builder.with_output_path(output_path);
+ }
+
+ if settings.cursor_only() {
+ let meta = RecordingMeta::load_for_project(&self.project_path)
+ .map_err(|e| format!("Failed to load recording meta: {e}"))?;
+ builder = builder.with_config(make_cursor_only_project(meta.project_config()));
+ }
+
+ let exporter_base = builder
+ .build()
+ .await
+ .map_err(|v| format!("Exporter build error: {v}"))?;
- let output_path = if let Some(output_path) = self.output_path {
- std::fs::copy(&exporter_output_path, &output_path).unwrap();
- output_path
- } else {
- exporter_output_path
+ let total_frames = exporter_base.total_frames(settings.fps());
+ let progress_json = self.progress_json;
+ let stdout = Arc::new(Mutex::new(stdout()));
+
+ if progress_json {
+ emit_export_message(
+ &stdout,
+ &ExportProgressMessage::Progress {
+ rendered_count: 0,
+ total_frames,
+ },
+ )?;
+ }
+
+ let progress_stdout = Arc::clone(&stdout);
+ let on_progress = move |frame_index: u32| {
+ if progress_json {
+ emit_export_message(
+ &progress_stdout,
+ &ExportProgressMessage::Progress {
+ rendered_count: (frame_index + 1).min(total_frames),
+ total_frames,
+ },
+ )
+ .is_ok()
+ } else {
+ true
+ }
};
+ let output_path = match settings {
+ CliExportSettings::Mp4(settings) => settings.export(exporter_base, on_progress).await,
+ CliExportSettings::Gif(settings) => settings.export(exporter_base, on_progress).await,
+ CliExportSettings::Mov(settings) => settings.export(exporter_base, on_progress).await,
+ }
+ .map_err(|v| format!("Exporter error: {v}"))?;
+
+ if self.progress_json {
+ emit_export_message(
+ &stdout,
+ &ExportProgressMessage::Completed { path: &output_path },
+ )?;
+ }
+
info!("Exported video to '{}'", output_path.display());
Ok(())
}
}
+fn emit_export_message(
+ stdout: &Arc<Mutex<std::io::Stdout>>,
+ message: &ExportProgressMessage<'_>,
+) -> Result<(), String> {
+ let mut stdout = stdout
+ .lock()
+ .map_err(|_| "Failed to lock stdout".to_string())?;
+ serde_json::to_writer(&mut *stdout, message).map_err(|e| e.to_string())?;
+ writeln!(&mut *stdout).map_err(|e| e.to_string())?;
+ stdout.flush().map_err(|e| e.to_string())
+}
+
// fn ffmpeg_callback_experiment() {
// unsafe {
// unsafe extern "C" fn ffmpeg_log_callback(
diff --git a/apps/desktop/scripts/prepare.js b/apps/desktop/scripts/prepare.js
index 05cc27d40..6ddc5f6b8 100644
--- a/apps/desktop/scripts/prepare.js
+++ b/apps/desktop/scripts/prepare.js
@@ -80,6 +80,7 @@ export async function createTauriPlatformConfigs(
baseConfig = {
...baseConfig,
bundle: {
+ externalBin: ["binaries/cap-muxer", "binaries/cap-exporter"],
resources: {
"../../../target/ffmpeg/bin/*.dll": "./",
},
@@ -99,6 +100,7 @@ export async function createTauriPlatformConfigs(
baseConfig = {
...baseConfig,
bundle: {
+ externalBin: ["binaries/cap-muxer", "binaries/cap-exporter"],
resources: {
"../../../target/native-deps/onnxruntime/lib/libonnxruntime.dylib":
"onnxruntime/lib/libonnxruntime.dylib",
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index d909b6c89..b9c9d50bc 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -14,11 +14,13 @@ use std::any::Any;
use std::panic::AssertUnwindSafe;
use std::{
path::{Path, PathBuf},
+ process::Stdio,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
+use tokio::io::AsyncBufReadExt;
use tracing::{error, info, instrument};
fn panic_message(panic: Box<dyn Any + Send>) -> String {
@@ -58,6 +60,232 @@ async fn run_protected_export(
}
}
+const EXPORTER_ENV_BIN_PATH: &str = "CAP_EXPORTER_BIN";
+const EXPORTER_STDERR_TAIL_LIMIT: usize = 80;
+
+#[derive(Deserialize)]
+#[serde(tag = "type")]
+enum ExportSidecarMessage {
+ Progress {
+ rendered_count: u32,
+ total_frames: u32,
+ },
+ Completed {
+ path: PathBuf,
+ },
+}
+
+async fn run_out_of_process_export(
+ project_path: &Path,
+ settings: &ExportSettings,
+ progress: &tauri::ipc::Channel<FramesRendered>,
+ force_ffmpeg: bool,
+) -> Result<PathBuf, String> {
+ match run_out_of_process_export_attempt(project_path, settings, progress, force_ffmpeg, false)
+ .await
+ {
+ Ok(path) => Ok(path),
+ Err(e) if e != "Export cancelled" => {
+ error!(
+ error = %e,
+ "Export worker failed, retrying with software rendering and encoding"
+ );
+ run_out_of_process_export_attempt(project_path, settings, progress, force_ffmpeg, true)
+ .await
+ }
+ Err(e) => Err(e),
+ }
+}
+
+async fn run_out_of_process_export_attempt(
+ project_path: &Path,
+ settings: &ExportSettings,
+ progress: &tauri::ipc::Channel<FramesRendered>,
+ force_ffmpeg: bool,
+ safe_mode: bool,
+) -> Result<PathBuf, String> {
+ let bin_path = resolve_exporter_binary()?;
+ let settings_json = serde_json::to_string(settings)
+ .map_err(|e| format!("Failed to serialize settings: {e}"))?;
+
+ info!(
+ path = %bin_path.display(),
+ project_path = %project_path.display(),
+ force_ffmpeg,
+ safe_mode,
+ "Starting export worker process"
+ );
+
+ let mut command = tokio::process::Command::new(&bin_path);
+ command
+ .arg("export")
+ .arg(project_path)
+ .arg("--settings-json")
+ .arg(settings_json)
+ .arg("--progress-json")
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ if force_ffmpeg {
+ command.arg("--force-ffmpeg-decoder");
+ }
+
+ if safe_mode {
+ command
+ .env("CAP_RENDER_FORCE_SOFTWARE_ADAPTER", "1")
+ .env("CAP_EXPORT_FORCE_SOFTWARE_ENCODER", "1");
+ }
+
+ let mut child = command.spawn().map_err(|e| {
+ format!(
+ "Failed to start export worker '{}': {e}",
+ bin_path.display()
+ )
+ })?;
+
+ let stdout = child
+ .stdout
+ .take()
+ .ok_or_else(|| "Export worker stdout was not captured".to_string())?;
+ let stderr = child
+ .stderr
+ .take()
+ .ok_or_else(|| "Export worker stderr was not captured".to_string())?;
+ let stderr_task = tokio::spawn(collect_exporter_stderr_tail(stderr));
+
+ let mut completed_path = None;
+ let mut stdout_lines = tokio::io::BufReader::new(stdout).lines();
+
+ while let Some(line) = stdout_lines
+ .next_line()
+ .await
+ .map_err(|e| format!("Failed reading export worker stdout: {e}"))?
+ {
+ match serde_json::from_str::<ExportSidecarMessage>(&line) {
+ Ok(ExportSidecarMessage::Progress {
+ rendered_count,
+ total_frames,
+ }) => {
+ if progress
+ .send(FramesRendered {
+ rendered_count,
+ total_frames,
+ })
+ .is_err()
+ {
+ let _ = child.kill().await;
+ return Err("Export cancelled".to_string());
+ }
+ }
+ Ok(ExportSidecarMessage::Completed { path }) => {
+ completed_path = Some(path);
+ }
+ Err(e) => {
+ error!(
+ line = %line,
+ error = %e,
+ "Ignoring invalid export worker stdout line"
+ );
+ }
+ }
+ }
+
+ let status = child
+ .wait()
+ .await
+ .map_err(|e| format!("Failed waiting for export worker: {e}"))?;
+ let stderr_tail = stderr_task.await.unwrap_or_default();
+
+ if !status.success() {
+ let stderr_tail = stderr_tail.join("\n");
+ return Err(format!(
+ "Export worker exited with status {status}. Stderr tail:\n{stderr_tail}"
+ ));
+ }
+
+ completed_path
+ .ok_or_else(|| "Export worker finished without reporting an output path".to_string())
+}
+
+async fn collect_exporter_stderr_tail(stderr: tokio::process::ChildStderr) -> Vec<String> {
+ let mut lines = tokio::io::BufReader::new(stderr).lines();
+ let mut tail = Vec::new();
+
+ loop {
+ match lines.next_line().await {
+ Ok(Some(line)) => {
+ info!(line = %line, "Export worker stderr");
+ tail.push(line);
+ if tail.len() > EXPORTER_STDERR_TAIL_LIMIT {
+ tail.remove(0);
+ }
+ }
+ Ok(None) => break,
+ Err(e) => {
+ tail.push(format!("failed reading stderr: {e}"));
+ break;
+ }
+ }
+ }
+
+ tail
+}
+
+fn resolve_exporter_binary() -> Result<PathBuf, String> {
+ if let Ok(override_path) = std::env::var(EXPORTER_ENV_BIN_PATH) {
+ let path = PathBuf::from(override_path);
+ if path.exists() {
+ return Ok(path);
+ }
+ return Err(format!(
+ "{EXPORTER_ENV_BIN_PATH} points to missing path: {}",
+ path.display()
+ ));
+ }
+
+ let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
+ if let Some(dir) = exe.parent() {
+ let candidate = dir.join(exporter_bin_name());
+ if candidate.exists() {
+ return Ok(candidate);
+ }
+
+ let candidate = dir.join("..").join("MacOS").join(exporter_bin_name());
+ if candidate.exists() {
+ return Ok(candidate);
+ }
+ }
+
+ if let Ok(cwd) = std::env::current_dir() {
+ for candidate in [
+ cwd.join("target").join("debug").join(cli_bin_name()),
+ cwd.join("target").join("release").join(cli_bin_name()),
+ ] {
+ if candidate.exists() {
+ return Ok(candidate);
+ }
+ }
+ }
+
+ Err(format!(
+ "Export worker binary not found; set {EXPORTER_ENV_BIN_PATH} or place {} next to the app executable",
+ exporter_bin_name()
+ ))
+}
+
+fn exporter_bin_name() -> &'static str {
+ if cfg!(windows) {
+ "cap-exporter.exe"
+ } else {
+ "cap-exporter"
+ }
+}
+
+fn cli_bin_name() -> &'static str {
+ if cfg!(windows) { "cap.exe" } else { "cap" }
+}
+
struct ExportActiveGuard<'a>(&'a AtomicBool);
impl Drop for ExportActiveGuard<'_> {
@@ -89,7 +317,7 @@ async fn wait_for_export_preview_idle(flag: &AtomicBool) {
}
}
-#[derive(Deserialize, Clone, Copy, Debug, Type)]
+#[derive(Serialize, Deserialize, Clone, Copy, Debug, Type)]
#[serde(tag = "format")]
pub enum ExportSettings {
Mp4(cap_export::mp4::Mp4ExportSettings),
@@ -206,14 +434,29 @@ fn is_frame_decode_error(error: &str) -> bool {
}
fn should_force_ffmpeg_export(_project_path: &Path, settings: &ExportSettings) -> bool {
- settings.force_ffmpeg_decoder() || should_use_windows_release_export_workaround()
+ settings.force_ffmpeg_decoder() || should_use_windows_release_ffmpeg_workaround()
}
fn should_force_ffmpeg_preview() -> bool {
- should_use_windows_release_export_workaround()
+ should_use_windows_release_ffmpeg_workaround()
+}
+
+fn should_use_out_of_process_export() -> bool {
+ should_use_release_export_sidecar()
}
-fn should_use_windows_release_export_workaround() -> bool {
+fn should_disable_in_process_export_preview() -> bool {
+ should_use_release_export_sidecar()
+}
+
+fn should_use_release_export_sidecar() -> bool {
+ cfg!(all(
+ any(target_os = "macos", target_os = "windows"),
+ not(debug_assertions)
+ ))
+}
+
+fn should_use_windows_release_ffmpeg_workaround() -> bool {
cfg!(all(target_os = "windows", not(debug_assertions)))
}
@@ -246,7 +489,11 @@ pub async fn export_video(
wait_for_export_preview_idle(&ed.export_preview_active).await;
}
- let result = run_protected_export(&project_path, &settings, &progress, force_ffmpeg).await;
+ let result = if should_use_out_of_process_export() {
+ run_out_of_process_export(&project_path, &settings, &progress, force_ffmpeg).await
+ } else {
+ run_protected_export(&project_path, &settings, &progress, force_ffmpeg).await
+ };
match result {
Ok(path) => {
@@ -437,6 +684,11 @@ async fn generate_export_preview_inner(
frame_time: f64,
settings: ExportPreviewSettings,
) -> Result<ExportPreviewResult, String> {
+ if should_disable_in_process_export_preview() {
+ info!("Skipping in-process export preview for production export sidecar build");
+ return Err("Export preview disabled for this build".to_string());
+ }
+
use base64::{Engine, engine::general_purpose::STANDARD};
use cap_editor::create_segments;
use std::time::Instant;
@@ -737,15 +989,14 @@ async fn generate_export_preview_fast_inner(
return Err("Export is in progress - preview generation skipped".to_string());
}
- #[cfg(all(target_os = "windows", not(debug_assertions)))]
+ #[cfg(all(any(target_os = "macos", target_os = "windows"), not(debug_assertions)))]
{
- let _preview_guard = ExportPreviewActiveGuard::try_new(&editor.export_preview_active)?;
- info!("Using isolated FFmpeg renderer for Windows export preview");
- return generate_export_preview_inner(editor.project_path.clone(), frame_time, settings)
- .await;
+ let _ = (editor, frame_time, settings);
+ info!("Skipping in-process export preview for production export sidecar build");
+ return Err("Export preview disabled for this build".to_string());
}
- #[cfg(any(not(target_os = "windows"), debug_assertions))]
+ #[cfg(any(not(any(target_os = "macos", target_os = "windows")), debug_assertions))]
{
use base64::{Engine, engine::general_purpose::STANDARD};
use std::time::Instant;
diff --git a/apps/desktop/src/routes/editor/ExportPage.tsx b/apps/desktop/src/routes/editor/ExportPage.tsx
index 06f9c66fa..8c20a5f57 100644
--- a/apps/desktop/src/routes/editor/ExportPage.tsx
+++ b/apps/desktop/src/routes/editor/ExportPage.tsx
@@ -275,6 +275,7 @@ export function ExportPage() {
const [previewUrl, setPreviewUrl] = createSignal<string | null>(null);
const [previewLoading, setPreviewLoading] = createSignal(false);
+ const [previewUnavailable, setPreviewUnavailable] = createSignal(false);
const [renderEstimate, setRenderEstimate] = createSignal<{
frameRenderTimeMs: number;
totalFrames: number;
@@ -388,6 +389,7 @@ export function ExportPage() {
if (!cachedEstimate) {
estimateCache.set(cacheKey, newEstimate);
}
+ setPreviewUnavailable(false);
setRenderEstimate(newEstimate);
} catch (e) {
console.error("Failed to generate preview:", e);
@@ -397,6 +399,7 @@ export function ExportPage() {
);
return runPreviewRequest(request, retryCount + 1);
}
+ setPreviewUnavailable(true);
}
};
@@ -407,6 +410,7 @@ export function ExportPage() {
resHeight: number,
bpp: number,
) => {
+ setPreviewUnavailable(false);
pendingPreviewRequest = { frameTime, fps, resWidth, resHeight, bpp };
if (previewInFlight) return;
@@ -768,7 +772,11 @@ export function ExportPage() {
fallback={
<div class="flex flex-col items-center gap-3 text-gray-10">
<IconLucideImage class="size-12 text-gray-8" />
- <span class="text-sm">Generating preview...</span>
+ <span class="text-sm">
+ {previewUnavailable()
+ ? "Preview unavailable"
+ : "Generating preview..."}
+ </span>
</div>
}
>
@@ -804,7 +812,9 @@ export function ExportPage() {
</div>
<Show
- when={!previewLoading() && renderEstimate()}
+ when={
+ !previewUnavailable() && !previewLoading() && renderEstimate()
+ }
fallback={
<div class="flex items-center justify-center gap-4 mt-4 h-4 text-xs text-gray-11">
<span class="flex items-center gap-1.5">
diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs
index ae8f1da80..6a863dc86 100644
--- a/crates/enc-ffmpeg/src/video/h264.rs
+++ b/crates/enc-ffmpeg/src/video/h264.rs
@@ -867,6 +867,10 @@ fn get_encoder_priority_with_override(
preset: H264Preset,
override_priority: Option<&'static [&'static str]>,
) -> &'static [&'static str] {
+ if force_software_encoder() {
+ return &["libx264"];
+ }
+
if requires_software_encoder(config, preset) {
return &["libx264"];
}
@@ -874,6 +878,15 @@ fn get_encoder_priority_with_override(
override_priority.unwrap_or_else(|| get_default_encoder_priority(config))
}
+fn force_software_encoder() -> bool {
+ std::env::var("CAP_EXPORT_FORCE_SOFTWARE_ENCODER").is_ok_and(|value| {
+ matches!(
+ value.to_ascii_lowercase().as_str(),
+ "1" | "true" | "yes" | "on"
+ )
+ })
+}
+
fn export_encoder_priority_override(
config: &VideoInfo,
preset: H264Preset,
diff --git a/crates/export/src/gif.rs b/crates/export/src/gif.rs
index 4398e56b6..f7cc4627f 100644
--- a/crates/export/src/gif.rs
+++ b/crates/export/src/gif.rs
@@ -1,14 +1,14 @@
use cap_project::XY;
use cap_rendering::{ProjectUniforms, RenderSegment, RenderedFrame};
use futures::FutureExt;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
use tracing::trace;
use crate::{ExportError, ExporterBase};
-#[derive(Deserialize, Clone, Copy, Debug, Type)]
+#[derive(Serialize, Deserialize, Clone, Copy, Debug, Type)]
pub struct GifQuality {
/// Encoding quality from 1-100 (default: 90)
pub quality: Option<u8>,
@@ -16,7 +16,7 @@ pub struct GifQuality {
pub fast: Option<bool>,
}
-#[derive(Deserialize, Clone, Copy, Debug, Type)]
+#[derive(Serialize, Deserialize, Clone, Copy, Debug, Type)]
pub struct GifExportSettings {
pub fps: u32,
pub resolution_base: XY<u32>,
diff --git a/crates/export/src/mp4.rs b/crates/export/src/mp4.rs
index d4e6f851d..51820281e 100644
--- a/crates/export/src/mp4.rs
+++ b/crates/export/src/mp4.rs
@@ -8,7 +8,7 @@ use cap_rendering::{
};
use futures::FutureExt;
use image::ImageBuffer;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use specta::Type;
use std::{
path::PathBuf,
@@ -20,7 +20,7 @@ use std::{
};
use tracing::{info, trace, warn};
-#[derive(Deserialize, Type, Clone, Copy, Debug)]
+#[derive(Serialize, Deserialize, Type, Clone, Copy, Debug)]
pub enum ExportCompression {
Maximum,
Social,
@@ -62,7 +62,7 @@ pub struct FirstFrameQueuedBenchmark {
pub nv12_render_startup_breakdown_ms: Option<cap_rendering::Nv12RenderStartupBreakdownMs>,
}
-#[derive(Deserialize, Type, Clone, Copy, Debug)]
+#[derive(Serialize, Deserialize, Type, Clone, Copy, Debug)]
pub struct Mp4ExportSettings {
pub fps: u32,
pub resolution_base: XY<u32>,
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index a87a27e61..8c9cb4fa6 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -108,6 +108,15 @@ pub fn is_software_wgpu_adapter(info: &wgpu::AdapterInfo) -> bool {
.contains("microsoft basic render driver")
}
+fn force_software_wgpu_adapter() -> bool {
+ std::env::var("CAP_RENDER_FORCE_SOFTWARE_ADAPTER").is_ok_and(|value| {
+ matches!(
+ value.to_ascii_lowercase().as_str(),
+ "1" | "true" | "yes" | "on"
+ )
+ })
+}
+
pub async fn create_wgpu_instance() -> wgpu::Instance {
#[cfg(not(target_os = "windows"))]
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
@@ -1564,14 +1573,23 @@ impl RenderVideoConstants {
let instance = create_wgpu_instance().await;
- let hardware_adapter = instance
- .request_adapter(&wgpu::RequestAdapterOptions {
- power_preference: wgpu::PowerPreference::HighPerformance,
- force_fallback_adapter: false,
- compatible_surface: None,
- })
- .await
- .ok();
+ let force_software_adapter = force_software_wgpu_adapter();
+ if force_software_adapter {
+ tracing::warn!("Forcing software WGPU adapter");
+ }
+
+ let hardware_adapter = if force_software_adapter {
+ None
+ } else {
+ instance
+ .request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::HighPerformance,
+ force_fallback_adapter: false,
+ compatible_surface: None,
+ })
+ .await
+ .ok()
+ };
let (adapter, is_software_adapter, adapter_name) = if let Some(adapter) = hardware_adapter {
let adapter_info = adapter.get_info();
diff --git a/package.json b/package.json
index 3b8398e5f..8ae22dd6d 100644
--- a/package.json
+++ b/package.json
@@ -25,7 +25,7 @@
"docker:up": "turbo run docker:up",
"format": "pnpm exec biome check --write",
"lint": "pnpm exec biome lint",
- "tauri:build": "node scripts/build-cap-muxer.mjs && dotenv -e .env -- pnpm --dir apps/desktop tauri build --verbose",
+ "tauri:build": "node scripts/build-cap-muxer.mjs && dotenv -e .env -- pnpm --dir apps/desktop run preparescript && dotenv -e .env -- pnpm --dir apps/desktop tauri build --verbose",
"typecheck": "pnpm --dir apps/web exec next typegen && pnpm tsc -b",
"test": "turbo run test",
"test:web": "pnpm --filter=@cap/web test",
diff --git a/scripts/build-cap-muxer.mjs b/scripts/build-cap-muxer.mjs
index c8224efc8..ef01f5a7d 100644
--- a/scripts/build-cap-muxer.mjs
+++ b/scripts/build-cap-muxer.mjs
@@ -65,29 +65,60 @@ async function main() {
const target =
process.argv[2] || process.env.RUST_TARGET_TRIPLE || detectHostTriple();
const ext = target.includes("windows") ? ".exe" : "";
+
+ await fs.mkdir(binariesDir, { recursive: true });
+
+ for (const sidecar of [
+ {
+ packageName: "cap-muxer",
+ sourceBinary: "cap-muxer",
+ destBinary: "cap-muxer",
+ watchPaths: [
+ path.join(repoRoot, "crates", "cap-muxer"),
+ path.join(repoRoot, "crates", "cap-muxer-protocol"),
+ path.join(repoRoot, "Cargo.lock"),
+ ],
+ },
+ {
+ packageName: "cap",
+ sourceBinary: "cap",
+ destBinary: "cap-exporter",
+ watchPaths: [
+ path.join(repoRoot, "apps", "cli"),
+ path.join(repoRoot, "crates", "editor"),
+ path.join(repoRoot, "crates", "enc-ffmpeg"),
+ path.join(repoRoot, "crates", "export"),
+ path.join(repoRoot, "crates", "media"),
+ path.join(repoRoot, "crates", "media-info"),
+ path.join(repoRoot, "crates", "project"),
+ path.join(repoRoot, "crates", "rendering"),
+ path.join(repoRoot, "Cargo.lock"),
+ ],
+ },
+ ]) {
+ await buildSidecar(sidecar, target, ext);
+ }
+}
+
+async function buildSidecar(sidecar, target, ext) {
const src = path.join(
repoRoot,
"target",
target,
"release",
- `cap-muxer${ext}`,
+ `${sidecar.sourceBinary}${ext}`,
);
- const dest = path.join(binariesDir, `cap-muxer-${target}${ext}`);
- const watchPaths = [
- path.join(repoRoot, "crates", "cap-muxer"),
- path.join(repoRoot, "crates", "cap-muxer-protocol"),
- path.join(repoRoot, "Cargo.lock"),
- ];
+ const dest = path.join(binariesDir, `${sidecar.destBinary}-${target}${ext}`);
- if (await isUpToDate(dest, watchPaths)) {
- console.log(`cap-muxer sidecar up to date: ${dest}`);
+ if (await isUpToDate(dest, sidecar.watchPaths)) {
+ console.log(`${sidecar.destBinary} sidecar up to date: ${dest}`);
return;
}
- console.log(`Building cap-muxer sidecar for ${target}...`);
+ console.log(`Building ${sidecar.destBinary} sidecar for ${target}...`);
const cargo = spawnSync(
"cargo",
- ["build", "--release", "-p", "cap-muxer", "--target", target],
+ ["build", "--release", "-p", sidecar.packageName, "--target", target],
{ stdio: "inherit", cwd: repoRoot },
);
if (cargo.status !== 0) {
@@ -99,7 +130,6 @@ async function main() {
process.exit(1);
}
- await fs.mkdir(binariesDir, { recursive: true });
await fs.copyFile(src, dest);
console.log(`Copied ${src} -> ${dest}`);
}
diff --git a/scripts/build-cap-muxer.sh b/scripts/build-cap-muxer.sh
index 69e9c2e4b..2fdd9bfb6 100755
--- a/scripts/build-cap-muxer.sh
+++ b/scripts/build-cap-muxer.sh
@@ -1,8 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
-# Build the cap-muxer sidecar binary with the target-triple suffix Tauri's
-# externalBin expects, and copy it into apps/desktop/src-tauri/binaries.
+# Build desktop sidecar binaries with the target-triple suffix Tauri's
+# externalBin expects, and copy them into apps/desktop/src-tauri/binaries.
#
# Usage:
# scripts/build-cap-muxer.sh # uses host triple
@@ -26,18 +26,27 @@ case "$TARGET" in
*windows*) EXT=".exe" ;;
esac
-echo "Building cap-muxer for $TARGET..."
-cargo build --release -p cap-muxer --target "$TARGET"
-
mkdir -p "$BINARIES_DIR"
-SRC="$REPO_ROOT/target/$TARGET/release/cap-muxer$EXT"
-DEST="$BINARIES_DIR/cap-muxer-$TARGET$EXT"
+build_sidecar() {
+ local package_name="$1"
+ local source_binary="$2"
+ local dest_binary="$3"
-if [[ ! -f "$SRC" ]]; then
- echo "error: built binary not found at $SRC" >&2
- exit 1
-fi
+ echo "Building $dest_binary for $TARGET..."
+ cargo build --release -p "$package_name" --target "$TARGET"
+
+ local src="$REPO_ROOT/target/$TARGET/release/$source_binary$EXT"
+ local dest="$BINARIES_DIR/$dest_binary-$TARGET$EXT"
+
+ if [[ ! -f "$src" ]]; then
+ echo "error: built binary not found at $src" >&2
+ exit 1
+ fi
+
+ cp "$src" "$dest"
+ echo "Copied $(realpath "$src" 2>/dev/null || echo "$src") -> $dest"
+}
-cp "$SRC" "$DEST"
-echo "Copied $(realpath "$SRC" 2>/dev/null || echo "$SRC") -> $DEST"
+build_sidecar "cap-muxer" "cap-muxer" "cap-muxer"
+build_sidecar "cap" "cap" "cap-exporter"