Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(export): report real native export progress to the UI

Etienne Lescot61ea4b6b0acd
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts
index 79937b14d..8c55cc5e4 100644
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@ -29,6 +29,10 @@ interface Window {
) => Promise<import("../src/native/contracts").NativeBridgeResponse<TData>>;
/** Export bench only (--bench=): tells main the run is over so it can quit. */
benchFinished?: () => Promise<void>;
+ /** Native (D3D) export progress — frames encoded so far, pushed at ~10 Hz max while
+ * `compositor.export`/`compositor.exportMulti` runs. Distinct from `exportOnFrameAck`,
+ * the OLD web/CPU pipeline's per-frame ack, not a progress signal. */
+ onNativeExportProgress?: (callback: (frames: number) => void) => () => void;
getSources: (opts: Electron.SourcesOptions) => Promise<ProcessedDesktopSource[]>;
switchToEditor: () => Promise<void>;
switchToHud: () => Promise<void>;
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index aa4ee121d..63fe43bc2 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -399,7 +399,15 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
compositorViewService.destroyView(request.payload.id);
return createSuccessResponse(requestId, { ok: true });
case "export": {
- const stats = await compositorViewService.export(request.payload.outPath);
+ const sender = event.sender;
+ const stats = await compositorViewService.export(
+ request.payload.outPath,
+ (frames) => {
+ if (!sender.isDestroyed()) {
+ sender.send("export:native-progress", frames);
+ }
+ },
+ );
if (!stats) {
return createErrorResponse(
requestId,
@@ -410,11 +418,17 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
return createSuccessResponse(requestId, stats);
}
case "exportMulti": {
+ const sender = event.sender;
const stats = await compositorViewService.exportMulti(
request.payload.clips,
request.payload.outPath,
request.payload.sceneJson,
request.payload.params,
+ (frames) => {
+ if (!sender.isDestroyed()) {
+ sender.send("export:native-progress", frames);
+ }
+ },
);
if (!stats) {
return createErrorResponse(
diff --git a/electron/native-bridge/services/compositorViewService.ts b/electron/native-bridge/services/compositorViewService.ts
index 78916472e..e3e53901e 100644
--- a/electron/native-bridge/services/compositorViewService.ts
+++ b/electron/native-bridge/services/compositorViewService.ts
@@ -313,26 +313,33 @@ export class CompositorViewService {
}
/** Native export (fixture -> MP4, C8). Auto-pauses live previews to free the GPU.
+ * `onProgress` (frames encoded so far) is optional, forwarded straight from the addon's
+ * own throttled (~10/s) callback — cheap, the encode loop already ticks this per frame.
* Returns null when the addon is absent. */
- async export(outPath?: string): Promise<ExportStats | null> {
+ async export(
+ outPath?: string,
+ onProgress?: (frames: number) => void,
+ ): Promise<ExportStats | null> {
const addon = this.ensureAddon();
if (!addon) {
return null;
}
const target = outPath ?? path.join(app.getPath("temp"), "openscreen-native-export.mp4");
- return addon.export(target);
+ return addon.export(target, onProgress);
}
/** Native multiclip export (real timeline -> MP4). Auto-pauses previews via the addon.
* `sceneJson` — same scene as the live preview (background/layout/webcam/cursor/effects);
* goes through the same asset-path resolution as `setScene` (wallpaper image, cursor theme
* sprite) since the native process can't resolve renderer-relative URLs either.
+ * `onProgress` — see `export()` above.
* Returns null when the addon is absent. */
async exportMulti(
clips: ClipInput[],
outPath?: string,
sceneJson?: string,
params?: ExportParamsInput,
+ onProgress?: (frames: number) => void,
): Promise<ExportStats | null> {
const addon = this.ensureAddon();
if (!addon) {
@@ -344,6 +351,7 @@ export class CompositorViewService {
target,
sceneJson ? resolveSceneAssetPaths(sceneJson) : undefined,
params,
+ onProgress,
);
}
}
diff --git a/electron/native/compositor-view/addon.d.ts b/electron/native/compositor-view/addon.d.ts
index 93eed62c2..42fa2c6ab 100644
--- a/electron/native/compositor-view/addon.d.ts
+++ b/electron/native/compositor-view/addon.d.ts
@@ -94,17 +94,22 @@ export interface CompositorViewAddon {
sourceTimeSec: number,
): void;
destroyView(id: number): void;
- /** Renders the fixture to `outPath` (C8), auto-pausing live previews. */
- export(outPath: string): Promise<ExportStats>;
+ /** Renders the fixture to `outPath` (C8), auto-pausing live previews. `onProgress`
+ * (frames encoded so far) is optional and called at most ~10/s from the render
+ * thread — cheap: the encode loop already ticks a progress hook every frame, this
+ * just forwards it (throttled) instead of the previous no-op. */
+ export(outPath: string, onProgress?: (frames: number) => void): Promise<ExportStats>;
/** Renders the real timeline (ordered clips + trims) to `outPath`, auto-pausing previews.
* `sceneJson` — same `SceneDescription` as the live preview (background/layout/webcam/cursor/
* effects); omitted or invalid → nothing configured is applied (not a masking fallback).
- * `params` — output size/fps/codec; omitted → 1920x1080/first clip's fps/h264. */
+ * `params` — output size/fps/codec; omitted → 1920x1080/first clip's fps/h264.
+ * `onProgress` (frames encoded so far) is optional, throttled to ~10/s. */
exportMulti(
clips: ClipInput[],
outPath: string,
sceneJson?: string,
params?: ExportParamsInput,
+ onProgress?: (frames: number) => void,
): Promise<ExportStats>;
}
diff --git a/electron/preload.ts b/electron/preload.ts
index 667f4ba0d..6137d3a24 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -55,6 +55,14 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.invoke("export:cancel", sessionId) as Promise<void>,
/** Export bench only (--bench=): tells main the run is over so it can quit. */
benchFinished: () => ipcRenderer.invoke("bench:finished") as Promise<void>,
+ /** Native (D3D) export progress — frames encoded so far, pushed at ~10 Hz max while
+ * `compositor.export`/`compositor.exportMulti` runs. Distinct from `exportOnFrameAck`
+ * above, which is the OLD web/CPU pipeline's per-frame ack, not a progress signal. */
+ onNativeExportProgress: (cb: (frames: number) => void) => {
+ const handler = (_e: unknown, frames: number) => cb(frames);
+ ipcRenderer.on("export:native-progress", handler);
+ return () => ipcRenderer.off("export:native-progress", handler);
+ },
invokeNativeBridge: <TData>(request: NativeBridgeRequest) => {
return ipcRenderer.invoke(NATIVE_BRIDGE_CHANNEL, request) as Promise<TData>;
},
diff --git a/poc-d3d/compositor-view-napi/src/lib.rs b/poc-d3d/compositor-view-napi/src/lib.rs
index 5676223d8..3bd4cdb92 100644
--- a/poc-d3d/compositor-view-napi/src/lib.rs
+++ b/poc-d3d/compositor-view-napi/src/lib.rs
@@ -6,7 +6,8 @@
//! et sont récupérés via `read_frame`.
use napi::bindgen_prelude::*;
-use napi::{Env, Task};
+use napi::threadsafe_function::{ErrorStrategy, ThreadsafeFunction, ThreadsafeFunctionCallMode};
+use napi::{Env, JsFunction, Task};
use napi_derive::napi;
use poc_d3d::compositor::{live_params_from_scene, Compositor};
use poc_d3d::cursor::CursorTrack;
@@ -229,6 +230,29 @@ pub struct ExportStats {
/// directement au bench headless. Le device/compositeur/encodeur vivent sur ce thread.
pub struct ExportTask {
out_path: String,
+ on_progress: Option<ThreadsafeFunction<u32, ErrorStrategy::Fatal>>,
+}
+
+/// Builds a `progress: &mut dyn FnMut(u64)` closure (the shape both `run_composited` and
+/// `run_composited_multi` already call once per encoded frame, for free — measured to not
+/// affect the C8 benchmark's fps) that forwards to `tsfn`, throttled to ~10/s. Encoding at
+/// typical export rates would otherwise cross the JS thread boundary dozens of times a
+/// second for no UI benefit; the throttle keeps that cost negligible regardless of encode
+/// speed. Always reports the very first tick (frame <= 1) so a fast/short export still
+/// shows at least one progress update instead of jumping straight to the final Promise
+/// resolution.
+fn throttled_progress(
+ tsfn: Option<ThreadsafeFunction<u32, ErrorStrategy::Fatal>>,
+) -> impl FnMut(u64) {
+ let mut last_sent = std::time::Instant::now() - std::time::Duration::from_secs(1);
+ move |frames: u64| {
+ let Some(tsfn) = &tsfn else { return };
+ let now = std::time::Instant::now();
+ if frames <= 1 || now.duration_since(last_sent).as_millis() >= 100 {
+ last_sent = now;
+ tsfn.call(frames as u32, ThreadsafeFunctionCallMode::NonBlocking);
+ }
+ }
}
/// Active/désactive la composition de toutes les previews vivantes (même process).
@@ -258,6 +282,7 @@ impl Task for ExportTask {
comp.set_cursor(t);
}
let cfg = config::all().pop().expect("au moins une config"); // C8
+ let mut progress = throttled_progress(self.on_progress.take());
let s = pipeline::run_composited(
&format!("{dir}/screen.mp4"),
&format!("{dir}/webcam.mp4"),
@@ -265,7 +290,7 @@ impl Task for ExportTask {
&gpu,
&comp,
&cfg,
- &mut |_| {},
+ &mut progress,
)
.map_err(|e| Error::from_reason(format!("{e:#}")))?;
Ok((s.frames as u32, s.wall_s, s.fps, s.video_duration_s))
@@ -279,10 +304,22 @@ impl Task for ExportTask {
}
}
+/// Convertit une fonction JS optionnelle en `ThreadsafeFunction` appelable depuis le thread
+/// libuv qui exécute `Task::compute` — c'est la seule façon de rappeler JS depuis là. Chaque
+/// appel transporte juste le nombre de frames encodées (`u32`) ; le JS connaît déjà le total
+/// attendu (durée × fps des clips) et calcule le pourcentage lui-même.
+fn make_progress_tsfn(
+ f: Option<JsFunction>,
+) -> Result<Option<ThreadsafeFunction<u32, ErrorStrategy::Fatal>>> {
+ f.map(|f| f.create_threadsafe_function(0, |ctx| Ok(vec![ctx.value])))
+ .transpose()
+}
+
/// Lance un export natif (fixture → MP4, C8) et résout `Promise<ExportStats>`.
+/// `on_progress(framesEncodées)` optionnel — rappelé côté JS à ~10 Hz max pendant le rendu.
#[napi]
-pub fn export(out_path: String) -> AsyncTask<ExportTask> {
- AsyncTask::new(ExportTask { out_path })
+pub fn export(out_path: String, on_progress: Option<JsFunction>) -> Result<AsyncTask<ExportTask>> {
+ Ok(AsyncTask::new(ExportTask { out_path, on_progress: make_progress_tsfn(on_progress)? }))
}
/// Un clip de la timeline pour l'export multiclip (JS : camelCase).
@@ -321,6 +358,7 @@ pub struct ExportMultiTask {
clips: Vec<pipeline::ClipSource>,
scene_json: Option<String>,
params: Option<ExportParamsInput>,
+ on_progress: Option<ThreadsafeFunction<u32, ErrorStrategy::Fatal>>,
}
impl Task for ExportMultiTask {
@@ -372,6 +410,7 @@ impl Task for ExportMultiTask {
}
}
+ let mut progress = throttled_progress(self.on_progress.take());
let s = pipeline::run_composited_multi(
&self.clips,
&self.out_path,
@@ -379,7 +418,7 @@ impl Task for ExportMultiTask {
&comp,
&cfg,
&export_params,
- &mut |_| {},
+ &mut progress,
)
.map_err(|e| Error::from_reason(format!("{e:#}")))?;
Ok((s.frames as u32, s.wall_s, s.fps, s.video_duration_s))
@@ -396,13 +435,16 @@ impl Task for ExportMultiTask {
/// Lance un export multiclip natif (vraie timeline → MP4) et résout `Promise<ExportStats>`.
/// `scene_json` : même `SceneDescription` que la preview (fond/layout/webcam/effets/curseur).
/// `params` : taille/cadence/codec de sortie voulus (absent → 1920x1080/fps du 1er clip/h264).
+/// `on_progress(framesEncodées)` optionnel — rappelé côté JS à ~10 Hz max pendant le rendu ;
+/// le JS calcule lui-même le pourcentage (il connaît déjà le total attendu, durée×fps des clips).
#[napi]
pub fn export_multi(
clips: Vec<ClipInput>,
out_path: String,
scene_json: Option<String>,
params: Option<ExportParamsInput>,
-) -> AsyncTask<ExportMultiTask> {
+ on_progress: Option<JsFunction>,
+) -> Result<AsyncTask<ExportMultiTask>> {
let clips = clips
.into_iter()
.map(|c| pipeline::ClipSource {
@@ -414,5 +456,11 @@ pub fn export_multi(
has_audio: c.has_audio,
})
.collect();
- AsyncTask::new(ExportMultiTask { out_path, clips, scene_json, params })
+ Ok(AsyncTask::new(ExportMultiTask {
+ out_path,
+ clips,
+ scene_json,
+ params,
+ on_progress: make_progress_tsfn(on_progress)?,
+ }))
}
diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsx
index 2baf205d9..714b2fc65 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -319,9 +319,30 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
// cursor/effects come from the same scene as the live preview.
if (format === "mp4") {
setPhase("rendering");
+ // Render the real timeline when there are clips; else fall back to the fixture.
+ const clips = buildNativeClipList(document);
+ // Total frames the encoder will produce, known upfront from the timeline (sum of
+ // each clip's trimmed source duration) — the native side only reports frames
+ // AFTER encoding one (onNativeExportProgress), it doesn't know/send a total, so
+ // this is computed here to turn that raw count into a percentage.
+ const totalDurationSec = clips.reduce(
+ (sum, c) => sum + Math.max(0, c.sourceEndSec - c.sourceStartSec),
+ 0,
+ );
+ const totalFrames = Math.max(1, Math.round(totalDurationSec * fps));
+ const startedAt = Date.now();
+ const unsubscribeProgress = window.electronAPI?.onNativeExportProgress?.((frames) => {
+ const elapsedS = (Date.now() - startedAt) / 1000;
+ const fractionDone = Math.min(1, frames / totalFrames);
+ const estimatedTimeRemaining = fractionDone > 0 ? elapsedS / fractionDone - elapsedS : 0;
+ setProgress({
+ currentFrame: frames,
+ totalFrames,
+ percentage: fractionDone * 100,
+ estimatedTimeRemaining,
+ });
+ });
try {
- // Render the real timeline when there are clips; else fall back to the fixture.
- const clips = buildNativeClipList(document);
const sceneJson = JSON.stringify(buildSceneDescription(document));
const outDims = tierOutputDims(quality);
const stats =
@@ -350,6 +371,8 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
toast.error(t("exportDialog.exportFailed"), {
description: err instanceof Error ? err.message : String(err),
});
+ } finally {
+ unsubscribeProgress?.();
}
return;
}