Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(compositor): select the CPU backend automatically, and tell the user
Etienne Lescotee557f90e4b0
diff --git a/crates/compositor-view-napi/src/lib.rs b/crates/compositor-view-napi/src/lib.rsindex d51bfb6d3..15a997045 100644--- a/crates/compositor-view-napi/src/lib.rs+++ b/crates/compositor-view-napi/src/lib.rs@@ -10,7 +10,7 @@ use napi::threadsafe_function::{ErrorStrategy, ThreadsafeFunction, ThreadsafeFunuse napi::{Env, JsFunction, Task};use napi_derive::napi;use openscreen_compositor::compositor::{live_params_from_scene, Compositor};-use openscreen_compositor::d3d::Gpu;+use openscreen_compositor::d3d::{Backend, Gpu};use openscreen_compositor::gif_export::{GifExportParams, GifStats};use openscreen_compositor::live::{LiveView, PausedPreviews};use openscreen_compositor::scene::Scene;@@ -52,6 +52,24 @@ fn registry() -> &'static Mutex<HashMap<i32, LiveView>> {////// `rect` ne sert plus que pour `width`/`height` (résolution cible du preview) ;/// `x`/`y` sont ignorés (compat structurelle — la position est gérée par CSS).+/// Quel backend cette machine utilisera : `"hardware"`, `"cpu"`, ou `"none"` si aucun+/// device D3D11 ne se crée (la vue échouera alors avec son propre message, plus précis).+///+/// Sert à PRÉVENIR : sur `"cpu"`, le rendu passe par WARP + décodage logiciel — la+/// preview tombe à ~8 fps avec tous les effets et l'export met des minutes au lieu de+/// secondes. L'utilisateur doit le savoir AVANT de lancer un export, pas après. D'où une+/// question posée au système et non à une vue : la modale d'export la pose sans qu'aucune+/// preview n'existe. Réponse mise en cache côté Rust — c'est une propriété de la machine.+#[napi]+pub fn probe_backend() -> String {+ match Gpu::probe() {+ Some(Backend::Hardware) => "hardware",+ Some(Backend::Cpu) => "cpu",+ None => "none",+ }+ .to_string()+}+#[napi]pub fn create_view(rect: CompositorViewRect,@@ -368,7 +386,9 @@ impl Task for ExportMultiTask {// Previews paused for the whole render (GPU 3D engine freed) and restored// exactly as found when this guard drops, including on the error paths.let _previews = PreviewPause::begin();- let gpu = Gpu::create(false).map_err(|e| Error::from_reason(format!("{e:#}")))?;+ // Même sélection que la preview : l'export d'un hôte sans GPU passe par+ // libopenh264 au lieu d'AMF, plutôt que d'échouer.+ let gpu = Gpu::create_auto(false).map_err(|e| Error::from_reason(format!("{e:#}")))?;let mut cfg = config::all().pop().expect("au moins une config"); // C8cfg.zoom = false;cfg.layout_anim = false;diff --git a/crates/compositor/src/d3d.rs b/crates/compositor/src/d3d.rsindex 09c4a3b1a..9733b86e0 100644--- a/crates/compositor/src/d3d.rs+++ b/crates/compositor/src/d3d.rs@@ -4,6 +4,7 @@//! ffmpeg et notre boucle de rendu toucheront le device depuis des threads distincts.use anyhow::{bail, Result};+use std::sync::OnceLock;use windows::core::Interface;use windows::Win32::Foundation::HMODULE;use windows::Win32::Graphics::Direct3D::{@@ -98,9 +99,11 @@ fn try_create(/// Message d'échec ACTIONNABLE : re-sonde pour distinguer les deux causes réelles.///-/// Ce message reste utile MÊME avec `Backend::Cpu` disponible : rien ne bascule tout-/// seul (voir `create`), donc quelqu'un doit savoir pourquoi le matériel a refusé et si-/// le repli logiciel est la bonne réponse à son cas.+/// Ce message reste utile MÊME maintenant que `create_auto` replie sur le backend CPU :+/// il part dans les logs à chaque repli, et c'est lui qui dit si l'utilisateur subit un+/// pilote à mettre à jour (réparable en cinq minutes) ou une VM sans GPU (structurel).+/// Sans lui, un utilisateur au rendu logiciel ne saurait jamais qu'il lui manque un+/// pilote. Et si WARP échoue aussi, c'est ce message-ci que `create_auto` remonte.////// PR #162 proposait de retomber sur `D3D_DRIVER_TYPE_WARP` en gardant tout le reste./// Mesuré (`tests/warp_device_cannot_decode.rs`) : WARP + `VIDEO_SUPPORT` ne se crée même@@ -137,13 +140,51 @@ impl Gpu {/// Crée le device conforme au §2. `debug=false` impératif dans tout run mesuré/// (§10 : la couche debug valide et sérialise chaque appel — facteur, pas %).///- /// Reste le device MATÉRIEL : le backend CPU ne s'obtient qu'en le demandant- /// (`create_backend`). Rien ne bascule tout seul — un repli silencieux vers un- /// rendu logiciel serait précisément le « l'app rame aujourd'hui » qu'on veut éviter.+ /// MATÉRIEL STRICT, sans repli : échoue plutôt que de rendre un device WARP. C'est ce+ /// que veulent les tests et les goldens (mesurer ou comparer le chemin GPU n'a aucun+ /// sens sur un rastériseur logiciel). Le chemin de production, lui, prend `create_auto`.pub fn create(debug: bool) -> Result<Gpu> {Gpu::create_backend(Backend::Hardware, debug)}+ /// Le device de PRODUCTION : matériel si possible, backend CPU sinon.+ ///+ /// C'est ici que le repli devient automatique, et il ne l'est qu'accompagné : l'app+ /// demande `probe()` et prévient l'utilisateur. Un basculement muet vers un rendu à+ /// ~8 fps serait exactement le « l'app rame aujourd'hui » que cette branche corrige.+ ///+ /// Si les DEUX échouent, c'est le diagnostic MATÉRIEL qu'on remonte en tête : c'est+ /// lui qui est actionnable (« pas de décodeur vidéo sur cet adaptateur »), pas+ /// « WARP indisponible », qui ne dit rien à personne.+ pub fn create_auto(debug: bool) -> Result<Gpu> {+ let hw_err = match Gpu::create_backend(Backend::Hardware, debug) {+ Ok(gpu) => return Ok(gpu),+ Err(err) => err,+ };+ eprintln!("[d3d] backend matériel indisponible ({hw_err:#}) — repli sur le backend CPU");+ Gpu::create_backend(Backend::Cpu, debug).map_err(|cpu_err| {+ anyhow::anyhow!("{hw_err:#} (le repli logiciel a échoué aussi : {cpu_err:#})")+ })+ }++ /// Le backend que cette machine obtiendra, sans créer de vue ni d'export.+ ///+ /// Mis en cache : créer un device coûte quelques dizaines de ms et la réponse ne+ /// change pas en cours de session (un pilote qui tombe en marche est un redémarrage,+ /// pas un rafraîchissement). `None` = ni matériel ni WARP — la vue échouera, et c'est+ /// son message d'erreur, plus précis, qui doit parler.+ pub fn probe() -> Option<Backend> {+ static PROBED: OnceLock<Option<Backend>> = OnceLock::new();+ *PROBED.get_or_init(|| {+ for backend in [Backend::Hardware, Backend::Cpu] {+ if Gpu::create_backend(backend, false).is_ok() {+ return Some(backend);+ }+ }+ None+ })+ }+/// Le device du backend demandé. `Backend::Cpu` ne diagnostique pas : si WARP/// lui-même échoue, il n'y a plus rien derrière à proposer.pub fn create_backend(backend: Backend, debug: bool) -> Result<Gpu> {diff --git a/crates/compositor/src/live.rs b/crates/compositor/src/live.rsindex 76323ce2e..26e7f00ac 100644--- a/crates/compositor/src/live.rs+++ b/crates/compositor/src/live.rs@@ -1038,7 +1038,8 @@ unsafe fn render_thread(webcam: &str,cursor_json: &str,) -> Result<()> {- let gpu = Gpu::create(false)?;+ // Chemin de PRODUCTION : matériel si possible, backend CPU sinon (voir `create_auto`).+ let gpu = Gpu::create_auto(false)?;let mut comp = Compositor::new(&gpu)?;// Vue live = le VRAI enregistrement, pas la fenêtre fixture (100s@6s, taillée pour l'ancien// fixture POC). On charge toute la piste depuis t=0 ; 24h couvre large toute recording réelle.diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.tsindex b411ae2e9..c99126b64 100644--- a/electron/ipc/nativeBridge.ts+++ b/electron/ipc/nativeBridge.ts@@ -346,6 +346,11 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {});return createSuccessResponse(requestId, { id });}+ case "probeBackend":+ // No view needed: the export dialog asks before any preview exists.+ return createSuccessResponse(requestId, {+ backend: compositorViewService.probeBackend(),+ });case "setRect":compositorViewService.setRect(request.payload.id, request.payload.rect);return createSuccessResponse(requestId, { ok: true });diff --git a/electron/native-bridge/services/compositorViewService.ts b/electron/native-bridge/services/compositorViewService.tsindex 2e835d4b1..fd30d95d4 100644--- a/electron/native-bridge/services/compositorViewService.ts+++ b/electron/native-bridge/services/compositorViewService.ts@@ -6,6 +6,7 @@ import { app } from "electron";import { resolveCursorSprites } from "../../../src/lib/cursor/cursorThemes";import type {ClipInput,+ CompositorBackend,CompositorParamValue,CompositorViewAddon,CompositorViewRect,@@ -364,6 +365,26 @@ export class CompositorViewService {return this.ensureAddon() !== null;}+ /** Which backend the compositor will use on this machine.+ *+ * `"none"` when the addon is absent — no native path at all, so there is nothing to+ * warn about; that is the pure-web/dev case, not a degraded GPU. Callers must not+ * read `"none"` as "slow", only `"cpu"` means that. */+ probeBackend(): CompositorBackend {+ const addon = this.ensureAddon();+ if (!addon) {+ return "none";+ }+ try {+ return addon.probeBackend();+ } catch (err) {+ // An older `.node` predates probeBackend. Treat as unknown rather than+ // crashing the bridge: a stale addon should not take the editor down.+ console.warn("[compositor-view] probeBackend unavailable:", err);+ return "none";+ }+ }+/** Allocates an offscreen compositor view sized to `rect.width`x`rect.height`.* `rect.x` / `rect.y` are vestigial (ignored native-side) — the renderer* keeps them on the wire so the existing `CompositorViewRect` shape staysdiff --git a/electron/native/compositor-view/addon.d.ts b/electron/native/compositor-view/addon.d.tsindex 67e617515..da0172c31 100644--- a/electron/native/compositor-view/addon.d.ts+++ b/electron/native/compositor-view/addon.d.ts@@ -89,7 +89,17 @@ export interface ClipInput {webcamOffsetSec: number;}+/** Which backend the compositor will run on. `"cpu"` = WARP rasterisation + software+ * decode/encode, used when no usable D3D11 GPU is present: correct output, but roughly+ * 8 fps preview with all effects and minutes-long exports. `"none"` = no D3D11 device at+ * all, so the view will fail with its own, more specific message. */+export type CompositorBackend = "hardware" | "cpu" | "none";+export interface CompositorViewAddon {+ /** What this machine offers, asked without allocating a view — the export dialog+ * needs the answer before any preview exists. Cached native-side. */+ probeBackend(): CompositorBackend;+/** Allocates an offscreen compositor view sized to `rect.width`x`rect.height` (the* target preview resolution; `rect.x` / `rect.y` are vestigial and ignored native-side).* No HWND/native-window-handle is passed: there's no OS window to parent to. Thediff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsxindex 0d09dca37..63dc382e9 100644--- a/src/components/ai-edition/ExportDialog.tsx+++ b/src/components/ai-edition/ExportDialog.tsx@@ -32,7 +32,8 @@ import {type GifSizePreset,} from "@/lib/exporter";import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";-import { exportGifNative, exportMultiNative } from "@/native";+import { exportGifNative, exportMultiNative, useIsCpuCompositor } from "@/native";+import { nativeBridgeClient } from "@/native/client";import type { CompositorClipInput } from "@/native/contracts";import { buildSceneDescription, resolveVisibleClips } from "@/native/sceneDescription";import { ModalShell } from "./Modals";@@ -112,6 +113,9 @@ interface ExportDialogProps {export function ExportDialog({ open, onClose, document }: ExportDialogProps) {const t = useScopedT("editor");const ts = useScopedT("settings");+ // No usable GPU: the export still applies every effect (output is identical), it+ // just runs on the software encoder and takes minutes instead of seconds.+ const cpuCompositor = useIsCpuCompositor();const [format, setFormat] = useState<ExportFormat>("mp4");const [quality, setQuality] = useState<ExportQuality>("good");const [fps, setFps] = useState<24 | 30 | 60>(60);@@ -608,6 +612,24 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {savedPath={savedPath}/>+ {cpuCompositor && phase !== "done" && (+ // Placed next to the export button, not in a toast: it has to land while+ // the user is still deciding. A CPU export renders every effect correctly+ // but takes minutes rather than seconds, and an unexplained ten-minute+ // wait reads as a hang.+ <p+ data-testid="export-cpu-warning"+ style={{+ margin: "0 0 4px",+ fontSize: "0.8125rem",+ lineHeight: 1.4,+ color: "var(--text-muted, rgb(0 0 0 / 0.65))",+ }}+ >+ {t("cpuCompositor.exportWarning")}+ </p>+ )}+<divstyle={{display: "flex",diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsxindex 1c0073781..4ad76f062 100644--- a/src/components/ai-edition/NativeCompositorOverlay.tsx+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx@@ -8,6 +8,7 @@ import {setCurrentNativeViewId,setNativePlaying,setNativeScene,+ useIsCpuCompositor,useNativeCompositorView,} from "@/native";import { buildSceneDescription, resolveVisibleClips } from "@/native/sceneDescription";@@ -103,6 +104,10 @@ export function NativeCompositorOverlay() {sources: sources ?? undefined,});const t = useScopedT("editor");+ // No usable GPU: the preview still renders every effect, just slowly (~8 fps with+ // everything on). Nothing is disabled — the output stays identical to the GPU path —+ // so this is a notice, not a degradation warning.+ const cpuCompositor = useIsCpuCompositor();// publie l'id de la vue active dans le store → l'inspector peut pousser des params// via setNativeParam sans connaître cet overlay.@@ -251,10 +256,39 @@ export function NativeCompositorOverlay() {// hitbox) that PreviewCanvas renders after it, but above nothing else —// the CPU-rendered video/webcam/blur pixels it replaces are hidden via CSS.return (- <canvas- ref={canvasRef}- data-testid="native-compositor-mount"- style={{ position: "absolute", inset: 0, zIndex: 0, width: "100%", height: "100%" }}- />+ <>+ <canvas+ ref={canvasRef}+ data-testid="native-compositor-mount"+ style={{ position: "absolute", inset: 0, zIndex: 0, width: "100%", height: "100%" }}+ />+ {cpuCompositor && (+ // Persistent rather than a toast: the question it answers ("why is this+ // choppy?") comes up whenever the user looks at the preview, not once at+ // mount. Kept small, low-contrast and pointer-events-none so it never+ // competes with the interactive layers PreviewCanvas stacks above.+ <output+ data-testid="native-compositor-cpu-notice"+ style={{+ position: "absolute",+ left: "50%",+ bottom: "0.75rem",+ transform: "translateX(-50%)",+ zIndex: 1,+ pointerEvents: "none",+ maxWidth: "min(90%, 46ch)",+ padding: "0.25rem 0.625rem",+ borderRadius: "999px",+ fontSize: "0.75rem",+ lineHeight: 1.3,+ textAlign: "center",+ background: "rgb(0 0 0 / 0.55)",+ color: "rgb(255 255 255 / 0.92)",+ }}+ >+ {t("cpuCompositor.notice")}+ </output>+ )}+ </>);}diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.jsonindex ee74d85c7..8a450b47a 100644--- a/src/i18n/locales/ar/editor.json+++ b/src/i18n/locales/ar/editor.json@@ -389,5 +389,9 @@"cancel": "إلغاء","save": "حفظ","saveAndUse": "حفظ واستخدام"+ },+ "cpuCompositor": {+ "notice": "لا توجد بطاقة رسومات متوافقة — تتم المعالجة على المعالج، لذا يكون التشغيل أبطأ.",+ "exportWarning": "لا توجد بطاقة رسومات متوافقة: يتم هذا التصدير على المعالج وسيستغرق وقتًا أطول بكثير من المعتاد."}}diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.jsonindex 8262a019d..34c5e6438 100644--- a/src/i18n/locales/en/editor.json+++ b/src/i18n/locales/en/editor.json@@ -389,5 +389,9 @@"cancel": "Cancel","save": "Save","saveAndUse": "Save & use"+ },+ "cpuCompositor": {+ "notice": "Running without a compatible GPU — rendering on CPU, so playback is slower.",+ "exportWarning": "No compatible GPU: this export runs on CPU and will take much longer than usual."}}diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.jsonindex f560a0ac8..b0f07e8ea 100644--- a/src/i18n/locales/es/editor.json+++ b/src/i18n/locales/es/editor.json@@ -389,5 +389,9 @@"cancel": "Cancelar","save": "Guardar","saveAndUse": "Guardar y usar"+ },+ "cpuCompositor": {+ "notice": "Sin GPU compatible: el renderizado se hace en la CPU, por lo que la reproducción es más lenta.",+ "exportWarning": "Sin GPU compatible: esta exportación se ejecuta en la CPU y tardará mucho más de lo normal."}}diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.jsonindex 26df2114f..3b03b9871 100644--- a/src/i18n/locales/fr/editor.json+++ b/src/i18n/locales/fr/editor.json@@ -389,5 +389,9 @@"cancel": "Annuler","save": "Enregistrer","saveAndUse": "Enregistrer et utiliser"+ },+ "cpuCompositor": {+ "notice": "Aucun GPU compatible — rendu sur CPU, la lecture est donc plus lente.",+ "exportWarning": "Aucun GPU compatible : cet export tourne sur CPU et sera beaucoup plus long que d'habitude."}}diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.jsonindex 945afe358..1b2bbbf0c 100644--- a/src/i18n/locales/it/editor.json+++ b/src/i18n/locales/it/editor.json@@ -389,5 +389,9 @@"cancel": "Annulla","save": "Salva","saveAndUse": "Salva e usa"+ },+ "cpuCompositor": {+ "notice": "Nessuna GPU compatibile: il rendering avviene sulla CPU, quindi la riproduzione è più lenta.",+ "exportWarning": "Nessuna GPU compatibile: questa esportazione viene eseguita sulla CPU e richiederà molto più tempo del solito."}}diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.jsonindex ca90aea7e..04970a21f 100644--- a/src/i18n/locales/ja-JP/editor.json+++ b/src/i18n/locales/ja-JP/editor.json@@ -389,5 +389,9 @@"cancel": "キャンセル","save": "保存","saveAndUse": "保存して使用"+ },+ "cpuCompositor": {+ "notice": "対応 GPU がないため CPU で描画しています。再生が遅くなります。",+ "exportWarning": "対応 GPU がありません。この書き出しは CPU で実行されるため、通常よりはるかに時間がかかります。"}}diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.jsonindex 4032d3abb..e7b986017 100644--- a/src/i18n/locales/ko-KR/editor.json+++ b/src/i18n/locales/ko-KR/editor.json@@ -389,5 +389,9 @@"cancel": "취소","save": "저장","saveAndUse": "저장 후 사용"+ },+ "cpuCompositor": {+ "notice": "호환되는 GPU가 없어 CPU로 렌더링합니다. 재생이 느려집니다.",+ "exportWarning": "호환되는 GPU가 없습니다. 이 내보내기는 CPU에서 실행되며 평소보다 훨씬 오래 걸립니다."}}diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.jsonindex 571ada2b3..5833af8aa 100644--- a/src/i18n/locales/pt-BR/editor.json+++ b/src/i18n/locales/pt-BR/editor.json@@ -389,5 +389,9 @@"cancel": "Cancelar","save": "Salvar","saveAndUse": "Salvar e usar"+ },+ "cpuCompositor": {+ "notice": "Sem GPU compatível — a renderização ocorre na CPU, então a reprodução fica mais lenta.",+ "exportWarning": "Sem GPU compatível: esta exportação roda na CPU e vai demorar muito mais que o normal."}}diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.jsonindex 303c22fd7..6ebd18453 100644--- a/src/i18n/locales/ru/editor.json+++ b/src/i18n/locales/ru/editor.json@@ -389,5 +389,9 @@"cancel": "Отмена","save": "Сохранить","saveAndUse": "Сохранить и использовать"+ },+ "cpuCompositor": {+ "notice": "Совместимый GPU не найден — отрисовка на CPU, поэтому воспроизведение медленнее.",+ "exportWarning": "Совместимый GPU не найден: этот экспорт выполняется на CPU и займёт намного больше времени."}}diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.jsonindex 96de7405b..067f0f069 100644--- a/src/i18n/locales/tr/editor.json+++ b/src/i18n/locales/tr/editor.json@@ -389,5 +389,9 @@"cancel": "İptal","save": "Kaydet","saveAndUse": "Kaydet ve kullan"+ },+ "cpuCompositor": {+ "notice": "Uyumlu GPU yok — işleme CPU üzerinde yapılıyor, bu yüzden oynatma daha yavaş.",+ "exportWarning": "Uyumlu GPU yok: bu dışa aktarma CPU üzerinde çalışır ve normalden çok daha uzun sürer."}}diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.jsonindex bc05026c1..e5e649486 100644--- a/src/i18n/locales/vi/editor.json+++ b/src/i18n/locales/vi/editor.json@@ -389,5 +389,9 @@"cancel": "Hủy","save": "Lưu","saveAndUse": "Lưu và dùng"+ },+ "cpuCompositor": {+ "notice": "Không có GPU tương thích — kết xuất trên CPU nên phát lại chậm hơn.",+ "exportWarning": "Không có GPU tương thích: lần xuất này chạy trên CPU và sẽ lâu hơn bình thường rất nhiều."}}diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.jsonindex 037fced82..1500049a1 100644--- a/src/i18n/locales/zh-CN/editor.json+++ b/src/i18n/locales/zh-CN/editor.json@@ -389,5 +389,9 @@"cancel": "取消","save": "保存","saveAndUse": "保存并使用"+ },+ "cpuCompositor": {+ "notice": "没有兼容的 GPU,正在使用 CPU 渲染,因此播放较慢。",+ "exportWarning": "没有兼容的 GPU:本次导出将在 CPU 上运行,耗时会比平常长很多。"}}diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.jsonindex b152666eb..b0b36e5a7 100644--- a/src/i18n/locales/zh-TW/editor.json+++ b/src/i18n/locales/zh-TW/editor.json@@ -389,5 +389,9 @@"cancel": "取消","save": "儲存","saveAndUse": "儲存並使用"+ },+ "cpuCompositor": {+ "notice": "沒有相容的 GPU,正在使用 CPU 算繪,因此播放較慢。",+ "exportWarning": "沒有相容的 GPU:這次匯出將在 CPU 上執行,耗時會比平常長很多。"}}diff --git a/src/native/compositorViewClient.ts b/src/native/compositorViewClient.tsindex 859dcb19f..68f062e62 100644--- a/src/native/compositorViewClient.ts+++ b/src/native/compositorViewClient.ts@@ -9,6 +9,8 @@import { requireNativeBridgeData } from "./client";import type {+ CompositorBackend,+ CompositorBackendResult,CompositorClipInput,CompositorExportGifParams,CompositorExportGifResult,@@ -20,6 +22,23 @@ import type {CompositorViewResult,} from "./contracts";+/** Which backend the native compositor will use here.+ *+ * Resolves `"none"` rather than rejecting when there is no bridge or no addon — callers+ * use this to decide whether to show a "running without a GPU" notice, and a missing+ * native path is not a degraded GPU. Only `"cpu"` warrants a warning. */+export async function probeCompositorBackend(): Promise<CompositorBackend> {+ try {+ const result = await requireNativeBridgeData<CompositorBackendResult>({+ domain: "compositor",+ action: "probeBackend",+ });+ return result.backend;+ } catch {+ return "none";+ }+}+export function createCompositorView(rect: CompositorViewRect,sources?: { screenPath?: string; webcamPath?: string; cursorPath?: string },diff --git a/src/native/contracts.ts b/src/native/contracts.tsindex e2ba5b18c..c9b1cf85f 100644--- a/src/native/contracts.ts+++ b/src/native/contracts.ts@@ -113,6 +113,21 @@ export interface CompositorViewResult {id: number;}+/** Which backend the native compositor runs on.+ *+ * `"cpu"` = WARP rasterisation with software decode and encode, selected automatically+ * when no usable D3D11 GPU is present. Output is identical to the GPU path — the effects+ * all render — but the preview runs at roughly 8 fps with everything on and exports take+ * minutes rather than seconds, so it is worth telling the user about.+ *+ * `"none"` = no native compositor at all (addon absent: pure-web dev, jsdom). NOT a+ * degraded-GPU signal — never warn on it. */+export type CompositorBackend = "hardware" | "cpu" | "none";++export interface CompositorBackendResult {+ backend: CompositorBackend;+}+/** A self-describing preview frame returned by `readFrame` (native → renderer): pixels* (`data`, RGBA8, `width * height * 4` bytes) plus their dimensions and a monotonic* generation. The hook keeps `gen` and passes it back as `sinceGen`; an unchanged frame@@ -655,6 +670,11 @@ export type NativeBridgeRequest =};requestId?: string;}+ | {+ domain: "compositor";+ action: "probeBackend";+ requestId?: string;+ }| {domain: "compositor";action: "setRect";diff --git a/src/native/hooks/useCompositorBackend.test.ts b/src/native/hooks/useCompositorBackend.test.tsnew file mode 100644index 000000000..e85410872--- /dev/null+++ b/src/native/hooks/useCompositorBackend.test.ts@@ -0,0 +1,67 @@+/**+ * The CPU-backend notice must fire on a degraded GPU and stay silent everywhere else.+ *+ * The failure worth guarding is the false positive: `"none"` means there is no native+ * compositor at all (pure-web `npm run dev`, jsdom, an addon that failed to load), which+ * is the normal state in development — warning there would put "no compatible GPU" in+ * front of every developer on every run. Only `"cpu"` is a real degraded machine.+ */++import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({ probeCompositorBackend: vi.fn() }));++vi.mock("../compositorViewClient", () => ({+ probeCompositorBackend: mocks.probeCompositorBackend,+}));++import {+ resetCompositorBackendProbeForTests,+ useCompositorBackend,+ useIsCpuCompositor,+} from "./useCompositorBackend";++describe("useCompositorBackend", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetCompositorBackendProbeForTests();+ });++ it("reports the degraded machine", async () => {+ mocks.probeCompositorBackend.mockResolvedValue("cpu");+ const { result } = renderHook(() => useIsCpuCompositor());+ await waitFor(() => expect(result.current).toBe(true));+ });++ it("stays silent on a normal GPU", async () => {+ mocks.probeCompositorBackend.mockResolvedValue("hardware");+ const { result } = renderHook(() => useCompositorBackend());+ await waitFor(() => expect(result.current).toBe("hardware"));+ expect(result.current === "cpu").toBe(false);+ });++ it("stays silent when there is no native compositor at all", async () => {+ mocks.probeCompositorBackend.mockResolvedValue("none");+ const { result } = renderHook(() => useIsCpuCompositor());+ await waitFor(() => expect(mocks.probeCompositorBackend).toHaveBeenCalled());+ expect(result.current).toBe(false);+ });++ it("starts silent, before the probe resolves", () => {+ mocks.probeCompositorBackend.mockReturnValue(new Promise(() => {}));+ const { result } = renderHook(() => useIsCpuCompositor());+ // No flash of "no compatible GPU" on a machine that turns out to have one.+ expect(result.current).toBe(false);+ });++ it("probes once for the whole session, however many consumers ask", async () => {+ mocks.probeCompositorBackend.mockResolvedValue("cpu");+ const a = renderHook(() => useIsCpuCompositor());+ const b = renderHook(() => useIsCpuCompositor());+ await waitFor(() => expect(a.result.current).toBe(true));+ await waitFor(() => expect(b.result.current).toBe(true));+ // Creating a D3D11 device is not free; the preview and the export dialog share one.+ expect(mocks.probeCompositorBackend).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/native/hooks/useCompositorBackend.ts b/src/native/hooks/useCompositorBackend.tsnew file mode 100644index 000000000..1b85fec6f--- /dev/null+++ b/src/native/hooks/useCompositorBackend.ts@@ -0,0 +1,57 @@+/**+ * Which backend the native compositor runs on, probed once per session.+ *+ * The answer is a property of the machine, not of a view, so it is cached in a+ * module-level promise: the preview and the export dialog both need it, and neither+ * should pay a second native device creation for it. The native side caches it too.+ *+ * Returns `null` until the probe resolves, so callers render nothing rather than+ * flashing a warning that may not apply.+ */++import { useEffect, useState } from "react";+import { probeCompositorBackend } from "../compositorViewClient";+import type { CompositorBackend } from "../contracts";++let cached: Promise<CompositorBackend> | null = null;++function probeOnce(): Promise<CompositorBackend> {+ if (!cached) {+ cached = probeCompositorBackend();+ }+ return cached;+}++/** Test seam: drops the memoised probe so each test observes its own mock. */+export function resetCompositorBackendProbeForTests(): void {+ cached = null;+}++export function useCompositorBackend(): CompositorBackend | null {+ const [backend, setBackend] = useState<CompositorBackend | null>(null);++ useEffect(() => {+ let disposed = false;+ probeOnce().then((value) => {+ if (!disposed) {+ setBackend(value);+ }+ });+ return () => {+ disposed = true;+ };+ }, []);++ return backend;+}++/**+ * True only when the compositor is running WITHOUT a usable GPU.+ *+ * Deliberately not `backend !== "hardware"`: `"none"` means there is no native compositor+ * at all (pure-web dev, jsdom), which is not a degraded machine and must never raise a+ * warning. `null` (still probing) is not degraded either.+ */+export function useIsCpuCompositor(): boolean {+ return useCompositorBackend() === "cpu";+}diff --git a/src/native/index.ts b/src/native/index.tsindex fb858d1d0..2660b7fc0 100644--- a/src/native/index.ts+++ b/src/native/index.ts@@ -1,6 +1,7 @@export * from "./client";export * from "./compositorViewClient";export * from "./contracts";+export * from "./hooks/useCompositorBackend";export * from "./hooks/useCursorRecordingData";export * from "./hooks/useCursorTelemetry";export * from "./hooks/useNativeCompositorView";diff --git a/technical-documentation/architecture/native-compositor.md b/technical-documentation/architecture/native-compositor.mdindex f3619a660..26763f9b1 100644--- a/technical-documentation/architecture/native-compositor.md+++ b/technical-documentation/architecture/native-compositor.md@@ -250,53 +250,51 @@ licence. D3D11VA + AMF survive the LGPL-shared build (verified:## Known gaps-- **The CPU backend exists, but nothing selects it automatically yet.**- `d3d::Backend::Cpu` runs the same pipeline on a WARP device with libavcodec- software decode ([`cpu_frames.rs`](../../crates/compositor/src/cpu_frames.rs)),- and renders **iso** with the GPU path (max deviation 3/255 across C1–C8 —- see [rendering-performance.md](../engineering/rendering-performance.md#the-cpu-backend-warp--software-decode--2026-07-27)).- `Gpu::create` still returns the hardware device and never falls back on its- own: a silent switch to a 6–9 fps preview is exactly the "the app is slow- today" failure this whole thread set out to remove. Selecting it, and the- effect policy it needs (background blur and motion blur cost 17× and 23× on- WARP and are what make C4+ unusable), is not wired.- **Export cannot use it at all**: `h264_amf` requires the real GPU, and encode- is a third axis with no software path — though the vendored LGPL build does- ship `libopenh264` and `h264_mf`, so that is a wiring gap rather than a wall.--- **The hardware path has no automatic fallback, and WARP alone could not be one.** `d3d::Gpu::create`- ([`crates/compositor/src/d3d.rs`](../../crates/compositor/src/d3d.rs)) requests- `D3D_DRIVER_TYPE_HARDWARE` and pins `D3D_FEATURE_LEVEL_11_1`, with- `VIDEO_SUPPORT` mandatory for `D3D11VA`. A machine without a GPU that- exposes FL 11_1 with video support hard-fails at startup; there is no- path that decodes on CPU, so the compositor is unusable on virtualised- environments that do not pass through a compatible adapter.-- Retrying in `D3D_DRIVER_TYPE_WARP` — the obvious repair, and what PR #162- originally scoped — does not work, and the reason is capability, not- speed. Measured (`crates/compositor/tests/warp_device_cannot_decode.rs`,- which fails if this ever stops being true): WARP **rejects the- `VIDEO_SUPPORT` flag outright** (`DXGI_ERROR_UNSUPPORTED`, `0x887A0004`),- and dropping the flag yields a FL 11_1 device that exposes no- `ID3D11VideoDevice` at all (`E_NOINTERFACE`, zero decoder profiles).- Since `pipeline.rs` hands this very device to ffmpeg as the- `AVD3D11VADeviceContext`, preview *and* export decode every frame on it —- a WARP device would produce none. Shipping the retry would only convert a- clear startup failure into an obscure ffmpeg one. So the answer to "is- WARP acceptable for export, or preview only?" is neither.-- What the compositor does instead is **fail legibly**: `Gpu::create`- re-probes on the failure path (same call, minus `VIDEO_SUPPORT`) to tell- "this adapter has no video decoder" — the Remote Desktop / VM case — apart- from "no FL 11_1 adapter at all", and says which, plus what to do about it.- That message reaches the user rather than a log: the render thread stores- its fatal error in `live::Shared`, the addon's `read_frame` returns it as- an `Err` on the next pull (~33 ms), and `NativeCompositorOverlay` renders- it in place of the canvas. Before this, `create_view` had already returned- `Ok` by the time the thread died, so the failure existed only as an- `eprintln!` and the user just saw a black preview.-- The WGC capture helper++- **The CPU fallback is a whole second backend, because WARP alone could not+ have been one.** `d3d::Gpu::create_auto` prefers the hardware device+ (`D3D_DRIVER_TYPE_HARDWARE`, FL 11_1, `VIDEO_SUPPORT` for `D3D11VA`) and falls+ back to `Backend::Cpu` — described in+ [rendering-performance.md](../engineering/rendering-performance.md#the-cpu-backend-warp--software-decode--2026-07-27).++ Retrying in `D3D_DRIVER_TYPE_WARP` and changing nothing else — the obvious+ repair, and what PR #162 originally scoped — does not work, and the reason is+ capability, not speed. Measured+ (`crates/compositor/tests/warp_device_cannot_decode.rs`, which fails if this+ ever stops being true): WARP **rejects the `VIDEO_SUPPORT` flag outright**+ (`DXGI_ERROR_UNSUPPORTED`, `0x887A0004`), and dropping the flag yields a FL+ 11_1 device that exposes no `ID3D11VideoDevice` at all (`E_NOINTERFACE`, zero+ decoder profiles). Since `pipeline.rs` hands this very device to ffmpeg as the+ `AVD3D11VADeviceContext`, a WARP device would have produced no frames at all.+ **Rendering and decoding are two axes**, and no software rasteriser on any+ platform covers the second — so the fallback needed libavcodec software decode+ (`cpu_frames.rs`) beside the WARP device. The third axis, encoding, is covered+ by `ExportCodec::candidates()` / `VideoEncoder`, which already probes the host+ for a working encoder and lands on `libopenh264` / `libkvazaar` when no+ hardware one opens — the CPU backend simply falls out of that list rather than+ needing a path of its own. Three axes, three answers.++ It is never silent. `Gpu::create` (hardware-strict, no fallback) is kept for+ tests and goldens; `create_auto` logs *why* the hardware device was refused+ via `diagnose()` — "this adapter has no video decoder" (Remote Desktop, VMs,+ Basic Render Driver) versus "no FL 11_1 adapter at all" — which is what tells+ a user whether a driver update would fix it. The renderer asks+ `probeBackend()` and shows a notice in the preview and a warning in the export+ dialog, so ~8 fps playback reads as "this machine has no GPU" rather than as+ the app hanging. **No effect is disabled on the CPU path**: output stays+ identical to the GPU path (max deviation 3/255), and 8 fps is what the 1.7.0+ preview delivered anyway, so trading correctness for frame rate would be a bad+ bargain in both directions.++ If **both** backends fail there is nothing left, and that failure is surfaced+ rather than logged: the render thread stores its fatal error in+ `live::Shared`, the addon's `read_frame` returns it as an `Err` on the next+ pull (~33 ms), and `NativeCompositorOverlay` renders it in place of the+ canvas. Before this, `create_view` had already returned `Ok` by the time the+ thread died, so the failure existed only as an `eprintln!` and the user just+ saw a black preview.++- **Capture is left hardware-only on purpose.** The WGC capture helper([`electron/native/wgc-capture/src/wgc_session.cpp`](../../electron/native/wgc-capture/src/wgc_session.cpp))is left hardware-only too, but for a different reason than the compositor:**WGC capture is not mandatory.** Windows recording already has a non-D3D