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): an interactive preview and export GUI

Etienne Lescot778b5ee07cfa
diff --git a/poc-d3d/Cargo.lock b/poc-d3d/Cargo.lock
index 883eef097..7412555dd 100644
--- a/poc-d3d/Cargo.lock
+++ b/poc-d3d/Cargo.lock
@@ -156,6 +156,17 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "poc-d3d"
+version = "0.0.0"
+dependencies = [
+ "anyhow",
+ "bindgen",
+ "cc",
+ "serde_json",
+ "windows",
+]
+
[[package]]
name = "prettyplease"
version = "0.2.37"
@@ -273,17 +284,6 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
-[[package]]
-name = "poc-d3d"
-version = "0.0.0"
-dependencies = [
- "anyhow",
- "bindgen",
- "cc",
- "serde_json",
- "windows",
-]
-
[[package]]
name = "syn"
version = "2.0.119"
diff --git a/poc-d3d/Cargo.toml b/poc-d3d/Cargo.toml
index 08ce4297a..0cf6873fc 100644
--- a/poc-d3d/Cargo.toml
+++ b/poc-d3d/Cargo.toml
@@ -32,5 +32,10 @@ features = [
"Win32_Graphics_Direct3D11",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
- "Win32_System_Performance", # QueryPerformanceCounter / Frequency (§10)
+ "Win32_Graphics_Gdi", # brosses/police GUI de la preview (app.rs)
+ "Win32_System_Performance", # QueryPerformanceCounter / Frequency (§10)
+ "Win32_System_LibraryLoader", # GetModuleHandleW (hInstance, app.rs)
+ "Win32_UI_WindowsAndMessaging", # fenêtre + contrôles natifs (app.rs)
+ "Win32_UI_Controls", # barre de progression (app.rs)
+ "Win32_UI_Input_KeyboardAndMouse", # EnableWindow (app.rs)
]
diff --git a/poc-d3d/README.md b/poc-d3d/README.md
index e2c1343c9..f754356fb 100644
--- a/poc-d3d/README.md
+++ b/poc-d3d/README.md
@@ -47,10 +47,23 @@ compositeur (WGSL natif à l'identique) + la carte des coûts.
## Build & run
-`x.bat` encapsule vcvars + ffmpeg/bin sur le PATH runtime :
+`x.bat` encapsule vcvars + ffmpeg/bin sur le PATH runtime. Deux modes :
+
+**GUI (défaut)** — preview/playback interactive + export. Rapproche le POC d'une intégration
+app : le même compositeur/pipeline mesuré alimente une vraie boucle de rendu.
+
+```
+x.bat run --release [-- --fixture fixture --out out]
+```
+
+Fenêtre native : preview du compositing en lecture bouclée (swapchain DXGI flip, blit
+zéro-copie du RT), sélecteur de preset C0→C8, Play/Pause, **Export** (barre de progression +
+bilan _temps + fps_). Écrit `out/export.mp4`. Détail : `docs/S7-preview-export.md`.
+
+**Bench (§9/§10)** — la mesure fps headless, inchangée :
```
-x.bat run --release -- --fixture fixture --cfg C0..C8 --repeat 3 --out out/
+x.bat run --release -- --cfg C0..C8 --fixture fixture --repeat 3 --out out/
```
Produit `out/C{0..8}.mp4` (1080p60, 360 frames), `out/C{n}_f{60,180,300}.png`,
@@ -64,6 +77,7 @@ dans `docs/S1-sources.md` ; `fixture/fixture.json` (le manifeste mesuré) est su
## Docs
-`docs/` = le parcours S0→S6 du POC : S0 décision framework, S1 sources/chaîne matérielle,
-S2 pipeline C0, S6 rapport + mesure des moteurs GPU + optimisations. `spikes/` = les probes
-jetables de S0 (Direct2D, NV12 render-target) conservés comme preuve.
+`docs/` = le parcours S0→S7 du POC : S0 décision framework, S1 sources/chaîne matérielle,
+S2 pipeline C0, S6 rapport + mesure des moteurs GPU + optimisations, S7 preview/export
+interactive (marche vers l'intégration app). `spikes/` = les probes jetables de S0
+(Direct2D, NV12 render-target) conservés comme preuve.
diff --git a/poc-d3d/docs/S7-preview-export.md b/poc-d3d/docs/S7-preview-export.md
new file mode 100644
index 000000000..738996098
--- /dev/null
+++ b/poc-d3d/docs/S7-preview-export.md
@@ -0,0 +1,73 @@
+# S7 — Preview/playback + export (marche vers l'intégration app)
+
+**Verdict.** Le POC n'est plus un batch qui écrit des MP4 : c'est une **app native**
+qui *montre* le compositing en lecture temps réel et l'exporte sur un bouton, avec barre
+de progression et bilan (**temps + fps**). Le compositeur et le pipeline mesurés (S2→S6)
+sont réutilisés tels quels — la GUI est une couche autour, pas une réécriture.
+
+## Ce que ça change (avant → après)
+
+| | Avant (S6) | Après (S7) |
+|---|---|---|
+| Interface | CLI batch `--cfg C0..C8` | fenêtre native + CLI batch (conservée) |
+| Voir le compositing | ouvrir les MP4/PNG produits | **preview bouclée temps réel** dans la fenêtre |
+| Exporter | chaque run réencode tout | **bouton Export** → `out/export.mp4` |
+| Retour d'export | table stdout | **barre de progression + bilan temps/fps** dans l'UI |
+| Choix des effets | argument `--cfg` | **sélecteur C0→C8** (preview + export en direct) |
+
+Lancement : `x.bat run --release` (défaut = GUI). Le bench headless reste `--cfg …`.
+
+## Architecture (mono-thread, coopératif)
+
+```
+fenêtre hôte (Win32)
+├─ enfant "preview" ── swapchain DXGI flip (R8G8B8A8) sur le device D3D11 PARTAGÉ
+│ └─ chaque tick : compose_frame → blit_to(backbuffer) → Present(vsync)
+└─ bande de contrôles natifs : combo preset · Play/Pause · Export · barre · label bilan
+```
+
+- **Un seul device D3D11**, celui de S2 : décodeurs, compositeur, encodeur ET la swapchain
+ de preview le partagent. Le blit preview = une passe `ps_tex` (RT RGBA → backbuffer,
+ letterboxé) — zéro conversion, zéro readback. Le backbuffer est en `R8G8B8A8_UNORM` pour
+ matcher le RT (passthrough sans swizzle).
+- **Contrôles Win32 natifs** (combo, boutons, `msctls_progress32`, label) : aucun rendu de
+ texte maison. La swapchain vit sur un enfant dédié *sans* sous-fenêtre — condition du
+ modèle flip (pas de contrôle par-dessus la surface flip).
+- **Cadence playback** : `WM_TIMER` ~60 Hz, avance des frames source par **horloge murale**
+ (accumulateur 1/60 s, garde anti-spirale). Boucle sur EOF par `av_seek_frame(0)` +
+ `avcodec_flush_buffers` — zéro réallocation de décodeur (la fixture démarre sur un IDR, §11).
+
+## Export : progression sans trahir la mesure (§10)
+
+L'export réutilise `run_composited` (le chemin C1→C8 mesuré). Le fps affiché **reste la
+mesure enveloppante** de §10 : une lecture d'horloge avant/après tout le run, rien
+d'instrumenté dans la boucle. La barre est alimentée par une sonde `progress(frames)`
+appelée par frame mais **throttlée au pourcent** — un `SendMessage(PBM_SETPOS)` (µs)
+négligeable devant ~8 ms/frame GPU. Côté bench la sonde est un no-op → **chiffres identiques**
+(vérifié : C0 237, C4 136, C8 135 fps, cf. S6).
+
+L'export tourne sur le thread UI **sans re-pomper** le message-loop (pas de réentrance
+wndproc → pas d'aliasing `&mut`). La barre et le label se rafraîchissent par
+`UpdateWindow` sur *leur* contrôle (repaint synchrone, hors de notre wndproc). Sur la
+fixture (~2,7 s en release) la fenêtre reste sous le seuil « Not Responding ».
+
+Bilan affiché à la fin : `Done — C8 · 360 frames · 2.67s · 134.9 fps -> out/export.mp4`.
+
+## Ce que ça démontre pour l'intégration app
+
+L'app OpenScreen (Electron) a besoin, d'un module natif, exactement de ces deux surfaces :
+**(1)** un flux de frames composées présentable dans un viewport (preview), **(2)** un export
+piloté avec progression et bilan. S7 prouve que le fast-path D3D11 les sert *depuis le même
+device*, sans copie CPU — le module natif exposerait `present()` / `export(on_progress)` en
+miroir de `blit_to` / `run_composited(progress)`.
+
+## Restes ouverts (hors périmètre POC)
+
+- **Frontière FFI** vers l'hôte (Electron/N-API ou fenêtre embarquée) — ici la fenêtre est
+ autonome Win32.
+- **Preview redimensionnable / DPI** : fenêtre à taille fixe (letterbox déjà géré) ; un vrai
+ intégrant ferait `ResizeBuffers` sur `WM_SIZE`.
+- **Sources dynamiques** : la timeline reste celle, figée, de la fixture (S1) ; l'intégration
+ brancherait les vraies pistes.
+- **Export cancel/threadé** : suffisant en coopératif pour la fixture ; un export long
+ voudrait un worker + `PostMessage` de progression.
diff --git a/poc-d3d/src/app.rs b/poc-d3d/src/app.rs
new file mode 100644
index 000000000..af07818a9
--- /dev/null
+++ b/poc-d3d/src/app.rs
@@ -0,0 +1,605 @@
+//! GUI native (Win32) : preview/playback du compositing + export avec barre de
+//! progression et bilan (temps + fps). Rapproche le POC d'une intégration app :
+//! le compositeur/pipeline mesuré alimente une vraie boucle de rendu interactive.
+//!
+//! Architecture :
+//! - une fenêtre hôte, un enfant "preview" portant une swapchain DXGI flip sur le
+//! device D3D11 partagé (blit zéro-copie du RT composité → backbuffer) ;
+//! - des contrôles Win32 natifs (combo preset, Play/Pause, Export, barre, label) —
+//! aucun rendu de texte maison ;
+//! - un modèle mono-thread coopératif : WM_TIMER cadence la playback à 60 fps ;
+//! l'export tourne sur le thread UI et rafraîchit la barre entre frames.
+
+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 anyhow::Result;
+use std::ffi::c_void;
+use std::time::Instant;
+use windows::core::{Interface, PCWSTR};
+use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM};
+use windows::Win32::Graphics::Direct3D11::ID3D11RenderTargetView;
+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_EFFECT_FLIP_DISCARD,
+ DXGI_USAGE_RENDER_TARGET_OUTPUT,
+};
+use windows::Win32::Graphics::Gdi::{
+ CreateFontW, GetSysColorBrush, UpdateWindow, COLOR_BTNFACE, HFONT,
+};
+use windows::Win32::System::LibraryLoader::GetModuleHandleW;
+use windows::Win32::UI::Input::KeyboardAndMouse::EnableWindow;
+use windows::Win32::UI::Controls::{
+ InitCommonControlsEx, ICC_PROGRESS_CLASS, ICC_STANDARD_CLASSES, INITCOMMONCONTROLSEX,
+ PBM_SETPOS, PBM_SETRANGE32,
+};
+use windows::Win32::UI::WindowsAndMessaging::*;
+
+const PREVIEW_W: i32 = 1280;
+const PREVIEW_H: i32 = 720;
+const STRIP_H: i32 = 64;
+const CLIENT_W: i32 = PREVIEW_W;
+const CLIENT_H: i32 = PREVIEW_H + STRIP_H;
+
+const ID_COMBO: isize = 101;
+const ID_PLAY: isize = 102;
+const ID_EXPORT: isize = 103;
+const ID_PROGRESS: isize = 104;
+const ID_STATUS: isize = 105;
+const TIMER_TICK: usize = 1;
+
+/// Chaîne UTF-16 terminée par NUL (durée de vie tenue par l'appelant).
+fn wide(s: &str) -> Vec<u16> {
+ s.encode_utf16().chain(std::iter::once(0)).collect()
+}
+
+/// Plus grand rectangle 16:9 centré dans `(cw, ch)` → viewport letterbox de la preview.
+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)
+}
+
+/// 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,
+ comp: Compositor,
+ player: Player,
+ cfgs: Vec<Cfg>,
+ cur: usize,
+ playing: bool,
+ exporting: bool,
+ total_frames: u64,
+ screen: String,
+ webcam: String,
+ out: String,
+ // win32
+ preview: HWND,
+ combo: HWND,
+ play_btn: HWND,
+ export_btn: HWND,
+ progress: HWND,
+ status: HWND,
+ // dxgi (preview)
+ swap: Option<IDXGISwapChain1>,
+ bb_rtv: Option<ID3D11RenderTargetView>,
+ // cadence playback
+ last: Instant,
+ acc: f64,
+}
+
+impl App {
+ /// Compose + affiche la 1re frame, avant l'ouverture de la fenêtre.
+ unsafe fn init_first_frame(&mut self) {
+ let cfg = self.cfgs[self.cur].clone();
+ let _ = self.player.step(&self.comp, &cfg);
+ let _ = self.render();
+ self.update_ready_status();
+ self.last = Instant::now();
+ }
+
+ /// Cadence 60 fps par horloge murale (accumulateur), avec garde anti-spirale.
+ unsafe fn on_tick(&mut self) -> Result<()> {
+ if self.exporting || !self.playing {
+ return Ok(());
+ }
+ let now = Instant::now();
+ let dt = (now - self.last).as_secs_f64().min(0.1);
+ self.last = now;
+ self.acc += dt;
+ let step = 1.0 / 60.0;
+ let cfg = self.cfgs[self.cur].clone();
+ let mut stepped = false;
+ let mut n = 0;
+ while self.acc >= step && n < 3 {
+ if self.player.step(&self.comp, &cfg)? {
+ stepped = true;
+ }
+ self.acc -= step;
+ n += 1;
+ }
+ if self.acc > step {
+ self.acc = 0.0; // largue le retard accumulé (fenêtre masquée, etc.)
+ }
+ if stepped {
+ self.render()?;
+ }
+ Ok(())
+ }
+
+ /// Blit du RT composité vers le backbuffer, letterboxé, puis Present (vsync).
+ unsafe fn render(&mut self) -> Result<()> {
+ let (Some(swap), Some(rtv)) = (self.swap.as_ref(), self.bb_rtv.as_ref()) else {
+ return Ok(());
+ };
+ let mut rc = RECT::default();
+ let _ = GetClientRect(self.preview, &mut rc);
+ let cw = (rc.right - rc.left).max(1) as f32;
+ let ch = (rc.bottom - rc.top).max(1) as f32;
+ let (x, y, w, h) = letterbox(cw, ch);
+ self.gpu.context.ClearRenderTargetView(rtv, &[0.02, 0.02, 0.03, 1.0]);
+ self.comp.blit_to(rtv, x, y, w, h);
+ let _ = swap.Present(1, DXGI_PRESENT(0));
+ Ok(())
+ }
+
+ unsafe fn on_command(&mut self, wp: WPARAM) -> Result<()> {
+ let id = (wp.0 & 0xffff) as isize;
+ let code = ((wp.0 >> 16) & 0xffff) as u32;
+ match id {
+ ID_PLAY => self.toggle_play(),
+ ID_EXPORT => self.run_export()?,
+ ID_COMBO if code == CBN_SELCHANGE => {
+ let sel = SendMessageW(self.combo, CB_GETCURSEL, WPARAM(0), LPARAM(0)).0;
+ if sel >= 0 && (sel as usize) < self.cfgs.len() {
+ self.cur = sel as usize;
+ if !self.playing {
+ let cfg = self.cfgs[self.cur].clone();
+ let _ = self.player.recompose(&self.comp, &cfg);
+ let _ = self.render();
+ }
+ self.update_ready_status();
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+ }
+
+ unsafe fn toggle_play(&mut self) {
+ self.playing = !self.playing;
+ let label = wide(if self.playing { "Pause" } else { "Play" });
+ let _ = SetWindowTextW(self.play_btn, PCWSTR(label.as_ptr()));
+ self.last = Instant::now();
+ self.acc = 0.0;
+ }
+
+ /// Export coopératif (thread UI) : la barre avance via SendMessage+UpdateWindow sur le
+ /// contrôle (pas de re-pompage du message-loop → aucune réentrance dans notre wndproc).
+ /// La mesure fps reste enveloppante (§10) dans `run_composited`.
+ unsafe fn run_export(&mut self) -> Result<()> {
+ if self.exporting {
+ return Ok(());
+ }
+ self.exporting = true;
+ self.playing = false;
+ let pl = wide("Play");
+ let _ = SetWindowTextW(self.play_btn, PCWSTR(pl.as_ptr()));
+ let _ = EnableWindow(self.export_btn, false);
+ let _ = EnableWindow(self.play_btn, false);
+ let _ = EnableWindow(self.combo, false);
+
+ SendMessageW(self.progress, PBM_SETRANGE32, WPARAM(0), LPARAM(self.total_frames as isize));
+ SendMessageW(self.progress, PBM_SETPOS, WPARAM(0), LPARAM(0));
+
+ let cfg = self.cfgs[self.cur].clone();
+ let s = wide(&format!("Exporting {} — {} …", cfg.name, cfg.desc));
+ let _ = SetWindowTextW(self.status, PCWSTR(s.as_ptr()));
+ let _ = UpdateWindow(self.status);
+ let _ = UpdateWindow(self.progress);
+
+ // sonde de progression : SendMessage throttlé au pourcent (µs, cf. §10).
+ let prog = self.progress;
+ let total = self.total_frames.max(1);
+ let mut last_pct: i64 = -1;
+ let mut cb = move |done: u64| {
+ let pct = (done as i64 * 100) / total as i64;
+ if pct != last_pct {
+ last_pct = pct;
+ SendMessageW(prog, PBM_SETPOS, WPARAM(done as usize), LPARAM(0));
+ let _ = UpdateWindow(prog);
+ }
+ };
+ let r = pipeline::run_composited(
+ &self.screen, &self.webcam, &self.out, &self.gpu, &self.comp, &cfg, &mut cb,
+ );
+ self.comp.clear_srv_cache();
+
+ let _ = EnableWindow(self.export_btn, true);
+ let _ = EnableWindow(self.play_btn, true);
+ let _ = EnableWindow(self.combo, true);
+ self.exporting = false;
+
+ match r {
+ Ok(st) => {
+ SendMessageW(self.progress, PBM_SETPOS, WPARAM(st.frames as usize), LPARAM(0));
+ let msg = format!(
+ "Done — {} · {} frames · {:.2}s · {:.1} fps -> {}",
+ cfg.name, st.frames, st.wall_s, st.fps, self.out
+ );
+ let w = wide(&msg);
+ let _ = SetWindowTextW(self.status, PCWSTR(w.as_ptr()));
+ }
+ Err(e) => {
+ let w = wide(&format!("Export failed: {e}"));
+ let _ = SetWindowTextW(self.status, PCWSTR(w.as_ptr()));
+ }
+ }
+
+ // reprise de la playback
+ self.playing = true;
+ let pb = wide("Pause");
+ let _ = SetWindowTextW(self.play_btn, PCWSTR(pb.as_ptr()));
+ self.last = Instant::now();
+ self.acc = 0.0;
+ Ok(())
+ }
+
+ unsafe fn update_ready_status(&self) {
+ let cfg = &self.cfgs[self.cur];
+ let s = wide(&format!(
+ "Ready - {} · {} ({} frames · export -> {})",
+ cfg.name, cfg.desc, self.total_frames, self.out
+ ));
+ let _ = SetWindowTextW(self.status, PCWSTR(s.as_ptr()));
+ }
+
+ unsafe fn report_err(&self, e: &anyhow::Error) {
+ let w = wide(&format!("error: {e}"));
+ let _ = SetWindowTextW(self.status, PCWSTR(w.as_ptr()));
+ eprintln!("[app] error: {e:#}");
+ }
+}
+
+/// Police Segoe UI 9pt ClearType — les contrôles créés par CreateWindowEx héritent sinon
+/// d'une vieille police bitmap système. Fuit un HFONT (durée de vie = process).
+unsafe fn ui_font() -> HFONT {
+ let face = wide("Segoe UI");
+ // (height=-12 ≈ 9pt @96dpi, weight=400, charset=DEFAULT(1), quality=CLEARTYPE(5))
+ CreateFontW(-12, 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 5, 0, PCWSTR(face.as_ptr()))
+}
+
+/// Crée l'enfant preview + les contrôles natifs. Renvoie leurs HWND.
+unsafe fn create_children(
+ parent: HWND,
+ hinst: windows::Win32::Foundation::HINSTANCE,
+ cfgs: &[Cfg],
+) -> Result<(HWND, HWND, HWND, HWND, HWND, HWND)> {
+ let btn_cls = wide("BUTTON");
+ let combo_cls = wide("COMBOBOX");
+ let static_cls = wide("STATIC");
+ let prog_cls = wide("msctls_progress32");
+ let prev_cls = wide("PocD3DPreview");
+
+ let preview = CreateWindowExW(
+ WINDOW_EX_STYLE(0),
+ PCWSTR(prev_cls.as_ptr()),
+ PCWSTR::null(),
+ WS_CHILD | WS_VISIBLE,
+ 0, 0, PREVIEW_W, PREVIEW_H,
+ parent,
+ HMENU::default(),
+ hinst,
+ None,
+ )?;
+
+ let y = PREVIEW_H + 18;
+ let combo_style =
+ WS_CHILD.0 | WS_VISIBLE.0 | WS_VSCROLL.0 | (CBS_DROPDOWNLIST as u32) | (CBS_HASSTRINGS as u32);
+ let combo = CreateWindowExW(
+ WINDOW_EX_STYLE(0),
+ PCWSTR(combo_cls.as_ptr()),
+ PCWSTR::null(),
+ WINDOW_STYLE(combo_style),
+ 14, y - 3, 250, 340,
+ parent,
+ HMENU(ID_COMBO as *mut c_void),
+ hinst,
+ None,
+ )?;
+ for c in cfgs {
+ let item = wide(&format!("{} — {}", c.name, c.desc));
+ SendMessageW(combo, CB_ADDSTRING, WPARAM(0), LPARAM(item.as_ptr() as isize));
+ }
+ SendMessageW(combo, CB_SETCURSEL, WPARAM(cfgs.len() - 1), LPARAM(0));
+
+ let pl = wide("Pause");
+ let play_btn = CreateWindowExW(
+ WINDOW_EX_STYLE(0),
+ PCWSTR(btn_cls.as_ptr()),
+ PCWSTR(pl.as_ptr()),
+ WINDOW_STYLE(WS_CHILD.0 | WS_VISIBLE.0 | (BS_PUSHBUTTON as u32)),
+ 278, y, 96, 30,
+ parent,
+ HMENU(ID_PLAY as *mut c_void),
+ hinst,
+ None,
+ )?;
+
+ let ex = wide("Export");
+ let export_btn = CreateWindowExW(
+ WINDOW_EX_STYLE(0),
+ PCWSTR(btn_cls.as_ptr()),
+ PCWSTR(ex.as_ptr()),
+ WINDOW_STYLE(WS_CHILD.0 | WS_VISIBLE.0 | (BS_PUSHBUTTON as u32)),
+ 382, y, 96, 30,
+ parent,
+ HMENU(ID_EXPORT as *mut c_void),
+ hinst,
+ None,
+ )?;
+
+ let progress = CreateWindowExW(
+ WINDOW_EX_STYLE(0),
+ PCWSTR(prog_cls.as_ptr()),
+ PCWSTR::null(),
+ WS_CHILD | WS_VISIBLE,
+ 494, y + 4, 300, 22,
+ parent,
+ HMENU(ID_PROGRESS as *mut c_void),
+ hinst,
+ None,
+ )?;
+
+ let st = wide("Ready");
+ let status = CreateWindowExW(
+ WINDOW_EX_STYLE(0),
+ PCWSTR(static_cls.as_ptr()),
+ PCWSTR(st.as_ptr()),
+ WS_CHILD | WS_VISIBLE,
+ 808, y + 6, 458, 40,
+ parent,
+ HMENU(ID_STATUS as *mut c_void),
+ hinst,
+ None,
+ )?;
+
+ let font = ui_font();
+ for c in [combo, play_btn, export_btn, status] {
+ SendMessageW(c, WM_SETFONT, WPARAM(font.0 as usize), LPARAM(1));
+ }
+ Ok((combo, play_btn, export_btn, progress, status, preview))
+}
+
+/// Crée la swapchain flip + RTV du backbuffer sur le device D3D11 partagé.
+unsafe fn create_swapchain(
+ device: &windows::Win32::Graphics::Direct3D11::ID3D11Device,
+ hwnd: HWND,
+) -> 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: PREVIEW_W as u32,
+ Height: PREVIEW_H as u32,
+ 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 bb: windows::Win32::Graphics::Direct3D11::ID3D11Texture2D = swap.GetBuffer(0)?;
+ let mut rtv: Option<ID3D11RenderTargetView> = None;
+ device.CreateRenderTargetView(&bb, None, Some(&mut rtv))?;
+ Ok((swap, rtv.unwrap()))
+}
+
+extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
+ unsafe {
+ let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut App;
+ if ptr.is_null() {
+ return DefWindowProcW(hwnd, msg, wp, lp);
+ }
+ let app = &mut *ptr;
+ match msg {
+ WM_TIMER => {
+ if let Err(e) = app.on_tick() {
+ app.report_err(&e);
+ }
+ LRESULT(0)
+ }
+ WM_COMMAND => {
+ if let Err(e) = app.on_command(wp) {
+ app.report_err(&e);
+ }
+ LRESULT(0)
+ }
+ WM_DESTROY => {
+ let _ = KillTimer(hwnd, TIMER_TICK);
+ PostQuitMessage(0);
+ LRESULT(0)
+ }
+ _ => DefWindowProcW(hwnd, msg, wp, lp),
+ }
+ }
+}
+
+/// Point d'entrée GUI (appelé par `main` quand aucun argument bench n'est passé).
+pub fn run_gui(screen: &str, webcam: &str, cursor_json: &str, out_dir: &str) -> Result<()> {
+ unsafe { run_gui_inner(screen, webcam, cursor_json, out_dir) }
+}
+
+unsafe fn run_gui_inner(screen: &str, webcam: &str, cursor_json: &str, out_dir: &str) -> Result<()> {
+ std::fs::create_dir_all(out_dir).ok();
+ let out = format!("{out_dir}/export.mp4");
+
+ let gpu = Gpu::create(false)?;
+ println!("d3d11 device ok (feature_level 0x{:X})", gpu.feature_level.0 as u32);
+ let mut comp = Compositor::new(&gpu)?;
+ if let Ok(track) = CursorTrack::load(cursor_json, 100_000.0, 6.0) {
+ comp.set_cursor(track);
+ }
+ let player = Player::open(screen, webcam, &gpu)?;
+ let total_frames = pipeline::probe_frame_count(screen).unwrap_or(FIXTURE_FRAMES as u64);
+ let cfgs = config::all();
+ let cur = cfgs.len() - 1; // C8 (tous effets) par défaut
+
+ let hinst = windows::Win32::Foundation::HINSTANCE(GetModuleHandleW(None)?.0);
+
+ let icc = INITCOMMONCONTROLSEX {
+ dwSize: std::mem::size_of::<INITCOMMONCONTROLSEX>() as u32,
+ dwICC: ICC_PROGRESS_CLASS | ICC_STANDARD_CLASSES,
+ };
+ let _ = InitCommonControlsEx(&icc);
+
+ let main_cls = wide("PocD3DMain");
+ let prev_cls = wide("PocD3DPreview");
+ let cursor = LoadCursorW(None, IDC_ARROW)?;
+ let wc_main = WNDCLASSW {
+ style: CS_HREDRAW | CS_VREDRAW,
+ lpfnWndProc: Some(wndproc),
+ hInstance: hinst,
+ lpszClassName: PCWSTR(main_cls.as_ptr()),
+ hCursor: cursor,
+ hbrBackground: GetSysColorBrush(COLOR_BTNFACE),
+ ..Default::default()
+ };
+ RegisterClassW(&wc_main);
+ let wc_prev = WNDCLASSW {
+ style: CS_HREDRAW | CS_VREDRAW,
+ lpfnWndProc: Some(wndproc), // USERDATA null sur l'enfant → DefWindowProcW
+ hInstance: hinst,
+ lpszClassName: PCWSTR(prev_cls.as_ptr()),
+ hCursor: cursor,
+ hbrBackground: windows::Win32::Graphics::Gdi::HBRUSH(std::ptr::null_mut()),
+ ..Default::default()
+ };
+ RegisterClassW(&wc_prev);
+
+ let style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
+ let mut rc = RECT { left: 0, top: 0, right: CLIENT_W, bottom: CLIENT_H };
+ let _ = AdjustWindowRectEx(&mut rc, style, false, WINDOW_EX_STYLE(0));
+ let ww = rc.right - rc.left;
+ let wh = rc.bottom - rc.top;
+
+ let title = wide("OpenScreen — POC D3D11 compositor · preview + export");
+ let hwnd = CreateWindowExW(
+ WINDOW_EX_STYLE(0),
+ PCWSTR(main_cls.as_ptr()),
+ PCWSTR(title.as_ptr()),
+ style,
+ CW_USEDEFAULT, CW_USEDEFAULT, ww, wh,
+ HWND::default(),
+ HMENU::default(),
+ hinst,
+ None,
+ )?;
+
+ let (combo, play_btn, export_btn, progress, status, preview) =
+ create_children(hwnd, hinst, &cfgs)?;
+ let (swap, bb_rtv) = create_swapchain(&gpu.device, preview)?;
+
+ let app = Box::new(App {
+ gpu,
+ comp,
+ player,
+ cfgs,
+ cur,
+ playing: true,
+ exporting: false,
+ total_frames,
+ screen: screen.to_string(),
+ webcam: webcam.to_string(),
+ out,
+ preview,
+ combo,
+ play_btn,
+ export_btn,
+ progress,
+ status,
+ swap: Some(swap),
+ bb_rtv: Some(bb_rtv),
+ last: Instant::now(),
+ acc: 0.0,
+ });
+ let app_ptr = Box::into_raw(app);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, app_ptr as isize);
+
+ (*app_ptr).init_first_frame();
+ let _ = ShowWindow(hwnd, SW_SHOW);
+ let _ = UpdateWindow(hwnd);
+ SetTimer(hwnd, TIMER_TICK, 15, None);
+
+ let mut msg = MSG::default();
+ while GetMessageW(&mut msg, HWND::default(), 0, 0).0 > 0 {
+ let _ = TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+
+ drop(Box::from_raw(app_ptr));
+ Ok(())
+}
diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rs
index 75e756a5d..57b50c7ff 100644
--- a/poc-d3d/src/compositor.rs
+++ b/poc-d3d/src/compositor.rs
@@ -971,4 +971,31 @@ impl Compositor {
std::fs::write(path, &out)?;
Ok(())
}
+
+ /// Blit du RT composité (RGBA) vers un render target externe (backbuffer swapchain),
+ /// mis à l'échelle dans le viewport `(x,y,w,h)` en pixels — sert la preview (§preview).
+ /// Passe de copie `ps_tex` : même échantillonnage que `render_nv12`, sans conversion.
+ /// Le caller a déjà clear le RTV (barres letterbox) avant l'appel.
+ pub unsafe fn blit_to(&self, rtv: &ID3D11RenderTargetView, x: f32, y: f32, w: f32, h: f32) {
+ self.ctx.OMSetBlendState(&self.blend_none, None, 0xffffffff);
+ self.ctx.OMSetRenderTargets(Some(&[Some(rtv.clone())]), None);
+ self.ctx.PSSetShaderResources(0, Some(&[Some(self.rt_srv.clone())]));
+ self.ctx.VSSetShader(&self.vs_fs, None);
+ self.ctx.PSSetShader(&self.ps_tex, None);
+ self.ctx.PSSetSamplers(0, Some(&[Some(self.sampler.clone())]));
+ self.ctx.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
+ let vp = D3D11_VIEWPORT {
+ TopLeftX: x, TopLeftY: y, Width: w, Height: h, MinDepth: 0.0, MaxDepth: 1.0,
+ };
+ self.ctx.RSSetViewports(Some(&[vp]));
+ self.upload_cb(&LayerCB::default());
+ self.ctx.Draw(3, 0);
+ self.ctx.PSSetShaderResources(0, Some(&[None]));
+ }
+
+ /// Vide le cache de SRV décodeur. À appeler après la fermeture d'un jeu de décodeurs
+ /// (p.ex. après un export) pour ne pas retenir indéfiniment des textures de pool.
+ pub fn clear_srv_cache(&self) {
+ self.srv_cache.borrow_mut().clear();
+ }
}
diff --git a/poc-d3d/src/main.rs b/poc-d3d/src/main.rs
index f927120ca..f1fa59c49 100644
--- a/poc-d3d/src/main.rs
+++ b/poc-d3d/src/main.rs
@@ -1,3 +1,4 @@
+mod app;
mod compositor;
mod config;
mod cursor;
@@ -9,12 +10,33 @@ use anyhow::Result;
use compositor::Compositor;
use std::fmt::Write as _;
-// spike-native.exe --fixture <dir> --cfg C0..C8 --repeat 3 --out out/
+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 get = |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())
- };
+ 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);
@@ -50,7 +72,7 @@ fn main() -> Result<()> {
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)?
+ pipeline::run_composited(&screen, &webcam, &path, &gpu, &comp, cfg, &mut |_| {})?
} else {
pipeline::run_c0(&screen, &path, &gpu)?
};
diff --git a/poc-d3d/src/pipeline.rs b/poc-d3d/src/pipeline.rs
index 7ba2a9f3a..4a1f7b06e 100644
--- a/poc-d3d/src/pipeline.rs
+++ b/poc-d3d/src/pipeline.rs
@@ -15,6 +15,7 @@ use windows::core::Interface;
// Macros libav non générées par bindgen (function-like). Valeurs Windows/MSVC.
const AVERROR_EAGAIN: i32 = -11; // -EAGAIN (EAGAIN=11 sur MSVC)
const AVERROR_EOF: i32 = -541478725; // -MKTAG('E','O','F',' ')
+const AVSEEK_FLAG_BACKWARD: i32 = 1; // seek vers la keyframe <= ts (macro non générée)
// Accesseurs shim.c (AVFormatContext opaque côté bindgen).
extern "C" {
@@ -349,7 +350,8 @@ unsafe fn run_c0_inner(screen: &str, out: &str, gpu: &Gpu) -> Result<Stats> {
}
/// Décodeur qui rend une frame à la fois (pour composer 2 sources en lockstep).
-struct Decoder {
+/// `pub(crate)` : réutilisé par la preview/playback (voir `app.rs`).
+pub(crate) struct Decoder {
fmt: *mut AVFormatContext,
dctx: *mut AVCodecContext,
hwdev: *mut AVBufferRef,
@@ -360,7 +362,7 @@ struct Decoder {
}
impl Decoder {
- unsafe fn open(path: &str, gpu: &Gpu) -> Result<Decoder> {
+ pub(crate) unsafe fn open(path: &str, gpu: &Gpu) -> Result<Decoder> {
let mut fmt: *mut AVFormatContext = ptr::null_mut();
let cpath = CString::new(path)?;
averr(
@@ -400,8 +402,23 @@ impl Decoder {
})
}
+ /// Dernière frame décodée (valide jusqu'au prochain `next`) — pour recomposer
+ /// la frame courante après un changement de config, sans réavancer (preview).
+ pub(crate) fn cur_frame(&self) -> *mut AVFrame {
+ self.frame
+ }
+
+ /// Repositionne le flux à la première keyframe (t=0) et vide le codec — pour boucler
+ /// la playback sans réallouer les décodeurs. La fixture démarre sur un IDR (§11).
+ pub(crate) unsafe fn rewind(&mut self) -> Result<()> {
+ averr(av_seek_frame(self.fmt, self.vidx, 0, AVSEEK_FLAG_BACKWARD), "seek")?;
+ avcodec_flush_buffers(self.dctx);
+ self.sent_eof = false;
+ Ok(())
+ }
+
/// Rend la prochaine frame (valide jusqu'au prochain appel), ou null à EOF.
- unsafe fn next(&mut self) -> Result<*mut AVFrame> {
+ pub(crate) unsafe fn next(&mut self) -> Result<*mut AVFrame> {
loop {
let r = avcodec_receive_frame(self.dctx, self.frame);
if r == 0 {
@@ -471,6 +488,9 @@ unsafe fn make_enc_frames(gpu: &Gpu, w: i32, h: i32) -> Result<(*mut AVBufferRef
}
/// C1..C8 (§9) : composite 2 sources → encode, effets gatés par `cfg`. Mesuré au plus extérieur (§10).
+/// `progress(frames_encodées)` est appelé à chaque frame — no-op côté bench (mesure inchangée),
+/// alimente la barre de progression côté GUI. La mesure reste enveloppante (§10) : la sonde est
+/// un simple `SendMessage` throttlé (µs), négligeable devant ~8 ms/frame GPU.
pub fn run_composited(
screen: &str,
webcam: &str,
@@ -478,8 +498,9 @@ pub fn run_composited(
gpu: &Gpu,
comp: &Compositor,
cfg: &Cfg,
+ progress: &mut dyn FnMut(u64),
) -> Result<Stats> {
- unsafe { run_c1_inner(screen, webcam, out, gpu, comp, cfg) }
+ unsafe { run_c1_inner(screen, webcam, out, gpu, comp, cfg, progress) }
}
unsafe fn run_c1_inner(
@@ -489,6 +510,7 @@ unsafe fn run_c1_inner(
gpu: &Gpu,
comp: &Compositor,
cfg: &Cfg,
+ progress: &mut dyn FnMut(u64),
) -> Result<Stats> {
let mut sdec = Decoder::open(screen, gpu)?;
let mut wdec = Decoder::open(webcam, gpu)?;
@@ -548,6 +570,7 @@ unsafe fn run_c1_inner(
drain_encoder(ectx, octx, ostream, opkt)?;
av_frame_free(&mut (outf as *mut _));
frames += 1;
+ progress(frames);
}
avcodec_send_frame(ectx, ptr::null_mut());
@@ -593,3 +616,39 @@ unsafe fn drain_encoder(
av_packet_unref(opkt);
}
}
+
+/// Nombre de frames du flux vidéo (borne de la barre de progression export). `nb_frames`
+/// si présent (le cas de la fixture MP4), sinon estimé par durée × cadence, sinon fallback.
+pub fn probe_frame_count(path: &str) -> Result<u64> {
+ unsafe {
+ let mut fmt: *mut AVFormatContext = ptr::null_mut();
+ let cpath = CString::new(path)?;
+ averr(
+ avformat_open_input(&mut fmt, cpath.as_ptr(), ptr::null_mut(), ptr::null_mut()),
+ "open_input",
+ )?;
+ averr(avformat_find_stream_info(fmt, ptr::null_mut()), "find_stream_info")?;
+ let vidx = av_find_best_stream(fmt, AVMediaType::AVMEDIA_TYPE_VIDEO, -1, -1, ptr::null_mut(), 0);
+ let mut n: u64 = 0;
+ if vidx >= 0 {
+ let stream = sn_fmt_stream(fmt, vidx);
+ let nb = (*stream).nb_frames;
+ if nb > 0 {
+ n = nb as u64;
+ } else {
+ let afr = (*stream).avg_frame_rate;
+ let dur = (*stream).duration;
+ let tb = (*stream).time_base;
+ if afr.num != 0 && afr.den != 0 && dur > 0 && tb.den != 0 {
+ let secs = dur as f64 * tb.num as f64 / tb.den as f64;
+ n = (secs * afr.num as f64 / afr.den as f64).round() as u64;
+ }
+ }
+ }
+ avformat_close_input(&mut fmt);
+ if n == 0 {
+ n = crate::compositor::FIXTURE_FRAMES as u64;
+ }
+ Ok(n)
+ }
+}