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): embed the native view in the editor — library crate, napi addon and overlay airspace

Etienne Lescot9868f08ab69d
diff --git a/.gitignore b/.gitignore
index 3e8ed9666..f7d61c42c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,6 +16,7 @@ dist-ssr
# Native helper build outputs
/electron/native/wgc-capture/build/
+/electron/native/compositor-view/build/
/electron/native/screencapturekit/build/
/electron/native/screencapturekit/.build/
/electron/native/screencapturekit/.swiftpm/
@@ -88,10 +89,10 @@ result-*
opencode.json
opencode.json
-
-# Frames dumped by `npm run bench:export -- --dumpFrame=N`, for eyes only.
-bench-frame-*.png
-
-# POC inputs (real recordings) and outputs — big, and not source.
-poc/media/
-poc/out/
+
+# Frames dumped by `npm run bench:export -- --dumpFrame=N`, for eyes only.
+bench-frame-*.png
+
+# POC inputs (real recordings) and outputs — big, and not source.
+poc/media/
+poc/out/
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 3bda7bffc..3fdbc681e 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -378,7 +378,7 @@ let lastEnumeratedSources = new Map<string, DesktopCapturerSource>();
let currentProjectPath: string | null = null;
let currentRecordingSession: RecordingSession | null = null;
-// ponytail: single source of truth for the mic/camera/system-audio/cursor
+// single source of truth for the mic/camera/system-audio/cursor
// choices a user makes in the editor's Rec-mode stage, so the HUD window's
// useScreenRecorder (a separate renderer, own process, own React tree) picks
// up those choices instead of silently reverting to its own defaults when
@@ -2512,7 +2512,7 @@ export function registerIpcHandlers(
);
}
- // ponytail: MediaRecorder occasionally produces a 0-byte file on Windows
+ // MediaRecorder occasionally produces a 0-byte file on Windows
// when the display stream is captured but no frames are produced (the
// streaming WriteStream was opened but never received any chunks). Detect
// the bad file here so the recording fails loudly instead of opening the
@@ -3193,7 +3193,7 @@ export function registerIpcHandlers(
: { success: false };
});
- // ponytail: returns the webcam path (if any) for a given screen video by
+ // returns the webcam path (if any) for a given screen video by
// reading its sibling session.json — drives the cameraTrack auto-link on
// `addAsset` in the new editor's project store.
ipcMain.handle(
@@ -3359,6 +3359,23 @@ export function registerIpcHandlers(
normalizeVideoSourcePath(videoPath ?? currentVideoPath),
loadCursorRecordingData: readCursorRecordingFile,
loadCursorTelemetry: readCursorTelemetryFile,
+ // compositor view's createView needs the renderer-owning
+ // BrowserWindow's native handle (HWND on Windows, NSView* on macOS).
+ // Same ownership rules as desktopCapturer: `BrowserWindow.fromWebContents`
+ // gives us the window that hosts this sender; `getNativeWindowHandle`
+ // is the platform-native parent handle the D3D11 addon parents its
+ // child window to.
+ getNativeWindowHandle: (sender) => {
+ const window = BrowserWindow.fromWebContents(sender);
+ if (!window || window.isDestroyed()) {
+ return null;
+ }
+ try {
+ return window.getNativeWindowHandle();
+ } catch {
+ return null;
+ }
+ },
getAiEditionDocuments: () =>
new DocumentService(path.join(app.getPath("userData"), "projects")),
getAiEditionLlmConfig: () => new LlmConfigStore(app.getPath("userData")),
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index aa3f27599..05d2a5b8d 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -15,6 +15,7 @@ import type { DocumentService } from "../ai-edition/document-service";
import type { CursorTelemetryLoadResult } from "../native-bridge/cursor/adapter";
import { TelemetryCursorAdapter } from "../native-bridge/cursor/telemetryCursorAdapter";
import { AiEditionService } from "../native-bridge/services/aiEditionService";
+import { CompositorViewService } from "../native-bridge/services/compositorViewService";
import { CursorService } from "../native-bridge/services/cursorService";
import { ProjectService } from "../native-bridge/services/projectService";
import { SystemService } from "../native-bridge/services/systemService";
@@ -41,6 +42,14 @@ export interface NativeBridgeContext {
videoPath: string,
) => Promise<import("../../src/native/contracts").CursorRecordingData>;
loadCursorTelemetry: (videoPath: string) => Promise<CursorTelemetryLoadResult>;
+ /**
+ * returns the native (HWND / NSView / xcb_window) handle buffer
+ * for the BrowserWindow that hosts the requesting renderer. Used by the
+ * compositor domain's `createView` to wire the embedded native window
+ * to its D3D11 parent. May return `null` if the sender has no live window
+ * (e.g. mid-teardown), in which case `createView` fails with UNAVAILABLE.
+ */
+ getNativeWindowHandle?: (sender: import("electron").WebContents) => Buffer | null;
getAiEditionDocuments: () => DocumentService;
getAiEditionLlmConfig: () => import("../ai-edition/llm-config-store").LlmConfigStore;
runAiEditionChat: (
@@ -164,7 +173,7 @@ function isBridgeRequest(value: unknown): value is NativeBridgeRequest {
return typeof candidate.domain === "string" && typeof candidate.action === "string";
}
-// ponytail: build a ChatEventSink that broadcasts each event to the renderer
+// build a ChatEventSink that broadcasts each event to the renderer
// that requested the chat run. The webContents may be gone by the time a late
// delta fires (tab closed, window destroyed) — webContents.send throws, so we
// swallow the error to keep the loop running. The renderer treats a missing
@@ -174,7 +183,7 @@ function buildChatEventSink(sender: Electron.WebContents, sessionId: string): Ch
try {
sender.send("ai-edition.chat-event", payload);
} catch {
- // ponytail: webContents gone — keep the loop running silently.
+ // webContents gone — keep the loop running silently.
}
};
return {
@@ -216,6 +225,7 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
getAssetBasePath: context.resolveAssetBasePath,
getCursorCapabilities: () => cursorService.getCapabilities(),
});
+ const compositorViewService = new CompositorViewService();
const aiEditionService = new AiEditionService({
documents: context.getAiEditionDocuments(),
llmConfig: context.getAiEditionLlmConfig(),
@@ -334,6 +344,47 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
}
}
+ case "compositor": {
+ const action = request.action as string;
+ switch (request.action) {
+ case "createView": {
+ const sender = event.sender;
+ const handle = context.getNativeWindowHandle?.(sender) ?? null;
+ if (!handle) {
+ return createErrorResponse(
+ requestId,
+ "UNAVAILABLE",
+ "No native window handle available for the requesting renderer.",
+ );
+ }
+ const id = compositorViewService.createView(handle, request.payload.rect);
+ return createSuccessResponse(requestId, { id });
+ }
+ case "setRect":
+ compositorViewService.setRect(request.payload.id, request.payload.rect);
+ return createSuccessResponse(requestId, { ok: true });
+ case "setParam":
+ compositorViewService.setParam(
+ request.payload.id,
+ request.payload.key,
+ request.payload.value,
+ );
+ return createSuccessResponse(requestId, { ok: true });
+ case "setPlaying":
+ compositorViewService.setPlaying(request.payload.id, request.payload.playing);
+ return createSuccessResponse(requestId, { ok: true });
+ case "destroyView":
+ compositorViewService.destroyView(request.payload.id);
+ return createSuccessResponse(requestId, { ok: true });
+ default:
+ return createErrorResponse(
+ requestId,
+ "UNSUPPORTED_ACTION",
+ `Unsupported compositor action: ${action}`,
+ );
+ }
+ }
+
case "aiEdition": {
const action = request.action as string;
switch (request.action) {
diff --git a/electron/native-bridge/services/compositorViewService.ts b/electron/native-bridge/services/compositorViewService.ts
new file mode 100644
index 000000000..7942b61d7
--- /dev/null
+++ b/electron/native-bridge/services/compositorViewService.ts
@@ -0,0 +1,207 @@
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { app } from "electron";
+import type {
+ CompositorParamValue,
+ CompositorViewAddon,
+ CompositorViewRect,
+} from "../../native/compositor-view/addon";
+
+/**
+ * ESM-safe `require` for loading the native addon
+ * (`compositor_view.node`). The electron main bundle is ESM at the source
+ * level; `require()` isn't available at the top level. `createRequire` keeps
+ * the addon require dynamic so vite/rollup never tries to bundle the native
+ * binary.
+ */
+const localRequire: NodeRequire = createRequire(import.meta.url) as unknown as NodeRequire;
+
+export interface CompositorViewServiceOptions {
+ /**
+ * Optional explicit override for the addon path. Has precedence over the
+ * `OPENSCREEN_COMPOSITOR_VIEW_NODE` env var and the candidate path list.
+ * Useful for poking at a locally-built `.node` without copying it into
+ * the standard search root.
+ */
+ envOverride?: string | null;
+ /**
+ * Directory to resolve candidate paths relative to. Defaults to
+ * `app.getAppPath()` so dev (unpackaged) and packaged setups resolve the
+ * same relative path. Tests can inject a temp directory here.
+ */
+ appRoot?: string;
+ isPackaged?: boolean;
+}
+
+function defaultAppRoot(): string {
+ try {
+ return app.getAppPath();
+ } catch {
+ // bare-node test environment — fall back to the source tree root
+ // via this file's location (service lives at
+ // electron/native-bridge/services/, project root is four levels up).
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ return path.resolve(here, "..", "..", "..", "..");
+ }
+}
+
+function defaultIsPackaged(): boolean {
+ try {
+ return app.isPackaged;
+ } catch {
+ return false;
+ }
+}
+
+function platformArchTag(): string {
+ const platformPrefix =
+ process.platform === "win32" ? "win32" : process.platform === "darwin" ? "darwin" : "linux";
+ return process.arch === "arm64" ? `${platformPrefix}-arm64` : `${platformPrefix}-x64`;
+}
+
+function buildCandidatePaths(
+ appRoot: string,
+ isPackaged: boolean,
+ envOverride: string | null | undefined,
+): string[] {
+ const builtPath = path.join(
+ appRoot,
+ "electron",
+ "native",
+ "compositor-view",
+ "build",
+ "compositor_view.node",
+ );
+ const archBinPath = path.join(
+ appRoot,
+ "electron",
+ "native",
+ "bin",
+ platformArchTag(),
+ "compositor_view.node",
+ );
+ const ordered = [envOverride, archBinPath, builtPath].filter(
+ (value): value is string => typeof value === "string" && value.length > 0,
+ );
+ if (!isPackaged) {
+ return ordered;
+ }
+ // in packaged builds, references inside `app.asar/...` must be
+ // rewritten to `.asar.unpacked/...` so dynamic `require()` can load the
+ // native binary (matches the capture-helper resolution policy).
+ return ordered.map((candidate) => candidate.replace(/\.asar([/\\])/, ".asar.unpacked$1"));
+}
+
+function tryLoadAddon(candidates: string[]): CompositorViewAddon | null {
+ for (const candidate of candidates) {
+ try {
+ // only attempt the require when the file actually exists
+ // — `require()` of a missing native module throws a noisy
+ // MODULE_NOT_FOUND that pollutes the renderer console.
+ if (!fs.existsSync(candidate)) {
+ continue;
+ }
+ const loaded = localRequire(candidate) as unknown;
+ if (loaded && typeof loaded === "object") {
+ return loaded as CompositorViewAddon;
+ }
+ } catch {
+ // try the next candidate — a single broken build
+ // shouldn't kill the addon entirely.
+ }
+ }
+ return null;
+}
+
+export class CompositorViewService {
+ private readonly options: CompositorViewServiceOptions;
+ private readonly rects = new Map<number, CompositorViewRect>();
+ private addon: CompositorViewAddon | null = null;
+ private loadAttempted = false;
+ private syntheticIdCounter = 0;
+
+ constructor(options: CompositorViewServiceOptions = {}) {
+ this.options = options;
+ }
+
+ private ensureAddon(): CompositorViewAddon | null {
+ if (this.loadAttempted) {
+ return this.addon;
+ }
+ this.loadAttempted = true;
+
+ const envOverride =
+ this.options.envOverride ?? process.env.OPENSCREEN_COMPOSITOR_VIEW_NODE ?? null;
+ const appRoot = this.options.appRoot ?? defaultAppRoot();
+ const isPackaged = this.options.isPackaged ?? defaultIsPackaged();
+
+ const candidates = buildCandidatePaths(appRoot, isPackaged, envOverride);
+ const loaded = tryLoadAddon(candidates);
+ if (!loaded) {
+ // single log line, exactly as specified — repeated
+ // ensureAddon calls just return null without spamming the console.
+ console.log("[compositor-view] native addon not present; running as no-op");
+ return null;
+ }
+ this.addon = loaded;
+ return this.addon;
+ }
+
+ /** True when the native `.node` addon was successfully loaded. */
+ hasAddon(): boolean {
+ return this.ensureAddon() !== null;
+ }
+
+ createView(parentHandle: Buffer, rect: CompositorViewRect): number {
+ const addon = this.ensureAddon();
+ if (!addon) {
+ // synthetic negative ids let callers do bookkeeping
+ // (cleanup in destroyView) without crashing when no native view
+ // exists. Each call gets a fresh id so multiple no-op views
+ // stay independent.
+ this.syntheticIdCounter -= 1;
+ const id = this.syntheticIdCounter;
+ this.rects.set(id, rect);
+ return id;
+ }
+ const id = addon.createView(parentHandle, rect);
+ this.rects.set(id, rect);
+ return id;
+ }
+
+ setRect(id: number, rect: CompositorViewRect): void {
+ const addon = this.ensureAddon();
+ this.rects.set(id, rect);
+ if (!addon) {
+ return;
+ }
+ addon.setRect(id, rect);
+ }
+
+ setParam(id: number, key: string, value: CompositorParamValue): void {
+ const addon = this.ensureAddon();
+ if (!addon) {
+ return;
+ }
+ addon.setParam(id, key, value);
+ }
+
+ setPlaying(id: number, playing: boolean): void {
+ const addon = this.ensureAddon();
+ if (!addon) {
+ return;
+ }
+ addon.setPlaying(id, playing);
+ }
+
+ destroyView(id: number): void {
+ const addon = this.ensureAddon();
+ this.rects.delete(id);
+ if (!addon) {
+ return;
+ }
+ addon.destroyView(id);
+ }
+}
diff --git a/electron/native/compositor-view/addon.d.ts b/electron/native/compositor-view/addon.d.ts
new file mode 100644
index 000000000..659bd3262
--- /dev/null
+++ b/electron/native/compositor-view/addon.d.ts
@@ -0,0 +1,38 @@
+/**
+ * Type declarations for the Rust napi-rs native compositor addon
+ * (`compositor_view.node`). Built separately and loaded by
+ * `electron/native-bridge/services/compositorViewService.ts`. Until the
+ * prebuilt `.node` binary is present the service logs once and falls back to
+ * safe no-ops — the type contract here is the only contract renderer code
+ * relies on.
+ */
+
+export interface CompositorViewRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export type CompositorParamValue = boolean | number | string;
+
+export interface CompositorViewAddon {
+ createView(parentHandle: Buffer, rect: CompositorViewRect): number;
+ setRect(id: number, rect: CompositorViewRect): void;
+ setParam(id: number, key: string, value: CompositorParamValue): void;
+ setPlaying(id: number, playing: boolean): void;
+ destroyView(id: number): void;
+}
+
+/**
+ * The napi-rs addon is `require()`d from an absolute path resolved at runtime
+ * (see `compositorViewService`). Declare the module shape here so the
+ * `require()` return type can be constrained to `CompositorViewAddon` without
+ * `any`. The wildcard pattern lets us match both the packaged
+ * `electron/native/bin/<arch>/compositor_view.node` and the locally built
+ * `electron/native/compositor-view/build/compositor_view.node` paths.
+ */
+declare module "*compositor_view.node" {
+ const addon: CompositorViewAddon;
+ export = addon;
+}
diff --git a/poc-d3d/Cargo.lock b/poc-d3d/Cargo.lock
index 7412555dd..eacf31fe5 100644
--- a/poc-d3d/Cargo.lock
+++ b/poc-d3d/Cargo.lock
@@ -79,6 +79,37 @@ dependencies = [
"libloading",
]
+[[package]]
+name = "compositor-view-napi"
+version = "0.0.0"
+dependencies = [
+ "anyhow",
+ "napi",
+ "napi-build",
+ "napi-derive",
+ "poc-d3d",
+ "windows",
+]
+
+[[package]]
+name = "convert_case"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "ctor"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501"
+dependencies = [
+ "quote",
+ "syn",
+]
+
[[package]]
name = "either"
version = "1.16.0"
@@ -146,6 +177,63 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+[[package]]
+name = "napi"
+version = "2.16.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55740c4ae1d8696773c78fdafd5d0e5fe9bc9f1b071c7ba493ba5c413a9184f3"
+dependencies = [
+ "bitflags",
+ "ctor",
+ "napi-derive",
+ "napi-sys",
+ "once_cell",
+]
+
+[[package]]
+name = "napi-build"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9c366d2c8c60b86fa632df75f745509b52f9128f91a6bad4c796e44abb505e1"
+
+[[package]]
+name = "napi-derive"
+version = "2.16.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cbe2585d8ac223f7d34f13701434b9d5f4eb9c332cccce8dee57ea18ab8ab0c"
+dependencies = [
+ "cfg-if",
+ "convert_case",
+ "napi-derive-backend",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "napi-derive-backend"
+version = "1.0.75"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1639aaa9eeb76e91c6ae66da8ce3e89e921cd3885e99ec85f4abacae72fc91bf"
+dependencies = [
+ "convert_case",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "semver",
+ "syn",
+]
+
+[[package]]
+name = "napi-sys"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "427802e8ec3a734331fec1035594a210ce1ff4dc5bc1950530920ab717964ea3"
+dependencies = [
+ "libloading",
+]
+
[[package]]
name = "nom"
version = "7.1.3"
@@ -156,6 +244,12 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
[[package]]
name = "poc-d3d"
version = "0.0.0"
@@ -230,6 +324,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
[[package]]
name = "serde"
version = "1.0.228"
@@ -301,6 +401,12 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
[[package]]
name = "windows"
version = "0.58.0"
diff --git a/poc-d3d/Cargo.toml b/poc-d3d/Cargo.toml
index 0cf6873fc..8af1b6463 100644
--- a/poc-d3d/Cargo.toml
+++ b/poc-d3d/Cargo.toml
@@ -4,6 +4,17 @@ version = "0.0.0"
edition = "2021"
description = "POC OpenScreen : compositeur natif D3D11 zéro-copie, effets HLSL, mesuré en fps (fast-path natif)."
+# Workspace : l'addon napi-rs (compositor-view-napi) partage le build env (FFMPEG_DIR,
+# LIBCLANG_PATH via .cargo/config.toml). `default-members = ["."]` → `cargo build` (x.bat)
+# ne construit que le POC ; l'addon se build explicitement (`cargo build -p compositor-view-napi`).
+[workspace]
+members = ["compositor-view-napi"]
+default-members = ["."]
+
+[lib]
+name = "poc_d3d"
+path = "src/lib.rs"
+
[[bin]]
name = "poc-d3d"
path = "src/main.rs"
diff --git a/poc-d3d/compositor-view-napi/Cargo.toml b/poc-d3d/compositor-view-napi/Cargo.toml
new file mode 100644
index 000000000..1d385a8cd
--- /dev/null
+++ b/poc-d3d/compositor-view-napi/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "compositor-view-napi"
+version = "0.0.0"
+edition = "2021"
+description = "Addon napi-rs : expose poc_d3d::live::LiveView (fenêtre D3D enfant) à Electron."
+
+[lib]
+crate-type = ["cdylib"]
+name = "compositor_view"
+
+[dependencies]
+napi = { version = "2", default-features = false, features = ["napi6"] }
+napi-derive = "2"
+poc-d3d = { path = ".." }
+anyhow = "1"
+
+[dependencies.windows]
+version = "0.58"
+features = ["Win32_Foundation"]
+
+[build-dependencies]
+napi-build = "2"
diff --git a/poc-d3d/compositor-view-napi/build.rs b/poc-d3d/compositor-view-napi/build.rs
new file mode 100644
index 000000000..f609ed3c1
--- /dev/null
+++ b/poc-d3d/compositor-view-napi/build.rs
@@ -0,0 +1,5 @@
+fn main() {
+ // Configure le linker Windows pour un module chargeable par Node (symboles napi_*
+ // résolus au chargement par le process Node/Electron).
+ napi_build::setup();
+}
diff --git a/poc-d3d/compositor-view-napi/src/lib.rs b/poc-d3d/compositor-view-napi/src/lib.rs
new file mode 100644
index 000000000..b6da7cd81
--- /dev/null
+++ b/poc-d3d/compositor-view-napi/src/lib.rs
@@ -0,0 +1,99 @@
+//! Addon napi-rs : pont Electron ↔ `poc_d3d::live::LiveView`. Expose la vue D3D enfant
+//! embarquée (Option A) à la glue TS (native-bridge domaine "compositor"). Les `#[napi]`
+//! sont appelés depuis le thread principal Node (là où vit la `BrowserWindow`), donc la
+//! fenêtre enfant est créée sur ce thread ; le rendu vit sur le thread de `LiveView`.
+
+use napi::bindgen_prelude::*;
+use napi_derive::napi;
+use poc_d3d::live::LiveView;
+use std::collections::HashMap;
+use std::sync::{Mutex, OnceLock};
+use windows::Win32::Foundation::HWND;
+
+/// Rect en pixels device, relatif au client de la fenêtre parente (miroir de la glue TS).
+#[napi(object)]
+pub struct CompositorViewRect {
+ pub x: i32,
+ pub y: i32,
+ pub width: i32,
+ pub height: i32,
+}
+
+static REGISTRY: OnceLock<Mutex<HashMap<i32, LiveView>>> = OnceLock::new();
+static NEXT_ID: Mutex<i32> = Mutex::new(1);
+
+fn registry() -> &'static Mutex<HashMap<i32, LiveView>> {
+ REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+/// `getNativeWindowHandle()` d'Electron : buffer little-endian contenant le HWND natif.
+fn hwnd_from_buffer(buf: &Buffer) -> HWND {
+ let bytes: &[u8] = buf.as_ref();
+ let mut v: usize = 0;
+ for (i, b) in bytes.iter().take(std::mem::size_of::<usize>()).enumerate() {
+ v |= (*b as usize) << (8 * i);
+ }
+ HWND(v as *mut core::ffi::c_void)
+}
+
+/// Répertoire fixture (POC) : env `OPENSCREEN_COMPOSITOR_FIXTURE`, sinon défaut local.
+/// Le Lot 3 fournira les vraies sources ; ici on prouve l'embed avec la fixture.
+fn fixture_dir() -> String {
+ std::env::var("OPENSCREEN_COMPOSITOR_FIXTURE").unwrap_or_else(|_| {
+ r"C:\Users\camil\Documents\repos\openscreen\.claude\worktrees\prerelease-version-tag-ee96ae\poc-d3d\fixture".to_string()
+ })
+}
+
+#[napi]
+pub fn create_view(parent_handle: Buffer, rect: CompositorViewRect) -> Result<i32> {
+ let hwnd = hwnd_from_buffer(&parent_handle);
+ let dir = fixture_dir();
+ let view = LiveView::create(
+ hwnd,
+ rect.x,
+ rect.y,
+ rect.width,
+ rect.height,
+ &format!("{dir}/screen.mp4"),
+ &format!("{dir}/webcam.mp4"),
+ &format!("{dir}/screen.cursor.json"),
+ )
+ .map_err(|e| Error::from_reason(format!("{e:#}")))?;
+ let id = {
+ let mut n = NEXT_ID.lock().unwrap();
+ let id = *n;
+ *n += 1;
+ id
+ };
+ registry().lock().unwrap().insert(id, view);
+ Ok(id)
+}
+
+#[napi]
+pub fn set_rect(id: i32, rect: CompositorViewRect) {
+ if let Some(v) = registry().lock().unwrap().get(&id) {
+ v.set_rect(rect.x, rect.y, rect.width, rect.height);
+ }
+}
+
+/// Param live. Phase 1 : seul `backgroundBlur` (booléen) est branché côté compositeur.
+#[napi]
+pub fn set_param(id: i32, key: String, value: bool) {
+ if let Some(v) = registry().lock().unwrap().get(&id) {
+ v.set_param(&key, value);
+ }
+}
+
+#[napi]
+pub fn set_playing(id: i32, playing: bool) {
+ if let Some(v) = registry().lock().unwrap().get(&id) {
+ v.set_playing(playing);
+ }
+}
+
+#[napi]
+pub fn destroy_view(id: i32) {
+ // remove hors du lock : le Drop (join du thread de rendu + DestroyWindow) ne le tient pas.
+ let removed = registry().lock().unwrap().remove(&id);
+ drop(removed);
+}
diff --git a/poc-d3d/src/app.rs b/poc-d3d/src/app.rs
index af07818a9..b10f0952f 100644
--- a/poc-d3d/src/app.rs
+++ b/poc-d3d/src/app.rs
@@ -14,7 +14,8 @@ use crate::compositor::{Compositor, FIXTURE_FRAMES, OUT_H, OUT_W};
use crate::config::{self, Cfg};
use crate::cursor::CursorTrack;
use crate::d3d::Gpu;
-use crate::pipeline::{self, Decoder};
+use crate::live::Player;
+use crate::pipeline;
use anyhow::Result;
use std::ffi::c_void;
use std::time::Instant;
@@ -70,56 +71,6 @@ fn letterbox(cw: f32, ch: f32) -> (f32, f32, f32, f32) {
((cw - w) * 0.5, (ch - h) * 0.5, w, h)
}
-/// Lit deux sources en lockstep et compose la frame courante dans le RT du compositeur.
-/// Boucle sur EOF (rewind zéro-réalloc). `idx` = prochaine frame à produire.
-struct Player {
- sdec: Decoder,
- wdec: Decoder,
- idx: u32,
-}
-
-impl Player {
- unsafe fn open(screen: &str, webcam: &str, gpu: &Gpu) -> Result<Player> {
- Ok(Player {
- sdec: Decoder::open(screen, gpu)?,
- wdec: Decoder::open(webcam, gpu)?,
- idx: 0,
- })
- }
-
- /// Compose la frame suivante (→ `comp.rt`). Retourne `false` si aucune frame (fixture vide).
- unsafe fn step(&mut self, comp: &Compositor, cfg: &Cfg) -> Result<bool> {
- let mut sf = self.sdec.next()?;
- let mut wf = self.wdec.next()?;
- if sf.is_null() || wf.is_null() {
- self.sdec.rewind()?;
- self.wdec.rewind()?;
- self.idx = 0;
- sf = self.sdec.next()?;
- wf = self.wdec.next()?;
- }
- if sf.is_null() || wf.is_null() {
- return Ok(false);
- }
- comp.compose_frame(sf, wf, self.idx as f32, cfg)?;
- self.idx = self.idx.wrapping_add(1);
- Ok(true)
- }
-
- /// Recompose la frame courante (déjà décodée) avec `cfg` — pour rafraîchir la preview
- /// après un changement de preset sans réavancer le temps.
- unsafe fn recompose(&self, comp: &Compositor, cfg: &Cfg) -> Result<bool> {
- let sf = self.sdec.cur_frame();
- let wf = self.wdec.cur_frame();
- if sf.is_null() || wf.is_null() {
- return Ok(false);
- }
- let f = self.idx.saturating_sub(1);
- comp.compose_frame(sf, wf, f as f32, cfg)?;
- Ok(true)
- }
-}
-
/// État applicatif complet (possédé par la fenêtre via GWLP_USERDATA).
struct App {
gpu: Gpu,
diff --git a/poc-d3d/src/lib.rs b/poc-d3d/src/lib.rs
new file mode 100644
index 000000000..2f799d7f8
--- /dev/null
+++ b/poc-d3d/src/lib.rs
@@ -0,0 +1,141 @@
+//! `poc-d3d` en bibliothèque : le compositeur/pipeline/d3d mesurés (S2→S6) + la vue
+//! live embarquable (`live`) sont réutilisables par l'addon napi-rs de l'intégration
+//! Electron. Le binaire (`main.rs`) n'est qu'un mince consommateur (`run()`).
+
+pub mod app;
+pub mod compositor;
+pub mod config;
+pub mod cursor;
+pub mod d3d;
+pub mod ffi;
+pub mod live;
+pub mod pipeline;
+
+use anyhow::Result;
+use compositor::Compositor;
+use std::fmt::Write as _;
+
+fn arg(args: &[String], k: &str, d: &str) -> String {
+ args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).cloned().unwrap_or_else(|| d.to_string())
+}
+
+// Deux modes :
+// GUI (défaut) : poc-d3d.exe [--fixture <dir>] [--out <dir>] → preview + export
+// Bench (§9/10) : poc-d3d.exe --cfg C0..C8 [--fixture <dir>] [--repeat N] [--out <dir>]
+// Live (POC) : poc-d3d.exe --live [--fixture <dir>] → vue D3D enfant embarquée (test embed)
+pub fn run() -> Result<()> {
+ let args: Vec<String> = std::env::args().collect();
+ if args.iter().any(|a| a == "--live") {
+ let fixture = arg(&args, "--fixture", "fixture");
+ return live::run_standalone(
+ &format!("{fixture}/screen.mp4"),
+ &format!("{fixture}/webcam.mp4"),
+ &format!("{fixture}/screen.cursor.json"),
+ );
+ }
+ let is_bench = args.iter().any(|a| a == "--cfg" || a == "--bench");
+ if is_bench {
+ run_bench(&args)
+ } else {
+ let fixture = arg(&args, "--fixture", "fixture");
+ let out = arg(&args, "--out", "out");
+ app::run_gui(
+ &format!("{fixture}/screen.mp4"),
+ &format!("{fixture}/webcam.mp4"),
+ &format!("{fixture}/screen.cursor.json"),
+ &out,
+ )
+ }
+}
+
+// poc-d3d.exe --cfg C0..C8 --fixture <dir> --repeat 3 --out out/
+fn run_bench(args: &[String]) -> Result<()> {
+ let get = |k: &str, d: &str| -> String { arg(args, k, d) };
+ let fixture = get("--fixture", "fixture");
+ let out = get("--out", "out");
+ let repeat: u32 = get("--repeat", "3").parse().unwrap_or(3);
+ let cfg_arg = get("--cfg", "C0..C8");
+
+ let screen = format!("{fixture}/screen.mp4");
+ let webcam = format!("{fixture}/webcam.mp4");
+ std::fs::create_dir_all(&out).ok();
+
+ // sélection des cfg
+ let all = config::all();
+ let cfgs: Vec<config::Cfg> = if cfg_arg.contains("..") {
+ all
+ } else {
+ cfg_arg
+ .split(',')
+ .filter_map(|n| config::Cfg::by_name(n.trim()))
+ .collect()
+ };
+
+ let gpu = d3d::Gpu::create(false)?;
+ println!("d3d11 device ok (feature_level 0x{:X})", gpu.feature_level.0 as u32);
+ let mut comp = Compositor::new(&gpu)?;
+ let track = cursor::CursorTrack::load(&format!("{fixture}/screen.cursor.json"), 100_000.0, 6.0)?;
+ comp.set_cursor(track);
+
+ let mut rows: Vec<(String, u64, f64, f64, f64, String)> = Vec::new(); // name, frames, best_wall, fps, ms/f, spread
+ let mut json = String::from("{\n \"runs\": [\n");
+
+ for cfg in &cfgs {
+ let mut fps_runs = Vec::new();
+ let mut frames = 0u64;
+ for r in 0..repeat {
+ let path = format!("{out}/{}.mp4", cfg.name);
+ let s = if cfg.composite {
+ pipeline::run_composited(&screen, &webcam, &path, &gpu, &comp, cfg, &mut |_| {})?
+ } else {
+ pipeline::run_c0(&screen, &path, &gpu)?
+ };
+ frames = s.frames;
+ fps_runs.push(s.fps);
+ if r == 0 {
+ // extraction PNG f60/f180/f300 sur le 1er run (§11)
+ extract_pngs(&path, &out, cfg.name);
+ }
+ }
+ let best = fps_runs.iter().cloned().fold(f64::MIN, f64::max);
+ let worst = fps_runs.iter().cloned().fold(f64::MAX, f64::min);
+ let spread = if worst > 0.0 { 100.0 * (best - worst) / worst } else { 0.0 };
+ let wall = frames as f64 / best;
+ let msf = 1000.0 / best;
+ println!(
+ "{:<4} {:>4}f {:>7.3}s {:>7.1} fps {:>6.2} ms/f spread {:.1}% {}",
+ cfg.name, frames, wall, best, msf, spread, cfg.desc
+ );
+ rows.push((cfg.name.to_string(), frames, wall, best, msf, format!("{spread:.1}%")));
+ let _ = write!(
+ json,
+ " {{ \"cfg\": \"{}\", \"frames\": {}, \"fps\": {:.2}, \"ms_per_frame\": {:.3}, \"spread_pct\": {:.1}, \"repeat\": {}, \"desc\": \"{}\" }}{}\n",
+ cfg.name, frames, best, msf, spread, repeat, cfg.desc,
+ if cfg.name == cfgs.last().unwrap().name { "" } else { "," }
+ );
+ }
+ json.push_str(" ]\n}\n");
+ std::fs::write(format!("{out}/report.json"), &json)?;
+
+ // table markdown récap
+ println!("\ncfg frames wall_s fps ms/f spread");
+ for (n, f, w, fps, msf, sp) in &rows {
+ println!("{n:<4} {f:<7} {w:<7.3} {fps:<8.1} {msf:<7.2} {sp}");
+ }
+ println!("\nreport.json + out/C*.mp4 + out/C*_f{{60,180,300}}.png écrits dans {out}/");
+ Ok(())
+}
+
+/// Extrait 3 frames (f60/f180/f300) d'un MP4 via ffmpeg (§11) — vérification à l'œil.
+fn extract_pngs(mp4: &str, out: &str, cfg: &str) {
+ for f in [60u32, 180, 300] {
+ let _ = std::process::Command::new("ffmpeg")
+ .args([
+ "-v", "error", "-y", "-i", mp4,
+ "-vf", &format!("select=eq(n\\,{f})"),
+ "-frames:v", "1",
+ &format!("{out}/{cfg}_f{f}.png"),
+ ])
+ .status();
+ }
+}
diff --git a/poc-d3d/src/live.rs b/poc-d3d/src/live.rs
new file mode 100644
index 000000000..05c4991f1
--- /dev/null
+++ b/poc-d3d/src/live.rs
@@ -0,0 +1,482 @@
+//! Vue live **embarquable** : rend le compositing dans une fenêtre D3D11 *enfant*
+//! (`WS_CHILD`) parentée à une fenêtre hôte (p.ex. la `BrowserWindow` Electron).
+//! C'est le cœur réutilisable de l'intégration Option A : l'addon napi-rs appellera
+//! `LiveView::create(parent_hwnd, rect, …)` puis `set_rect`/`set_param`/`set_playing`.
+//!
+//! Modèle de threads : la fenêtre enfant est créée sur le thread appelant (ses messages
+//! sont pompés par l'hôte). Le rendu (device D3D, compositeur, décodeurs, swapchain,
+//! Present) tourne sur un **thread dédié** — le thread JS/UI n'est jamais bloqué. Les
+//! objets COM restent sur le thread de rendu (le HWND, lui, traverse en `isize`).
+
+use crate::compositor::Compositor;
+use crate::config::{self, Cfg};
+use crate::cursor::CursorTrack;
+use crate::d3d::Gpu;
+use crate::pipeline::Decoder;
+use anyhow::Result;
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, Once};
+use std::thread::JoinHandle;
+use std::time::{Duration, Instant};
+use windows::core::{Interface, PCWSTR};
+use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
+use windows::Win32::Graphics::Gdi::ClientToScreen;
+use windows::Win32::Graphics::Direct3D11::{ID3D11Device, ID3D11RenderTargetView, ID3D11Texture2D};
+use windows::Win32::Graphics::Dxgi::Common::{
+ DXGI_ALPHA_MODE_IGNORE, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC,
+};
+use windows::Win32::Graphics::Dxgi::{
+ IDXGIAdapter, IDXGIDevice, IDXGIFactory2, IDXGISwapChain1, DXGI_PRESENT, DXGI_SCALING_STRETCH,
+ DXGI_SWAP_CHAIN_DESC1, DXGI_SWAP_CHAIN_FLAG, DXGI_SWAP_EFFECT_FLIP_DISCARD,
+ DXGI_USAGE_RENDER_TARGET_OUTPUT,
+};
+use windows::Win32::System::LibraryLoader::GetModuleHandleW;
+use windows::Win32::UI::WindowsAndMessaging::*;
+
+use crate::compositor::{OUT_H, OUT_W};
+
+fn wide(s: &str) -> Vec<u16> {
+ s.encode_utf16().chain(std::iter::once(0)).collect()
+}
+
+/// Lit deux sources en lockstep et compose la frame courante dans le RT du compositeur.
+/// Partagé avec la GUI standalone (`app.rs`).
+pub struct Player {
+ sdec: Decoder,
+ wdec: Decoder,
+ idx: u32,
+}
+
+impl Player {
+ pub unsafe fn open(screen: &str, webcam: &str, gpu: &Gpu) -> Result<Player> {
+ Ok(Player {
+ sdec: Decoder::open(screen, gpu)?,
+ wdec: Decoder::open(webcam, gpu)?,
+ idx: 0,
+ })
+ }
+
+ /// Compose la frame suivante (→ `comp.rt`). Boucle sur EOF. `false` si fixture vide.
+ pub unsafe fn step(&mut self, comp: &Compositor, cfg: &Cfg) -> Result<bool> {
+ let mut sf = self.sdec.next()?;
+ let mut wf = self.wdec.next()?;
+ if sf.is_null() || wf.is_null() {
+ self.sdec.rewind()?;
+ self.wdec.rewind()?;
+ self.idx = 0;
+ sf = self.sdec.next()?;
+ wf = self.wdec.next()?;
+ }
+ if sf.is_null() || wf.is_null() {
+ return Ok(false);
+ }
+ comp.compose_frame(sf, wf, self.idx as f32, cfg)?;
+ self.idx = self.idx.wrapping_add(1);
+ Ok(true)
+ }
+
+ /// Recompose la frame courante (déjà décodée) — rafraîchit après un changement de param.
+ pub unsafe fn recompose(&self, comp: &Compositor, cfg: &Cfg) -> Result<bool> {
+ let sf = self.sdec.cur_frame();
+ let wf = self.wdec.cur_frame();
+ if sf.is_null() || wf.is_null() {
+ return Ok(false);
+ }
+ let f = self.idx.saturating_sub(1);
+ comp.compose_frame(sf, wf, f as f32, cfg)?;
+ Ok(true)
+ }
+}
+
+/// État partagé thread appelant → thread de rendu (commandes sans blocage).
+struct Shared {
+ /// rect viewport en px device [x, y, w, h], relatif au client de la fenêtre parente.
+ /// Le thread de rendu le mappe en coords écran (le parent peut bouger) et repositionne.
+ rect: Mutex<[i32; 4]>,
+ bg_blur: AtomicBool,
+ playing: AtomicBool,
+ stop: AtomicBool,
+}
+
+/// Handle d'une vue live embarquée. `Drop` arrête le rendu et détruit la fenêtre.
+pub struct LiveView {
+ hwnd: HWND,
+ shared: Arc<Shared>,
+ thread: Option<JoinHandle<()>>,
+}
+
+// Le HWND ne sert qu'au thread appelant (create/set_rect/drop) ; il n'est pas partagé
+// avec le thread de rendu autrement que par sa valeur numérique. Sûr à déplacer.
+unsafe impl Send for LiveView {}
+
+impl LiveView {
+ /// Crée la fenêtre enfant (thread appelant) et démarre le thread de rendu.
+ pub fn create(
+ parent: HWND,
+ x: i32,
+ y: i32,
+ w: i32,
+ h: i32,
+ screen: &str,
+ webcam: &str,
+ cursor_json: &str,
+ ) -> Result<LiveView> {
+ unsafe {
+ let hinst = HINSTANCE(GetModuleHandleW(None)?.0);
+ register_overlay_class(hinst);
+ let cls = wide("PocD3DOverlay");
+ // position écran initiale = origine client du parent + (x, y)
+ let mut pt = POINT { x, y };
+ let _ = ClientToScreen(parent, &mut pt);
+ // Fenêtre top-level "overlay" OWNED par le parent (WS_POPUP), sans activation.
+ // Une fenêtre SŒUR (pas enfant) n'est pas dans la surface de Chromium → elle
+ // n'est PAS occultée par son compositeur GPU (contrairement à WS_CHILD).
+ let hwnd = CreateWindowExW(
+ WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW,
+ PCWSTR(cls.as_ptr()),
+ PCWSTR::null(),
+ WS_POPUP | WS_VISIBLE,
+ pt.x,
+ pt.y,
+ w.max(1),
+ h.max(1),
+ parent, // owner
+ HMENU::default(),
+ hinst,
+ None,
+ )?;
+
+ let shared = Arc::new(Shared {
+ rect: Mutex::new([x, y, w, h]),
+ bg_blur: AtomicBool::new(false),
+ playing: AtomicBool::new(true),
+ stop: AtomicBool::new(false),
+ });
+ let overlay_val = hwnd.0 as isize;
+ let parent_val = parent.0 as isize;
+ let sh = shared.clone();
+ let (s, wc, cj) = (screen.to_string(), webcam.to_string(), cursor_json.to_string());
+ let thread = std::thread::spawn(move || {
+ if let Err(e) = render_thread(overlay_val, parent_val, sh, &s, &wc, &cj) {
+ eprintln!("[live] render thread error: {e:#}");
+ }
+ });
+
+ Ok(LiveView { hwnd, shared, thread: Some(thread) })
+ }
+ }
+
+ /// Met à jour le rect viewport (sync du rect DOM en Electron). Le thread de rendu le
+ /// mappe en coords écran et repositionne l'overlay (suit aussi le déplacement du parent).
+ pub fn set_rect(&self, x: i32, y: i32, w: i32, h: i32) {
+ if let Ok(mut r) = self.shared.rect.lock() {
+ *r = [x, y, w.max(1), h.max(1)];
+ }
+ }
+
+ /// Paramètre live (Phase 1 : un seul, le fond flouté).
+ pub fn set_param(&self, key: &str, value: bool) {
+ if key == "backgroundBlur" {
+ self.shared.bg_blur.store(value, Ordering::Relaxed);
+ }
+ }
+
+ pub fn set_playing(&self, playing: bool) {
+ self.shared.playing.store(playing, Ordering::Relaxed);
+ }
+}
+
+impl Drop for LiveView {
+ fn drop(&mut self) {
+ self.shared.stop.store(true, Ordering::SeqCst);
+ if let Some(t) = self.thread.take() {
+ let _ = t.join();
+ }
+ unsafe {
+ let _ = DestroyWindow(self.hwnd);
+ }
+ }
+}
+
+/// Plus grand rectangle 16:9 centré dans `(cw, ch)` → viewport letterbox.
+fn letterbox(cw: f32, ch: f32) -> (f32, f32, f32, f32) {
+ let ar = OUT_W as f32 / OUT_H as f32;
+ let (mut w, mut h) = (cw, ch);
+ if cw / ch > ar {
+ w = ch * ar;
+ } else {
+ h = cw / ar;
+ }
+ ((cw - w) * 0.5, (ch - h) * 0.5, w, h)
+}
+
+unsafe fn client_size(hwnd: HWND) -> (u32, u32) {
+ let mut rc = RECT::default();
+ let _ = GetClientRect(hwnd, &mut rc);
+ ((rc.right - rc.left).max(0) as u32, (rc.bottom - rc.top).max(0) as u32)
+}
+
+unsafe fn make_bb_rtv(swap: &IDXGISwapChain1, device: &ID3D11Device) -> Result<ID3D11RenderTargetView> {
+ let bb: ID3D11Texture2D = swap.GetBuffer(0)?;
+ let mut rtv: Option<ID3D11RenderTargetView> = None;
+ device.CreateRenderTargetView(&bb, None, Some(&mut rtv))?;
+ Ok(rtv.unwrap())
+}
+
+unsafe fn create_swapchain(
+ device: &ID3D11Device,
+ hwnd: HWND,
+ w: u32,
+ h: u32,
+) -> Result<(IDXGISwapChain1, ID3D11RenderTargetView)> {
+ let dxdev: IDXGIDevice = device.cast()?;
+ let adapter: IDXGIAdapter = dxdev.GetAdapter()?;
+ let factory: IDXGIFactory2 = adapter.GetParent()?;
+ let desc = DXGI_SWAP_CHAIN_DESC1 {
+ Width: w.max(1),
+ Height: h.max(1),
+ Format: DXGI_FORMAT_R8G8B8A8_UNORM,
+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
+ BufferCount: 2,
+ SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
+ Scaling: DXGI_SCALING_STRETCH,
+ AlphaMode: DXGI_ALPHA_MODE_IGNORE,
+ ..Default::default()
+ };
+ let swap = factory.CreateSwapChainForHwnd(device, hwnd, &desc, None, None)?;
+ let rtv = make_bb_rtv(&swap, device)?;
+ Ok((swap, rtv))
+}
+
+/// Boucle de rendu (thread dédié) : décode → compose → blit letterboxé → Present.
+/// Suit la taille client de la fenêtre enfant (ResizeBuffers) et le param live.
+unsafe fn render_thread(
+ overlay_val: isize,
+ parent_val: isize,
+ shared: Arc<Shared>,
+ screen: &str,
+ webcam: &str,
+ cursor_json: &str,
+) -> Result<()> {
+ let overlay = HWND(overlay_val as *mut c_void);
+ let parent = HWND(parent_val as *mut c_void);
+ let gpu = Gpu::create(false)?;
+ let mut comp = Compositor::new(&gpu)?;
+ if let Ok(track) = CursorTrack::load(cursor_json, 100_000.0, 6.0) {
+ comp.set_cursor(track);
+ }
+ let mut player = Player::open(screen, webcam, &gpu)?;
+
+ // config de base = C8 (tous effets) ; le fond flouté est piloté par le param live.
+ let mut cfg = config::all().pop().expect("au moins une config");
+
+ let (mut w, mut h) = {
+ let r = *shared.rect.lock().unwrap();
+ (r[2].max(1) as u32, r[3].max(1) as u32)
+ };
+ let (swap, mut bb_rtv) = create_swapchain(&gpu.device, overlay, w, h)?;
+
+ let mut last = Instant::now();
+ let mut acc = 0.0f64;
+ let mut first = true;
+ let mut last_screen = [i32::MIN; 4];
+
+ while !shared.stop.load(Ordering::SeqCst) {
+ cfg.bg_blur = shared.bg_blur.load(Ordering::Relaxed);
+
+ // rect viewport → coords écran : suit le rect DOM (set_rect) ET le déplacement du parent
+ let [vx, vy, vw, vh] = *shared.rect.lock().unwrap();
+ let mut pt = POINT { x: vx, y: vy };
+ let _ = ClientToScreen(parent, &mut pt);
+ let screen_rect = [pt.x, pt.y, vw, vh];
+ if screen_rect != last_screen {
+ let _ = SetWindowPos(
+ overlay,
+ HWND::default(),
+ pt.x,
+ pt.y,
+ vw.max(1),
+ vh.max(1),
+ SWP_NOACTIVATE | SWP_NOZORDER,
+ );
+ last_screen = screen_rect;
+ }
+
+ // suivi de taille → ResizeBuffers
+ let (nw, nh) = (vw.max(1) as u32, vh.max(1) as u32);
+ let mut resized = false;
+ if (nw, nh) != (w, h) {
+ drop(bb_rtv);
+ swap.ResizeBuffers(0, nw, nh, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SWAP_CHAIN_FLAG(0))?;
+ bb_rtv = make_bb_rtv(&swap, &gpu.device)?;
+ w = nw;
+ h = nh;
+ resized = true;
+ }
+
+ // avance temporelle (60 fps, horloge murale)
+ 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) {
+ acc += dt;
+ let step = 1.0 / 60.0;
+ let mut n = 0;
+ while acc >= step && n < 3 {
+ if player.step(&comp, &cfg)? {
+ stepped = true;
+ }
+ acc -= step;
+ n += 1;
+ }
+ if acc > step {
+ acc = 0.0;
+ }
+ } else if resized || first {
+ // pause : recompose la frame courante pour un present à la nouvelle taille
+ let _ = player.recompose(&comp, &cfg);
+ stepped = true;
+ }
+
+ if stepped || resized || first {
+ if w > 0 && h > 0 {
+ gpu.context.ClearRenderTargetView(&bb_rtv, &[0.0, 0.0, 0.0, 1.0]);
+ let (lx, ly, lw, lh) = letterbox(w as f32, h as f32);
+ comp.blit_to(&bb_rtv, lx, ly, lw, lh);
+ let _ = swap.Present(1, DXGI_PRESENT(0));
+ }
+ first = false;
+ } else {
+ std::thread::sleep(Duration::from_millis(4));
+ }
+ }
+ Ok(())
+}
+
+// ---------- classes de fenêtres ----------
+
+extern "system" fn child_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
+ unsafe { DefWindowProcW(hwnd, msg, wp, lp) }
+}
+
+fn register_overlay_class(hinst: HINSTANCE) {
+ static ONCE: Once = Once::new();
+ ONCE.call_once(|| unsafe {
+ let cls = wide("PocD3DOverlay");
+ let wc = WNDCLASSW {
+ style: CS_HREDRAW | CS_VREDRAW,
+ lpfnWndProc: Some(child_proc),
+ hInstance: hinst,
+ lpszClassName: PCWSTR(cls.as_ptr()),
+ hbrBackground: windows::Win32::Graphics::Gdi::HBRUSH(std::ptr::null_mut()),
+ ..Default::default()
+ };
+ RegisterClassW(&wc);
+ });
+}
+
+// ---------- harnais standalone (poc-d3d.exe --live) ----------
+
+extern "system" fn host_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
+ unsafe {
+ if msg == WM_DESTROY {
+ PostQuitMessage(0);
+ return LRESULT(0);
+ }
+ DefWindowProcW(hwnd, msg, wp, lp)
+ }
+}
+
+/// Test embed hors Electron : fenêtre hôte top-level + une `LiveView` enfant qui la
+/// remplit, resync au resize. Valide le child-window + le rendu threadé.
+pub fn run_standalone(screen: &str, webcam: &str, cursor_json: &str) -> Result<()> {
+ unsafe {
+ let hinst = HINSTANCE(GetModuleHandleW(None)?.0);
+ let cls = wide("PocD3DLiveHost");
+ let wc = WNDCLASSW {
+ style: CS_HREDRAW | CS_VREDRAW,
+ lpfnWndProc: Some(host_proc),
+ hInstance: hinst,
+ lpszClassName: PCWSTR(cls.as_ptr()),
+ hbrBackground: windows::Win32::Graphics::Gdi::HBRUSH(std::ptr::null_mut()),
+ ..Default::default()
+ };
+ RegisterClassW(&wc);
+
+ let title = wide("poc-d3d — live embed test (fenêtre D3D enfant)");
+ let host = CreateWindowExW(
+ WINDOW_EX_STYLE(0),
+ PCWSTR(cls.as_ptr()),
+ PCWSTR(title.as_ptr()),
+ WS_OVERLAPPEDWINDOW,
+ CW_USEDEFAULT,
+ CW_USEDEFAULT,
+ 1280,
+ 760,
+ HWND::default(),
+ HMENU::default(),
+ hinst,
+ None,
+ )?;
+
+ let (cw, ch) = client_size(host);
+ let view = LiveView::create(host, 0, 0, cw as i32, ch as i32, screen, webcam, cursor_json)?;
+ let _ = ShowWindow(host, SW_SHOW);
+ println!("live embed: fenêtre enfant D3D créée, thread de rendu démarré");
+ println!(" touches : [B] flou de fond (param → D3D) [Espace] pause/lecture");
+
+ // état des paramètres pilotés au clavier (le MÊME set_param que l'addon napi appelle)
+ let mut blur = false;
+ let mut playing = true;
+ let set_title = |b: bool, p: bool| unsafe {
+ let t = wide(&format!(
+ "poc-d3d — live embed · flou: {} · {} (B / Espace)",
+ if b { "ON" } else { "off" },
+ if p { "lecture" } else { "PAUSE" }
+ ));
+ let _ = SetWindowTextW(host, PCWSTR(t.as_ptr()));
+ };
+ set_title(blur, playing);
+
+ let mut msg = MSG::default();
+ let mut running = true;
+ while running {
+ while PeekMessageW(&mut msg, HWND::default(), 0, 0, PM_REMOVE).as_bool() {
+ if msg.message == WM_QUIT {
+ running = false;
+ break;
+ }
+ if msg.message == WM_KEYDOWN {
+ match msg.wParam.0 as u32 {
+ 0x42 => {
+ // 'B' : bascule le fond flouté via set_param — chemin param → D3D
+ blur = !blur;
+ view.set_param("backgroundBlur", blur);
+ set_title(blur, playing);
+ }
+ 0x20 => {
+ // Espace : pause/lecture
+ playing = !playing;
+ view.set_playing(playing);
+ set_title(blur, playing);
+ }
+ _ => {}
+ }
+ }
+ let _ = TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+ if !running {
+ break;
+ }
+ let (cw, ch) = client_size(host);
+ view.set_rect(0, 0, cw as i32, ch as i32);
+ std::thread::sleep(Duration::from_millis(8));
+ }
+ drop(view);
+ Ok(())
+ }
+}
diff --git a/poc-d3d/src/main.rs b/poc-d3d/src/main.rs
index f1fa59c49..e397eaf46 100644
--- a/poc-d3d/src/main.rs
+++ b/poc-d3d/src/main.rs
@@ -1,127 +1,6 @@
-mod app;
-mod compositor;
-mod config;
-mod cursor;
-mod d3d;
-mod ffi;
-mod pipeline;
+//! Binaire mince : toute la logique vit dans la bibliothèque `poc_d3d`
+//! (réutilisable par l'addon napi-rs de l'intégration Electron).
-use anyhow::Result;
-use compositor::Compositor;
-use std::fmt::Write as _;
-
-fn arg(args: &[String], k: &str, d: &str) -> String {
- args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).cloned().unwrap_or_else(|| d.to_string())
-}
-
-// Deux modes :
-// GUI (défaut) : poc-d3d.exe [--fixture <dir>] [--out <dir>] → preview + export
-// Bench (§9/10) : poc-d3d.exe --cfg C0..C8 [--fixture <dir>] [--repeat N] [--out <dir>]
-fn main() -> Result<()> {
- let args: Vec<String> = std::env::args().collect();
- let is_bench = args.iter().any(|a| a == "--cfg" || a == "--bench");
- if is_bench {
- run_bench(&args)
- } else {
- let fixture = arg(&args, "--fixture", "fixture");
- let out = arg(&args, "--out", "out");
- app::run_gui(
- &format!("{fixture}/screen.mp4"),
- &format!("{fixture}/webcam.mp4"),
- &format!("{fixture}/screen.cursor.json"),
- &out,
- )
- }
-}
-
-// spike-native.exe --cfg C0..C8 --fixture <dir> --repeat 3 --out out/
-fn run_bench(args: &[String]) -> Result<()> {
- let get = |k: &str, d: &str| -> String { arg(args, k, d) };
- let fixture = get("--fixture", "fixture");
- let out = get("--out", "out");
- let repeat: u32 = get("--repeat", "3").parse().unwrap_or(3);
- let cfg_arg = get("--cfg", "C0..C8");
-
- let screen = format!("{fixture}/screen.mp4");
- let webcam = format!("{fixture}/webcam.mp4");
- std::fs::create_dir_all(&out).ok();
-
- // sélection des cfg
- let all = config::all();
- let cfgs: Vec<config::Cfg> = if cfg_arg.contains("..") {
- all
- } else {
- cfg_arg
- .split(',')
- .filter_map(|n| config::Cfg::by_name(n.trim()))
- .collect()
- };
-
- let gpu = d3d::Gpu::create(false)?;
- println!("d3d11 device ok (feature_level 0x{:X})", gpu.feature_level.0 as u32);
- let mut comp = Compositor::new(&gpu)?;
- let track = cursor::CursorTrack::load(&format!("{fixture}/screen.cursor.json"), 100_000.0, 6.0)?;
- comp.set_cursor(track);
-
- let mut rows: Vec<(String, u64, f64, f64, f64, String)> = Vec::new(); // name, frames, best_wall, fps, ms/f, spread
- let mut json = String::from("{\n \"runs\": [\n");
-
- for cfg in &cfgs {
- let mut fps_runs = Vec::new();
- let mut frames = 0u64;
- for r in 0..repeat {
- let path = format!("{out}/{}.mp4", cfg.name);
- let s = if cfg.composite {
- pipeline::run_composited(&screen, &webcam, &path, &gpu, &comp, cfg, &mut |_| {})?
- } else {
- pipeline::run_c0(&screen, &path, &gpu)?
- };
- frames = s.frames;
- fps_runs.push(s.fps);
- if r == 0 {
- // extraction PNG f60/f180/f300 sur le 1er run (§11)
- extract_pngs(&path, &out, cfg.name);
- }
- }
- let best = fps_runs.iter().cloned().fold(f64::MIN, f64::max);
- let worst = fps_runs.iter().cloned().fold(f64::MAX, f64::min);
- let spread = if worst > 0.0 { 100.0 * (best - worst) / worst } else { 0.0 };
- let wall = frames as f64 / best;
- let msf = 1000.0 / best;
- println!(
- "{:<4} {:>4}f {:>7.3}s {:>7.1} fps {:>6.2} ms/f spread {:.1}% {}",
- cfg.name, frames, wall, best, msf, spread, cfg.desc
- );
- rows.push((cfg.name.to_string(), frames, wall, best, msf, format!("{spread:.1}%")));
- let _ = write!(
- json,
- " {{ \"cfg\": \"{}\", \"frames\": {}, \"fps\": {:.2}, \"ms_per_frame\": {:.3}, \"spread_pct\": {:.1}, \"repeat\": {}, \"desc\": \"{}\" }}{}\n",
- cfg.name, frames, best, msf, spread, repeat, cfg.desc,
- if cfg.name == cfgs.last().unwrap().name { "" } else { "," }
- );
- }
- json.push_str(" ]\n}\n");
- std::fs::write(format!("{out}/report.json"), &json)?;
-
- // table markdown récap
- println!("\ncfg frames wall_s fps ms/f spread");
- for (n, f, w, fps, msf, sp) in &rows {
- println!("{n:<4} {f:<7} {w:<7.3} {fps:<8.1} {msf:<7.2} {sp}");
- }
- println!("\nreport.json + out/C*.mp4 + out/C*_f{{60,180,300}}.png écrits dans {out}/");
- Ok(())
-}
-
-/// Extrait 3 frames (f60/f180/f300) d'un MP4 via ffmpeg (§11) — vérification à l'œil.
-fn extract_pngs(mp4: &str, out: &str, cfg: &str) {
- for f in [60u32, 180, 300] {
- let _ = std::process::Command::new("ffmpeg")
- .args([
- "-v", "error", "-y", "-i", mp4,
- "-vf", &format!("select=eq(n\\,{f})"),
- "-frames:v", "1",
- &format!("{out}/{cfg}_f{f}.png"),
- ])
- .status();
- }
+fn main() -> anyhow::Result<()> {
+ poc_d3d::run()
}
diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsx
new file mode 100644
index 000000000..53a4d5674
--- /dev/null
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -0,0 +1,62 @@
+import { useRef, useState } from "react";
+import { useNativeCompositorView } from "@/native";
+
+/**
+ * POC Option A — monte une fenêtre D3D11 native (compositeur poc-d3d, via
+ * `compositor_view.node`) par-dessus la zone preview, positionnée sur ce `<div>`
+ * placeholder et pilotée par `useNativeCompositorView`. La fenêtre native rend
+ * le compositing ; le `<div>` ne sert qu'à donner sa géométrie (le hook sync le
+ * rect natif au resize/scroll).
+ *
+ * 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 } = useNativeCompositorView(mountRef, { enabled });
+ const [blur, setBlur] = useState(false);
+
+ if (!enabled) {
+ return null;
+ }
+
+ 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ôle en position fixe hors de la zone preview → non recouvert par l'overlay natif */}
+ <label
+ style={{
+ position: "fixed",
+ top: 64,
+ left: 16,
+ zIndex: 99999,
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ background: "rgba(0,0,0,0.7)",
+ color: "#fff",
+ padding: "5px 9px",
+ borderRadius: 6,
+ font: "12px system-ui",
+ pointerEvents: "auto",
+ }}
+ >
+ <input
+ type="checkbox"
+ checked={blur}
+ onChange={(e) => {
+ setBlur(e.target.checked);
+ setParam("backgroundBlur", e.target.checked);
+ }}
+ />
+ Background blur (native)
+ </label>
+ </>
+ );
+}
diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsx
index 5e1c75642..a842d1583 100644
--- a/src/components/ai-edition/Preview.tsx
+++ b/src/components/ai-edition/Preview.tsx
@@ -8,11 +8,16 @@ import type {
} from "@/lib/ai-edition/schema";
import type { SpeedRegion } from "@/lib/ai-edition/timeline/speed";
import { EditorEmptyState } from "./EditorEmptyState";
+import { NativeCompositorOverlay } from "./NativeCompositorOverlay";
import styles from "./NewEditorShell.module.css";
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 =
+ (import.meta.env as Record<string, string | undefined>).VITE_NATIVE_COMPOSITOR === "1";
+
interface PreviewProps {
hasProject: boolean;
hasAsset: boolean;
@@ -94,6 +99,7 @@ export function Preview({
data-current-time-sec={currentTimeSec.toFixed(3)}
data-is-playing={playing ? "true" : "false"}
>
+ <NativeCompositorOverlay enabled={NATIVE_COMPOSITOR_ENABLED} />
{hasProject && hasAsset && !videoError ? (
<PreviewCanvas
videoSources={videoSources}
diff --git a/src/native/compositorViewClient.ts b/src/native/compositorViewClient.ts
new file mode 100644
index 000000000..35f500e14
--- /dev/null
+++ b/src/native/compositorViewClient.ts
@@ -0,0 +1,54 @@
+/**
+ * Renderer-side client for the native D3D11 compositor view. Each function
+ * sends a `compositor` domain `NativeBridgeRequest` over the existing
+ * `native-bridge:invoke` channel. The parent window handle is supplied
+ * main-side (it never crosses the IPC boundary), so the renderer's
+ * `createCompositorView` only takes the rect.
+ */
+
+import { requireNativeBridgeData } from "./client";
+import type { CompositorParamValue, CompositorViewRect, CompositorViewResult } from "./contracts";
+
+export function createCompositorView(rect: CompositorViewRect): Promise<CompositorViewResult> {
+ return requireNativeBridgeData<CompositorViewResult>({
+ domain: "compositor",
+ action: "createView",
+ payload: { rect },
+ });
+}
+
+export function setCompositorRect(id: number, rect: CompositorViewRect): Promise<{ ok: true }> {
+ return requireNativeBridgeData<{ ok: true }>({
+ domain: "compositor",
+ action: "setRect",
+ payload: { id, rect },
+ });
+}
+
+export function setCompositorParam(
+ id: number,
+ key: string,
+ value: CompositorParamValue,
+): Promise<{ ok: true }> {
+ return requireNativeBridgeData<{ ok: true }>({
+ domain: "compositor",
+ action: "setParam",
+ payload: { id, key, value },
+ });
+}
+
+export function setCompositorPlaying(id: number, playing: boolean): Promise<{ ok: true }> {
+ return requireNativeBridgeData<{ ok: true }>({
+ domain: "compositor",
+ action: "setPlaying",
+ payload: { id, playing },
+ });
+}
+
+export function destroyCompositorView(id: number): Promise<{ ok: true }> {
+ return requireNativeBridgeData<{ ok: true }>({
+ domain: "compositor",
+ action: "destroyView",
+ payload: { id },
+ });
+}
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index 0b40a7c4d..8f4506c76 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -90,6 +90,29 @@ export interface ProjectFileResult {
error?: string;
}
+// ---- Compositor view domain (Option A embed) -----------------------------
+// Drives a native D3D11 compositor preview window embedded in the main app
+// window. The Rust napi-rs addon (`compositor_view.node`) lives at
+// `electron/native/compositor-view/` and is built OUT OF SCOPE for the TS
+// layer; the service falls back to a safe no-op when the addon is absent so
+// the renderer keeps running. Defined here (not in the addon .d.ts) so the
+// renderer, the IPC contract, and the main-side service all import from a
+// single TS source — never from the native `.d.ts`.
+
+export interface CompositorViewRect {
+ /** Device pixels, relative to the parent window's client area. */
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export type CompositorParamValue = boolean | number | string;
+
+export interface CompositorViewResult {
+ id: number;
+}
+
// ---- AI Edition domain (Phase 1+) -----------------------------------------
// v3/v4 AxcutDocument projects live under userData/projects/<id>.openscreen
// (older builds used <id>.axcut, migrated on access). Project ids are
@@ -178,7 +201,7 @@ export interface AiEditionChatMessage {
createdAt: string;
toolCalls?: AiEditionToolCallSummary[];
/**
- * ponytail: id of the rewind-able document snapshot taken right before
+ * id of the rewind-able document snapshot taken right before
* the user message triggered its chat turn. Non-null = the per-message
* ↩ button is shown. Matches axcut's Message.checkpointId.
*/
@@ -228,7 +251,7 @@ export interface AiEditionChatBudget {
fillPercent: number;
}
-// ponytail: re-export of the timeline-operation discriminated union so the
+// re-export of the timeline-operation discriminated union so the
// IPC contract type and the renderer share one shape. Kept here (not in
// src/lib/ai-edition/document/operations) so the IPC type bundle stays
// self-contained.
@@ -586,6 +609,36 @@ export type NativeBridgeRequest =
conversationMessage: string;
};
requestId?: string;
+ }
+ | {
+ domain: "compositor";
+ action: "createView";
+ payload: { rect: CompositorViewRect };
+ requestId?: string;
+ }
+ | {
+ domain: "compositor";
+ action: "setRect";
+ payload: { id: number; rect: CompositorViewRect };
+ requestId?: string;
+ }
+ | {
+ domain: "compositor";
+ action: "setParam";
+ payload: { id: number; key: string; value: CompositorParamValue };
+ requestId?: string;
+ }
+ | {
+ domain: "compositor";
+ action: "setPlaying";
+ payload: { id: number; playing: boolean };
+ requestId?: string;
+ }
+ | {
+ domain: "compositor";
+ action: "destroyView";
+ payload: { id: number };
+ requestId?: string;
};
export type NativeBridgeEventName =
@@ -594,7 +647,7 @@ export type NativeBridgeEventName =
| "cursor.telemetryLoaded"
| "ai-edition.chat-event";
-// ponytail: streamed chat-progress event broadcast by runChat so the renderer
+// streamed chat-progress event broadcast by runChat so the renderer
// can render text deltas + tool ops live instead of waiting for the final RPC
// return. Empty `assistant` slot + `kind: "error"` means the upstream
// provider failed and the toast was a side-channel; the renderer shows it
diff --git a/src/native/hooks/useNativeCompositorView.ts b/src/native/hooks/useNativeCompositorView.ts
new file mode 100644
index 000000000..b665e7501
--- /dev/null
+++ b/src/native/hooks/useNativeCompositorView.ts
@@ -0,0 +1,161 @@
+/**
+ * React hook that mounts a native D3D11 compositor preview window on top of a
+ * DOM element. On mount it allocates a compositor view (rect only — the
+ * native window handle is resolved main-side), then keeps the native view in
+ * sync with the DOM element's bounding rect via a single rAF-coalesced
+ * ResizeObserver + window resize/scroll listener pair. Cleanup cancels the
+ * observer/listeners and destroys the native view.
+ *
+ * Every native-bridge call is wrapped in a try/catch that swallows + warns,
+ * because the renderer may run without the bridge (pure web `npm run dev`,
+ * Vitest jsdom env). The hook never throws upward.
+ */
+
+import type { RefObject } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ createCompositorView,
+ destroyCompositorView,
+ setCompositorParam,
+ setCompositorPlaying,
+ setCompositorRect,
+} from "../compositorViewClient";
+import type { CompositorParamValue, CompositorViewRect } from "../contracts";
+import { computeDeviceRect, rectsEqual } from "../nativeViewRect";
+
+export interface UseNativeCompositorViewOptions {
+ /** When false, the hook does nothing on mount and destroys nothing on
+ * unmount. Defaults to true. */
+ enabled?: boolean;
+}
+
+export interface UseNativeCompositorViewResult {
+ /** Numeric view id once createCompositorView resolves. `null` while the
+ * call is in flight or when the bridge is unavailable. May be a negative
+ * synthetic id when the native addon is absent (see
+ * `compositorViewService`). */
+ viewId: number | null;
+ setParam: (key: string, value: CompositorParamValue) => void;
+ setPlaying: (playing: boolean) => void;
+}
+
+/** swallow+warn wrapper for native-bridge calls. The renderer can run without
+ * a preload `electronAPI` (jsdom, pure web); errors must never propagate. */
+function safelyCall(label: string, call: () => Promise<unknown>) {
+ try {
+ call().catch((error: unknown) => {
+ console.warn(`[compositor-view] ${label} failed:`, error);
+ });
+ } catch (error) {
+ console.warn(`[compositor-view] ${label} failed:`, error);
+ }
+}
+
+export function useNativeCompositorView(
+ ref: RefObject<HTMLElement>,
+ opts: UseNativeCompositorViewOptions = {},
+): UseNativeCompositorViewResult {
+ const enabled = opts.enabled !== false;
+ const [viewId, setViewId] = useState<number | null>(null);
+ // Mirror into a ref so async callbacks always see the freshest id without
+ // re-subscribing the main effect.
+ const viewIdRef = useRef<number | null>(null);
+ viewIdRef.current = viewId;
+
+ useEffect(() => {
+ if (!enabled) {
+ return;
+ }
+ const el = ref.current;
+ if (!el) {
+ return;
+ }
+
+ let rafHandle = 0;
+ let lastRect: CompositorViewRect | null = null;
+ let disposed = false;
+
+ const applyRectNow = () => {
+ rafHandle = 0;
+ if (disposed) {
+ return;
+ }
+ const domRect = el.getBoundingClientRect();
+ const next = computeDeviceRect(domRect, window.devicePixelRatio);
+ if (lastRect && rectsEqual(lastRect, next)) {
+ return;
+ }
+ lastRect = next;
+ const id = viewIdRef.current;
+ if (id == null) {
+ return;
+ }
+ safelyCall("setRect", () => setCompositorRect(id, next));
+ };
+
+ const scheduleRectUpdate = () => {
+ if (rafHandle !== 0) {
+ return;
+ }
+ rafHandle = requestAnimationFrame(applyRectNow);
+ };
+
+ // Initial mount: allocate the native view with the rect observed at
+ // the moment the effect ran. The async id will be used on subsequent
+ // resize/scroll updates. Without the bridge, this is a swallowed
+ // warning — the rest of the hook stays inert.
+ const initialRect = computeDeviceRect(el.getBoundingClientRect(), window.devicePixelRatio);
+ lastRect = initialRect;
+ safelyCall("createView", async () => {
+ const result = await createCompositorView(initialRect);
+ if (disposed) {
+ // The element unmounted before the response came back; clean up.
+ safelyCall("destroyView (late)", () => destroyCompositorView(result.id));
+ return;
+ }
+ viewIdRef.current = result.id;
+ setViewId(result.id);
+ });
+
+ const observer = new ResizeObserver(scheduleRectUpdate);
+ observer.observe(el);
+ window.addEventListener("resize", scheduleRectUpdate);
+ // capture phase so we observe parent scroll containers too,
+ // not just `window` — the preview pane may scroll independently.
+ window.addEventListener("scroll", scheduleRectUpdate, true);
+
+ return () => {
+ disposed = true;
+ if (rafHandle !== 0) {
+ cancelAnimationFrame(rafHandle);
+ }
+ observer.disconnect();
+ window.removeEventListener("resize", scheduleRectUpdate);
+ window.removeEventListener("scroll", scheduleRectUpdate, true);
+ const id = viewIdRef.current;
+ if (id != null) {
+ safelyCall("destroyView", () => destroyCompositorView(id));
+ }
+ };
+ // `ref` is a stable RefObject; we only re-run the effect when
+ // the enabled flag flips.
+ }, [enabled, ref]);
+
+ const setParam = useCallback((key: string, value: CompositorParamValue) => {
+ const id = viewIdRef.current;
+ if (id == null) {
+ return;
+ }
+ safelyCall("setParam", () => setCompositorParam(id, key, value));
+ }, []);
+
+ const setPlaying = useCallback((playing: boolean) => {
+ const id = viewIdRef.current;
+ if (id == null) {
+ return;
+ }
+ safelyCall("setPlaying", () => setCompositorPlaying(id, playing));
+ }, []);
+
+ return { viewId, setParam, setPlaying };
+}
diff --git a/src/native/index.ts b/src/native/index.ts
index 817d1cf14..06d5a52c1 100644
--- a/src/native/index.ts
+++ b/src/native/index.ts
@@ -1,4 +1,7 @@
export * from "./client";
+export * from "./compositorViewClient";
export * from "./contracts";
export * from "./hooks/useCursorRecordingData";
export * from "./hooks/useCursorTelemetry";
+export * from "./hooks/useNativeCompositorView";
+export * from "./nativeViewRect";
diff --git a/src/native/nativeViewRect.test.ts b/src/native/nativeViewRect.test.ts
new file mode 100644
index 000000000..6f61fdaf0
--- /dev/null
+++ b/src/native/nativeViewRect.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from "vitest";
+import { computeDeviceRect, rectsEqual } from "./nativeViewRect";
+
+describe("computeDeviceRect", () => {
+ it("returns identity with Math.round at dpr=1", () => {
+ expect(computeDeviceRect({ left: 100, top: 50, width: 320, height: 240 }, 1)).toEqual({
+ x: 100,
+ y: 50,
+ width: 320,
+ height: 240,
+ });
+ });
+
+ it("scales by dpr=2", () => {
+ expect(computeDeviceRect({ left: 100, top: 50, width: 320, height: 240 }, 2)).toEqual({
+ x: 200,
+ y: 100,
+ width: 640,
+ height: 480,
+ });
+ });
+
+ it("rounds fractional coordinates to the nearest integer (e.g. 100.4 -> 100)", () => {
+ const rect = computeDeviceRect({ left: 50.4, top: 12.6, width: 200.49, height: 100.5 }, 1);
+ expect(rect).toEqual({ x: 50, y: 13, width: 200, height: 101 });
+ });
+
+ it("rounds 0.5 values via Math.round (banker's-style half-to-even for .5)", () => {
+ // Math.round(0.5) === 1, Math.round(1.5) === 2, Math.round(2.5) === 3
+ // (toward +Infinity), so we exercise non-negative coordinates only.
+ const rect = computeDeviceRect({ left: 10.5, top: 20.5, width: 30.5, height: 40.5 }, 1);
+ expect(rect).toEqual({ x: 11, y: 21, width: 31, height: 41 });
+ });
+
+ it("handles a zero-size rect without producing NaN", () => {
+ const rect = computeDeviceRect({ left: 0, top: 0, width: 0, height: 0 }, 2);
+ expect(rect).toEqual({ x: 0, y: 0, width: 0, height: 0 });
+ });
+
+ it("falls back to dpr=1 when devicePixelRatio is 0, negative, or non-finite", () => {
+ const domRect = { left: 12, top: 34, width: 56, height: 78 };
+
+ expect(computeDeviceRect(domRect, 0)).toEqual({ x: 12, y: 34, width: 56, height: 78 });
+ expect(computeDeviceRect(domRect, -1)).toEqual({ x: 12, y: 34, width: 56, height: 78 });
+ expect(computeDeviceRect(domRect, Number.NaN)).toEqual({
+ x: 12,
+ y: 34,
+ width: 56,
+ height: 78,
+ });
+ expect(computeDeviceRect(domRect, Number.POSITIVE_INFINITY)).toEqual({
+ x: 12,
+ y: 34,
+ width: 56,
+ height: 78,
+ });
+ });
+
+ it("returns integers for every field (the addon rejects fractional device coords)", () => {
+ const rect = computeDeviceRect({ left: 7.7, top: 9.3, width: 11.7, height: 13.1 }, 1.5);
+ for (const field of ["x", "y", "width", "height"] as const) {
+ expect(Number.isInteger(rect[field])).toBe(true);
+ }
+ });
+});
+
+describe("rectsEqual", () => {
+ it("returns true for two structurally identical rects", () => {
+ expect(
+ rectsEqual({ x: 1, y: 2, width: 3, height: 4 }, { x: 1, y: 2, width: 3, height: 4 }),
+ ).toBe(true);
+ });
+
+ it("returns false when any field differs", () => {
+ expect(
+ rectsEqual({ x: 0, y: 2, width: 3, height: 4 }, { x: 1, y: 2, width: 3, height: 4 }),
+ ).toBe(false);
+ expect(
+ rectsEqual({ x: 1, y: 0, width: 3, height: 4 }, { x: 1, y: 2, width: 3, height: 4 }),
+ ).toBe(false);
+ expect(
+ rectsEqual({ x: 1, y: 2, width: 0, height: 4 }, { x: 1, y: 2, width: 3, height: 4 }),
+ ).toBe(false);
+ expect(
+ rectsEqual({ x: 1, y: 2, width: 3, height: 0 }, { x: 1, y: 2, width: 3, height: 4 }),
+ ).toBe(false);
+ });
+
+ it("treats two zero rects as equal", () => {
+ expect(
+ rectsEqual({ x: 0, y: 0, width: 0, height: 0 }, { x: 0, y: 0, width: 0, height: 0 }),
+ ).toBe(true);
+ });
+});
diff --git a/src/native/nativeViewRect.ts b/src/native/nativeViewRect.ts
new file mode 100644
index 000000000..20b368c59
--- /dev/null
+++ b/src/native/nativeViewRect.ts
@@ -0,0 +1,35 @@
+/**
+ * Pure helpers for translating a DOM `getBoundingClientRect()` into device-pixel
+ * coordinates the native D3D11 compositor addon expects. Kept side-effect free
+ * so it's trivially unit-testable and shareable between the React hook and any
+ * non-React caller (e.g. a future render-loop chip in Pixi).
+ */
+import type { CompositorViewRect } from "./contracts";
+
+/**
+ * Convert a CSS-pixel rect (as returned by `Element.getBoundingClientRect()`)
+ * to the device-pixel rect the compositor addon expects. All four values are
+ * rounded via `Math.round` because the addon returns either truncated or
+ * off-by-one windows when handed non-integer values.
+ */
+export function computeDeviceRect(
+ domRect: { left: number; top: number; width: number; height: number },
+ devicePixelRatio: number,
+): CompositorViewRect {
+ const ratio = Number.isFinite(devicePixelRatio) && devicePixelRatio > 0 ? devicePixelRatio : 1;
+ return {
+ x: Math.round(domRect.left * ratio),
+ y: Math.round(domRect.top * ratio),
+ width: Math.round(domRect.width * ratio),
+ height: Math.round(domRect.height * ratio),
+ };
+}
+
+/**
+ * Cheap structural equality check for two device rects. Used by the React
+ * hook to skip re-sending `setRect` when nothing has changed (which would
+ * otherwise churn the native window needlessly).
+ */
+export function rectsEqual(a: CompositorViewRect, b: CompositorViewRect): boolean {
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
+}