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): let the CPU backend reach the export encoder
Etienne Lescot0ae372b286d7
diff --git a/crates/compositor/src/compositor.rs b/crates/compositor/src/compositor.rsindex 7c7754c86..e0004a41f 100644--- a/crates/compositor/src/compositor.rs+++ b/crates/compositor/src/compositor.rs@@ -493,6 +493,10 @@ pub struct Compositor {/// de prévisualisation demandée (variable, contrairement au `staging` fixe à/// OUT_W×OUT_H). Recréée quand la taille change — voir `readback_resized`.live_readback_staging: RefCell<Option<(u32, u32, ID3D11Texture2D)>>,+ /// Staging NV12 du readback d'ENCODAGE (backend CPU) — même motif de cache par taille+ /// que `live_readback_staging`, mais en NV12 et non en RGBA : l'encodeur logiciel veut+ /// les plans Y/UV, pas des pixels RGBA. Voir `read_nv12_scaled`.+ nv12_readback_staging: RefCell<Option<(u32, u32, ID3D11Texture2D)>>,}/// Ressources d'un resize export à une taille cible : RGBA intermédiaire (résultat du@@ -1143,6 +1147,7 @@ impl Compositor {render_size: Cell::new((out_w, out_h)),resize_target: RefCell::new(None),live_readback_staging: RefCell::new(None),+ nv12_readback_staging: RefCell::new(None),})}@@ -3045,15 +3050,32 @@ impl Compositor {// → aucun resize à faire, on convertit le RT directement. Comparé à la// taille de rendu COURANTE et non à une constante : une fois le RT aligné// sur `output`, c'est justement le cas nominal.+ // Produire le NV12 (partagé avec l'encodeur logiciel), puis le copier GPU→GPU+ // vers le pool de l'encodeur matériel — la seule partie qui lui soit propre.+ let src_tex = self.nv12_source(target_w, target_h)?;+ let src: ID3D11Resource = src_tex.cast()?;+ let dst_tex = ID3D11Texture2D::from_raw_borrowed(&out_tex).unwrap().clone();+ let dst: ID3D11Resource = dst_tex.cast()?;+ self.ctx.CopySubresourceRegion(&dst, slice, 0, 0, 0, &src, 0, None);+ Ok(())+ }++ /// Rastérise le NV12 de sortie à `target_w`×`target_h` et rend LA TEXTURE du+ /// compositeur qui le porte. C'est la moitié commune aux deux encodeurs : le matériel+ /// la copie GPU→GPU vers le pool AMF (`rgb_to_nv12_scaled` ci-dessus), le logiciel la+ /// relit vers la RAM (`read_nv12_scaled` ci-dessous). Extraite pour que les deux+ /// backends produisent le MÊME NV12 — sinon l'export CPU dériverait du matériel sur+ /// un détail de conversion, exactement ce que l'iso doit empêcher.+ unsafe fn nv12_source(&self, target_w: u32, target_h: u32) -> Result<ID3D11Texture2D> {let (rw_i, rh_i) = self.render_dims();if target_w == rw_i && target_h == rh_i {- return self.rgb_to_nv12(out_tex, slice);+ self.render_nv12();+ return Ok(self.nv12.clone());}+ // Même séquence que `rgb_to_nv12_scaled`, dont c'est la partie « produire ».self.blit_resized(target_w, target_h)?;let cache = self.resize_target.borrow();let t = cache.as_ref().unwrap();-- // rgba (cible) -> NV12 (cible) : mêmes passes Y/UV que `render_nv12`, paramétrées.self.ctx.OMSetRenderTargets(Some(&[Some(t.nv12_rtv_y.clone())]), None);self.ctx.PSSetShaderResources(0, Some(&[Some(t.rgba_srv.clone())]));let vp_y = D3D11_VIEWPORT {@@ -3073,12 +3095,73 @@ impl Compositor {self.ctx.PSSetShader(&self.ps_uv, None);self.ctx.Draw(3, 0);self.ctx.PSSetShaderResources(0, Some(&[None]));+ Ok(t.nv12.clone())+ }- // 3) copie GPU->GPU vers le pool encodeur (identique à rgb_to_nv12).- let src: ID3D11Resource = t.nv12.cast()?;- let dst_tex = ID3D11Texture2D::from_raw_borrowed(&out_tex).unwrap().clone();- let dst: ID3D11Resource = dst_tex.cast()?;- self.ctx.CopySubresourceRegion(&dst, slice, 0, 0, 0, &src, 0, None);+ /// Le NV12 de sortie LU vers la mémoire système, plan Y puis plan UV.+ ///+ /// Pendant de `rgb_to_nv12_scaled` pour un encodeur LOGICIEL : `libopenh264` ne sait+ /// pas prendre une texture D3D11, il veut des plans en RAM. C'est la seule copie+ /// GPU→CPU du chemin d'export CPU, et elle est inévitable — le backend CPU rastérise+ /// sur WARP (donc déjà en RAM côté pilote) mais D3D11 n'expose pas ces octets+ /// autrement que par une staging.+ ///+ /// `dst_y`/`dst_uv` doivent tenir `target_h * pitch_y` et `target_h/2 * pitch_uv`+ /// octets — typiquement les `data[0]`/`data[1]` d'une `AVFrame` NV12.+ pub unsafe fn read_nv12_scaled(+ &self,+ target_w: u32,+ target_h: u32,+ dst_y: *mut u8,+ pitch_y: usize,+ dst_uv: *mut u8,+ pitch_uv: usize,+ ) -> Result<()> {+ let src_tex = self.nv12_source(target_w, target_h)?;++ // Staging NV12 cachée par taille (même idiome que `live_readback_staging`) :+ // une allocation par changement de résolution, pas une par frame.+ let mut cache = self.nv12_readback_staging.borrow_mut();+ if cache.as_ref().map(|(w, h, _)| (*w, *h)) != Some((target_w, target_h)) {+ let sd = D3D11_TEXTURE2D_DESC {+ Width: target_w,+ Height: target_h,+ MipLevels: 1,+ ArraySize: 1,+ Format: DXGI_FORMAT_NV12,+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },+ Usage: D3D11_USAGE_STAGING,+ BindFlags: 0,+ CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,+ MiscFlags: 0,+ };+ let mut t: Option<ID3D11Texture2D> = None;+ self.dev.CreateTexture2D(&sd, None, Some(&mut t))?;+ *cache = Some((target_w, target_h, t.unwrap()));+ }+ let staging = &cache.as_ref().unwrap().2;++ let src: ID3D11Resource = src_tex.cast()?;+ let dst: ID3D11Resource = staging.cast()?;+ self.ctx.CopyResource(&dst, &src);++ let mut m = D3D11_MAPPED_SUBRESOURCE::default();+ self.ctx.Map(&dst, 0, D3D11_MAP_READ, 0, Some(&mut m))?;+ // Disposition NV12 mappée : Y sur `target_h` lignes de `RowPitch`, puis UV sur+ // `target_h/2` lignes au même pitch. Copie ligne par ligne — les deux pitchs+ // diffèrent (le driver pad, ffmpeg aligne sur son propre SIMD).+ let row = (target_w as usize).min(m.RowPitch as usize).min(pitch_y);+ for y in 0..target_h as usize {+ let s = (m.pData as *const u8).add(y * m.RowPitch as usize);+ std::ptr::copy_nonoverlapping(s, dst_y.add(y * pitch_y), row);+ }+ let uv_src = (m.pData as *const u8).add(m.RowPitch as usize * target_h as usize);+ let uv_row = (target_w as usize).min(m.RowPitch as usize).min(pitch_uv);+ for y in 0..(target_h as usize / 2) {+ let s = uv_src.add(y * m.RowPitch as usize);+ std::ptr::copy_nonoverlapping(s, dst_uv.add(y * pitch_uv), uv_row);+ }+ self.ctx.Unmap(&dst, 0);Ok(())}diff --git a/crates/compositor/src/pipeline.rs b/crates/compositor/src/pipeline.rsindex 0359cd2a0..af9f657e5 100644--- a/crates/compositor/src/pipeline.rs+++ b/crates/compositor/src/pipeline.rs@@ -1033,10 +1033,17 @@ impl VideoEncoder {let forced = std::env::var("OPENSCREEN_EXPORT_ENCODER").ok();let mut refused: Vec<String> = Vec::new();for &candidate in codec.candidates() {- let (name, _) = candidate;+ let (name, pix_fmt) = candidate;if forced.as_deref().is_some_and(|forced| forced != name) {continue;}+ // Sans pool D3D11 (backend CPU), les candidats zéro-copie n'ont rien à consommer :+ // les écarter ici plutôt que de leur passer un `hw_frames_ctx` nul, dont l'échec+ // remonterait comme un refus de driver et masquerait la vraie raison.+ if hw_frames.is_null() && pix_fmt == AVPixelFormat::AV_PIX_FMT_D3D11 {+ refused.push(format!("{name}: pas de pool D3D11 (backend CPU)"));+ continue;+ }let encoder = match Self::try_open(candidate, w, h, fps, bit_rate, hw_frames) {Ok(encoder) => encoder,Err(error) => {@@ -1146,6 +1153,38 @@ impl VideoEncoder {(*self.sw).pts = (*frame).pts;averr(avcodec_send_frame(self.ctx, self.sw), "send_frame")}++ /// Même chose depuis le backend CPU, où il n'y a PAS de frame D3D11 à descendre.+ ///+ /// `av_hwframe_transfer_data` suppose un pool `hw_frames_ctx`, et sur WARP il n'y en a+ /// pas : `av_hwdevice_ctx_init(D3D11VA)` échoue faute d'`ID3D11VideoDevice` — le même+ /// manque qui interdit le décodage matériel. Le compositeur lit donc son NV12+ /// directement en mémoire système, et le reste (conversion planaire, réutilisation des+ /// tampons, pts) suit exactement le chemin logiciel de `send`.+ unsafe fn send_composited(+ &mut self,+ comp: &Compositor,+ w: u32,+ h: u32,+ pts: i64,+ ) -> Result<()> {+ debug_assert!(!self.sw.is_null(), "backend CPU : aucun candidat D3D11 ne doit gagner");+ averr(av_frame_make_writable(self.sw), "frame_make_writable")?;+ let landing = if self.nv12.is_null() { self.sw } else { self.nv12 };+ comp.read_nv12_scaled(+ w,+ h,+ (*landing).data[0],+ (*landing).linesize[0] as usize,+ (*landing).data[1],+ (*landing).linesize[1] as usize,+ )?;+ if !self.nv12.is_null() {+ nv12_to_yuv420p(self.nv12, self.sw);+ }+ (*self.sw).pts = pts;+ averr(avcodec_send_frame(self.ctx, self.sw), "send_frame")+ }}/// Frame système allouée une fois, réutilisée à chaque envoi.@@ -1243,6 +1282,52 @@ pub(crate) unsafe fn walk_composited_timeline(let cursor_smoothing = scene.as_ref().map(|s| s.cursor.smoothing).unwrap_or(0.0);let mut cursor_tracks: HashMap<String, CursorTrack> = HashMap::new();let mut cursor_active_path: Option<String> = None;++ // ---- encodeur (choisi à l'exécution, cf. ExportCodec::candidates) + mux ----+ // Backend CPU : pas de pool D3D11 du tout. `av_hwdevice_ctx_init(D3D11VA)` échoue sur+ // WARP (pas d'`ID3D11VideoDevice`), donc on n'essaie même pas — `VideoEncoder::open`+ // écarte alors les candidats zéro-copie et le compositeur alimente l'encodeur en+ // mémoire système via `send_composited`.+ let software_frames = gpu.backend == Backend::Cpu;+ let (mut enc_hwdev, mut enc_frames) = if software_frames {+ (ptr::null_mut(), ptr::null_mut())+ } else {+ make_enc_frames(gpu, out_w as i32, out_h as i32)?+ };+ // débit proportionnel à la surface de sortie (référence : 8Mbps @ 1920x1080), plancher+ // 2Mbps pour rester regardable sur les petites tailles.+ let bit_rate = ((out_w as i64 * out_h as i64 * 8_000_000) / (1920 * 1080)).max(2_000_000);+ let mut enc = VideoEncoder::open(+ ¶ms.codec,+ out_w as i32,+ out_h as i32,+ out_fps,+ bit_rate,+ enc_frames,+ )?;+ let ectx = enc.ctx;++ let mut octx: *mut AVFormatContext = ptr::null_mut();+ let outc = CString::new(out)?;+ averr(+ avformat_alloc_output_context2(&mut octx, ptr::null(), ptr::null(), outc.as_ptr()),+ "alloc_output_context2",+ )?;+ let ostream = avformat_new_stream(octx, ptr::null());+ if ostream.is_null() {+ bail!("video avformat_new_stream");+ }+ averr(avcodec_parameters_from_context((*ostream).codecpar, ectx), "params_from_ctx")?;+ (*ostream).time_base = (*ectx).time_base;+ // Les deux streams doivent exister avant le header MP4 ; l'AAC reste ouvert pendant le+ // rendu puis reçoit le PCM assemblé à partir des comptes de frames réellement produits.+ let mut audio_encoder = AacEncoder::open(octx)?;+ let mut pb: *mut AVIOContext = ptr::null_mut();+ averr(avio_open(&mut pb, outc.as_ptr(), AVIO_FLAG_WRITE as i32), "avio_open")?;+ sn_fmt_set_pb(octx, pb);+ averr(avformat_write_header(octx, ptr::null_mut()), "write_header")?;++ let opkt = av_packet_alloc();let mut frames: u64 = 0;for (clip_index, clip) in clips.iter().enumerate() {@@ -1372,6 +1457,20 @@ pub(crate) unsafe fn walk_composited_timeline(}comp.compose_frame(sf, wf, frames as f32, cfg)?;+ if software_frames {+ enc.send_composited(comp, out_w, out_h, frames as i64)?;+ drain_encoder(ectx, octx, ostream, opkt)?;+ } else {+ let outf = av_frame_alloc();+ averr(av_hwframe_get_buffer(enc_frames, outf, 0), "hwframe_get_buffer")?;+ let out_tex = (*outf).data[0] as *mut c_void;+ let out_slice = (*outf).data[1] as u32;+ comp.rgb_to_nv12_scaled(out_w, out_h, out_tex, out_slice)?;+ (*outf).pts = frames as i64;+ enc.send(outf)?;+ drain_encoder(ectx, octx, ostream, opkt)?;+ av_frame_free(&mut (outf as *mut _));+ }on_frame(frames)?;frames += 1;}diff --git a/crates/poc-d3d/src/bench.rs b/crates/poc-d3d/src/bench.rsindex 2c5fc9c9a..3e4595098 100644--- a/crates/poc-d3d/src/bench.rs+++ b/crates/poc-d3d/src/bench.rs@@ -84,7 +84,14 @@ fn run_bench(args: &[String]) -> Result<()> {"hardware" | "gpu" => d3d::Backend::Hardware,other => anyhow::bail!("--backend {other} inconnu (hardware|cpu)"),};- let preview_only = args.iter().any(|a| a == "--preview") || backend == d3d::Backend::Cpu;+ // `--export` : le VRAI chemin d'export (`run_composited_multi` → `VideoEncoder` + mux),+ // sur le backend demandé. Seul moyen de mesurer l'encodage (le mode preview s'arrête au+ // readback) et surtout de VÉRIFIER que le backend CPU sort un fichier lisible : sur un+ // device WARP aucun encodeur matériel n'ouvre, donc `ExportCodec::candidates()` doit+ // descendre jusqu'à libopenh264 tout seul. C'est cette descente que le test exerce.+ let exporting = args.iter().any(|a| a == "--export");+ let preview_only =+ !exporting && (args.iter().any(|a| a == "--preview") || backend == d3d::Backend::Cpu);// Frames composées par run en mode preview. Assez pour noyer le bruit, assez court// pour qu'un backend lent reste mesurable en une poignée de minutes.let preview_frames: u64 = get("--frames", "300").parse().unwrap_or(300);@@ -122,6 +129,31 @@ fn run_bench(args: &[String]) -> Result<()> {println!("scène chargée depuis {scene_arg}");}+ if exporting {+ let params = pipeline::ExportParams::default();+ for cfg in &cfgs {+ // `ClipSource` n'est pas `Clone` et l'appel le prend par tranche : reconstruit+ // par cfg plutôt que d'ajouter un derive pour le seul harnais de mesure.+ let clip = pipeline::ClipSource {+ screen: screen.clone(),+ webcam: webcam.clone(),+ source_start_sec: 0.0,+ source_end_sec: 6.0, // la fixture entière (§ fixture.json : 6 s, 360 frames)+ webcam_offset_sec: 0.0,+ has_audio: false,+ };+ let path = format!("{out}/{}_{:?}.mp4", cfg.name, backend).to_lowercase();+ let s = pipeline::run_composited_multi(+ &[clip], &path, &gpu, &comp, cfg, ¶ms, &mut |_| {},+ )?;+ println!(+ "{:<4} {:>4}f {:>8.3}s {:>7.2} fps {:>7.2} ms/f → {}",+ cfg.name, s.frames, s.wall_s, s.fps, 1000.0 / s.fps, path+ );+ }+ return Ok(());+ }+let mut rows: Vec<(String, u64, f64, f64, f64, String)> = Vec::new(); // name, frames, best_wall, fps, ms/f, spreadlet mut json = String::from("{\n \"runs\": [\n");diff --git a/technical-documentation/architecture/native-compositor.md b/technical-documentation/architecture/native-compositor.mdindex 26763f9b1..02be63309 100644--- a/technical-documentation/architecture/native-compositor.md+++ b/technical-documentation/architecture/native-compositor.md@@ -268,11 +268,20 @@ licence. D3D11VA + AMF survive the LGPL-shared build (verified:`AVD3D11VADeviceContext`, a WARP device would have produced no frames at all.**Rendering and decoding are two axes**, and no software rasteriser on anyplatform 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.+ (`cpu_frames.rs`) beside the WARP device.++ Encoding is the third axis, and it is **half** covered by+ `ExportCodec::candidates()` / `VideoEncoder`: that machinery already probes the+ host and lands on `h264_mf` / `libopenh264` (`libkvazaar` for H.265) when no+ hardware encoder opens, so the CPU backend needs no encoder logic of its own.+ What it did need is a different **frame source**. `VideoEncoder::send` feeds+ software encoders with `av_hwframe_transfer_data`, which presupposes a D3D11+ pool — and on WARP there is none: `av_hwdevice_ctx_init(D3D11VA)` fails for the+ very reason decoding does, no `ID3D11VideoDevice`. So on `Backend::Cpu` the+ pool is never created, zero-copy candidates are dropped from the list with a+ stated reason, and `VideoEncoder::send_composited` reads the composed NV12+ straight out of the compositor (`Compositor::read_nv12_scaled`) into the same+ buffers the software path already used. Three axes, three answers.It is never silent. `Gpu::create` (hardware-strict, no fallback) is kept fortests and goldens; `create_auto` logs *why* the hardware device was refuseddiff --git a/technical-documentation/engineering/rendering-performance.md b/technical-documentation/engineering/rendering-performance.mdindex a361e2708..b1d4e0658 100644--- a/technical-documentation/engineering/rendering-performance.md+++ b/technical-documentation/engineering/rendering-performance.md@@ -136,6 +136,38 @@ pixel-golden test that spans backends needs a tolerance rather than an exact bas> machine. C6's negative delta is the same C5–C7 plateau noise the> [admissible hardware run](#one-admissible-run--2026-07-27) documents.+#### CPU export — the third axis++`ExportCodec::candidates()` already picks a working encoder per host, so the CPU backend+needs no encoder logic of its own. It needed a different **frame source**:+`VideoEncoder::send` downloads via `av_hwframe_transfer_data`, which presupposes a D3D11+pool, and WARP cannot create one (`av_hwdevice_ctx_init(D3D11VA)` fails for the same+missing `ID3D11VideoDevice` that blocks decoding). So on `Backend::Cpu` the pool is+skipped, zero-copy candidates are dropped with a stated reason, and `send_composited`+reads the composed NV12 out of the compositor directly.++`x.bat run --release -- --cfg C8 --backend cpu --export` on the fixture (360 frames):++| path | encoder chosen | fps | ms/f |+|---|---|---:|---:|+| hardware | `h264_amf` (D3D11, zero-copy) | **88.2** | 11.34 |+| CPU backend | `h264_mf` (system frames) | **4.8** | 207.87 |+| CPU, forced last resort | `libopenh264` | **4.6** | 218.91 |++All three produce valid 360-frame 1080p MP4s that decode clean under `ffmpeg -f null -`.++**`h264_mf` winning on the CPU backend is a local artefact, not the no-GPU answer.** Media+Foundation picks its own encoder MFT independently of our D3D device, so on this machine —+which *has* an AMD GPU, just not one this compositor is using — it can still reach hardware.+On a genuinely GPU-less host `h264_mf` would fall to its own software encoder or fail, and+`libopenh264` is the floor. The forced row is there precisely because the automatic one+cannot be trusted to represent that host: `OPENSCREEN_EXPORT_ENCODER=libopenh264` is the+only way to exercise the real last resort from a machine that has a GPU.++The encoder is not the bottleneck either way — the two CPU rows differ by 5 %, while the+gap to hardware is 18×. That gap is the blur and motion-blur shaders (see the table above),+not the codec.+## How we got here — the WebCodecs trail> **This section is history.** It records the measurements that killed the browser-based export pipeline and motivated the native one. The code it describes is **gone**: `src/lib/exporter/videoExporter.ts`, `src/bench/runBench.ts` and the `npm run bench:export` script were deleted with the web MP4 pipeline. It is kept because it is the evidence for [why the compositor, not the encoder, was the wall](#the-wall-is-the-compositor) — which is the entire reason `crates/compositor/` exists — and because the [measurement hazards](#measurement-hazards) it uncovered still apply to any new benchmark here.