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(poc-d3d): time-addressable rendering, with the app transport driving the native view

Etienne Lescot0b312a34331c
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index 44afc098b..fe4cdf30b 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -373,6 +373,9 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
case "setPlaying":
compositorViewService.setPlaying(request.payload.id, request.payload.playing);
return createSuccessResponse(requestId, { ok: true });
+ case "presentTime":
+ compositorViewService.presentTime(request.payload.id, request.payload.seconds);
+ return createSuccessResponse(requestId, { ok: true });
case "destroyView":
compositorViewService.destroyView(request.payload.id);
return createSuccessResponse(requestId, { ok: true });
diff --git a/electron/native-bridge/services/compositorViewService.ts b/electron/native-bridge/services/compositorViewService.ts
index aeb34c21e..bb4582788 100644
--- a/electron/native-bridge/services/compositorViewService.ts
+++ b/electron/native-bridge/services/compositorViewService.ts
@@ -197,6 +197,14 @@ export class CompositorViewService {
addon.setPlaying(id, playing);
}
+ presentTime(id: number, seconds: number): void {
+ const addon = this.ensureAddon();
+ if (!addon) {
+ return;
+ }
+ addon.presentTime(id, seconds);
+ }
+
destroyView(id: number): void {
const addon = this.ensureAddon();
this.rects.delete(id);
diff --git a/electron/native/compositor-view/addon.d.ts b/electron/native/compositor-view/addon.d.ts
index 09b1926a0..351327cf5 100644
--- a/electron/native/compositor-view/addon.d.ts
+++ b/electron/native/compositor-view/addon.d.ts
@@ -27,6 +27,8 @@ export interface CompositorViewAddon {
setRect(id: number, rect: CompositorViewRect): void;
setParam(id: number, key: string, value: CompositorParamValue): void;
setPlaying(id: number, playing: boolean): void;
+ /** Seeks the view to `seconds` (app playhead-driven). */
+ presentTime(id: number, seconds: number): void;
destroyView(id: number): void;
/** Renders the fixture to `outPath` (C8), auto-pausing live previews. */
export(outPath: string): Promise<ExportStats>;
diff --git a/poc-d3d/compositor-view-napi/src/lib.rs b/poc-d3d/compositor-view-napi/src/lib.rs
index 6b9356165..583d50d35 100644
--- a/poc-d3d/compositor-view-napi/src/lib.rs
+++ b/poc-d3d/compositor-view-napi/src/lib.rs
@@ -102,6 +102,14 @@ pub fn set_playing(id: i32, playing: bool) {
}
}
+/// Positionne la vue au temps `seconds` (seek piloté par la playhead de l'app).
+#[napi]
+pub fn present_time(id: i32, seconds: f64) {
+ if let Some(v) = registry().lock().unwrap().get(&id) {
+ v.set_time(seconds);
+ }
+}
+
#[napi]
pub fn destroy_view(id: i32) {
// remove hors du lock : le Drop (join du thread de rendu + DestroyWindow) ne le tient pas.
diff --git a/poc-d3d/src/live.rs b/poc-d3d/src/live.rs
index b3b5b07dc..9605ec17b 100644
--- a/poc-d3d/src/live.rs
+++ b/poc-d3d/src/live.rs
@@ -34,7 +34,7 @@ use windows::Win32::Graphics::Dxgi::{
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::WindowsAndMessaging::*;
-use crate::compositor::{OUT_H, OUT_W};
+use crate::compositor::{FIXTURE_FRAMES, OUT_H, OUT_W};
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
@@ -99,6 +99,41 @@ impl Player {
comp.compose_frame(sf, wf, f as f32, cfg)?;
Ok(true)
}
+
+ /// Compose la frame à l'index `target` (seek). Seek arrière → rewind puis décodage avant ;
+ /// seek avant → décodage avant en jetant les frames intermédiaires. Simple et robuste
+ /// (pas de calcul PTS/keyframe ; optimisation keyframe possible plus tard).
+ pub unsafe fn present_frame(&mut self, comp: &Compositor, cfg: &Cfg, target: u32) -> Result<bool> {
+ if target < self.idx {
+ self.sdec.rewind()?;
+ self.wdec.rewind()?;
+ self.idx = 0;
+ }
+ loop {
+ let sf = self.sdec.next()?;
+ let wf = self.wdec.next()?;
+ if sf.is_null() || wf.is_null() {
+ // au-delà de la fixture → clamp sur la frame 0
+ self.sdec.rewind()?;
+ self.wdec.rewind()?;
+ self.idx = 0;
+ let sf = self.sdec.next()?;
+ let wf = self.wdec.next()?;
+ if sf.is_null() || wf.is_null() {
+ return Ok(false);
+ }
+ comp.compose_frame(sf, wf, 0.0, cfg)?;
+ self.idx = 1;
+ return Ok(true);
+ }
+ let produced = self.idx;
+ self.idx += 1;
+ if produced == target {
+ comp.compose_frame(sf, wf, produced as f32, cfg)?;
+ return Ok(true);
+ }
+ }
+ }
}
/// Paramètres inspector pilotés depuis l'UI (setParam). Le thread de rendu les applique :
@@ -130,6 +165,8 @@ struct Shared {
/// Le thread de rendu le mappe en coords écran (le parent peut bouger) et repositionne.
rect: Mutex<[i32; 4]>,
inspector: Mutex<InspectorParams>,
+ /// frame demandée par l'app (presentTime/seek) ; prioritaire sur la lecture libre.
+ requested_frame: Mutex<Option<u32>>,
playing: AtomicBool,
stop: AtomicBool,
}
@@ -185,6 +222,7 @@ impl LiveView {
let shared = Arc::new(Shared {
rect: Mutex::new([x, y, w, h]),
inspector: Mutex::new(InspectorParams::default()),
+ requested_frame: Mutex::new(None),
playing: AtomicBool::new(true),
stop: AtomicBool::new(false),
});
@@ -247,6 +285,16 @@ impl LiveView {
pub fn set_playing(&self, playing: bool) {
self.shared.playing.store(playing, Ordering::Relaxed);
}
+
+ /// Positionne la vue sur le temps `seconds` (seek, piloté par la playhead de l'app).
+ /// La fixture boucle (6 s) : le temps est ramené modulo la durée.
+ pub fn set_time(&self, seconds: f64) {
+ let frame = (seconds * 60.0).round() as i64;
+ let frame = frame.rem_euclid(FIXTURE_FRAMES as i64) as u32;
+ if let Ok(mut r) = self.shared.requested_frame.lock() {
+ *r = Some(frame);
+ }
+ }
}
impl Drop for LiveView {
@@ -388,12 +436,18 @@ unsafe fn render_thread(
resized = true;
}
- // avance temporelle (60 fps, horloge murale)
+ // avance : seek app-piloté (presentTime) prioritaire, sinon lecture libre (60 fps)
+ let requested = shared.requested_frame.lock().unwrap().take();
let now = Instant::now();
let dt = (now - last).as_secs_f64().min(0.1);
last = now;
let mut stepped = false;
- if shared.playing.load(Ordering::Relaxed) {
+ if let Some(target) = requested {
+ if player.present_frame(&comp, &cfg, target)? {
+ stepped = true;
+ }
+ acc = 0.0; // resynchronise l'accumulateur de lecture libre après un seek
+ } else if shared.playing.load(Ordering::Relaxed) {
acc += dt;
let step = 1.0 / 60.0;
let mut n = 0;
diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsx
index 17aaea7cc..68eb7ac99 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -28,6 +28,7 @@ import {
type GifSizePreset,
} from "@/lib/exporter";
import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";
+import { exportNative } from "@/native";
import { nativeBridgeClient } from "@/native/client";
import {
type AspectRatio,
@@ -36,6 +37,7 @@ import {
} from "@/utils/aspectRatioUtils";
import { ModalShell } from "./Modals";
import styles from "./NewEditorShell.module.css";
+import { NATIVE_COMPOSITOR_ENABLED } from "./Preview";
type Phase = "idle" | "configuring" | "rendering" | "writing" | "done" | "error";
@@ -182,6 +184,36 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
return;
}
+ // Native compositor POC: route the real export modal to the native D3D
+ // exporter. It renders the fixture (not yet the document) straight to the
+ // picked path and returns measured stats; the format/quality/codec options
+ // above don't feed the POC pipeline yet. Flag-gated so the web exporter is
+ // the default path and untouched when the flag is off.
+ if (NATIVE_COMPOSITOR_ENABLED) {
+ setPhase("rendering");
+ try {
+ const stats = await exportNative(pickedPath);
+ setSavedPath(pickedPath);
+ setPhase("done");
+ toast.success(t("exportDialog.exportedVideo"), {
+ description: `${pickedPath} · ${stats.fps.toFixed(1)} fps · ${stats.frames} frames · ${stats.wallS.toFixed(2)}s`,
+ action: {
+ label: t("exportDialog.showInFolder"),
+ onClick: () => {
+ void window.electronAPI?.revealInFolder?.(pickedPath);
+ },
+ },
+ });
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ setPhase("error");
+ toast.error(t("exportDialog.exportFailed"), {
+ description: err instanceof Error ? err.message : String(err),
+ });
+ }
+ return;
+ }
+
setPhase("rendering");
const options: DocumentExportOptions = {
format,
diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsx
index 7195ecec0..e26a74f0d 100644
--- a/src/components/ai-edition/NativeCompositorOverlay.tsx
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -1,5 +1,5 @@
-import { useEffect, useRef, useState } from "react";
-import { exportNative, setCurrentNativeViewId, useNativeCompositorView } from "@/native";
+import { useEffect, useRef } from "react";
+import { setCurrentNativeViewId, useNativeCompositorView } from "@/native";
/**
* POC Option A — monte une fenêtre D3D11 native (compositeur poc-d3d, via
@@ -8,13 +8,17 @@ import { exportNative, setCurrentNativeViewId, useNativeCompositorView } from "@
* le compositing ; le `<div>` ne sert qu'à donner sa géométrie (le hook sync le
* rect natif au resize/scroll).
*
+ * Aucun contrôle ici : les paramètres viennent de l'inspector (barre latérale) via
+ * le store `nativeCompositorStore` (`setNativeParam`), la lecture via
+ * `useNativePlaybackSync`, et l'export via la vraie modale (`ExportDialog`). Le
+ * `<div>` est recouvert par la fenêtre native, donc on n'y met rien de cliquable.
+ *
* Opt-in via le flag Vite `VITE_NATIVE_COMPOSITOR=1` : par défaut le composant ne
* rend rien et la preview web existante reste inchangée.
*/
export function NativeCompositorOverlay({ enabled }: { enabled: boolean }) {
const mountRef = useRef<HTMLDivElement>(null);
- const { setParam, viewId } = useNativeCompositorView(mountRef, { enabled });
- const [blur, setBlur] = useState(false);
+ const { viewId } = useNativeCompositorView(mountRef, { enabled });
// publie l'id de la vue active dans le store → l'inspector (autre composant) peut
// pousser des params via setNativeParam sans connaître cet overlay.
@@ -22,83 +26,17 @@ export function NativeCompositorOverlay({ enabled }: { enabled: boolean }) {
setCurrentNativeViewId(viewId);
return () => setCurrentNativeViewId(null);
}, [viewId]);
- const [exporting, setExporting] = useState(false);
- const [exportStatus, setExportStatus] = useState("");
if (!enabled) {
return null;
}
- const runExport = async () => {
- setExporting(true);
- setExportStatus("Exporting… (preview paused)");
- try {
- const s = await exportNative();
- setExportStatus(`${s.fps.toFixed(1)} fps · ${s.wallS.toFixed(2)}s · ${s.frames} frames`);
- } catch (err) {
- setExportStatus("export failed");
- console.warn("[compositor-view] export failed:", err);
- } finally {
- setExporting(false);
- }
- };
-
+ // placeholder : sert de géométrie à la fenêtre D3D native (le hook sync le rect).
return (
- <>
- {/* placeholder : sert de géométrie à la fenêtre D3D native (le hook sync le rect).
- Il est recouvert par la fenêtre native, donc on n'y met aucun contrôle. */}
- <div
- ref={mountRef}
- data-testid="native-compositor-mount"
- style={{ position: "absolute", inset: 0, zIndex: 5 }}
- />
- {/* contrôles en position fixe hors de la zone preview → non recouverts par l'overlay natif */}
- <div
- style={{
- position: "fixed",
- top: 64,
- left: 16,
- zIndex: 99999,
- display: "flex",
- flexDirection: "column",
- gap: 6,
- background: "rgba(0,0,0,0.72)",
- color: "#fff",
- padding: "8px 10px",
- borderRadius: 8,
- font: "12px system-ui",
- pointerEvents: "auto",
- }}
- >
- <label style={{ display: "flex", alignItems: "center", gap: 6 }}>
- <input
- type="checkbox"
- checked={blur}
- onChange={(e) => {
- setBlur(e.target.checked);
- setParam("backgroundBlur", e.target.checked);
- }}
- />
- Background blur (native)
- </label>
- <button
- type="button"
- disabled={exporting}
- onClick={runExport}
- style={{
- cursor: exporting ? "default" : "pointer",
- padding: "4px 8px",
- borderRadius: 5,
- border: "none",
- background: "#22dd88",
- color: "#000",
- font: "12px system-ui",
- }}
- >
- {exporting ? "Exporting…" : "Export (native)"}
- </button>
- {exportStatus && <div style={{ opacity: 0.9 }}>{exportStatus}</div>}
- </div>
- </>
+ <div
+ ref={mountRef}
+ data-testid="native-compositor-mount"
+ style={{ position: "absolute", inset: 0, zIndex: 5 }}
+ />
);
}
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index dd698d4f0..c60799171 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -13,6 +13,7 @@ import { PLACEHOLDER_DURATION_SEC, useTimeline } from "@/lib/ai-edition/store/us
import { matchesShortcut } from "@/lib/shortcuts";
import { nativeBridgeClient } from "@/native";
import type { AiEditionProjectSummary } from "@/native/contracts";
+import { useNativePlaybackSync } from "@/native/useNativePlaybackSync";
import { ExportDialog } from "./ExportDialog";
import { LeftPanel } from "./LeftPanel";
import {
@@ -23,7 +24,7 @@ import {
UnsavedChangesModal,
type UnsavedChoice,
} from "./Modals";
-import { Preview } from "./Preview";
+import { NATIVE_COMPOSITOR_ENABLED, Preview } from "./Preview";
import v4 from "./v4/EditorShellV4.module.css";
import { type EditorMode, EditorTopBar } from "./v4/EditorTopBar";
import { type Facet, FloatingInspector } from "./v4/FloatingInspector";
@@ -58,6 +59,8 @@ export function NewEditorShell() {
const [videoElement, setVideoElement] = useState<HTMLVideoElement | null>(null);
const [playing, setPlaying] = useState(false);
const [loop, setLoop] = useState(false);
+ // Mirror transport/playhead onto the native compositor view (no-op if inactive).
+ useNativePlaybackSync(playing, currentTimeSec);
// v4 shell: three modes (Media / Edit / Rec), a collapsible agent (chat)
// column, and a floating facet inspector over the stage.
const [mode, setMode] = useState<EditorMode>("edit");
@@ -1172,7 +1175,17 @@ export function NewEditorShell() {
// overlaying the preview — so top/bottom/left only need a
// thin margin off the stage's rounded corners, not a large
// fixed chunk that dwarfs the card on smaller windows.
- padding: `16px ${inspectorOpen ? 320 : 74}px 16px 16px`,
+ //
+ // Native compositor: the D3D overlay is an opaque, always-on-top
+ // window that would DRAW OVER the floating inspector (airspace —
+ // it can't sit behind a DOM layer), truncating the panel. The web
+ // design lets the translucent panel float over the video (320 < the
+ // inspector's real 380px footprint = right:20 + rail:50 + gap:10 +
+ // panel:300), but in native mode we must reserve the full footprint
+ // so the overlay stops clear of it (≈400 = 380 + a small gap).
+ padding: `16px ${
+ inspectorOpen ? (NATIVE_COMPOSITOR_ENABLED ? 400 : 320) : 74
+ }px 16px 16px`,
boxSizing: "border-box",
}}
>
diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsx
index a842d1583..957c2e733 100644
--- a/src/components/ai-edition/Preview.tsx
+++ b/src/components/ai-edition/Preview.tsx
@@ -15,7 +15,7 @@ import { PreviewCanvas } from "./PreviewCanvas";
type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;
// POC Option A : preview rendue par la fenêtre D3D native embarquée (opt-in via flag Vite).
-const NATIVE_COMPOSITOR_ENABLED =
+export const NATIVE_COMPOSITOR_ENABLED =
(import.meta.env as Record<string, string | undefined>).VITE_NATIVE_COMPOSITOR === "1";
interface PreviewProps {
diff --git a/src/native/compositorViewClient.ts b/src/native/compositorViewClient.ts
index 3a24144fc..806fcdcf8 100644
--- a/src/native/compositorViewClient.ts
+++ b/src/native/compositorViewClient.ts
@@ -50,6 +50,14 @@ export function setCompositorPlaying(id: number, playing: boolean): Promise<{ ok
});
}
+export function setCompositorTime(id: number, seconds: number): Promise<{ ok: true }> {
+ return requireNativeBridgeData<{ ok: true }>({
+ domain: "compositor",
+ action: "presentTime",
+ payload: { id, seconds },
+ });
+}
+
export function destroyCompositorView(id: number): Promise<{ ok: true }> {
return requireNativeBridgeData<{ ok: true }>({
domain: "compositor",
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index 91a577247..b48866564 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -652,6 +652,12 @@ export type NativeBridgeRequest =
action: "export";
payload: { outPath?: string };
requestId?: string;
+ }
+ | {
+ domain: "compositor";
+ action: "presentTime";
+ payload: { id: number; seconds: number };
+ requestId?: string;
};
export type NativeBridgeEventName =
diff --git a/src/native/nativeCompositorStore.ts b/src/native/nativeCompositorStore.ts
index a336bf862..fabfd632b 100644
--- a/src/native/nativeCompositorStore.ts
+++ b/src/native/nativeCompositorStore.ts
@@ -4,7 +4,11 @@
* pousser un paramètre via `setNativeParam` sans connaître l'overlay. No-op tant qu'aucune
* vue n'est active (flag `VITE_NATIVE_COMPOSITOR` off ou addon absent).
*/
-import { setCompositorParam } from "./compositorViewClient";
+import {
+ setCompositorParam,
+ setCompositorPlaying,
+ setCompositorTime,
+} from "./compositorViewClient";
import type { CompositorParamValue } from "./contracts";
let currentViewId: number | null = null;
@@ -52,6 +56,27 @@ export function setNativeParam(key: string, value: CompositorParamValue): void {
});
}
+/** Seek la vue native active au temps `seconds` (playhead de l'app). No-op si aucune vue.
+ * Transitoire (position de lecture) → non mémorisé/rejoué, contrairement à setNativeParam. */
+export function setNativeTime(seconds: number): void {
+ if (currentViewId === null) {
+ return;
+ }
+ setCompositorTime(currentViewId, seconds).catch((error: unknown) => {
+ console.warn("[compositor-view] setNativeTime failed:", error);
+ });
+}
+
+/** Play/pause de la vue native active (lecture libre côté natif). No-op si aucune vue. */
+export function setNativePlaying(playing: boolean): void {
+ if (currentViewId === null) {
+ return;
+ }
+ setCompositorPlaying(currentViewId, playing).catch((error: unknown) => {
+ console.warn("[compositor-view] setNativePlaying failed:", error);
+ });
+}
+
/** S'abonner à l'activité de la vue native (React: via useSyncExternalStore). */
export function subscribeNativeCompositor(listener: () => void): () => void {
listeners.add(listener);
diff --git a/src/native/useNativePlaybackSync.ts b/src/native/useNativePlaybackSync.ts
new file mode 100644
index 000000000..adafcffa8
--- /dev/null
+++ b/src/native/useNativePlaybackSync.ts
@@ -0,0 +1,51 @@
+/**
+ * Mirrors the app's transport (play/pause) and playhead (scrub/step) onto the
+ * active native compositor view. Mounted once in the editor shell; a no-op
+ * whenever no native view is active (flag off / addon absent), so it's safe to
+ * call unconditionally.
+ *
+ * Playback model — why we don't push a seek every frame:
+ * - Play/pause maps to native *free-run* (`setNativePlaying`). While playing,
+ * the native decoder advances its own frames sequentially (cheap).
+ * - `currentTimeSec` ticks every rAF frame during playback. Pushing
+ * `setNativeTime` per tick would force an O(n) rewind+decode seek each frame
+ * AND fight the free-run (the render thread prioritises app-requested frames
+ * over free-run). So discrete seeks are only sent while *paused* — i.e. real
+ * scrub/step interactions. Pausing also re-snaps native to the app playhead.
+ *
+ * Known POC limitation: during free-run the native clock and the app clock can
+ * drift (independent tickers); acceptable for the fixture (~6 s loop). A pause
+ * re-aligns them.
+ */
+import { useEffect, useSyncExternalStore } from "react";
+import {
+ getCurrentNativeViewId,
+ setNativePlaying,
+ setNativeTime,
+ subscribeNativeCompositor,
+} from "./nativeCompositorStore";
+
+export function useNativePlaybackSync(playing: boolean, currentTimeSec: number): void {
+ // Reactive "is a native view active?" so activation mid-session re-pushes the
+ // current transport/playhead (time & playing aren't memoised in the store).
+ const active = useSyncExternalStore(
+ subscribeNativeCompositor,
+ () => getCurrentNativeViewId() !== null,
+ );
+
+ // Play/pause → native free-run.
+ useEffect(() => {
+ if (!active) {
+ return;
+ }
+ setNativePlaying(playing);
+ }, [active, playing]);
+
+ // Scrub/step while paused → discrete seek (see header for why not during play).
+ useEffect(() => {
+ if (!active || playing) {
+ return;
+ }
+ setNativeTime(currentTimeSec);
+ }, [active, playing, currentTimeSec]);
+}