Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M-HW: NVENC on top of the shared hardware-encoding setting (#183); never-crash fixes

Brandon Thomas853f03b1aabc
diff --cc ATTRIBUTION.md
index e3bf7cde5,e3bf7cde5..4b28b9539
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@@ -139,6 -139,6 +139,15 @@@ remove them (AGENTS.md §1.8)
| `docs/brand/artcraft-mark.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft trademark, not open source; `docs/brand/LICENSE-brand.txt` (not MIT/Apache) |
| `docs/brand/artcraft-mark.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft trademark, not open source; `docs/brand/LICENSE-brand.txt` (not MIT/Apache) |
++## Third-party source code
++
++Source files that are transcribed from third-party code rather than written from scratch. Each keeps
++the original copyright and permission notice in its header.
++
++| File | Author | Source | Licence |
++|---|---|---|---|
++| `crates/platform/src/nvenc/ffi.rs` | NVIDIA Corporation (`nvEncodeAPI.h`); FilmCraft contributors (Rust transcription) | Structures, function table and constants transcribed from `nvEncodeAPI.h`, NVIDIA Video Codec SDK, API 12.1 (https://developer.nvidia.com/video-codec-sdk) | MIT (Copyright (c) 2010-2023 NVIDIA Corporation; notice kept in the file header) |
++
## Downloaded at runtime
These files are never in the repository or the app bundle. FilmCraft downloads them into the
diff --cc README.md
index 847f37a63,37cdca72d..62742389b
--- a/README.md
+++ b/README.md
@@@ -286,7 -286,7 +286,7 @@@ We track two numbers ([ROADMAP.md](ROAD
The biggest gaps today:
- - **Speed on big footage.** Hardware decoding works on macOS and Windows; Linux has no hardware path yet. Blend modes and the most common effects run on the GPU, but Lumetri, keys and most of export still run on the CPU; H.264 export can use NVIDIA's encoder on Windows (opt-in, Export ▸ Hardware encoding) ([#30](https://github.com/storytold/filmcraft/issues/30)).
-- **Speed on big footage.** Hardware decoding works on macOS and Windows; Linux has no hardware path yet. Blend modes and the most common effects run on the GPU, but Lumetri, keys and export rendering still run on the CPU; H.264 encoding can use the hardware encoder on macOS (opt-in), and H.265 export is hardware-only there ([#30](https://github.com/storytold/filmcraft/issues/30)).
++- **Speed on big footage.** Hardware decoding works on macOS and Windows; Linux has no hardware path yet. Blend modes and the most common effects run on the GPU, but Lumetri, keys and export rendering still run on the CPU; H.264 encoding can use the hardware encoder on macOS and on Windows with an NVIDIA GPU (opt-in, Export ▸ Hardware encoding), and H.265 export is hardware-only there ([#30](https://github.com/storytold/filmcraft/issues/30)).
- **No plugins.** No VST3 / Audio Units or OpenFX hosting.
- **Delivery codecs.** H.264 is our only delivery-codec export; no HEVC or AV1 export yet.
- **Real-world media and platforms.** Our decoders are bit-exact on conformance streams, but camera and phone files in the wild are less tested. Windows and Linux get far less testing than macOS.
diff --cc ROADMAP.md
index 9d0f92937,f3deeccd7..29c0409fb
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -36,7 -36,7 +36,7 @@@ before choosing work
| **Correctness in depth** | not tracked | **~60–70%** | A first-time contributor found four real bugs in core paths within hours (#5–#8: AIFF import failed, Slide left linked audio behind, transitions didn't follow ripple trims, export ignored start/end times). User reports: Color Matte always grey with no picker (#29); ALSA audio error on Linux (#23). Settings are "most wired", not all. |
| **Codecs and media** | ~90% | **~75%** | Our decoders are bit-exact on conformance streams. Real camera and phone media (variable frame rate, damaged files, unusual containers) is far less tested. No camera RAW (RED, BRAW, ARRIRAW), no E-AC-3. |
| **Export** | ~92% | **~70%** | Delivery: H.264 only (ProRes, DNxHR and image sequences cover mastering). No HEVC or AV1 export. AAF and OMF have never been validated in Avid Media Composer or Pro Tools. Export renders and encodes on the CPU only. |
- | **Performance and hardware** | ~62% | **~35–40%** | Premiere runs effects, decoding and encoding on the GPU and the hardware media engines. Here, hardware decode works on macOS (VideoToolbox, #33; active in the desktop app only since #41, so releases up to 0.2.1 decoded in software) and Windows (Media Foundation / Direct3D 11 DXVA: H.264, HEVC Main / Main 10, #30). The GPU does compositing, blend modes (#32) and 31 common effects (GPU2): colour adjustments, crop/flip/transform, blurs, sharpen. Lumetri, keys, masks, the remaining effects and export are CPU, and H.264 encoding is hardware only on Windows with an NVIDIA GPU (NVENC, opt-in: Export ▸ Hardware encoding). Linux has no hardware path. 8K isn't real-time . The effect list shows Premiere's "GPU accelerated" badge, but only 31 effect ids run on the GPU here; the rest, Lumetri included, run on the CPU. |
-| **Performance and hardware** | ~62% | **~35–40%** | Premiere runs effects, decoding and encoding on the GPU and the hardware media engines. Here, hardware decode works on macOS (VideoToolbox, #33; active in the desktop app only since #41, so releases up to 0.2.1 decoded in software) and Windows (Media Foundation / Direct3D 11 DXVA, H.264, HEVC Main / Main 10, VP9 and AV1 4:2:0 8/10-bit, #30). The GPU does compositing, blend modes (#32) and 31 common effects (GPU2): colour adjustments, crop/flip/transform, blurs, sharpen. Lumetri, keys, masks, the remaining effects and export rendering are CPU; H.264 encoding can use VideoToolbox on macOS (opt-in per export, no B-frames), and H.265 (HEVC) export exists there only, through the same hardware encoder. Linux has no hardware path. 8K isn't real-time (AV1 is on Windows with a hardware decoder). The effect list shows Premiere's "GPU accelerated" badge, but only 31 effect ids run on the GPU here; the rest, Lumetri included, run on the CPU. |
++| **Performance and hardware** | ~62% | **~35–40%** | Premiere runs effects, decoding and encoding on the GPU and the hardware media engines. Here, hardware decode works on macOS (VideoToolbox, #33; active in the desktop app only since #41, so releases up to 0.2.1 decoded in software) and Windows (Media Foundation / Direct3D 11 DXVA, H.264, HEVC Main / Main 10, VP9 and AV1 4:2:0 8/10-bit, #30). The GPU does compositing, blend modes (#32) and 31 common effects (GPU2): colour adjustments, crop/flip/transform, blurs, sharpen. Lumetri, keys, masks, the remaining effects and export rendering are CPU; H.264 encoding can use VideoToolbox on macOS (opt-in per export, no B-frames) and NVENC on Windows with an NVIDIA GPU (opt-in per export), and H.265 (HEVC) export exists there only, through the same hardware encoder. Linux has no hardware path. 8K isn't real-time (AV1 is on Windows with a hardware decoder). The effect list shows Premiere's "GPU accelerated" badge, but only 31 effect ids run on the GPU here; the rest, Lumetri included, run on the CPU. |
| **Stability** | not tracked | **improving, unproven** | The never-crash pass (no panics in product code, last-resort guards) landed on 2026-10-04. There's no field record from real users' projects yet. |
| **Plugins and pro ecosystem** | not tracked | **~0–10%** | No audio plugin hosting (VST3 / Audio Units) and no third-party video effects (OpenFX). For many professional editors this alone rules FilmCraft out. Team Projects and Productions are out of scope by design. |
| **AI features** | partial | **~25–35%** | Speech to text exists but is off in default builds (the `whisper` feature). Enhance Speech is a DSP chain, not a model. Auto Reframe is approximate. No Generative Extend, and no media-intelligence search or auto colour. |
@@@ -48,10 -48,10 +48,10 @@@
In priority order. Agents should prefer this work over adding more checklist items.
1. **Hardware acceleration** (#30), the most visible gap to users:
- - hardware decode on Linux (VA-API); VP9 / AV1 on Windows;
+ - hardware decode on Linux (VA-API);
- zero-copy decoded frames into wgpu;
- the remaining effects on the GPU: Lumetri, keys, Vignette, Video Limiter, masks (31 common effects are done);
- - GPU export, then hardware encode (H.264 / HEVC; H.264 on NVENC is in, opt-in, Windows only).
- - GPU export, then hardware encode: H.264 and H.265 on macOS are in (H.264 opt-in; H.265 has no other encoder); other systems remain.
++ - GPU export, then hardware encode: H.264 and H.265 on macOS are in (H.264 opt-in; H.265 has no other encoder), H.264 on NVENC (Windows, opt-in); HEVC on Windows and Linux remain.
2. **A measured parity number.** Add `cargo xtask parity`, run in CI. It should cover menus,
commands, effects, transitions, panels, preferences and formats against the Premiere snapshot in
`plan/premiere/`. It should report presence and fidelity separately (exact, approximate, stub).
@@@ -154,7 -154,7 +154,7 @@@ Status: ✅ done · 🟡 in progress �
## Running now
- - **Hardware acceleration (#30):** landed: blend modes on the GPU (#32); VideoToolbox hardware decode + the `platform` FFI crate (#33); 31 common effects on the GPU (GPU2). Windows: Media Foundation / Direct3D 11 H.264 + HEVC decode (HW2), NVENC H.264 export (HW4, opt-in). Next: VA-API (Linux) decode, zero-copy upload, Lumetri on the GPU, hardware HEVC / AV1 encode.
-- **Hardware acceleration (#30):** landed: blend modes on the GPU (#32); VideoToolbox hardware decode + the `platform` FFI crate (#33); 31 common effects on the GPU (GPU2). Windows: Media Foundation / Direct3D 11 H.264 + HEVC decode (HW2) and VP9 + AV1 (HW3). Next: VA-API (Linux) decode, zero-copy upload, Lumetri on the GPU.
++- **Hardware acceleration (#30):** landed: blend modes on the GPU (#32); VideoToolbox hardware decode + the `platform` FFI crate (#33); 31 common effects on the GPU (GPU2). Windows: Media Foundation / Direct3D 11 H.264 + HEVC decode (HW2) and VP9 + AV1 (HW3), NVENC H.264 export (HW4, opt-in). Next: VA-API (Linux) decode, zero-copy upload, Lumetri on the GPU.
- **Next:** [Where we are lacking](#where-we-are-lacking) items 1–5. GPU export waits for the export-crate work (#19 and the never-crash follow-up) to land.
## Log
diff --cc crates/export/src/lib.rs
index ff0f85768,0c59e9ae4..bcec623e4
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@@ -248,7 -267,9 +267,9 @@@ pub struct ExportSettings
/// stream needs is raised.
pub h264_level: Option<u8>,
pub bitrate_mode: BitrateMode,
- /// May H.264 be encoded by the GPU (NVENC)? Off unless asked for.
- /// May H.264 be encoded by the system's hardware encoder (VideoToolbox on macOS)? Off unless
- /// asked for: hardware output depends on the machine, so it is not byte-reproducible like the
- /// built-in encoder's (`determinism_tests`).
++ /// May H.264 be encoded by the system's hardware encoder (VideoToolbox on macOS, NVENC on
++ /// Windows)? Off unless asked for: hardware output depends on the machine, so it is not
++ /// byte-reproducible like the built-in encoder's (`determinism_tests`).
#[serde(default)]
pub hardware_encoding: HardwareEncoding,
/// VBR maximum bitrate (None = 1.5 × target).
@@@ -557,43 -601,18 +601,53 @@@ fn audio_factories() -> &'static RwLock
F.get_or_init(|| RwLock::new(vec![aac_factory]))
}
+/// Hardware encoder counters (`perf.stats` `export.hardware`): pictures encoded by hardware
+/// encoders, encoders created, and requests a hardware encoder declined (the software encoder
+/// took them).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct HwEncodeStats {
+ pub frames: u64,
+ pub sessions: u64,
+ pub declined: u64,
+}
+
+static HW_FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+static HW_SESSIONS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+static HW_DECLINED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// The hardware encoder counters so far.
+pub fn hw_encode_stats() -> HwEncodeStats {
+ use std::sync::atomic::Ordering::Relaxed;
+ HwEncodeStats { frames: HW_FRAMES.load(Relaxed), sessions: HW_SESSIONS.load(Relaxed), declined: HW_DECLINED.load(Relaxed) }
+}
+
+/// A hardware encoder encoded a picture.
+pub fn note_hw_encode_frame() {
+ HW_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+}
+
+/// A hardware encoder was created.
+pub fn note_hw_encode_session() {
+ HW_SESSIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+}
+
+/// A hardware encoder declined a request (the software encoder takes it).
+pub fn note_hw_encode_declined() {
+ HW_DECLINED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+}
+
+ /// Register a video encoder factory (tried before the built-in ones and those registered earlier).
+ /// Registering the same factory twice is harmless.
pub fn register_encoder(f: EncoderFactory) {
- video_factories().write().unwrap_or_else(|e| e.into_inner()).insert(0, f);
+ let mut g = video_factories().write().unwrap_or_else(|e| e.into_inner());
+ if !g.iter().any(|x| std::ptr::fn_addr_eq(*x, f)) {
+ g.insert(0, f);
+ }
+ }
+
+ /// Whether `f` is among the registered video encoder factories (startup diagnostics, tests).
+ pub fn encoder_registered(f: EncoderFactory) -> bool {
+ video_factories().read().unwrap_or_else(|e| e.into_inner()).iter().any(|x| std::ptr::fn_addr_eq(*x, f))
}
pub fn register_audio_encoder(f: AudioEncoderFactory) {
audio_factories().write().unwrap_or_else(|e| e.into_inner()).insert(0, f);
diff --cc crates/export/src/settings.rs
index 06b7a904e,d0cd32cc5..34cf205a2
--- a/crates/export/src/settings.rs
+++ b/crates/export/src/settings.rs
@@@ -61,10 -61,9 +61,10 @@@ impl H264Profile
}
}
- /// Export ▸ Hardware encoding: whether H.264 may be encoded by the GPU's video engine (NVENC on
- /// NVIDIA GPUs, Windows) instead of FilmCraft's own encoder. Off by default: hardware encoders
- /// make different (usually larger for the same quality) streams, and exports are otherwise
- /// byte-identical from run to run and machine to machine.
+ /// Export ▸ Hardware encoding: whether H.264 may be encoded by the system's hardware video encoder
-/// (VideoToolbox on macOS) instead of FilmCraft's own encoder. Off by default: hardware encoders make
-/// different streams, and exports are otherwise byte-identical from run to run and machine to machine.
++/// (VideoToolbox on macOS, NVENC on NVIDIA GPUs on Windows) instead of FilmCraft's own encoder. Off
++/// by default: hardware encoders make different streams, and exports are otherwise byte-identical
++/// from run to run and machine to machine.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum HardwareEncoding {
diff --cc crates/platform/README.md
index 9f71125cc,990ae371c..eb361484c
--- a/crates/platform/README.md
+++ b/crates/platform/README.md
@@@ -92,9 -149,7 +158,10 @@@ level and flags are the encoder's own.
| `tests/videotoolbox.rs` (macOS) | H.264 High, HEVC Main (open GOP: CRA + RASL) and HEVC Main 10, 640×360 (coded 368: cropping) with B-frames: every picture **bit-exact** with our software decoder, same pts order, count, colour and aspect, also after `reset` + reseek to every later sync sample, mid-stream `flush`, and a full pass after resets; forced mid-stream failures (`VtDecoder::fail_after`) at five points continue with the software decoder's exact output; seeded mutation of samples and parameter sets (bit flips, truncation, corrupt length prefixes) never panics or hangs; HEVC 4:2:2 10-bit is bit-exact with ffmpeg's decode |
| `tests/fallback.rs` (every OS) | `HybridDecoder` with a stand-in hardware decoder failing after N samples (every sync sample ± a few, first / last sample, after a seek): output identical to the software decoder; in-band parameter sets identical to the sample entry's stay in hardware, different ones switch to software |
| `tests/setting.rs` | Hardware decoding Off gives the software decoder through `make_video_decoder` and the media stack (no hardware frames); Auto gives VideoToolbox where available |
+ | `tests/hardware_encode.rs` (macOS) | what the hardware path takes and declines; round trip through our software decoder (every picture, in order, luma PSNR above 30 dB, keyframes no further apart than asked, no composition offsets); an export through `filmcraft_export` that decodes in our decoder and in ffmpeg / ffprobe (profile, size, frame count, BT.709); the built-in encoder still exporting everything hardware declines; exact output size at sizes that are not multiples of 16; hostile configurations (zero, huge, odd sizes, frame rates, bitrates, keyframe intervals, wrong planes) give errors and never panic; encoders dropped at any point do not crash or hang. The same for **HEVC**: Main profile, 8-bit 4:2:0, `hvc1` entry with VPS / SPS / PPS and 4-byte lengths, MP4 and QuickTime, AAC audio, two-pass refused, the format list agreeing with the probe, ffprobe reading `codec_name=hevc`, `profile=Main`, `codec_tag_string=hvc1`, `pix_fmt=yuv420p`, BT.709 |
+| `tests/nvenc.rs` (Windows, NVIDIA) | H.264 from NVENC (1280×720, 6 Mbps, 72 frames) decodes with our decoder at worst 46.9 dB luma PSNR; IDR at 0, 24 and 48; dts / pts right |
+| `tests/nvenc_export.rs` (Windows, NVIDIA) | Export with hardware encoding against the software encoder through the export pipeline: the two decoded files at worst 54.8 dB luma PSNR; ffmpeg decodes the file without errors; declined cases go to the software encoder; the counters |
+| `src/nvenc/abi_tests.rs` (Windows) | FFI structs' sizes, alignments, field offsets, constants and GUIDs against a C compiler's view of NVIDIA's `nvEncodeAPI.h` (12.1) |
Fixtures are made with ffmpeg into `target/fixtures/platform/` (generator only, never linked);
tests skip without ffmpeg or without a hardware decoder.
@@@ -109,5 -176,5 +188,6 @@@ playback with no dropped frames at Full
## Not yet
Zero-copy upload of decoded pictures into wgpu textures (`CVPixelBuffer`s on macOS, Direct3D 11
- textures on Windows); HEVC and AV1 encoding, 10-bit and HDR hardware encoding, and encoders from
- other vendors (through Media Foundation); VA-API (Linux) decoders; field-coded H.264.
+ textures on Windows); B-frames and 10-bit / HDR HEVC (Main 10) in hardware encoding; VA-API (Linux)
-decoders; field-coded H.264; VP9 / AV1 4:4:4 and 12-bit on Windows.
++decoders; field-coded H.264; HEVC, 10-bit and HDR encoding with NVENC, and encoders from other
++vendors on Windows (through Media Foundation); VP9 / AV1 4:4:4 and 12-bit on Windows.
diff --cc crates/platform/src/nvenc/export.rs
index 43bf4d389,000000000..9d833147d
mode 100644,000000..100644
--- a/crates/platform/src/nvenc/export.rs
+++ b/crates/platform/src/nvenc/export.rs
@@@ -1,129 -1,0 +1,166 @@@
+//! NVENC as an Export encoder: [`factory`] is registered in front of the software H.264 encoder
+//! (`filmcraft_export::register_encoder`) and takes an export only when Export ▸ Hardware encoding
+//! is Auto and NVENC can do what the settings ask; otherwise it returns `None` and the software
+//! encoder runs, exactly as before.
+//!
+//! A hardware encoder that fails in the middle of an export (a lost device) ends the export with an
+//! error naming it; unlike a decoder it cannot be replayed into the software encoder, because the
+//! two write different streams.
+
+use filmcraft_export::{
+ BitrateMode, EncodedPacket, EncoderFrame, ExportError, ExportSettings, FieldOrder, Format, H264Pass, H264Profile, HardwareEncoding, Result, VideoEncoder,
+};
+use filmcraft_isobmff::{AvcConfig, SampleEntry};
+use filmcraft_time::FrameRate;
+
+use super::{Config, NvencH264, Profile};
+
+/// The NVENC export encoder.
+struct NvencEncoder {
+ enc: NvencH264,
+ w: u32,
+ h: u32,
+ rate: FrameRate,
+ y: Vec<u8>,
+ u: Vec<u8>,
+ v: Vec<u8>,
+}
+
+impl NvencEncoder {
+ fn packets(&self, ps: Vec<super::Packet>) -> Vec<EncodedPacket> {
+ let den = self.rate.den;
- ps.into_iter().map(|p| EncodedPacket { data: p.data, key: p.key, duration: den as u32, composition_offset: ((p.pts - p.dts) * den) as i32 }).collect()
++ let duration = u32::try_from(den).unwrap_or(u32::MAX);
++ ps.into_iter().map(|p| EncodedPacket { data: p.data, key: p.key, duration, composition_offset: composition_offset(p.pts, p.dts, den) }).collect()
+ }
+}
+
++/// `(pts - dts) × den` as an MP4 composition offset. It is a few frames (the B-frame delay); a
++/// hostile value saturates instead of wrapping.
++fn composition_offset(pts: i64, dts: i64, den: i64) -> i32 {
++ let offset = pts.saturating_sub(dts).saturating_mul(den);
++ i32::try_from(offset).unwrap_or(if offset < 0 { i32::MIN } else { i32::MAX })
++}
++
+impl VideoEncoder for NvencEncoder {
+ fn sample_entry(&self) -> SampleEntry {
+ let (sps, pps) = self.enc.parameter_sets();
- SampleEntry::avc(AvcConfig::new(vec![sps.to_vec()], vec![pps.to_vec()], 4), self.w as u16, self.h as u16)
++ // `config` declines sizes above u16::MAX
++ let (w, h) = (u16::try_from(self.w).unwrap_or(u16::MAX), u16::try_from(self.h).unwrap_or(u16::MAX));
++ SampleEntry::avc(AvcConfig::new(vec![sps.to_vec()], vec![pps.to_vec()], 4), w, h)
+ }
+
+ fn timescale(&self) -> u32 {
- self.rate.num as u32
++ u32::try_from(self.rate.num).unwrap_or(u32::MAX)
+ }
+
+ fn encode(&mut self, f: &EncoderFrame) -> Result<Vec<EncodedPacket>> {
+ if f.width != self.w || f.height != self.h {
+ return Err(ExportError::Encode(format!("NVENC: a {}x{} picture for a {}x{} encoder", f.width, f.height, self.w, self.h)));
+ }
+ filmcraft_export::rgba_to_yuv420_8(f.rgba, self.w as usize, self.h as usize, &mut self.y, &mut self.u, &mut self.v);
+ let ps = self
+ .enc
+ .encode(&self.y, &self.u, &self.v, f.index)
+ .map_err(|e| ExportError::Encode(format!("NVENC: {e} (turn Export ▸ Hardware encoding off to use the software encoder)")))?;
+ filmcraft_export::note_hw_encode_frame();
+ Ok(self.packets(ps))
+ }
+
+ fn flush(&mut self) -> Result<Vec<EncodedPacket>> {
+ let ps = self.enc.flush().map_err(|e| ExportError::Encode(format!("NVENC: {e}")))?;
+ Ok(self.packets(ps))
+ }
+
+ fn media_start(&self) -> Option<i64> {
+ // with B-frames the first DTS is `delay` frames before the first PTS
- (self.enc.delay() > 0).then_some(i64::from(self.enc.delay()) * self.rate.den)
++ (self.enc.delay() > 0).then_some(i64::from(self.enc.delay()).saturating_mul(self.rate.den))
+ }
+}
+
+/// Why NVENC does not take this export (the software encoder does), or the encoder's configuration.
+fn config(format: Format, w: u32, h: u32, rate: FrameRate, s: &ExportSettings) -> std::result::Result<Config, String> {
+ if format != Format::H264 || s.format.is_mxf() {
+ return Err("only MP4 / MOV H.264 exports".into());
+ }
+ if s.signal.is_hdr() {
+ return Err("HDR (8-bit H.264 here carries it with software signalling)".into());
+ }
+ if !matches!(s.h264_pass, H264Pass::Single) {
+ return Err("two-pass VBR".into());
+ }
+ if s.field_order != FieldOrder::Progressive {
+ return Err("interlaced output".into());
+ }
++ if w > u32::from(u16::MAX) || h > u32::from(u16::MAX) {
++ return Err(format!("{w}x{h} does not fit an MP4 sample entry"));
++ }
+ if rate.num <= 0 || rate.den <= 0 || rate.num > i64::from(u32::MAX) || rate.den > i64::from(u32::MAX) {
+ return Err("frame rate".into());
+ }
- let fps = (rate.num as u32, rate.den as u32);
++ let (Ok(num), Ok(den)) = (u32::try_from(rate.num), u32::try_from(rate.den)) else {
++ return Err("frame rate".into());
++ };
++ let fps = (num, den);
+ let kbps = s.bitrate_kbps.max(100);
+ Ok(Config {
+ width: w,
+ height: h,
+ fps,
+ bitrate_kbps: kbps,
+ max_bitrate_kbps: s.max_bitrate_kbps.filter(|m| *m >= kbps).unwrap_or(kbps / 2 * 3),
+ cbr: s.bitrate_mode == BitrateMode::Cbr,
+ keyint: s.keyframe_distance.filter(|k| *k > 0).unwrap_or_else(|| (f64::from(fps.0) / f64::from(fps.1) * 2.0).round().max(1.0) as u32),
+ profile: match s.h264_profile {
+ H264Profile::Baseline => Profile::Baseline,
+ H264Profile::Main => Profile::Main,
+ H264Profile::High => Profile::High,
+ },
+ level: s.h264_level,
+ sar: s.pixel_aspect,
+ bframes: true,
+ })
+}
+
+/// The Export encoder factory (see the module documentation).
+pub fn factory(format: Format, w: u32, h: u32, rate: FrameRate, s: &ExportSettings) -> Option<Result<Box<dyn VideoEncoder>>> {
+ if s.hardware_encoding != HardwareEncoding::Auto || format != Format::H264 {
+ return None;
+ }
+ let declined = |why: &str| {
+ log::info!("hardware encoding declined: {why}");
+ filmcraft_export::note_hw_encode_declined();
+ None
+ };
+ let cfg = match config(format, w, h, rate, s) {
+ Ok(c) => c,
+ Err(why) => return declined(&why),
+ };
+ match NvencH264::new(&cfg) {
+ Ok(enc) => {
+ filmcraft_export::note_hw_encode_session();
+ Some(Ok(Box::new(NvencEncoder { enc, w, h, rate, y: Vec::new(), u: Vec::new(), v: Vec::new() })))
+ }
+ Err(why) => declined(&why),
+ }
+}
++
++#[cfg(test)]
++mod tests {
++ use super::*;
++
++ #[test]
++ fn composition_offsets_saturate() {
++ assert_eq!(composition_offset(3, 1, 1001), 2002);
++ assert_eq!(composition_offset(0, -2, 1001), 2002);
++ assert_eq!(composition_offset(i64::MAX, i64::MIN, 1001), i32::MAX);
++ assert_eq!(composition_offset(i64::MIN, i64::MAX, 1001), i32::MIN);
++ assert_eq!(composition_offset(1 << 40, 0, 1), i32::MAX);
++ }
++
++ #[test]
++ fn oversized_pictures_are_declined() {
++ let s = ExportSettings { format: Format::H264, hardware_encoding: HardwareEncoding::Auto, ..Default::default() };
++ assert!(config(Format::H264, 70_000, 64, FrameRate::FPS_24, &s).is_err());
++ assert!(config(Format::H264, 64, 70_000, FrameRate::FPS_24, &s).is_err());
++ }
++}
diff --cc crates/platform/src/nvenc/ffi.rs
index 41cd16701,000000000..cae6fa0e8
mode 100644,000000..100644
--- a/crates/platform/src/nvenc/ffi.rs
+++ b/crates/platform/src/nvenc/ffi.rs
@@@ -1,473 -1,0 +1,499 @@@
++// The declarations in this file are transcribed from NVIDIA's `nvEncodeAPI.h` (Video Codec SDK,
++// API 12.1), which carries this notice:
++//
++// Copyright (c) 2010-2023 NVIDIA Corporation
++//
++// Permission is hereby granted, free of charge, to any person
++// obtaining a copy of this software and associated documentation
++// files (the "Software"), to deal in the Software without
++// restriction, including without limitation the rights to use,
++// copy, modify, merge, publish, distribute, sublicense, and/or sell
++// copies of the software, and to permit persons to whom the
++// software is furnished to do so, subject to the following
++// conditions:
++//
++// The above copyright notice and this permission notice shall be
++// included in all copies or substantial portions of the Software.
++//
++// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
++// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
++// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
++// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
++// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
++// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
++// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
++// OTHER DEALINGS IN THE SOFTWARE.
++
+//! The NVIDIA Video Codec SDK's encode API (`nvEncodeAPI.h`, API 12.1, MIT-licensed header by
+//! NVIDIA) as the driver's `nvEncodeAPI64.dll` expects it: the structures this backend fills in,
+//! the function table, and the constants it uses. Written from the public header; sizes and field
+//! offsets are checked against a C compiler's by the generated `abi_tests.rs`.
+//!
+//! API 12.1 is targeted on purpose: it is understood by every driver since 531.x, and the encoder
+//! features used here (H.264, presets, rate control) are the same in later versions.
+//!
+//! FFI module (docs/adr/0001-platform-ffi.md): plain `repr(C)` data, no logic.
+
+#![allow(non_snake_case, non_camel_case_types, dead_code)]
+
+use std::ffi::{c_char, c_int, c_void};
+
+use windows::core::GUID;
+
+pub const NVENCAPI_VERSION: u32 = 12 | (1 << 24);
+
+/// `NVENCAPI_STRUCT_VERSION(ver)`.
+pub const fn struct_version(ver: u32) -> u32 {
+ NVENCAPI_VERSION | (ver << 16) | (0x7 << 28)
+}
+
+pub const NV_ENCODE_API_FUNCTION_LIST_VER: u32 = struct_version(2);
+pub const NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER: u32 = struct_version(1);
+pub const NV_ENC_CAPS_PARAM_VER: u32 = struct_version(1);
+pub const NV_ENC_CONFIG_VER: u32 = struct_version(8) | (1 << 31);
+pub const NV_ENC_INITIALIZE_PARAMS_VER: u32 = struct_version(6) | (1 << 31);
+pub const NV_ENC_PRESET_CONFIG_VER: u32 = struct_version(4) | (1 << 31);
+pub const NV_ENC_RC_PARAMS_VER: u32 = struct_version(1);
+pub const NV_ENC_CREATE_INPUT_BUFFER_VER: u32 = struct_version(1);
+pub const NV_ENC_CREATE_BITSTREAM_BUFFER_VER: u32 = struct_version(1);
+pub const NV_ENC_PIC_PARAMS_VER: u32 = struct_version(6) | (1 << 31);
+pub const NV_ENC_LOCK_BITSTREAM_VER: u32 = struct_version(1) | (1 << 31);
+pub const NV_ENC_LOCK_INPUT_BUFFER_VER: u32 = struct_version(1);
+pub const NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER: u32 = struct_version(1);
+
+pub type NvStatus = c_int;
+pub const NV_ENC_SUCCESS: NvStatus = 0;
+pub const NV_ENC_ERR_NEED_MORE_INPUT: NvStatus = 17;
+pub const NV_ENC_ERR_INVALID_VERSION: NvStatus = 15;
+pub const NV_ENC_ERR_UNSUPPORTED_DEVICE: NvStatus = 2;
+pub const NV_ENC_ERR_ENCODER_BUSY: NvStatus = 18;
+pub const NV_ENC_ERR_LOCK_BUSY: NvStatus = 13;
+
+pub const NV_ENC_DEVICE_TYPE_DIRECTX: u32 = 0;
+pub const NV_ENC_MEMORY_HEAP_SYSMEM_CACHED: u32 = 2;
+pub const NV_ENC_BUFFER_FORMAT_NV12: u32 = 0x1;
+pub const NV_ENC_PARAMS_RC_VBR: u32 = 1;
+pub const NV_ENC_PARAMS_RC_CBR: u32 = 2;
+pub const NV_ENC_TUNING_INFO_HIGH_QUALITY: u32 = 1;
+pub const NV_ENC_PIC_STRUCT_FRAME: u32 = 1;
+pub const NV_ENC_PIC_TYPE_P: u32 = 0;
+pub const NV_ENC_PIC_TYPE_B: u32 = 1;
+pub const NV_ENC_PIC_TYPE_I: u32 = 2;
+pub const NV_ENC_PIC_TYPE_IDR: u32 = 3;
+pub const NV_ENC_PIC_FLAG_EOS: u32 = 0x8;
+pub const NV_ENC_LEVEL_AUTOSELECT: u32 = 0;
+pub const NV_ENC_H264_ENTROPY_CODING_MODE_CABAC: u32 = 1;
+pub const NV_ENC_VUI_VIDEO_FORMAT_UNSPECIFIED: u32 = 5;
+pub const NV_ENC_VUI_COLOR_PRIMARIES_BT709: u32 = 1;
+pub const NV_ENC_VUI_TRANSFER_CHARACTERISTIC_BT709: u32 = 1;
+pub const NV_ENC_VUI_MATRIX_COEFFS_BT709: u32 = 1;
+
+/// `NV_ENC_CAPS` values (the enum counts from zero in the header's order).
+pub const NV_ENC_CAPS_NUM_MAX_BFRAMES: u32 = 0;
+pub const NV_ENC_CAPS_SUPPORTED_RATECONTROL_MODES: u32 = 1;
+pub const NV_ENC_CAPS_WIDTH_MAX: u32 = 16;
+pub const NV_ENC_CAPS_HEIGHT_MAX: u32 = 17;
+pub const NV_ENC_CAPS_WIDTH_MIN: u32 = 45;
+pub const NV_ENC_CAPS_HEIGHT_MIN: u32 = 46;
+
+pub const NV_ENC_CODEC_H264_GUID: GUID = GUID::from_values(0x6bc82762, 0x4e63, 0x4ca4, [0xaa, 0x85, 0x1e, 0x50, 0xf3, 0x21, 0xf6, 0xbf]);
+pub const NV_ENC_H264_PROFILE_BASELINE_GUID: GUID = GUID::from_values(0x0727bcaa, 0x78c4, 0x4c83, [0x8c, 0x2f, 0xef, 0x3d, 0xff, 0x26, 0x7c, 0x6a]);
+pub const NV_ENC_H264_PROFILE_MAIN_GUID: GUID = GUID::from_values(0x60b5c1d4, 0x67fe, 0x4790, [0x94, 0xd5, 0xc4, 0x72, 0x6d, 0x7b, 0x6e, 0x6d]);
+pub const NV_ENC_H264_PROFILE_HIGH_GUID: GUID = GUID::from_values(0xe7cbc309, 0x4f7a, 0x4b89, [0xaf, 0x2a, 0xd5, 0x37, 0xc9, 0x2b, 0xe3, 0x10]);
+pub const NV_ENC_PRESET_P4_GUID: GUID = GUID::from_values(0x90a7b826, 0xdf06, 0x4862, [0xb9, 0xd2, 0xcd, 0x6d, 0x73, 0xa0, 0x86, 0x81]);
+pub const NV_ENC_PRESET_P5_GUID: GUID = GUID::from_values(0x21c6e6b4, 0x297a, 0x4cba, [0x99, 0x8f, 0xb6, 0xcb, 0xde, 0x72, 0xad, 0xe3]);
+
+pub type Handle = *mut c_void;
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS {
+ pub version: u32,
+ pub deviceType: u32,
+ pub device: *mut c_void,
+ pub reserved: *mut c_void,
+ pub apiVersion: u32,
+ pub reserved1: [u32; 253],
+ pub reserved2: [*mut c_void; 64],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_CAPS_PARAM {
+ pub version: u32,
+ pub capsToQuery: u32,
+ pub reserved: [u32; 62],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_QP {
+ pub qpInterP: u32,
+ pub qpInterB: u32,
+ pub qpIntra: u32,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_RC_PARAMS {
+ pub version: u32,
+ pub rateControlMode: u32,
+ pub constQP: NV_ENC_QP,
+ pub averageBitRate: u32,
+ pub maxBitRate: u32,
+ pub vbvBufferSize: u32,
+ pub vbvInitialDelay: u32,
+ /// enableMinQP:1, enableMaxQP:1, enableInitialRCQP:1, enableAQ:1, reservedBitField1:1,
+ /// enableLookahead:1, disableIadapt:1, disableBadapt:1, enableTemporalAQ:1, zeroReorderDelay:1,
+ /// enableNonRefP:1, strictGOPTarget:1, aqStrength:4, enableExtLookahead:1, reserved:15.
+ pub flags: u32,
+ pub minQP: NV_ENC_QP,
+ pub maxQP: NV_ENC_QP,
+ pub initialRCQP: NV_ENC_QP,
+ pub temporallayerIdxMask: u32,
+ pub temporalLayerQP: [u8; 8],
+ pub targetQuality: u8,
+ pub targetQualityLSB: u8,
+ pub lookaheadDepth: u16,
+ pub lowDelayKeyFrameScale: u8,
+ pub yDcQPIndexOffset: i8,
+ pub uDcQPIndexOffset: i8,
+ pub vDcQPIndexOffset: i8,
+ pub qpMapMode: u32,
+ pub multiPass: u32,
+ pub alphaLayerBitrateRatio: u32,
+ pub cbQPIndexOffset: i8,
+ pub crQPIndexOffset: i8,
+ pub reserved2: u16,
+ pub reserved: [u32; 4],
+}
+
+pub const RC_ENABLE_AQ: u32 = 1 << 3;
+pub const RC_ENABLE_LOOKAHEAD: u32 = 1 << 5;
+pub const RC_ZERO_REORDER_DELAY: u32 = 1 << 9;
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_CONFIG_H264_VUI_PARAMETERS {
+ pub overscanInfoPresentFlag: u32,
+ pub overscanInfo: u32,
+ pub videoSignalTypePresentFlag: u32,
+ pub videoFormat: u32,
+ pub videoFullRangeFlag: u32,
+ pub colourDescriptionPresentFlag: u32,
+ pub colourPrimaries: u32,
+ pub transferCharacteristics: u32,
+ pub colourMatrix: u32,
+ pub chromaSampleLocationFlag: u32,
+ pub chromaSampleLocationTop: u32,
+ pub chromaSampleLocationBot: u32,
+ pub bitstreamRestrictionFlag: u32,
+ pub timingInfoPresentFlag: u32,
+ pub numUnitInTicks: u32,
+ pub timeScale: u32,
+ pub reserved: [u32; 12],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_CONFIG_H264 {
+ /// enableTemporalSVC:1, enableStereoMVC:1, hierarchicalPFrames:1, hierarchicalBFrames:1,
+ /// outputBufferingPeriodSEI:1, outputPictureTimingSEI:1, outputAUD:1, disableSPSPPS:1,
+ /// outputFramePackingSEI:1, outputRecoveryPointSEI:1, enableIntraRefresh:1,
+ /// enableConstrainedEncoding:1, repeatSPSPPS:1, enableVFR:1, enableLTR:1, ...
+ pub flags: u32,
+ pub level: u32,
+ pub idrPeriod: u32,
+ pub separateColourPlaneFlag: u32,
+ pub disableDeblockingFilterIDC: u32,
+ pub numTemporalLayers: u32,
+ pub spsId: u32,
+ pub ppsId: u32,
+ pub adaptiveTransformMode: u32,
+ pub fmoMode: u32,
+ pub bdirectMode: u32,
+ pub entropyCodingMode: u32,
+ pub stereoMode: u32,
+ pub intraRefreshPeriod: u32,
+ pub intraRefreshCnt: u32,
+ pub maxNumRefFrames: u32,
+ pub sliceMode: u32,
+ pub sliceModeData: u32,
+ pub h264VUIParameters: NV_ENC_CONFIG_H264_VUI_PARAMETERS,
+ pub ltrNumFrames: u32,
+ pub ltrTrustMode: u32,
+ pub chromaFormatIDC: u32,
+ pub maxTemporalLayers: u32,
+ pub useBFramesAsRef: u32,
+ pub numRefL0: u32,
+ pub numRefL1: u32,
+ pub reserved1: [u32; 267],
+ pub reserved2: [*mut c_void; 64],
+}
+
+pub const H264_OUTPUT_AUD: u32 = 1 << 6;
+pub const H264_REPEAT_SPSPPS: u32 = 1 << 12;
+pub const H264_OUTPUT_RECOVERY_POINT_SEI: u32 = 1 << 9;
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub union NV_ENC_CODEC_CONFIG {
+ pub h264Config: NV_ENC_CONFIG_H264,
+ pub reserved: [u32; 320],
+ align: [*mut c_void; 0],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_CONFIG {
+ pub version: u32,
+ pub profileGUID: GUID,
+ pub gopLength: u32,
+ pub frameIntervalP: i32,
+ pub monoChromeEncoding: u32,
+ pub frameFieldMode: u32,
+ pub mvPrecision: u32,
+ pub rcParams: NV_ENC_RC_PARAMS,
+ pub encodeCodecConfig: NV_ENC_CODEC_CONFIG,
+ pub reserved: [u32; 278],
+ pub reserved2: [*mut c_void; 64],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_PRESET_CONFIG {
+ pub version: u32,
+ pub presetCfg: NV_ENC_CONFIG,
+ pub reserved1: [u32; 255],
+ pub reserved2: [*mut c_void; 64],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE {
+ pub bits: u32,
+ pub reserved1: [u32; 3],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_INITIALIZE_PARAMS {
+ pub version: u32,
+ pub encodeGUID: GUID,
+ pub presetGUID: GUID,
+ pub encodeWidth: u32,
+ pub encodeHeight: u32,
+ pub darWidth: u32,
+ pub darHeight: u32,
+ pub frameRateNum: u32,
+ pub frameRateDen: u32,
+ pub enableEncodeAsync: u32,
+ pub enablePTD: u32,
+ /// reportSliceOffsets:1, enableSubFrameWrite:1, enableExternalMEHints:1, enableMEOnlyMode:1,
+ /// enableWeightedPrediction:1, splitEncodeMode:4, enableOutputInVidmem:1,
+ /// enableReconFrameOutput:1, enableOutputStats:1, reserved:20.
+ pub flags: u32,
+ pub privDataSize: u32,
+ pub privData: *mut c_void,
+ pub encodeConfig: *mut NV_ENC_CONFIG,
+ pub maxEncodeWidth: u32,
+ pub maxEncodeHeight: u32,
+ pub maxMEHintCountsPerBlock: [NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE; 2],
+ pub tuningInfo: u32,
+ pub bufferFormat: u32,
+ pub numStateBuffers: u32,
+ pub outputStatsLevel: u32,
+ pub reserved: [u32; 285],
+ pub reserved2: [*mut c_void; 64],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_CREATE_INPUT_BUFFER {
+ pub version: u32,
+ pub width: u32,
+ pub height: u32,
+ pub memoryHeap: u32,
+ pub bufferFmt: u32,
+ pub reserved: u32,
+ pub inputBuffer: *mut c_void,
+ pub pSysMemBuffer: *mut c_void,
+ pub reserved1: [u32; 57],
+ pub reserved2: [*mut c_void; 63],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_CREATE_BITSTREAM_BUFFER {
+ pub version: u32,
+ pub size: u32,
+ pub memoryHeap: u32,
+ pub reserved: u32,
+ pub bitstreamBuffer: *mut c_void,
+ pub bitstreamBufferPtr: *mut c_void,
+ pub reserved1: [u32; 58],
+ pub reserved2: [*mut c_void; 64],
+}
+
+/// `NV_ENC_CODEC_PIC_PARAMS`: a union of codec structures, all zero here (defaults).
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_CODEC_PIC_PARAMS {
+ pub reserved: [u32; 388],
+ align: [*mut c_void; 0],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_PIC_PARAMS {
+ pub version: u32,
+ pub inputWidth: u32,
+ pub inputHeight: u32,
+ pub inputPitch: u32,
+ pub encodePicFlags: u32,
+ pub frameIdx: u32,
+ pub inputTimeStamp: u64,
+ pub inputDuration: u64,
+ pub inputBuffer: *mut c_void,
+ pub outputBitstream: *mut c_void,
+ pub completionEvent: *mut c_void,
+ pub bufferFmt: u32,
+ pub pictureStruct: u32,
+ pub pictureType: u32,
+ pub codecPicParams: NV_ENC_CODEC_PIC_PARAMS,
+ pub meHintCountsPerBlock: [NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE; 2],
+ pub meExternalHints: *mut c_void,
+ pub reserved1: [u32; 6],
+ pub reserved2: [*mut c_void; 2],
+ pub qpDeltaMap: *mut i8,
+ pub qpDeltaMapSize: u32,
+ pub reservedBitFields: u32,
+ pub meHintRefPicDist: [u16; 2],
+ pub alphaBuffer: *mut c_void,
+ pub meExternalSbHints: *mut c_void,
+ pub meSbHintsCount: u32,
+ pub stateBufferIdx: u32,
+ pub outputReconBuffer: *mut c_void,
+ pub reserved3: [u32; 284],
+ pub reserved4: [*mut c_void; 57],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_LOCK_BITSTREAM {
+ pub version: u32,
+ /// doNotWait:1, ltrFrame:1, getRCStats:1, reserved:29.
+ pub flags: u32,
+ pub outputBitstream: *mut c_void,
+ pub sliceOffsets: *mut u32,
+ pub frameIdx: u32,
+ pub hwEncodeStatus: u32,
+ pub numSlices: u32,
+ pub bitstreamSizeInBytes: u32,
+ pub outputTimeStamp: u64,
+ pub outputDuration: u64,
+ pub bitstreamBufferPtr: *mut c_void,
+ pub pictureType: u32,
+ pub pictureStruct: u32,
+ pub frameAvgQP: u32,
+ pub frameSatd: u32,
+ pub ltrFrameIdx: u32,
+ pub ltrFrameBitmap: u32,
+ pub temporalId: u32,
+ pub intraMBCount: u32,
+ pub interMBCount: u32,
+ pub averageMVX: i32,
+ pub averageMVY: i32,
+ pub alphaLayerSizeInBytes: u32,
+ pub outputStatsPtrSize: u32,
+ pub outputStatsPtr: *mut c_void,
+ pub frameIdxDisplay: u32,
+ pub reserved1: [u32; 220],
+ pub reserved2: [*mut c_void; 63],
+ pub reservedInternal: [u32; 8],
+}
+
+pub const LOCK_DO_NOT_WAIT: u32 = 1;
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_LOCK_INPUT_BUFFER {
+ pub version: u32,
+ /// doNotWait:1, reserved:31.
+ pub flags: u32,
+ pub inputBuffer: *mut c_void,
+ pub bufferDataPtr: *mut c_void,
+ pub pitch: u32,
+ pub reserved1: [u32; 251],
+ pub reserved2: [*mut c_void; 64],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct NV_ENC_SEQUENCE_PARAM_PAYLOAD {
+ pub version: u32,
+ pub inBufferSize: u32,
+ pub spsId: u32,
+ pub ppsId: u32,
+ pub spsppsBuffer: *mut c_void,
+ pub outSPSPPSPayloadSize: *mut u32,
+ pub reserved: [u32; 250],
+ pub reserved2: [*mut c_void; 64],
+}
+
+type Unused = *const c_void;
+
+/// The driver's function table (`NV_ENCODE_API_FUNCTION_LIST`); the entries this backend does not
+/// call are plain pointers.
+#[repr(C)]
+pub struct NV_ENCODE_API_FUNCTION_LIST {
+ pub version: u32,
+ pub reserved: u32,
+ pub nvEncOpenEncodeSession: Unused,
+ pub nvEncGetEncodeGUIDCount: Unused,
+ pub nvEncGetEncodeProfileGUIDCount: Unused,
+ pub nvEncGetEncodeProfileGUIDs: Unused,
+ pub nvEncGetEncodeGUIDs: Unused,
+ pub nvEncGetInputFormatCount: Unused,
+ pub nvEncGetInputFormats: Unused,
+ pub nvEncGetEncodeCaps: Option<unsafe extern "system" fn(Handle, GUID, *mut NV_ENC_CAPS_PARAM, *mut c_int) -> NvStatus>,
+ pub nvEncGetEncodePresetCount: Unused,
+ pub nvEncGetEncodePresetGUIDs: Unused,
+ pub nvEncGetEncodePresetConfig: Unused,
+ pub nvEncInitializeEncoder: Option<unsafe extern "system" fn(Handle, *mut NV_ENC_INITIALIZE_PARAMS) -> NvStatus>,
+ pub nvEncCreateInputBuffer: Option<unsafe extern "system" fn(Handle, *mut NV_ENC_CREATE_INPUT_BUFFER) -> NvStatus>,
+ pub nvEncDestroyInputBuffer: Option<unsafe extern "system" fn(Handle, *mut c_void) -> NvStatus>,
+ pub nvEncCreateBitstreamBuffer: Option<unsafe extern "system" fn(Handle, *mut NV_ENC_CREATE_BITSTREAM_BUFFER) -> NvStatus>,
+ pub nvEncDestroyBitstreamBuffer: Option<unsafe extern "system" fn(Handle, *mut c_void) -> NvStatus>,
+ pub nvEncEncodePicture: Option<unsafe extern "system" fn(Handle, *mut NV_ENC_PIC_PARAMS) -> NvStatus>,
+ pub nvEncLockBitstream: Option<unsafe extern "system" fn(Handle, *mut NV_ENC_LOCK_BITSTREAM) -> NvStatus>,
+ pub nvEncUnlockBitstream: Option<unsafe extern "system" fn(Handle, *mut c_void) -> NvStatus>,
+ pub nvEncLockInputBuffer: Option<unsafe extern "system" fn(Handle, *mut NV_ENC_LOCK_INPUT_BUFFER) -> NvStatus>,
+ pub nvEncUnlockInputBuffer: Option<unsafe extern "system" fn(Handle, *mut c_void) -> NvStatus>,
+ pub nvEncGetEncodeStats: Unused,
+ pub nvEncGetSequenceParams: Option<unsafe extern "system" fn(Handle, *mut NV_ENC_SEQUENCE_PARAM_PAYLOAD) -> NvStatus>,
+ pub nvEncRegisterAsyncEvent: Unused,
+ pub nvEncUnregisterAsyncEvent: Unused,
+ pub nvEncMapInputResource: Unused,
+ pub nvEncUnmapInputResource: Unused,
+ pub nvEncDestroyEncoder: Option<unsafe extern "system" fn(Handle) -> NvStatus>,
+ pub nvEncInvalidateRefFrames: Unused,
+ pub nvEncOpenEncodeSessionEx: Option<unsafe extern "system" fn(*mut NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS, *mut Handle) -> NvStatus>,
+ pub nvEncRegisterResource: Unused,
+ pub nvEncUnregisterResource: Unused,
+ pub nvEncReconfigureEncoder: Unused,
+ pub reserved1: Unused,
+ pub nvEncCreateMVBuffer: Unused,
+ pub nvEncDestroyMVBuffer: Unused,
+ pub nvEncRunMotionEstimationOnly: Unused,
+ pub nvEncGetLastErrorString: Option<unsafe extern "system" fn(Handle) -> *const c_char>,
+ pub nvEncSetIOCudaStreams: Unused,
+ pub nvEncGetEncodePresetConfigEx: Option<unsafe extern "system" fn(Handle, GUID, GUID, u32, *mut NV_ENC_PRESET_CONFIG) -> NvStatus>,
+ pub nvEncGetSequenceParamEx: Unused,
+ pub nvEncRestoreEncoderState: Unused,
+ pub nvEncLookaheadPicture: Unused,
+ pub reserved2: [Unused; 275],
+}
+
+pub type CreateInstanceFn = unsafe extern "system" fn(*mut NV_ENCODE_API_FUNCTION_LIST) -> NvStatus;
+pub type MaxSupportedVersionFn = unsafe extern "system" fn(*mut u32) -> NvStatus;
diff --cc crates/platform/src/nvenc/mod.rs
index 18b25c47e,000000000..d0723adcc
mode 100644,000000..100644
--- a/crates/platform/src/nvenc/mod.rs
+++ b/crates/platform/src/nvenc/mod.rs
@@@ -1,308 -1,0 +1,339 @@@
+//! NVIDIA NVENC H.264 hardware encoding (Windows).
+//!
+//! The encoder runs on the GPU's NVENC engine through the driver's `nvEncodeAPI64.dll` (API 12.1,
+//! [`ffi`]; no CUDA, no SDK to install): pictures go in as NV12 input buffers, the Annex B output
+//! comes back as length-prefixed H.264 samples with the parameter sets split out for the `avcC`.
+//! [`export`] plugs it into Export as an alternative to the software encoder.
+//!
+//! ```text
+//! RGBA (the export pipeline) ──► BT.709 limited 4:2:0 (the software encoder's conversion)
+//! ──► NV12 input buffer ──NVENC──► Annex B ──► length-prefixed samples + avcC
+//! ```
+//!
+//! `unsafe` is confined to `ffi` (data) and `session` (every driver call); this module is safe
+//! code. Hardware encoding never replaces an export that works in software: the factory declines
+//! what NVENC cannot do (no NVIDIA GPU or driver, sizes, HDR, two-pass, MXF...) and the software
+//! encoder takes over.
+
+pub mod export;
+#[allow(unsafe_code)]
+mod ffi;
+#[allow(unsafe_code)]
+mod session;
+
+#[cfg(test)]
+mod abi_tests;
+
+use std::collections::VecDeque;
+
+pub use self::session::{Caps, Params};
+use self::session::{Locked, Session, Submitted};
+
+/// H.264 profile (`profile_idc` 66 / 77 / 100).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Profile {
+ Baseline,
+ Main,
+ High,
+}
+
+/// What to encode.
+#[derive(Clone, Debug)]
+pub struct Config {
+ pub width: u32,
+ pub height: u32,
+ /// Frame rate as numerator / denominator.
+ pub fps: (u32, u32),
+ pub bitrate_kbps: u32,
+ pub max_bitrate_kbps: u32,
+ pub cbr: bool,
+ /// Frames between IDR pictures.
+ pub keyint: u32,
+ pub profile: Profile,
+ /// Level × 10 (41 = 4.1); `None` lets the encoder pick.
+ pub level: Option<u8>,
+ /// Sample aspect ratio.
+ pub sar: Option<(u32, u32)>,
+ /// Allow one B-frame between references when the encoder and the profile support it.
+ pub bframes: bool,
+}
+
+/// One encoded picture in decoding order.
+pub struct Packet {
+ /// Length-prefixed (4 bytes) NAL units, without parameter sets or access unit delimiters.
+ pub data: Vec<u8>,
+ pub key: bool,
+ /// Presentation / decoding time in frames.
+ pub pts: i64,
+ pub dts: i64,
+}
+
+/// Pictures in flight: input / output buffer pairs.
+const RING: usize = 8;
+
+/// An NVENC H.264 encoder.
+pub struct NvencH264 {
+ session: Session,
+ sps: Vec<u8>,
+ pps: Vec<u8>,
+ /// Frames the output is delayed by reordering (0 or 1).
+ delay: u32,
+ free: Vec<usize>,
+ /// Slots submitted and not read yet, in submission order, and how many of them are ready.
+ pending: VecDeque<usize>,
+ ready: usize,
+ emitted: i64,
+ size: (u32, u32),
+}
+
+/// Whether this system has an NVIDIA GPU with a driver that has NVENC.
+pub fn available() -> bool {
+ Session::open().is_ok()
+}
+
+impl NvencH264 {
+ /// Open an encoder, or say why NVENC does not take this configuration.
+ pub fn new(cfg: &Config) -> Result<Self, String> {
+ let (w, h) = (cfg.width, cfg.height);
+ if w == 0 || h == 0 || w % 2 != 0 || h % 2 != 0 {
+ return Err(format!("{w}x{h}: NVENC needs even dimensions"));
+ }
+ if cfg.fps.0 == 0 || cfg.fps.1 == 0 {
+ return Err("frame rate".into());
+ }
+ let mut session = Session::open()?;
+ let caps = session.caps()?;
+ if w < caps.min_size.0 || h < caps.min_size.1 || w > caps.max_size.0 || h > caps.max_size.1 {
+ return Err(format!("{w}x{h} is outside NVENC's {}x{} - {}x{}", caps.min_size.0, caps.min_size.1, caps.max_size.0, caps.max_size.1));
+ }
+ let bframes = u32::from(cfg.bframes && cfg.profile != Profile::Baseline && caps.max_bframes >= 1);
+ let params = Params {
+ width: w,
+ height: h,
+ fps: cfg.fps,
+ bitrate: cfg.bitrate_kbps.max(1),
+ max_bitrate: cfg.max_bitrate_kbps,
+ cbr: cfg.cbr,
+ gop: cfg.keyint.max(1),
+ profile: match cfg.profile {
+ Profile::Baseline => 0,
+ Profile::Main => 1,
+ Profile::High => 2,
+ },
+ level: cfg.level,
+ sar: cfg.sar,
+ bframes,
+ };
+ session.initialize(&params, RING)?;
+ let (sps, pps) = split_parameter_sets(&session.sequence_params()?)?;
+ let slots = session.slots();
+ Ok(Self { session, sps, pps, delay: bframes, free: (0..slots).rev().collect(), pending: VecDeque::new(), ready: 0, emitted: 0, size: (w, h) })
+ }
+
+ /// The sequence and picture parameter sets (NAL units without start codes).
+ pub fn parameter_sets(&self) -> (&[u8], &[u8]) {
+ (&self.sps, &self.pps)
+ }
+
+ /// Frames the decoding time runs behind the presentation time (B-frame reordering).
+ pub fn delay(&self) -> u32 {
+ self.delay
+ }
+
+ /// Encode picture `index` from planar 4:2:0 (`u`, `v` at half size, rows `w` and `w / 2` bytes).
+ /// Returns the pictures that came out (usually the oldest; none while the ring fills).
+ pub fn encode(&mut self, y: &[u8], u: &[u8], v: &[u8], index: u64) -> Result<Vec<Packet>, String> {
+ let (w, h) = (self.size.0 as usize, self.size.1 as usize);
+ if y.len() < w * h || u.len() < w / 2 * (h / 2) || v.len() < w / 2 * (h / 2) {
+ return Err("the picture is smaller than the encoder's size".into());
+ }
+ let mut out = Vec::new();
+ let slot = match self.free.pop() {
+ Some(s) => s,
+ None => {
+ // the ring is full: the oldest picture must come out first
+ if self.ready == 0 {
+ return Err("the encoder holds more pictures than it can".into());
+ }
+ out.push(self.read_oldest()?);
+ self.free.pop().ok_or("no free encoder buffer")?
+ }
+ };
+ let st = self.session.submit(slot, index, |l| fill_nv12(l, y, u, v, w, h));
+ let st = match st {
+ Ok(s) => s,
+ Err(e) => {
+ self.free.push(slot);
+ return Err(e);
+ }
+ };
+ self.pending.push_back(slot);
+ if st == Submitted::Ready {
+ self.ready = self.pending.len();
+ }
+ Ok(out)
+ }
+
+ /// Finish the stream: every picture still inside comes out.
+ pub fn flush(&mut self) -> Result<Vec<Packet>, String> {
+ if !self.pending.is_empty() {
+ self.session.end_of_stream()?;
+ self.ready = self.pending.len();
+ }
+ let mut out = Vec::new();
+ while self.ready > 0 {
+ out.push(self.read_oldest()?);
+ }
+ Ok(out)
+ }
+
+ fn read_oldest(&mut self) -> Result<Packet, String> {
+ let slot = self.pending.pop_front().ok_or("no picture in flight")?;
+ self.ready = self.ready.saturating_sub(1);
+ let r = self.session.read(slot);
+ self.free.push(slot);
+ let o = r?;
+ let data = annex_b_to_length_prefixed(&o.data)?;
+ let k = self.emitted;
- self.emitted += 1;
- Ok(Packet { data, key: o.pic_type == ffi::NV_ENC_PIC_TYPE_IDR, pts: o.pts as i64, dts: k - i64::from(self.delay) })
++ self.emitted = self.emitted.saturating_add(1);
++ let pts = i64::try_from(o.pts).unwrap_or(i64::MAX);
++ Ok(Packet { data, key: o.pic_type == ffi::NV_ENC_PIC_TYPE_IDR, pts, dts: k.saturating_sub(i64::from(self.delay)) })
+ }
+}
+
+/// Copy planar 4:2:0 into an NV12 input buffer.
+fn fill_nv12(l: Locked<'_>, y: &[u8], u: &[u8], v: &[u8], w: usize, h: usize) {
+ let pitch = l.pitch;
+ let (luma, chroma) = l.data.split_at_mut((pitch * h).min(l.data.len()));
++ if w == 0 || pitch == 0 {
++ return;
++ }
+ for (row, dst) in y.chunks_exact(w).zip(luma.chunks_exact_mut(pitch)).take(h) {
- dst[..w].copy_from_slice(row);
++ // `submit` rejects a pitch narrower than a row; a short row is skipped, never overrun
++ if let Some(d) = dst.get_mut(..w) {
++ d.copy_from_slice(row);
++ }
+ }
+ let cw = w / 2;
++ if cw == 0 {
++ return;
++ }
+ for ((ur, vr), dst) in u.chunks_exact(cw).zip(v.chunks_exact(cw)).zip(chroma.chunks_exact_mut(pitch)).take(h / 2) {
- for ((d, a), b) in dst[..w].chunks_exact_mut(2).zip(ur).zip(vr) {
- d[0] = *a;
- d[1] = *b;
++ let Some(dst) = dst.get_mut(..w) else { continue };
++ for (([du, dv], a), b) in dst.as_chunks_mut::<2>().0.iter_mut().zip(ur).zip(vr) {
++ *du = *a;
++ *dv = *b;
+ }
+ }
+}
+
+/// The NAL units of an Annex B byte stream (start codes `00 00 01` / `00 00 00 01`).
+pub fn annex_b_nals(data: &[u8]) -> Vec<&[u8]> {
+ let mut starts = Vec::new();
- let mut i = 0;
- while i + 3 <= data.len() {
- if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
++ let mut i = 0usize;
++ while let Some(w) = data.get(i..i.saturating_add(3)) {
++ if w == [0, 0, 1] {
+ starts.push(i + 3);
+ i += 3;
+ } else {
+ i += 1;
+ }
+ }
+ let mut out = Vec::with_capacity(starts.len());
+ for (k, &s) in starts.iter().enumerate() {
- let mut e = starts.get(k + 1).map_or(data.len(), |n| n - 3);
++ let mut e = starts.get(k + 1).map_or(data.len(), |n| n.saturating_sub(3));
+ // trailing zero bytes belong to the next start code (4-byte form) or are padding
- while e > s && data[e - 1] == 0 {
++ while e > s && data.get(e - 1) == Some(&0) {
+ e -= 1;
+ }
- if e > s {
- out.push(&data[s..e]);
++ if let Some(n) = data.get(s..e).filter(|n| !n.is_empty()) {
++ out.push(n);
+ }
+ }
+ out
+}
+
+/// Annex B to 4-byte length-prefixed NAL units, dropping parameter sets (they live in the `avcC`)
+/// and access unit delimiters. Errors on a stream without NAL units.
+pub fn annex_b_to_length_prefixed(data: &[u8]) -> Result<Vec<u8>, String> {
+ let nals = annex_b_nals(data);
+ if nals.is_empty() {
+ return Err("the encoder produced no NAL units".into());
+ }
+ let mut out = Vec::with_capacity(data.len());
+ for n in nals {
- if matches!(n[0] & 0x1f, 7..=9) {
++ if n.first().is_none_or(|b| matches!(b & 0x1f, 7..=9)) {
+ continue;
+ }
+ out.extend_from_slice(&(n.len() as u32).to_be_bytes());
+ out.extend_from_slice(n);
+ }
+ if out.is_empty() {
+ return Err("the encoder produced no picture data".into());
+ }
+ Ok(out)
+}
+
+/// The SPS and PPS NAL units of an Annex B byte string.
+pub fn split_parameter_sets(data: &[u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
+ let nals = annex_b_nals(data);
- let find = |t: u8| nals.iter().find(|n| n[0] & 0x1f == t).map(|n| n.to_vec());
++ let find = |t: u8| nals.iter().find(|n| n.first().is_some_and(|b| b & 0x1f == t)).map(|n| n.to_vec());
+ match (find(7), find(8)) {
+ (Some(s), Some(p)) => Ok((s, p)),
+ _ => Err("the encoder returned no SPS / PPS".into()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn splits_annex_b_with_both_start_code_forms() {
+ let s = [0, 0, 0, 1, 0x67, 1, 2, 0, 0, 1, 0x68, 3, 0, 0, 0, 1, 0x65, 9, 9, 0];
+ let n = annex_b_nals(&s);
+ assert_eq!(n, vec![&[0x67, 1, 2][..], &[0x68, 3][..], &[0x65, 9, 9][..]]);
+ assert_eq!(annex_b_to_length_prefixed(&s).unwrap(), [0, 0, 0, 3, 0x65, 9, 9]);
+ assert_eq!(split_parameter_sets(&s).unwrap(), (vec![0x67, 1, 2], vec![0x68, 3]));
+ }
+
+ #[test]
+ fn hostile_streams_are_errors() {
+ for s in [&[][..], &[0, 0, 1], &[1, 2, 3], &[0, 0, 1, 0x09, 0xf0], &[0, 0, 0, 1, 0x67, 1]] {
+ assert!(annex_b_to_length_prefixed(s).is_err(), "{s:?}");
+ }
+ assert!(split_parameter_sets(&[0, 0, 1, 0x65, 1]).is_err());
+ }
+
+ #[test]
+ fn nv12_is_interleaved_chroma_after_luma_rows() {
+ let (w, h, pitch) = (4usize, 2usize, 8usize);
+ let y: Vec<u8> = (0..8).collect();
+ let (u, v) = (vec![100, 101], vec![200, 201]);
+ let mut buf = vec![0u8; pitch * h * 3 / 2];
+ fill_nv12(Locked { data: &mut buf, pitch }, &y, &u, &v, w, h);
+ assert_eq!(&buf[..4], &[0, 1, 2, 3]);
+ assert_eq!(&buf[pitch..pitch + 4], &[4, 5, 6, 7]);
+ assert_eq!(&buf[pitch * h..pitch * h + 4], &[100, 200, 101, 201]);
+ }
++
++ #[test]
++ fn nv12_never_writes_past_a_narrow_pitch() {
++ // a driver pitch narrower than the row (rejected by `submit`) must not panic here either
++ let (w, h, pitch) = (8usize, 4usize, 4usize);
++ let y = vec![7u8; w * h];
++ let (u, v) = (vec![1u8; w * h / 4], vec![2u8; w * h / 4]);
++ let mut buf = vec![0u8; pitch * h * 3 / 2];
++ fill_nv12(Locked { data: &mut buf, pitch }, &y, &u, &v, w, h);
++ // and empty or zero-sized inputs
++ fill_nv12(Locked { data: &mut [], pitch: 0 }, &[], &[], &[], 0, 0);
++ fill_nv12(Locked { data: &mut buf, pitch }, &[1], &[], &[], 1, 1);
++ }
++
++ #[test]
++ fn empty_nal_units_are_skipped() {
++ assert!(annex_b_nals(&[0, 0, 1, 0, 0, 1]).is_empty());
++ assert!(annex_b_to_length_prefixed(&[0, 0, 1, 0, 0, 0, 1]).is_err());
++ assert!(split_parameter_sets(&[0, 0, 1]).is_err());
++ }
+}
diff --cc crates/platform/src/nvenc/session.rs
index 054b13cd7,000000000..0aa362c8a
mode 100644,000000..100644
--- a/crates/platform/src/nvenc/session.rs
+++ b/crates/platform/src/nvenc/session.rs
@@@ -1,493 -1,0 +1,508 @@@
+//! An NVENC H.264 encode session: the driver library, the Direct3D 11 device it is opened on, the
+//! encoder configuration, and the input / output buffers (every call into the driver).
+//!
+//! FFI module (docs/adr/0001-platform-ffi.md): every `unsafe` block has a `// SAFETY:` comment, the
+//! public items are safe and return `Result<_, String>`, no driver pointer leaves this module.
+
+use std::ffi::{CStr, c_void};
+use std::sync::OnceLock;
+
+use windows::Win32::Foundation::HMODULE;
+use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_UNKNOWN;
+use windows::Win32::Graphics::Direct3D11::{D3D11_CREATE_DEVICE_FLAG, D3D11_SDK_VERSION, D3D11CreateDevice, ID3D11Device};
+use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory1};
+use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW};
+use windows::core::{Interface, PCSTR, w};
+
+use super::ffi::*;
+
+/// NVIDIA's PCI vendor id.
+const NVIDIA: u32 = 0x10DE;
+
+/// The driver's entry points (loaded once).
+struct Api {
+ list: NV_ENCODE_API_FUNCTION_LIST,
+}
+
+// SAFETY: the function table is plain function pointers, immutable after loading; NVENC's API is
+// callable from any thread (calls on one encoder session are serialised by `&mut Session`).
+unsafe impl Send for Api {}
+// SAFETY: see above.
+unsafe impl Sync for Api {}
+
+fn api() -> Result<&'static Api, String> {
+ static API: OnceLock<Result<Api, String>> = OnceLock::new();
+ API.get_or_init(load).as_ref().map_err(Clone::clone)
+}
+
+fn load() -> Result<Api, String> {
+ // SAFETY: loads the driver's library from the system directory only.
+ let module: HMODULE =
+ unsafe { LoadLibraryExW(w!("nvEncodeAPI64.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.map_err(|_| "no NVIDIA encoder driver".to_string())?;
+ // SAFETY: both symbols are looked up with the signatures of nvEncodeAPI.h; the table is
+ // zero-initialised (all-zero is valid: null pointers) with its version set, as the API asks.
+ unsafe {
+ let version: MaxSupportedVersionFn = std::mem::transmute(
+ GetProcAddress(module, PCSTR(c"NvEncodeAPIGetMaxSupportedVersion".as_ptr().cast())).ok_or("driver lacks NvEncodeAPIGetMaxSupportedVersion")?,
+ );
+ let create: CreateInstanceFn =
+ std::mem::transmute(GetProcAddress(module, PCSTR(c"NvEncodeAPICreateInstance".as_ptr().cast())).ok_or("driver lacks NvEncodeAPICreateInstance")?);
+ let mut v = 0u32;
+ if version(&mut v) != NV_ENC_SUCCESS {
+ return Err("cannot query the NVENC version".into());
+ }
+ let ours = (NVENCAPI_VERSION & 0xf) << 4 | ((NVENCAPI_VERSION >> 24) & 0xf);
+ if v < ours {
+ return Err(format!("the NVIDIA driver's NVENC ({}.{}) is older than {}.{}", v >> 4, v & 0xf, ours >> 4, ours & 0xf));
+ }
+ let mut list: NV_ENCODE_API_FUNCTION_LIST = std::mem::zeroed();
+ list.version = NV_ENCODE_API_FUNCTION_LIST_VER;
+ if create(&mut list) != NV_ENC_SUCCESS {
+ return Err("NvEncodeAPICreateInstance failed".into());
+ }
+ Ok(Api { list })
+ }
+}
+
+/// A Direct3D 11 device on the first NVIDIA adapter (what an NVENC session is opened on).
+fn nvidia_device() -> Result<ID3D11Device, String> {
+ // SAFETY: plain COM / D3D calls with valid out-pointers; the adapter outlives the call.
+ unsafe {
+ let factory: IDXGIFactory1 = CreateDXGIFactory1().map_err(|e| format!("no DXGI: {e}"))?;
+ let mut i = 0;
+ while let Ok(adapter) = factory.EnumAdapters1(i) {
+ i += 1;
+ let Ok(desc) = adapter.GetDesc1() else { continue };
+ if desc.VendorId != NVIDIA {
+ continue;
+ }
+ let mut device = None;
+ let adapter: IDXGIAdapter = adapter.cast().map_err(|e| e.to_string())?;
+ if D3D11CreateDevice(
+ &adapter,
+ D3D_DRIVER_TYPE_UNKNOWN,
+ HMODULE::default(),
+ D3D11_CREATE_DEVICE_FLAG(0),
+ None,
+ D3D11_SDK_VERSION,
+ Some(&mut device),
+ None,
+ None,
+ )
+ .is_ok()
+ && let Some(d) = device
+ {
+ return Ok(d);
+ }
+ }
+ }
+ Err("no NVIDIA adapter".into())
+}
+
+/// What the encoder says it can do for H.264.
+#[derive(Clone, Copy, Debug)]
+pub struct Caps {
+ pub max_bframes: u32,
+ pub min_size: (u32, u32),
+ pub max_size: (u32, u32),
+}
+
+/// Encoder settings (already validated by the caller).
+#[derive(Clone, Debug)]
+pub struct Params {
+ pub width: u32,
+ pub height: u32,
+ pub fps: (u32, u32),
+ pub bitrate: u32,
+ pub max_bitrate: u32,
+ pub cbr: bool,
+ pub gop: u32,
+ /// 0 baseline, 1 main, 2 high.
+ pub profile: u8,
+ pub level: Option<u8>,
+ pub sar: Option<(u32, u32)>,
+ /// B-frames between references (0 or 1).
+ pub bframes: u32,
+}
+
+/// An input buffer locked for writing: NV12 rows go to `data` at `pitch` bytes per row, the
+/// chroma plane after `pitch * height` bytes.
+pub struct Locked<'a> {
+ pub data: &'a mut [u8],
+ pub pitch: usize,
+}
+
+/// A finished picture's bitstream.
+pub struct Output {
+ /// Annex B bytes.
+ pub data: Vec<u8>,
+ pub pts: u64,
+ /// `NV_ENC_PIC_TYPE_*`.
+ pub pic_type: u32,
+}
+
+/// The result of submitting a picture.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Submitted {
+ /// The pictures submitted so far have their bitstreams ready.
+ Ready,
+ /// The encoder wants more input (B-frame reordering) before it has output.
+ NeedMoreInput,
+}
+
+struct Slot {
+ input: *mut c_void,
+ output: *mut c_void,
+}
+
+/// An initialised encoder with its buffers.
+pub struct Session {
+ api: &'static Api,
+ enc: Handle,
+ // keeps the Direct3D device (the session's device) alive
+ _device: ID3D11Device,
+ slots: Vec<Slot>,
+ size: (u32, u32),
+ out_size: u32,
+}
+
+// SAFETY: an encoder session and its buffers are driver objects used from one thread at a time (the
+// session is `&mut`-driven); the Direct3D device is a free-threaded COM object.
+unsafe impl Send for Session {}
+
+/// A readable form of a driver status.
+fn status(what: &str, s: NvStatus, enc: Handle, api: &Api) -> String {
+ let detail = (!enc.is_null())
+ .then(|| {
+ // SAFETY: a valid session handle; the driver returns a NUL-terminated string it owns.
+ api.list.nvEncGetLastErrorString.and_then(|f| unsafe {
+ let p = f(enc);
+ (!p.is_null()).then(|| CStr::from_ptr(p).to_string_lossy().into_owned())
+ })
+ })
+ .flatten()
+ .filter(|d| !d.is_empty());
+ match detail {
+ Some(d) => format!("{what} failed ({s}): {d}"),
+ None => format!("{what} failed ({s})"),
+ }
+}
+
+impl Session {
+ /// Open a session on the system's NVIDIA GPU, or say why not.
+ pub fn open() -> Result<Session, String> {
+ let api = api()?;
+ let device = nvidia_device()?;
+ // SAFETY: a zeroed parameter block with its version and the device's COM pointer; the
- // device is kept in the session for as long as the encoder lives.
++ // device is kept in the session for as long as the encoder lives. On failure a non-null
++ // handle is the driver's and is destroyed exactly once, here, before returning.
+ let enc = unsafe {
+ let mut p: NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS = std::mem::zeroed();
+ p.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
+ p.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
+ p.device = device.as_raw();
+ p.apiVersion = NVENCAPI_VERSION;
+ let open = api.list.nvEncOpenEncodeSessionEx.ok_or("the driver has no nvEncOpenEncodeSessionEx")?;
+ let mut enc: Handle = std::ptr::null_mut();
+ let s = open(&mut p, &mut enc);
+ if s != NV_ENC_SUCCESS || enc.is_null() {
- return Err(status("opening the NVENC session", s, enc, api));
++ let e = status("opening the NVENC session", s, enc, api);
++ // a failed open may still hand back a session; destroy it so the GPU's encoder
++ // session limit is not used up by sessions nobody owns
++ if !enc.is_null()
++ && let Some(d) = api.list.nvEncDestroyEncoder
++ {
++ d(enc);
++ }
++ return Err(e);
+ }
+ enc
+ };
+ Ok(Session { api, enc, _device: device, slots: Vec::new(), size: (0, 0), out_size: 0 })
+ }
+
+ /// The encoder's limits for H.264.
+ pub fn caps(&self) -> Result<Caps, String> {
+ let get = |cap: u32| -> Result<u32, String> {
+ let f = self.api.list.nvEncGetEncodeCaps.ok_or("no nvEncGetEncodeCaps")?;
+ // SAFETY: a valid session, a zeroed parameter block with its version, one int out.
+ unsafe {
+ let mut p: NV_ENC_CAPS_PARAM = std::mem::zeroed();
+ p.version = NV_ENC_CAPS_PARAM_VER;
+ p.capsToQuery = cap;
+ let mut v = 0i32;
+ let s = f(self.enc, NV_ENC_CODEC_H264_GUID, &mut p, &mut v);
+ if s != NV_ENC_SUCCESS {
+ return Err(status("querying the encoder", s, self.enc, self.api));
+ }
+ Ok(v.max(0) as u32)
+ }
+ };
+ Ok(Caps {
+ max_bframes: get(NV_ENC_CAPS_NUM_MAX_BFRAMES)?,
+ min_size: (get(NV_ENC_CAPS_WIDTH_MIN)?, get(NV_ENC_CAPS_HEIGHT_MIN)?),
+ max_size: (get(NV_ENC_CAPS_WIDTH_MAX)?, get(NV_ENC_CAPS_HEIGHT_MAX)?),
+ })
+ }
+
+ /// Configure the encoder (preset P5, high quality tuning, the settings' rate control) and
+ /// create `ring` pairs of input / output buffers.
+ pub fn initialize(&mut self, p: &Params, ring: usize) -> Result<(), String> {
+ let preset_fn = self.api.list.nvEncGetEncodePresetConfigEx.ok_or("no nvEncGetEncodePresetConfigEx")?;
+ let init_fn = self.api.list.nvEncInitializeEncoder.ok_or("no nvEncInitializeEncoder")?;
+ // SAFETY: zeroed parameter blocks with their versions; the preset call fills `preset`; the
+ // configuration lives in a box that outlives `nvEncInitializeEncoder`, which copies it.
+ unsafe {
+ let mut preset: Box<NV_ENC_PRESET_CONFIG> = Box::new(std::mem::zeroed());
+ preset.version = NV_ENC_PRESET_CONFIG_VER;
+ preset.presetCfg.version = NV_ENC_CONFIG_VER;
+ let s = preset_fn(self.enc, NV_ENC_CODEC_H264_GUID, NV_ENC_PRESET_P5_GUID, NV_ENC_TUNING_INFO_HIGH_QUALITY, &mut *preset);
+ if s != NV_ENC_SUCCESS {
+ return Err(status("reading the encoder preset", s, self.enc, self.api));
+ }
+ let mut cfg: Box<NV_ENC_CONFIG> = Box::new(preset.presetCfg);
+ cfg.version = NV_ENC_CONFIG_VER;
+ cfg.profileGUID = match p.profile {
+ 0 => NV_ENC_H264_PROFILE_BASELINE_GUID,
+ 1 => NV_ENC_H264_PROFILE_MAIN_GUID,
+ _ => NV_ENC_H264_PROFILE_HIGH_GUID,
+ };
+ cfg.gopLength = p.gop.max(1);
+ cfg.frameIntervalP = 1 + p.bframes as i32;
+ let rc = &mut cfg.rcParams;
+ rc.version = NV_ENC_RC_PARAMS_VER;
+ rc.rateControlMode = if p.cbr { NV_ENC_PARAMS_RC_CBR } else { NV_ENC_PARAMS_RC_VBR };
+ rc.averageBitRate = p.bitrate.saturating_mul(1000);
+ rc.maxBitRate = if p.cbr { rc.averageBitRate } else { p.max_bitrate.max(p.bitrate).saturating_mul(1000) };
+ // a one-second buffer, the usual for streaming-style rate control
+ rc.vbvBufferSize = rc.maxBitRate;
+ rc.vbvInitialDelay = rc.vbvBufferSize;
+ let h = &mut cfg.encodeCodecConfig.h264Config;
+ h.idrPeriod = p.gop.max(1);
+ h.level = p.level.map_or(NV_ENC_LEVEL_AUTOSELECT, u32::from);
+ h.flags &= !(H264_OUTPUT_AUD | H264_REPEAT_SPSPPS);
+ h.entropyCodingMode = if p.profile == 0 { 2 } else { NV_ENC_H264_ENTROPY_CODING_MODE_CABAC };
+ h.maxNumRefFrames = 0;
+ // BT.709 limited range, like our own encoder's default signalling
+ let vui = &mut h.h264VUIParameters;
+ vui.videoSignalTypePresentFlag = 1;
+ vui.videoFormat = NV_ENC_VUI_VIDEO_FORMAT_UNSPECIFIED;
+ vui.videoFullRangeFlag = 0;
+ vui.colourDescriptionPresentFlag = 1;
+ vui.colourPrimaries = NV_ENC_VUI_COLOR_PRIMARIES_BT709;
+ vui.transferCharacteristics = NV_ENC_VUI_TRANSFER_CHARACTERISTIC_BT709;
+ vui.colourMatrix = NV_ENC_VUI_MATRIX_COEFFS_BT709;
+ vui.timingInfoPresentFlag = 1;
+ vui.numUnitInTicks = p.fps.1;
+ vui.timeScale = p.fps.0.saturating_mul(2);
+
+ let mut init: Box<NV_ENC_INITIALIZE_PARAMS> = Box::new(std::mem::zeroed());
+ init.version = NV_ENC_INITIALIZE_PARAMS_VER;
+ init.encodeGUID = NV_ENC_CODEC_H264_GUID;
+ init.presetGUID = NV_ENC_PRESET_P5_GUID;
+ init.encodeWidth = p.width;
+ init.encodeHeight = p.height;
+ let (sn, sd) = p.sar.unwrap_or((1, 1));
+ init.darWidth = p.width.saturating_mul(sn.max(1));
+ init.darHeight = p.height.saturating_mul(sd.max(1));
+ init.frameRateNum = p.fps.0;
+ init.frameRateDen = p.fps.1;
+ init.enablePTD = 1;
+ init.encodeConfig = &mut *cfg;
+ init.tuningInfo = NV_ENC_TUNING_INFO_HIGH_QUALITY;
+ init.bufferFormat = NV_ENC_BUFFER_FORMAT_NV12;
+ let s = init_fn(self.enc, &mut *init);
+ if s != NV_ENC_SUCCESS {
+ return Err(status("initialising the encoder", s, self.enc, self.api));
+ }
+ }
+ self.size = (p.width, p.height);
+ self.out_size = (p.width.saturating_mul(p.height).saturating_mul(2)).max(1 << 20);
+ for _ in 0..ring.max(1) {
+ self.add_slot()?;
+ }
+ Ok(())
+ }
+
+ fn add_slot(&mut self) -> Result<(), String> {
+ let (create_in, create_out) = (
+ self.api.list.nvEncCreateInputBuffer.ok_or("no nvEncCreateInputBuffer")?,
+ self.api.list.nvEncCreateBitstreamBuffer.ok_or("no nvEncCreateBitstreamBuffer")?,
+ );
+ // SAFETY: zeroed parameter blocks with their versions; the driver fills in the buffer
+ // handles, which `Drop` destroys.
+ unsafe {
+ let mut i: NV_ENC_CREATE_INPUT_BUFFER = std::mem::zeroed();
+ i.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
+ i.width = self.size.0;
+ i.height = self.size.1;
+ i.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
+ i.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12;
+ let s = create_in(self.enc, &mut i);
+ if s != NV_ENC_SUCCESS {
+ return Err(status("creating an input buffer", s, self.enc, self.api));
+ }
+ let mut o: NV_ENC_CREATE_BITSTREAM_BUFFER = std::mem::zeroed();
+ o.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
+ o.size = self.out_size;
+ o.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
+ let s = create_out(self.enc, &mut o);
+ if s != NV_ENC_SUCCESS {
+ if let Some(d) = self.api.list.nvEncDestroyInputBuffer {
+ d(self.enc, i.inputBuffer);
+ }
+ return Err(status("creating an output buffer", s, self.enc, self.api));
+ }
+ self.slots.push(Slot { input: i.inputBuffer, output: o.bitstreamBuffer });
+ }
+ Ok(())
+ }
+
+ /// Number of buffer slots.
+ pub fn slots(&self) -> usize {
+ self.slots.len()
+ }
+
+ /// The SPS and PPS as one Annex B byte string.
+ pub fn sequence_params(&self) -> Result<Vec<u8>, String> {
+ let f = self.api.list.nvEncGetSequenceParams.ok_or("no nvEncGetSequenceParams")?;
+ let mut buf = vec![0u8; 1024];
+ let mut len = 0u32;
+ // SAFETY: a zeroed parameter block with its version; `buf` and `len` outlive the call and
+ // the driver writes at most `inBufferSize` bytes into `buf`.
+ unsafe {
+ let mut p: NV_ENC_SEQUENCE_PARAM_PAYLOAD = std::mem::zeroed();
+ p.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
+ p.inBufferSize = buf.len() as u32;
+ p.spsppsBuffer = buf.as_mut_ptr().cast();
+ p.outSPSPPSPayloadSize = &mut len;
+ let s = f(self.enc, &mut p);
+ if s != NV_ENC_SUCCESS {
+ return Err(status("reading the parameter sets", s, self.enc, self.api));
+ }
+ }
+ buf.truncate(len as usize);
+ Ok(buf)
+ }
+
+ /// Write a picture into slot `slot`'s input buffer through `fill` (which gets the locked
+ /// buffer), then submit it with timestamp `pts`; `output_slot` receives the bitstream.
+ pub fn submit(&mut self, slot: usize, pts: u64, fill: impl FnOnce(Locked<'_>)) -> Result<Submitted, String> {
+ let s = self.slots.get(slot).ok_or("no such buffer slot")?;
+ let (input, output) = (s.input, s.output);
+ let (lock, unlock, encode) = (
+ self.api.list.nvEncLockInputBuffer.ok_or("no nvEncLockInputBuffer")?,
+ self.api.list.nvEncUnlockInputBuffer.ok_or("no nvEncUnlockInputBuffer")?,
+ self.api.list.nvEncEncodePicture.ok_or("no nvEncEncodePicture")?,
+ );
+ let (w, h) = self.size;
+ // SAFETY: the buffer handle is one this session created. `LockInputBuffer` returns a
+ // writable block of `pitch * h * 3 / 2` bytes (NV12: luma rows then chroma rows) that stays
+ // valid until `UnlockInputBuffer`; the slice borrows it only inside `fill`.
+ let pitch = unsafe {
+ let mut l: NV_ENC_LOCK_INPUT_BUFFER = std::mem::zeroed();
+ l.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
+ l.inputBuffer = input;
+ let st = lock(self.enc, &mut l);
+ if st != NV_ENC_SUCCESS || l.bufferDataPtr.is_null() || l.pitch == 0 {
+ return Err(status("locking an input buffer", st, self.enc, self.api));
+ }
++ // a driver pitch narrower than a row would make `fill` write past each row
++ if (l.pitch as usize) < w as usize {
++ // the lock succeeded, so release it before giving up (its status no longer matters)
++ let _ = unlock(self.enc, input);
++ return Err(format!("the driver returned an input pitch of {} bytes for {w}-pixel rows", l.pitch));
++ }
+ let len = (l.pitch as usize).saturating_mul(h as usize).saturating_mul(3) / 2;
+ fill(Locked { data: std::slice::from_raw_parts_mut(l.bufferDataPtr.cast::<u8>(), len), pitch: l.pitch as usize });
+ let st = unlock(self.enc, input);
+ if st != NV_ENC_SUCCESS {
+ return Err(status("unlocking an input buffer", st, self.enc, self.api));
+ }
+ l.pitch
+ };
+ // SAFETY: a zeroed parameter block with its version; the buffers are this session's.
+ let st = unsafe {
+ let mut e: NV_ENC_PIC_PARAMS = std::mem::zeroed();
+ e.version = NV_ENC_PIC_PARAMS_VER;
+ e.inputWidth = w;
+ e.inputHeight = h;
+ e.inputPitch = pitch;
+ e.inputBuffer = input;
+ e.outputBitstream = output;
+ e.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12;
+ e.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
+ e.inputTimeStamp = pts;
+ e.inputDuration = 1;
+ encode(self.enc, &mut e)
+ };
+ match st {
+ NV_ENC_SUCCESS => Ok(Submitted::Ready),
+ NV_ENC_ERR_NEED_MORE_INPUT => Ok(Submitted::NeedMoreInput),
+ s => Err(status("encoding a picture", s, self.enc, self.api)),
+ }
+ }
+
+ /// Tell the encoder the stream ends: every picture it still holds becomes ready.
+ pub fn end_of_stream(&mut self) -> Result<(), String> {
+ let encode = self.api.list.nvEncEncodePicture.ok_or("no nvEncEncodePicture")?;
+ // SAFETY: a zeroed parameter block with its version and the EOS flag (no input buffer).
+ let st = unsafe {
+ let mut e: NV_ENC_PIC_PARAMS = std::mem::zeroed();
+ e.version = NV_ENC_PIC_PARAMS_VER;
+ e.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
+ encode(self.enc, &mut e)
+ };
+ if st != NV_ENC_SUCCESS {
+ return Err(status("ending the stream", st, self.enc, self.api));
+ }
+ Ok(())
+ }
+
+ /// Read the finished bitstream of slot `slot` (blocks until the encoder has it).
+ pub fn read(&mut self, slot: usize) -> Result<Output, String> {
+ let output = self.slots.get(slot).ok_or("no such buffer slot")?.output;
+ let (lock, unlock) =
+ (self.api.list.nvEncLockBitstream.ok_or("no nvEncLockBitstream")?, self.api.list.nvEncUnlockBitstream.ok_or("no nvEncUnlockBitstream")?);
+ // SAFETY: a zeroed parameter block with its version and a buffer of this session; after a
+ // successful lock `bitstreamBufferPtr` addresses `bitstreamSizeInBytes` readable bytes until
+ // `UnlockBitstream`, and they are copied before it.
+ unsafe {
+ let mut l: NV_ENC_LOCK_BITSTREAM = std::mem::zeroed();
+ l.version = NV_ENC_LOCK_BITSTREAM_VER;
+ l.outputBitstream = output;
+ let st = lock(self.enc, &mut l);
+ if st != NV_ENC_SUCCESS {
+ return Err(status("reading a bitstream", st, self.enc, self.api));
+ }
+ let n = l.bitstreamSizeInBytes as usize;
+ let data =
+ if l.bitstreamBufferPtr.is_null() || n == 0 { Vec::new() } else { std::slice::from_raw_parts(l.bitstreamBufferPtr.cast::<u8>(), n).to_vec() };
+ let out = Output { data, pts: l.outputTimeStamp, pic_type: l.pictureType };
+ let st = unlock(self.enc, output);
+ if st != NV_ENC_SUCCESS {
+ return Err(status("releasing a bitstream", st, self.enc, self.api));
+ }
+ Ok(out)
+ }
+ }
+}
+
+impl Drop for Session {
+ fn drop(&mut self) {
+ // SAFETY: every handle was created by this session and is destroyed once, buffers first.
+ unsafe {
+ for s in self.slots.drain(..) {
+ if let Some(d) = self.api.list.nvEncDestroyInputBuffer {
+ d(self.enc, s.input);
+ }
+ if let Some(d) = self.api.list.nvEncDestroyBitstreamBuffer {
+ d(self.enc, s.output);
+ }
+ }
+ if let Some(d) = self.api.list.nvEncDestroyEncoder {
+ d(self.enc);
+ }
+ }
+ }
+}
diff --cc crates/ui-egui/examples/bench/sections.rs
index 9d0465ee2,97ea0521e..25438e5cf
--- a/crates/ui-egui/examples/bench/sections.rs
+++ b/crates/ui-egui/examples/bench/sections.rs
@@@ -485,8 -482,6 +485,8 @@@ pub fn export(o: &Opts) -> Vec<Value>
"format": label, "frames": frames, "seconds": best, "fps": frames as f64 / best,
"realtime": frames as f64 / best / FrameRate::FPS_23_976.as_f64(), "cpu_ms_per_frame": median(&cpu),
"mbytes": bytes as f64 / 1e6, "runs_s": runs, "load": load_avg(),
+ // pictures encoded by a hardware encoder during this row (zero with --hw off or where there is none)
- "hw_frames": filmcraft_engine::export::hw_encode_stats().frames - hw0.frames,
++ "hw_frames": filmcraft_engine::export::hw_encode_stats().frames.saturating_sub(hw0.frames),
}));
}
let _ = std::fs::remove_dir_all(&dir);
diff --cc crates/ui-egui/src/panels/export_mode.rs
index 3087cf0ce,e079ce96a..23d3d7e97
--- a/crates/ui-egui/src/panels/export_mode.rs
+++ b/crates/ui-egui/src/panels/export_mode.rs
@@@ -661,6 -667,17 +667,18 @@@ fn video_section(ui: &mut egui::Ui, reg
*k = v as u32;
}
});
- // The operating system's hardware encoder where there is one (macOS); everything it does
- // not take (two-pass, HDR, MXF) and every machine without one keeps the built-in encoder.
++ // The system's hardware encoder where there is one (VideoToolbox on macOS, NVENC on NVIDIA
++ // GPUs on Windows); everything it does not take (two-pass, HDR, MXF) and every machine
++ // without one keeps the built-in encoder.
+ // H.265 has only the hardware encoder: choosing the format is the opt-in.
+ if !hevc {
+ row(ui, t, "Hardware Encoding", |ui| {
+ let mut on = s.hardware_encoding == HardwareEncoding::Auto;
+ if check(ui, reg, "export.video.hardwareEncoding", &mut on, "Use the hardware encoder when available") {
+ s.hardware_encoding = if on { HardwareEncoding::Auto } else { HardwareEncoding::Off };
+ }
+ });
+ }
}
Format::ProRes => {
row(ui, t, "Profile", |ui| {
diff --cc docs/architecture.md
index e545a4131,ac8dafd97..e0a7885c8
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@@ -72,7 -72,7 +72,7 @@@ and `filmcraft-cli`
| `engine` | L4 | `Session`, command registry, undo history, media pool, jobs, interchange glue |
| `ui-egui` | L5 | the egui frontend: docking, panels, timeline, monitors, playback, control-channel handlers |
| `automation` | L5 | MCP server (`rmcp`, stdio), headless or bridged to the running app |
- | `platform` | L5 | OS media FFI only: hardware video decoding (VideoToolbox H.264 / HEVC on macOS; Media Foundation / Direct3D 11 H.264 / HEVC on Windows; a no-op elsewhere) behind `codecs::VideoDecoder`, with transparent fallback to our decoders; NVIDIA NVENC H.264 encoding behind the Export encoder registry (Windows). The one crate allowed `unsafe` ([ADR 0001](adr/0001-platform-ffi.md), [README](../crates/platform/README.md)) |
-| `platform` | L5 | OS media FFI only: hardware video decoding (VideoToolbox H.264 / HEVC on macOS; Media Foundation / Direct3D 11 H.264 / HEVC on Windows; a no-op elsewhere) behind `codecs::VideoDecoder`, with transparent fallback to our decoders, and hardware H.264 encoding (VideoToolbox, opt-in) and H.265 encoding (VideoToolbox, the only H.265 encoder; the format exists only where a hardware encoder does) behind `export::VideoEncoder`; H.264 declines to the built-in encoder for what the hardware does not take. The one crate allowed `unsafe` ([ADR 0001](adr/0001-platform-ffi.md), [README](../crates/platform/README.md)) |
++| `platform` | L5 | OS media FFI only: hardware video decoding (VideoToolbox H.264 / HEVC on macOS; Media Foundation / Direct3D 11 H.264 / HEVC on Windows; a no-op elsewhere) behind `codecs::VideoDecoder`, with transparent fallback to our decoders, and hardware H.264 encoding (VideoToolbox, opt-in) and H.265 encoding (VideoToolbox, the only H.265 encoder; the format exists only where a hardware encoder does) and NVIDIA NVENC H.264 encoding (Windows, opt-in) behind `export::VideoEncoder`; H.264 declines to the built-in encoder for what the hardware does not take. The one crate allowed `unsafe` ([ADR 0001](adr/0001-platform-ffi.md), [README](../crates/platform/README.md)) |
| `filmcraft` | L6 | desktop binary: eframe/wgpu window, cpal audio output, file dialogs, native macOS menu, TCP control server |
| `filmcraft-cli` | L6 | headless CLI: `exec`, `run`, `inspect`, `describe`, `commands`, `import`, `export`, `render`, `probe`, `mcp`; `--bridge` targets the running app |
| `filmcraft-web` | L6 | the browser app (wasm32): eframe web runner on WebGPU/WebGL2, Blob-backed services, OPFS recovery, WebAudio, WebCodecs, `window.filmcraft` API ([web.md](web.md)) |
diff --cc docs/performance.md
index 21c962c2e,d74811667..5fd62d739
--- a/docs/performance.md
+++ b/docs/performance.md
@@@ -172,26 -301,34 +301,54 @@@ frame, about 8 cores busy); Auto uses
Draft playback (1/2 draft: 410–416 → 93–105 CPU ms/frame) is dominated by the draft plan's decimation,
as on macOS, because the hardware ignores draft mode.
+## Results (HW4: Windows NVENC H.264 export, software → hardware)
+
+Same machine as the HW2 results (Xeon E5-2680 v4, 28 threads, RTX 5060, driver 617.14, idle,
+2026-10-07). `cargo xtask bench --sections export --only h264 --hw off|auto --repeat 3`: the export
+of 8 s of a 1080p23.976 H.264 clip (191 frames) to H.264 with the default preset, VBR one pass.
+`--hw off` runs the software encoder; `--hw auto` sets `hardwareEncoding` to auto and runs NVENC
+(preset P5, high-quality tuning). Every NVENC row had `hw frames` = 573 = 191 × 3 repeats.
+
+| encoder | fps | CPU ms/frame | MB |
+|---|---|---|---|
+| software | 15.0 (12.7–12.8 s) | 1050 | 20.4 |
+| **NVENC** | **44** (4.3 s) | **356–373** | 21.7 |
+
+- The remaining CPU is the compositing and render of the frames and the RGBA → YUV conversion, not
+ the encoder.
+- The NVENC file is slightly larger at the same settings (21.7 vs 20.4 MB). The bitrate is not
+ matched, so these rows are not a quality comparison.
+
+Quality at equal bitrate: see the PR description.
+
+ ## Results (HW2 follow-up: Windows VP9 and AV1 hardware decoding, Off → Auto)
+
+ Same machine and method as the H.264 / HEVC results above (Xeon E5-2680 v4, RTX 5060 driver 617.14,
+ idle, 2026-10-07, two alternating rounds of `--hw off` / `--hw auto`, the same binary). MFTs:
+ `VP9VideoExtensionDecoder` and `AV1VideoExtension` (Microsoft Store codec extensions), DXVA on the
+ GPU's NVDEC (profiles VP9 0 / 2, AV1 main). AV1 fixtures here are libaom (`libsvtav1` is not in this
+ ffmpeg build; the bench falls back to it) and VP9 are libvpx-vp9, as in the bench's `dec_*` specs.
+ `cargo xtask bench --sections decode --only dec_vp9 --repeat 3 --hw off|auto` (likewise `dec_av1`),
+ `--sections playback --only "av1-2160 full" --hw off|auto`.
+
+ | codec | size | CPU ms/frame Off → **Auto** | fps Off → **Auto** (best of 3) |
+ |---|---|---|---|
+ | VP9 | 1080p | 38-43 → **3.5-3.6** | 60 → **281-283** |
+ | VP9 | 2160p | 165-169 → **15-16** | 16 → **70-79** |
+ | AV1 | 1080p | 55-56 → **3.3-3.4** | 22 → **373-374** |
+ | AV1 | 2160p | 219-221 → **10.9-11.3** | 5.5 → **106-107** |
+
+ Every Auto row had `hw frames` = frames × 3 repeats, 3 sessions, 0 fallbacks, 0 declined.
+
+ | playback 8 s, Full | shown/dropped Off → **Auto** | CPU ms/frame Off → **Auto** |
+ |---|---|---|
+ | VP9 2160p | 11-12/180-181 → **191/1** | 117-124 → **24-27** |
+ | AV1 2160p | 0/192 → **192/0** | 47.5-47.9 → **17-20** |
+
+ Software AV1 decodes 4K at 5.5 fps here, so it never plays in real time; with the hardware decoder it
+ plays without a drop. As on the other codecs, the hardware ignores draft mode and what is left on the
+ CPU is the readback and plane conversion.
+
## Results (GPU1: blend modes on the GPU compositor, #30, before → after)
Before = this change with the old whole-frame CPU fallback for non-Normal blend modes put back
diff --cc docs/testing.md
index e080ba6e2,bb99de045..a1640bbbf
--- a/docs/testing.md
+++ b/docs/testing.md
@@@ -68,14 -68,9 +68,15 @@@ are never linked or shipped ([AGENTS.md
H.264 and HEVC fixtures need ffmpeg built with libx264 and libx265. VideoToolbox fixtures are
generated only on macOS. The Media Foundation parity tests (`crates/platform/tests/media_foundation.rs`,
Windows only) make their 640x360, 1080p and 2160p H.264 / HEVC / Main 10 fixtures with ffmpeg and skip
- without a Direct3D 11 video device or the HEVC Video Extensions.
+ without a Direct3D 11 video device or the HEVC / VP9 / AV1 codec extensions of the Microsoft Store. The VP9 and
+ AV1 fixtures (libvpx-vp9, libaom-av1; 360p, 1080p, 2160p, hidden alt-ref frames, two GOPs) need an ffmpeg with those encoders.
+The NVENC tests (`crates/platform/tests/nvenc.rs` and `nvenc_export.rs`, Windows only) skip without an
+NVIDIA GPU with NVENC. The FFI layout tests in `crates/platform/src/nvenc/abi_tests.rs` were generated
+from a C program built with MSVC against NVIDIA's MIT-licensed `nvEncodeAPI.h` (12.1); to regenerate
+them, print the sizes, alignments, offsets, constants and GUIDs of `src/nvenc/ffi.rs` from that
+program and update the asserts.
+
### Pass criteria per codec
| Crate | Oracle check | Criterion |