FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Windows: NVENC H.264 hardware encoding for Export (work in progress, #30)
Davi Andrei6db932a9ba53
diff --git a/Cargo.lock b/Cargo.lockindex 7505dec2d..072b03849 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2099,9 +2099,12 @@ version = "0.2.1"dependencies = ["filmcraft-codecs","filmcraft-color",+ "filmcraft-export","filmcraft-frame","filmcraft-isobmff","filmcraft-media",+ "filmcraft-project",+ "filmcraft-render","filmcraft-testkit","filmcraft-time","log",diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 9da455f04..2c1b641fb 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1017,7 +1017,7 @@ fn build() -> Vec<CommandSpec> {"Media…",["File", "Export"],None,- r#"{"path":str,"preset":str?,"settings":ExportSettings?,"format":"h264|prores|dnxhr|apv|mjpeg|mxf-op1a|mxf-opatom|png|tiff|bmp|gif|wav|aiff"?,"width":u32?,"height":u32?,"fps":f64?,"bitrateKbps":u32?,"bitrateMode":"cbr|vbr1Pass|vbr2Pass"?,"scale":f32=1,"audio":bool=true,"quality":0..100,"burnCaptions":bool=false,"captionSidecar":"srt|vtt"?,"loudnessLufs":f64?,"proresProfile":"proxy|lt|standard|hq"?,"dnxProfile":"lb|sq|hq|hqx"?,"apvProfile":"422-10|422-12|444-10|444-12"?,"mxfVideoCodec":"dnxhr|proRes|h264"?,"sequence":id?,"range":"entire|inOut|workArea|custom"?,"startSeconds":f64?,"endSeconds":f64?,"wait":bool=false}"#,+ r#"{"path":str,"preset":str?,"settings":ExportSettings?,"format":"h264|prores|dnxhr|apv|mjpeg|mxf-op1a|mxf-opatom|png|tiff|bmp|gif|wav|aiff"?,"width":u32?,"height":u32?,"fps":f64?,"bitrateKbps":u32?,"bitrateMode":"cbr|vbr1Pass|vbr2Pass"?,"hardwareEncoding":"off|auto"?,"scale":f32=1,"audio":bool=true,"quality":0..100,"burnCaptions":bool=false,"captionSidecar":"srt|vtt"?,"loudnessLufs":f64?,"proresProfile":"proxy|lt|standard|hq"?,"dnxProfile":"lb|sq|hq|hqx"?,"apvProfile":"422-10|422-12|444-10|444-12"?,"mxfVideoCodec":"dnxhr|proRes|h264"?,"sequence":id?,"range":"entire|inOut|workArea|custom"?,"startSeconds":f64?,"endSeconds":f64?,"wait":bool=false}"#,has_seq,crate::export_tools::export_media),diff --git a/crates/engine/src/export_tools.rs b/crates/engine/src/export_tools.rsindex a6cee1284..768065baf 100644--- a/crates/engine/src/export_tools.rs+++ b/crates/engine/src/export_tools.rs@@ -197,6 +197,9 @@ pub fn settings_from_params(s: &Session, p: &Value, cmd: &str) -> Result<(Optionif let Some(v) = str_p(p, "bitrateMode") {settings.bitrate_mode = serde_json::from_value(json!(v)).map_err(|_| bad(cmd, "bitrateMode: cbr | vbr1Pass | vbr2Pass"))?;}+ if let Some(v) = str_p(p, "hardwareEncoding") {+ settings.hardware_encoding = serde_json::from_value(json!(v)).map_err(|_| bad(cmd, "hardwareEncoding: off | auto"))?;+ }if let Some(v) = u64_p(p, "keyframeDistance") {settings.keyframe_distance = Some(v as u32);}diff --git a/crates/engine/src/perf.rs b/crates/engine/src/perf.rsindex 947246b28..c909b50ea 100644--- a/crates/engine/src/perf.rs+++ b/crates/engine/src/perf.rs@@ -48,11 +48,18 @@ pub fn decode_json() -> Value {})}+/// Export counters: pictures encoded by hardware encoders, sessions, declined requests.+pub fn export_json() -> Value {+ let hw = filmcraft_export::hw_encode_stats();+ json!({"hardware": {"frames": hw.frames, "sessions": hw.sessions, "declined": hw.declined}})+}+/// The engine's `perf.stats`.pub fn stats(s: &Session) -> Value {let running = s.jobs.iter().filter(|j| j.result.lock().map(|r| r.is_none()).unwrap_or(false)).count();json!({"decode": decode_json(),+ "export": export_json(),"media": {"openSources": s.media.open_sources()},"jobs": {"total": s.jobs.len(), "running": running},})@@ -95,6 +102,9 @@ mod tests {}assert!(v["decode"]["hardware"]["enabled"].is_boolean());assert!(v["decode"]["hardware"]["backend"].is_null() || v["decode"]["hardware"]["backend"].is_string());+ for k in ["frames", "sessions", "declined"] {+ assert!(v["export"]["hardware"][k].is_number(), "export.hardware.{k} in {v}");+ }assert!(v["media"]["openSources"].is_number());assert_eq!(v["jobs"]["running"], json!(0));assert_eq!(s.history.undo.len(), undo, "a query adds no undo step");diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex d50e1f30c..ff0f85768 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -248,6 +248,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.+ #[serde(default)]+ pub hardware_encoding: HardwareEncoding,/// VBR maximum bitrate (None = 1.5 × target).pub max_bitrate_kbps: Option<u32>,/// Adaptive bitrate (the Match Source presets): bits per pixel per frame; replaces@@ -429,6 +432,7 @@ impl Default for ExportSettings {h264_profile: H264Profile::High,h264_level: None,bitrate_mode: BitrateMode::default(),+ hardware_encoding: HardwareEncoding::default(),max_bitrate_kbps: None,adaptive_bitrate: None,keyframe_distance: None,@@ -553,6 +557,41 @@ fn audio_factories() -> &'static RwLock<Vec<AudioEncoderFactory>> {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);+}+pub fn register_encoder(f: EncoderFactory) {video_factories().write().unwrap_or_else(|e| e.into_inner()).insert(0, f);}diff --git a/crates/export/src/settings.rs b/crates/export/src/settings.rsindex 76a4443e7..06b7a904e 100644--- a/crates/export/src/settings.rs+++ b/crates/export/src/settings.rs@@ -61,6 +61,20 @@ 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.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum HardwareEncoding {+ #[default]+ Off,+ /// Use the hardware encoder when the system has one and it takes the settings; otherwise the+ /// software encoder.+ Auto,+}+/// Bitrate encoding of bitrate-driven codecs (H.264).#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]diff --git a/crates/platform/Cargo.toml b/crates/platform/Cargo.tomlindex 128b1b0c0..f52c12906 100644--- a/crates/platform/Cargo.toml+++ b/crates/platform/Cargo.toml@@ -23,6 +23,7 @@ undocumented_unsafe_blocks = "deny"[dependencies]filmcraft-codecs = { workspace = true }filmcraft-color = { workspace = true }+filmcraft-export = { workspace = true }filmcraft-frame = { workspace = true }filmcraft-isobmff = { workspace = true }filmcraft-time = { workspace = true }@@ -52,3 +53,5 @@ windows = { version = "0.62", features = [filmcraft-testkit = { workspace = true }filmcraft-media = { workspace = true }filmcraft-frame = { workspace = true }+filmcraft-project = { workspace = true }+filmcraft-render = { workspace = true }diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rsindex e89f4fedb..15b624da4 100644--- a/crates/platform/src/lib.rs+++ b/crates/platform/src/lib.rs@@ -27,6 +27,8 @@ mod biplanar;pub mod hybrid;#[cfg(target_os = "windows")]pub mod media_foundation;+#[cfg(target_os = "windows")]+pub mod nvenc;#[cfg(target_os = "macos")]#[allow(unsafe_code)]pub mod videotoolbox;@@ -54,6 +56,10 @@ pub fn register() -> Availability {}#[cfg(target_os = "windows")]{+ static ENCODERS: std::sync::Once = std::sync::Once::new();+ // Export ▸ Hardware encoding (NVENC H.264): in front of the software encoder, taking an+ // export only when asked for and when NVENC can do it+ ENCODERS.call_once(|| filmcraft_export::register_encoder(nvenc::export::factory));filmcraft_codecs::register_video_decoder(media_foundation_factory);filmcraft_codecs::hw::set_hw_backend("Media Foundation");Availability::Available("Media Foundation")diff --git a/crates/platform/src/nvenc/abi_tests.rs b/crates/platform/src/nvenc/abi_tests.rsnew file mode 100644index 000000000..20b9e9907--- /dev/null+++ b/crates/platform/src/nvenc/abi_tests.rs@@ -0,0 +1,367 @@+//! The NVENC FFI structures against the C compiler's view of `nvEncodeAPI.h` (API 12.1): sizes,+//! alignments, field offsets, constants and GUIDs. Generated by running a C program (built with+//! MSVC from the NVIDIA header) that prints them; the header itself is not in this repository.+//! To regenerate, put NVIDIA's MIT-licensed `nvEncodeAPI.h` 12.1 in `ffnvcodec/` next to a program+//! printing `sizeof` / `offsetof` of the structures of `src/nvenc/ffi.rs` and the constants it uses.+#![allow(clippy::unreadable_literal)]++use super::ffi::*;+use std::mem::{align_of, offset_of, size_of};++#[test]+fn layouts_match_the_header() {+ assert_eq!(+ (size_of::<NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS>(), align_of::<NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS>()),+ (1552, 8),+ "NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS"+ );+ assert_eq!(offset_of!(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS, version), 0, "NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS.version");+ assert_eq!(offset_of!(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS, deviceType), 4, "NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS.deviceType");+ assert_eq!(offset_of!(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS, device), 8, "NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS.device");+ assert_eq!(offset_of!(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS, reserved), 16, "NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS.reserved");+ assert_eq!(offset_of!(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS, apiVersion), 24, "NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS.apiVersion");+ assert_eq!(offset_of!(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS, reserved1), 28, "NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS.reserved1");+ assert_eq!(offset_of!(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS, reserved2), 1040, "NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS.reserved2");+ assert_eq!((size_of::<NV_ENC_CAPS_PARAM>(), align_of::<NV_ENC_CAPS_PARAM>()), (256, 4), "NV_ENC_CAPS_PARAM");+ assert_eq!(offset_of!(NV_ENC_CAPS_PARAM, version), 0, "NV_ENC_CAPS_PARAM.version");+ assert_eq!(offset_of!(NV_ENC_CAPS_PARAM, capsToQuery), 4, "NV_ENC_CAPS_PARAM.capsToQuery");+ assert_eq!(offset_of!(NV_ENC_CAPS_PARAM, reserved), 8, "NV_ENC_CAPS_PARAM.reserved");+ assert_eq!((size_of::<NV_ENC_QP>(), align_of::<NV_ENC_QP>()), (12, 4), "NV_ENC_QP");+ assert_eq!(offset_of!(NV_ENC_QP, qpInterP), 0, "NV_ENC_QP.qpInterP");+ assert_eq!(offset_of!(NV_ENC_QP, qpInterB), 4, "NV_ENC_QP.qpInterB");+ assert_eq!(offset_of!(NV_ENC_QP, qpIntra), 8, "NV_ENC_QP.qpIntra");+ assert_eq!((size_of::<NV_ENC_RC_PARAMS>(), align_of::<NV_ENC_RC_PARAMS>()), (128, 4), "NV_ENC_RC_PARAMS");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, version), 0, "NV_ENC_RC_PARAMS.version");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, rateControlMode), 4, "NV_ENC_RC_PARAMS.rateControlMode");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, constQP), 8, "NV_ENC_RC_PARAMS.constQP");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, averageBitRate), 20, "NV_ENC_RC_PARAMS.averageBitRate");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, maxBitRate), 24, "NV_ENC_RC_PARAMS.maxBitRate");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, vbvBufferSize), 28, "NV_ENC_RC_PARAMS.vbvBufferSize");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, vbvInitialDelay), 32, "NV_ENC_RC_PARAMS.vbvInitialDelay");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, minQP), 40, "NV_ENC_RC_PARAMS.minQP");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, maxQP), 52, "NV_ENC_RC_PARAMS.maxQP");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, initialRCQP), 64, "NV_ENC_RC_PARAMS.initialRCQP");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, temporallayerIdxMask), 76, "NV_ENC_RC_PARAMS.temporallayerIdxMask");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, temporalLayerQP), 80, "NV_ENC_RC_PARAMS.temporalLayerQP");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, targetQuality), 88, "NV_ENC_RC_PARAMS.targetQuality");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, targetQualityLSB), 89, "NV_ENC_RC_PARAMS.targetQualityLSB");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, lookaheadDepth), 90, "NV_ENC_RC_PARAMS.lookaheadDepth");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, lowDelayKeyFrameScale), 92, "NV_ENC_RC_PARAMS.lowDelayKeyFrameScale");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, yDcQPIndexOffset), 93, "NV_ENC_RC_PARAMS.yDcQPIndexOffset");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, uDcQPIndexOffset), 94, "NV_ENC_RC_PARAMS.uDcQPIndexOffset");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, vDcQPIndexOffset), 95, "NV_ENC_RC_PARAMS.vDcQPIndexOffset");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, qpMapMode), 96, "NV_ENC_RC_PARAMS.qpMapMode");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, multiPass), 100, "NV_ENC_RC_PARAMS.multiPass");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, alphaLayerBitrateRatio), 104, "NV_ENC_RC_PARAMS.alphaLayerBitrateRatio");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, cbQPIndexOffset), 108, "NV_ENC_RC_PARAMS.cbQPIndexOffset");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, crQPIndexOffset), 109, "NV_ENC_RC_PARAMS.crQPIndexOffset");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, reserved2), 110, "NV_ENC_RC_PARAMS.reserved2");+ assert_eq!(offset_of!(NV_ENC_RC_PARAMS, reserved), 112, "NV_ENC_RC_PARAMS.reserved");+ assert_eq!(+ (size_of::<NV_ENC_CONFIG_H264_VUI_PARAMETERS>(), align_of::<NV_ENC_CONFIG_H264_VUI_PARAMETERS>()),+ (112, 4),+ "NV_ENC_CONFIG_H264_VUI_PARAMETERS"+ );+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, overscanInfoPresentFlag), 0, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.overscanInfoPresentFlag");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, overscanInfo), 4, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.overscanInfo");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, videoSignalTypePresentFlag), 8, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.videoSignalTypePresentFlag");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, videoFormat), 12, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.videoFormat");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, videoFullRangeFlag), 16, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.videoFullRangeFlag");+ assert_eq!(+ offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, colourDescriptionPresentFlag),+ 20,+ "NV_ENC_CONFIG_H264_VUI_PARAMETERS.colourDescriptionPresentFlag"+ );+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, colourPrimaries), 24, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.colourPrimaries");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, transferCharacteristics), 28, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.transferCharacteristics");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, colourMatrix), 32, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.colourMatrix");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, chromaSampleLocationFlag), 36, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.chromaSampleLocationFlag");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, chromaSampleLocationTop), 40, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.chromaSampleLocationTop");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, chromaSampleLocationBot), 44, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.chromaSampleLocationBot");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, bitstreamRestrictionFlag), 48, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.bitstreamRestrictionFlag");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, timingInfoPresentFlag), 52, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.timingInfoPresentFlag");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, numUnitInTicks), 56, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.numUnitInTicks");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, timeScale), 60, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.timeScale");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264_VUI_PARAMETERS, reserved), 64, "NV_ENC_CONFIG_H264_VUI_PARAMETERS.reserved");+ assert_eq!((size_of::<NV_ENC_CONFIG_H264>(), align_of::<NV_ENC_CONFIG_H264>()), (1792, 8), "NV_ENC_CONFIG_H264");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, level), 4, "NV_ENC_CONFIG_H264.level");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, idrPeriod), 8, "NV_ENC_CONFIG_H264.idrPeriod");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, separateColourPlaneFlag), 12, "NV_ENC_CONFIG_H264.separateColourPlaneFlag");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, disableDeblockingFilterIDC), 16, "NV_ENC_CONFIG_H264.disableDeblockingFilterIDC");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, numTemporalLayers), 20, "NV_ENC_CONFIG_H264.numTemporalLayers");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, spsId), 24, "NV_ENC_CONFIG_H264.spsId");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, ppsId), 28, "NV_ENC_CONFIG_H264.ppsId");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, adaptiveTransformMode), 32, "NV_ENC_CONFIG_H264.adaptiveTransformMode");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, fmoMode), 36, "NV_ENC_CONFIG_H264.fmoMode");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, bdirectMode), 40, "NV_ENC_CONFIG_H264.bdirectMode");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, entropyCodingMode), 44, "NV_ENC_CONFIG_H264.entropyCodingMode");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, stereoMode), 48, "NV_ENC_CONFIG_H264.stereoMode");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, intraRefreshPeriod), 52, "NV_ENC_CONFIG_H264.intraRefreshPeriod");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, intraRefreshCnt), 56, "NV_ENC_CONFIG_H264.intraRefreshCnt");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, maxNumRefFrames), 60, "NV_ENC_CONFIG_H264.maxNumRefFrames");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, sliceMode), 64, "NV_ENC_CONFIG_H264.sliceMode");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, sliceModeData), 68, "NV_ENC_CONFIG_H264.sliceModeData");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, h264VUIParameters), 72, "NV_ENC_CONFIG_H264.h264VUIParameters");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, ltrNumFrames), 184, "NV_ENC_CONFIG_H264.ltrNumFrames");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, ltrTrustMode), 188, "NV_ENC_CONFIG_H264.ltrTrustMode");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, chromaFormatIDC), 192, "NV_ENC_CONFIG_H264.chromaFormatIDC");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, maxTemporalLayers), 196, "NV_ENC_CONFIG_H264.maxTemporalLayers");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, useBFramesAsRef), 200, "NV_ENC_CONFIG_H264.useBFramesAsRef");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, numRefL0), 204, "NV_ENC_CONFIG_H264.numRefL0");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, numRefL1), 208, "NV_ENC_CONFIG_H264.numRefL1");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, reserved1), 212, "NV_ENC_CONFIG_H264.reserved1");+ assert_eq!(offset_of!(NV_ENC_CONFIG_H264, reserved2), 1280, "NV_ENC_CONFIG_H264.reserved2");+ assert_eq!((size_of::<NV_ENC_CODEC_CONFIG>(), align_of::<NV_ENC_CODEC_CONFIG>()), (1792, 8), "NV_ENC_CODEC_CONFIG");+ assert_eq!(offset_of!(NV_ENC_CODEC_CONFIG, h264Config), 0, "NV_ENC_CODEC_CONFIG.h264Config");+ assert_eq!(offset_of!(NV_ENC_CODEC_CONFIG, reserved), 0, "NV_ENC_CODEC_CONFIG.reserved");+ assert_eq!((size_of::<NV_ENC_CONFIG>(), align_of::<NV_ENC_CONFIG>()), (3584, 8), "NV_ENC_CONFIG");+ assert_eq!(offset_of!(NV_ENC_CONFIG, version), 0, "NV_ENC_CONFIG.version");+ assert_eq!(offset_of!(NV_ENC_CONFIG, profileGUID), 4, "NV_ENC_CONFIG.profileGUID");+ assert_eq!(offset_of!(NV_ENC_CONFIG, gopLength), 20, "NV_ENC_CONFIG.gopLength");+ assert_eq!(offset_of!(NV_ENC_CONFIG, frameIntervalP), 24, "NV_ENC_CONFIG.frameIntervalP");+ assert_eq!(offset_of!(NV_ENC_CONFIG, monoChromeEncoding), 28, "NV_ENC_CONFIG.monoChromeEncoding");+ assert_eq!(offset_of!(NV_ENC_CONFIG, frameFieldMode), 32, "NV_ENC_CONFIG.frameFieldMode");+ assert_eq!(offset_of!(NV_ENC_CONFIG, mvPrecision), 36, "NV_ENC_CONFIG.mvPrecision");+ assert_eq!(offset_of!(NV_ENC_CONFIG, rcParams), 40, "NV_ENC_CONFIG.rcParams");+ assert_eq!(offset_of!(NV_ENC_CONFIG, encodeCodecConfig), 168, "NV_ENC_CONFIG.encodeCodecConfig");+ assert_eq!(offset_of!(NV_ENC_CONFIG, reserved), 1960, "NV_ENC_CONFIG.reserved");+ assert_eq!(offset_of!(NV_ENC_CONFIG, reserved2), 3072, "NV_ENC_CONFIG.reserved2");+ assert_eq!((size_of::<NV_ENC_PRESET_CONFIG>(), align_of::<NV_ENC_PRESET_CONFIG>()), (5128, 8), "NV_ENC_PRESET_CONFIG");+ assert_eq!(offset_of!(NV_ENC_PRESET_CONFIG, version), 0, "NV_ENC_PRESET_CONFIG.version");+ assert_eq!(offset_of!(NV_ENC_PRESET_CONFIG, presetCfg), 8, "NV_ENC_PRESET_CONFIG.presetCfg");+ assert_eq!(offset_of!(NV_ENC_PRESET_CONFIG, reserved1), 3592, "NV_ENC_PRESET_CONFIG.reserved1");+ assert_eq!(offset_of!(NV_ENC_PRESET_CONFIG, reserved2), 4616, "NV_ENC_PRESET_CONFIG.reserved2");+ assert_eq!(+ (size_of::<NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE>(), align_of::<NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE>()),+ (16, 4),+ "NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE"+ );+ assert_eq!(offset_of!(NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE, reserved1), 4, "NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE.reserved1");+ assert_eq!((size_of::<NV_ENC_INITIALIZE_PARAMS>(), align_of::<NV_ENC_INITIALIZE_PARAMS>()), (1808, 8), "NV_ENC_INITIALIZE_PARAMS");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, version), 0, "NV_ENC_INITIALIZE_PARAMS.version");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, encodeGUID), 4, "NV_ENC_INITIALIZE_PARAMS.encodeGUID");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, presetGUID), 20, "NV_ENC_INITIALIZE_PARAMS.presetGUID");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, encodeWidth), 36, "NV_ENC_INITIALIZE_PARAMS.encodeWidth");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, encodeHeight), 40, "NV_ENC_INITIALIZE_PARAMS.encodeHeight");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, darWidth), 44, "NV_ENC_INITIALIZE_PARAMS.darWidth");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, darHeight), 48, "NV_ENC_INITIALIZE_PARAMS.darHeight");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, frameRateNum), 52, "NV_ENC_INITIALIZE_PARAMS.frameRateNum");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, frameRateDen), 56, "NV_ENC_INITIALIZE_PARAMS.frameRateDen");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, enableEncodeAsync), 60, "NV_ENC_INITIALIZE_PARAMS.enableEncodeAsync");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, enablePTD), 64, "NV_ENC_INITIALIZE_PARAMS.enablePTD");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, privDataSize), 72, "NV_ENC_INITIALIZE_PARAMS.privDataSize");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, privData), 80, "NV_ENC_INITIALIZE_PARAMS.privData");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, encodeConfig), 88, "NV_ENC_INITIALIZE_PARAMS.encodeConfig");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, maxEncodeWidth), 96, "NV_ENC_INITIALIZE_PARAMS.maxEncodeWidth");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, maxEncodeHeight), 100, "NV_ENC_INITIALIZE_PARAMS.maxEncodeHeight");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, maxMEHintCountsPerBlock), 104, "NV_ENC_INITIALIZE_PARAMS.maxMEHintCountsPerBlock");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, tuningInfo), 136, "NV_ENC_INITIALIZE_PARAMS.tuningInfo");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, bufferFormat), 140, "NV_ENC_INITIALIZE_PARAMS.bufferFormat");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, numStateBuffers), 144, "NV_ENC_INITIALIZE_PARAMS.numStateBuffers");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, outputStatsLevel), 148, "NV_ENC_INITIALIZE_PARAMS.outputStatsLevel");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, reserved), 152, "NV_ENC_INITIALIZE_PARAMS.reserved");+ assert_eq!(offset_of!(NV_ENC_INITIALIZE_PARAMS, reserved2), 1296, "NV_ENC_INITIALIZE_PARAMS.reserved2");+ assert_eq!((size_of::<NV_ENC_CREATE_INPUT_BUFFER>(), align_of::<NV_ENC_CREATE_INPUT_BUFFER>()), (776, 8), "NV_ENC_CREATE_INPUT_BUFFER");+ assert_eq!(offset_of!(NV_ENC_CREATE_INPUT_BUFFER, version), 0, "NV_ENC_CREATE_INPUT_BUFFER.version");+ assert_eq!(offset_of!(NV_ENC_CREATE_INPUT_BUFFER, width), 4, "NV_ENC_CREATE_INPUT_BUFFER.width");+ assert_eq!(offset_of!(NV_ENC_CREATE_INPUT_BUFFER, height), 8, "NV_ENC_CREATE_INPUT_BUFFER.height");+ assert_eq!(offset_of!(NV_ENC_CREATE_INPUT_BUFFER, memoryHeap), 12, "NV_ENC_CREATE_INPUT_BUFFER.memoryHeap");+ assert_eq!(offset_of!(NV_ENC_CREATE_INPUT_BUFFER, bufferFmt), 16, "NV_ENC_CREATE_INPUT_BUFFER.bufferFmt");+ assert_eq!(offset_of!(NV_ENC_CREATE_INPUT_BUFFER, reserved), 20, "NV_ENC_CREATE_INPUT_BUFFER.reserved");+ assert_eq!(offset_of!(NV_ENC_CREATE_INPUT_BUFFER, inputBuffer), 24, "NV_ENC_CREATE_INPUT_BUFFER.inputBuffer");+ assert_eq!(offset_of!(NV_ENC_CREATE_INPUT_BUFFER, pSysMemBuffer), 32, "NV_ENC_CREATE_INPUT_BUFFER.pSysMemBuffer");+ assert_eq!(offset_of!(NV_ENC_CREATE_INPUT_BUFFER, reserved1), 40, "NV_ENC_CREATE_INPUT_BUFFER.reserved1");+ assert_eq!(offset_of!(NV_ENC_CREATE_INPUT_BUFFER, reserved2), 272, "NV_ENC_CREATE_INPUT_BUFFER.reserved2");+ assert_eq!((size_of::<NV_ENC_CREATE_BITSTREAM_BUFFER>(), align_of::<NV_ENC_CREATE_BITSTREAM_BUFFER>()), (776, 8), "NV_ENC_CREATE_BITSTREAM_BUFFER");+ assert_eq!(offset_of!(NV_ENC_CREATE_BITSTREAM_BUFFER, version), 0, "NV_ENC_CREATE_BITSTREAM_BUFFER.version");+ assert_eq!(offset_of!(NV_ENC_CREATE_BITSTREAM_BUFFER, size), 4, "NV_ENC_CREATE_BITSTREAM_BUFFER.size");+ assert_eq!(offset_of!(NV_ENC_CREATE_BITSTREAM_BUFFER, memoryHeap), 8, "NV_ENC_CREATE_BITSTREAM_BUFFER.memoryHeap");+ assert_eq!(offset_of!(NV_ENC_CREATE_BITSTREAM_BUFFER, reserved), 12, "NV_ENC_CREATE_BITSTREAM_BUFFER.reserved");+ assert_eq!(offset_of!(NV_ENC_CREATE_BITSTREAM_BUFFER, bitstreamBuffer), 16, "NV_ENC_CREATE_BITSTREAM_BUFFER.bitstreamBuffer");+ assert_eq!(offset_of!(NV_ENC_CREATE_BITSTREAM_BUFFER, bitstreamBufferPtr), 24, "NV_ENC_CREATE_BITSTREAM_BUFFER.bitstreamBufferPtr");+ assert_eq!(offset_of!(NV_ENC_CREATE_BITSTREAM_BUFFER, reserved1), 32, "NV_ENC_CREATE_BITSTREAM_BUFFER.reserved1");+ assert_eq!(offset_of!(NV_ENC_CREATE_BITSTREAM_BUFFER, reserved2), 264, "NV_ENC_CREATE_BITSTREAM_BUFFER.reserved2");+ assert_eq!((size_of::<NV_ENC_CODEC_PIC_PARAMS>(), align_of::<NV_ENC_CODEC_PIC_PARAMS>()), (1552, 8), "NV_ENC_CODEC_PIC_PARAMS");+ assert_eq!((size_of::<NV_ENC_PIC_PARAMS>(), align_of::<NV_ENC_PIC_PARAMS>()), (3360, 8), "NV_ENC_PIC_PARAMS");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, version), 0, "NV_ENC_PIC_PARAMS.version");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, inputWidth), 4, "NV_ENC_PIC_PARAMS.inputWidth");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, inputHeight), 8, "NV_ENC_PIC_PARAMS.inputHeight");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, inputPitch), 12, "NV_ENC_PIC_PARAMS.inputPitch");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, encodePicFlags), 16, "NV_ENC_PIC_PARAMS.encodePicFlags");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, frameIdx), 20, "NV_ENC_PIC_PARAMS.frameIdx");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, inputTimeStamp), 24, "NV_ENC_PIC_PARAMS.inputTimeStamp");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, inputDuration), 32, "NV_ENC_PIC_PARAMS.inputDuration");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, inputBuffer), 40, "NV_ENC_PIC_PARAMS.inputBuffer");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, outputBitstream), 48, "NV_ENC_PIC_PARAMS.outputBitstream");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, completionEvent), 56, "NV_ENC_PIC_PARAMS.completionEvent");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, bufferFmt), 64, "NV_ENC_PIC_PARAMS.bufferFmt");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, pictureStruct), 68, "NV_ENC_PIC_PARAMS.pictureStruct");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, pictureType), 72, "NV_ENC_PIC_PARAMS.pictureType");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, codecPicParams), 80, "NV_ENC_PIC_PARAMS.codecPicParams");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, meHintCountsPerBlock), 1632, "NV_ENC_PIC_PARAMS.meHintCountsPerBlock");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, meExternalHints), 1664, "NV_ENC_PIC_PARAMS.meExternalHints");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, reserved1), 1672, "NV_ENC_PIC_PARAMS.reserved1");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, reserved2), 1696, "NV_ENC_PIC_PARAMS.reserved2");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, qpDeltaMap), 1712, "NV_ENC_PIC_PARAMS.qpDeltaMap");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, qpDeltaMapSize), 1720, "NV_ENC_PIC_PARAMS.qpDeltaMapSize");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, reservedBitFields), 1724, "NV_ENC_PIC_PARAMS.reservedBitFields");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, meHintRefPicDist), 1728, "NV_ENC_PIC_PARAMS.meHintRefPicDist");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, alphaBuffer), 1736, "NV_ENC_PIC_PARAMS.alphaBuffer");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, meExternalSbHints), 1744, "NV_ENC_PIC_PARAMS.meExternalSbHints");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, meSbHintsCount), 1752, "NV_ENC_PIC_PARAMS.meSbHintsCount");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, stateBufferIdx), 1756, "NV_ENC_PIC_PARAMS.stateBufferIdx");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, outputReconBuffer), 1760, "NV_ENC_PIC_PARAMS.outputReconBuffer");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, reserved3), 1768, "NV_ENC_PIC_PARAMS.reserved3");+ assert_eq!(offset_of!(NV_ENC_PIC_PARAMS, reserved4), 2904, "NV_ENC_PIC_PARAMS.reserved4");+ assert_eq!((size_of::<NV_ENC_LOCK_BITSTREAM>(), align_of::<NV_ENC_LOCK_BITSTREAM>()), (1552, 8), "NV_ENC_LOCK_BITSTREAM");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, version), 0, "NV_ENC_LOCK_BITSTREAM.version");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, outputBitstream), 8, "NV_ENC_LOCK_BITSTREAM.outputBitstream");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, sliceOffsets), 16, "NV_ENC_LOCK_BITSTREAM.sliceOffsets");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, frameIdx), 24, "NV_ENC_LOCK_BITSTREAM.frameIdx");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, hwEncodeStatus), 28, "NV_ENC_LOCK_BITSTREAM.hwEncodeStatus");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, numSlices), 32, "NV_ENC_LOCK_BITSTREAM.numSlices");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, bitstreamSizeInBytes), 36, "NV_ENC_LOCK_BITSTREAM.bitstreamSizeInBytes");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, outputTimeStamp), 40, "NV_ENC_LOCK_BITSTREAM.outputTimeStamp");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, outputDuration), 48, "NV_ENC_LOCK_BITSTREAM.outputDuration");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, bitstreamBufferPtr), 56, "NV_ENC_LOCK_BITSTREAM.bitstreamBufferPtr");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, pictureType), 64, "NV_ENC_LOCK_BITSTREAM.pictureType");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, pictureStruct), 68, "NV_ENC_LOCK_BITSTREAM.pictureStruct");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, frameAvgQP), 72, "NV_ENC_LOCK_BITSTREAM.frameAvgQP");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, frameSatd), 76, "NV_ENC_LOCK_BITSTREAM.frameSatd");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, ltrFrameIdx), 80, "NV_ENC_LOCK_BITSTREAM.ltrFrameIdx");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, ltrFrameBitmap), 84, "NV_ENC_LOCK_BITSTREAM.ltrFrameBitmap");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, temporalId), 88, "NV_ENC_LOCK_BITSTREAM.temporalId");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, intraMBCount), 92, "NV_ENC_LOCK_BITSTREAM.intraMBCount");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, interMBCount), 96, "NV_ENC_LOCK_BITSTREAM.interMBCount");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, averageMVX), 100, "NV_ENC_LOCK_BITSTREAM.averageMVX");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, averageMVY), 104, "NV_ENC_LOCK_BITSTREAM.averageMVY");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, alphaLayerSizeInBytes), 108, "NV_ENC_LOCK_BITSTREAM.alphaLayerSizeInBytes");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, outputStatsPtrSize), 112, "NV_ENC_LOCK_BITSTREAM.outputStatsPtrSize");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, outputStatsPtr), 120, "NV_ENC_LOCK_BITSTREAM.outputStatsPtr");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, frameIdxDisplay), 128, "NV_ENC_LOCK_BITSTREAM.frameIdxDisplay");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, reserved1), 132, "NV_ENC_LOCK_BITSTREAM.reserved1");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, reserved2), 1016, "NV_ENC_LOCK_BITSTREAM.reserved2");+ assert_eq!(offset_of!(NV_ENC_LOCK_BITSTREAM, reservedInternal), 1520, "NV_ENC_LOCK_BITSTREAM.reservedInternal");+ assert_eq!((size_of::<NV_ENC_LOCK_INPUT_BUFFER>(), align_of::<NV_ENC_LOCK_INPUT_BUFFER>()), (1544, 8), "NV_ENC_LOCK_INPUT_BUFFER");+ assert_eq!(offset_of!(NV_ENC_LOCK_INPUT_BUFFER, version), 0, "NV_ENC_LOCK_INPUT_BUFFER.version");+ assert_eq!(offset_of!(NV_ENC_LOCK_INPUT_BUFFER, inputBuffer), 8, "NV_ENC_LOCK_INPUT_BUFFER.inputBuffer");+ assert_eq!(offset_of!(NV_ENC_LOCK_INPUT_BUFFER, bufferDataPtr), 16, "NV_ENC_LOCK_INPUT_BUFFER.bufferDataPtr");+ assert_eq!(offset_of!(NV_ENC_LOCK_INPUT_BUFFER, pitch), 24, "NV_ENC_LOCK_INPUT_BUFFER.pitch");+ assert_eq!(offset_of!(NV_ENC_LOCK_INPUT_BUFFER, reserved1), 28, "NV_ENC_LOCK_INPUT_BUFFER.reserved1");+ assert_eq!(offset_of!(NV_ENC_LOCK_INPUT_BUFFER, reserved2), 1032, "NV_ENC_LOCK_INPUT_BUFFER.reserved2");+ assert_eq!((size_of::<NV_ENC_SEQUENCE_PARAM_PAYLOAD>(), align_of::<NV_ENC_SEQUENCE_PARAM_PAYLOAD>()), (1544, 8), "NV_ENC_SEQUENCE_PARAM_PAYLOAD");+ assert_eq!(offset_of!(NV_ENC_SEQUENCE_PARAM_PAYLOAD, version), 0, "NV_ENC_SEQUENCE_PARAM_PAYLOAD.version");+ assert_eq!(offset_of!(NV_ENC_SEQUENCE_PARAM_PAYLOAD, inBufferSize), 4, "NV_ENC_SEQUENCE_PARAM_PAYLOAD.inBufferSize");+ assert_eq!(offset_of!(NV_ENC_SEQUENCE_PARAM_PAYLOAD, spsId), 8, "NV_ENC_SEQUENCE_PARAM_PAYLOAD.spsId");+ assert_eq!(offset_of!(NV_ENC_SEQUENCE_PARAM_PAYLOAD, ppsId), 12, "NV_ENC_SEQUENCE_PARAM_PAYLOAD.ppsId");+ assert_eq!(offset_of!(NV_ENC_SEQUENCE_PARAM_PAYLOAD, spsppsBuffer), 16, "NV_ENC_SEQUENCE_PARAM_PAYLOAD.spsppsBuffer");+ assert_eq!(offset_of!(NV_ENC_SEQUENCE_PARAM_PAYLOAD, outSPSPPSPayloadSize), 24, "NV_ENC_SEQUENCE_PARAM_PAYLOAD.outSPSPPSPayloadSize");+ assert_eq!(offset_of!(NV_ENC_SEQUENCE_PARAM_PAYLOAD, reserved), 32, "NV_ENC_SEQUENCE_PARAM_PAYLOAD.reserved");+ assert_eq!(offset_of!(NV_ENC_SEQUENCE_PARAM_PAYLOAD, reserved2), 1032, "NV_ENC_SEQUENCE_PARAM_PAYLOAD.reserved2");+ assert_eq!((size_of::<NV_ENCODE_API_FUNCTION_LIST>(), align_of::<NV_ENCODE_API_FUNCTION_LIST>()), (2552, 8), "NV_ENCODE_API_FUNCTION_LIST");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, version), 0, "NV_ENCODE_API_FUNCTION_LIST.version");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, reserved), 4, "NV_ENCODE_API_FUNCTION_LIST.reserved");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncOpenEncodeSession), 8, "NV_ENCODE_API_FUNCTION_LIST.nvEncOpenEncodeSession");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetEncodeGUIDCount), 16, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetEncodeGUIDCount");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetEncodeProfileGUIDCount), 24, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetEncodeProfileGUIDCount");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetEncodeProfileGUIDs), 32, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetEncodeProfileGUIDs");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetEncodeGUIDs), 40, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetEncodeGUIDs");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetInputFormatCount), 48, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetInputFormatCount");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetInputFormats), 56, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetInputFormats");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetEncodeCaps), 64, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetEncodeCaps");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetEncodePresetCount), 72, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetEncodePresetCount");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetEncodePresetGUIDs), 80, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetEncodePresetGUIDs");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetEncodePresetConfig), 88, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetEncodePresetConfig");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncInitializeEncoder), 96, "NV_ENCODE_API_FUNCTION_LIST.nvEncInitializeEncoder");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncCreateInputBuffer), 104, "NV_ENCODE_API_FUNCTION_LIST.nvEncCreateInputBuffer");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncDestroyInputBuffer), 112, "NV_ENCODE_API_FUNCTION_LIST.nvEncDestroyInputBuffer");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncCreateBitstreamBuffer), 120, "NV_ENCODE_API_FUNCTION_LIST.nvEncCreateBitstreamBuffer");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncDestroyBitstreamBuffer), 128, "NV_ENCODE_API_FUNCTION_LIST.nvEncDestroyBitstreamBuffer");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncEncodePicture), 136, "NV_ENCODE_API_FUNCTION_LIST.nvEncEncodePicture");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncLockBitstream), 144, "NV_ENCODE_API_FUNCTION_LIST.nvEncLockBitstream");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncUnlockBitstream), 152, "NV_ENCODE_API_FUNCTION_LIST.nvEncUnlockBitstream");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncLockInputBuffer), 160, "NV_ENCODE_API_FUNCTION_LIST.nvEncLockInputBuffer");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncUnlockInputBuffer), 168, "NV_ENCODE_API_FUNCTION_LIST.nvEncUnlockInputBuffer");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetEncodeStats), 176, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetEncodeStats");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetSequenceParams), 184, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetSequenceParams");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncRegisterAsyncEvent), 192, "NV_ENCODE_API_FUNCTION_LIST.nvEncRegisterAsyncEvent");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncUnregisterAsyncEvent), 200, "NV_ENCODE_API_FUNCTION_LIST.nvEncUnregisterAsyncEvent");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncMapInputResource), 208, "NV_ENCODE_API_FUNCTION_LIST.nvEncMapInputResource");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncUnmapInputResource), 216, "NV_ENCODE_API_FUNCTION_LIST.nvEncUnmapInputResource");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncDestroyEncoder), 224, "NV_ENCODE_API_FUNCTION_LIST.nvEncDestroyEncoder");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncInvalidateRefFrames), 232, "NV_ENCODE_API_FUNCTION_LIST.nvEncInvalidateRefFrames");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncOpenEncodeSessionEx), 240, "NV_ENCODE_API_FUNCTION_LIST.nvEncOpenEncodeSessionEx");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncRegisterResource), 248, "NV_ENCODE_API_FUNCTION_LIST.nvEncRegisterResource");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncUnregisterResource), 256, "NV_ENCODE_API_FUNCTION_LIST.nvEncUnregisterResource");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncReconfigureEncoder), 264, "NV_ENCODE_API_FUNCTION_LIST.nvEncReconfigureEncoder");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, reserved1), 272, "NV_ENCODE_API_FUNCTION_LIST.reserved1");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncCreateMVBuffer), 280, "NV_ENCODE_API_FUNCTION_LIST.nvEncCreateMVBuffer");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncDestroyMVBuffer), 288, "NV_ENCODE_API_FUNCTION_LIST.nvEncDestroyMVBuffer");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncRunMotionEstimationOnly), 296, "NV_ENCODE_API_FUNCTION_LIST.nvEncRunMotionEstimationOnly");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetLastErrorString), 304, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetLastErrorString");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncSetIOCudaStreams), 312, "NV_ENCODE_API_FUNCTION_LIST.nvEncSetIOCudaStreams");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetEncodePresetConfigEx), 320, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetEncodePresetConfigEx");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncGetSequenceParamEx), 328, "NV_ENCODE_API_FUNCTION_LIST.nvEncGetSequenceParamEx");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncRestoreEncoderState), 336, "NV_ENCODE_API_FUNCTION_LIST.nvEncRestoreEncoderState");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, nvEncLookaheadPicture), 344, "NV_ENCODE_API_FUNCTION_LIST.nvEncLookaheadPicture");+ assert_eq!(offset_of!(NV_ENCODE_API_FUNCTION_LIST, reserved2), 352, "NV_ENCODE_API_FUNCTION_LIST.reserved2");+}++#[test]+fn constants_match_the_header() {+ assert_eq!(NVENCAPI_VERSION as i64, 16777228, "NVENCAPI_VERSION");+ assert_eq!(NV_ENC_SUCCESS as i64, 0, "NV_ENC_SUCCESS");+ assert_eq!(NV_ENC_ERR_INVALID_VERSION as i64, 15, "NV_ENC_ERR_INVALID_VERSION");+ assert_eq!(NV_ENC_ERR_UNSUPPORTED_DEVICE as i64, 2, "NV_ENC_ERR_UNSUPPORTED_DEVICE");+ assert_eq!(NV_ENC_ERR_ENCODER_BUSY as i64, 18, "NV_ENC_ERR_ENCODER_BUSY");+ assert_eq!(NV_ENC_ERR_LOCK_BUSY as i64, 13, "NV_ENC_ERR_LOCK_BUSY");+ assert_eq!(NV_ENC_DEVICE_TYPE_DIRECTX as i64, 0, "NV_ENC_DEVICE_TYPE_DIRECTX");+ assert_eq!(NV_ENC_MEMORY_HEAP_SYSMEM_CACHED as i64, 2, "NV_ENC_MEMORY_HEAP_SYSMEM_CACHED");+ assert_eq!(NV_ENC_BUFFER_FORMAT_NV12 as i64, 1, "NV_ENC_BUFFER_FORMAT_NV12");+ assert_eq!(NV_ENC_PARAMS_RC_VBR as i64, 1, "NV_ENC_PARAMS_RC_VBR");+ assert_eq!(NV_ENC_PARAMS_RC_CBR as i64, 2, "NV_ENC_PARAMS_RC_CBR");+ assert_eq!(NV_ENC_TUNING_INFO_HIGH_QUALITY as i64, 1, "NV_ENC_TUNING_INFO_HIGH_QUALITY");+ assert_eq!(NV_ENC_PIC_STRUCT_FRAME as i64, 1, "NV_ENC_PIC_STRUCT_FRAME");+ assert_eq!(NV_ENC_PIC_TYPE_P as i64, 0, "NV_ENC_PIC_TYPE_P");+ assert_eq!(NV_ENC_PIC_TYPE_B as i64, 1, "NV_ENC_PIC_TYPE_B");+ assert_eq!(NV_ENC_PIC_TYPE_I as i64, 2, "NV_ENC_PIC_TYPE_I");+ assert_eq!(NV_ENC_PIC_TYPE_IDR as i64, 3, "NV_ENC_PIC_TYPE_IDR");+ assert_eq!(NV_ENC_PIC_FLAG_EOS as i64, 8, "NV_ENC_PIC_FLAG_EOS");+ assert_eq!(NV_ENC_LEVEL_AUTOSELECT as i64, 0, "NV_ENC_LEVEL_AUTOSELECT");+ assert_eq!(NV_ENC_H264_ENTROPY_CODING_MODE_CABAC as i64, 1, "NV_ENC_H264_ENTROPY_CODING_MODE_CABAC");+ assert_eq!(NV_ENC_VUI_VIDEO_FORMAT_UNSPECIFIED as i64, 5, "NV_ENC_VUI_VIDEO_FORMAT_UNSPECIFIED");+ assert_eq!(NV_ENC_VUI_COLOR_PRIMARIES_BT709 as i64, 1, "NV_ENC_VUI_COLOR_PRIMARIES_BT709");+ assert_eq!(NV_ENC_VUI_TRANSFER_CHARACTERISTIC_BT709 as i64, 1, "NV_ENC_VUI_TRANSFER_CHARACTERISTIC_BT709");+ assert_eq!(NV_ENC_VUI_MATRIX_COEFFS_BT709 as i64, 1, "NV_ENC_VUI_MATRIX_COEFFS_BT709");+ assert_eq!(NV_ENC_CAPS_NUM_MAX_BFRAMES as i64, 0, "NV_ENC_CAPS_NUM_MAX_BFRAMES");+ assert_eq!(NV_ENC_CAPS_SUPPORTED_RATECONTROL_MODES as i64, 1, "NV_ENC_CAPS_SUPPORTED_RATECONTROL_MODES");+ assert_eq!(NV_ENC_CAPS_WIDTH_MAX as i64, 16, "NV_ENC_CAPS_WIDTH_MAX");+ assert_eq!(NV_ENC_CAPS_HEIGHT_MAX as i64, 17, "NV_ENC_CAPS_HEIGHT_MAX");+ assert_eq!(NV_ENC_CAPS_WIDTH_MIN as i64, 45, "NV_ENC_CAPS_WIDTH_MIN");+ assert_eq!(NV_ENC_CAPS_HEIGHT_MIN as i64, 46, "NV_ENC_CAPS_HEIGHT_MIN");+ assert_eq!(NV_ENC_ERR_NEED_MORE_INPUT as i64, 17, "NV_ENC_ERR_NEED_MORE_INPUT");+ assert_eq!(NV_ENCODE_API_FUNCTION_LIST_VER as i64, 1895956492, "NV_ENCODE_API_FUNCTION_LIST_VER");+ assert_eq!(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER as i64, 1895890956, "NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER");+ assert_eq!(NV_ENC_CAPS_PARAM_VER as i64, 1895890956, "NV_ENC_CAPS_PARAM_VER");+ assert_eq!(NV_ENC_CONFIG_VER as i64, 4043833356, "NV_ENC_CONFIG_VER");+ assert_eq!(NV_ENC_INITIALIZE_PARAMS_VER as i64, 4043702284, "NV_ENC_INITIALIZE_PARAMS_VER");+ assert_eq!(NV_ENC_PRESET_CONFIG_VER as i64, 4043571212, "NV_ENC_PRESET_CONFIG_VER");+ assert_eq!(NV_ENC_RC_PARAMS_VER as i64, 1895890956, "NV_ENC_RC_PARAMS_VER");+ assert_eq!(NV_ENC_CREATE_INPUT_BUFFER_VER as i64, 1895890956, "NV_ENC_CREATE_INPUT_BUFFER_VER");+ assert_eq!(NV_ENC_CREATE_BITSTREAM_BUFFER_VER as i64, 1895890956, "NV_ENC_CREATE_BITSTREAM_BUFFER_VER");+ assert_eq!(NV_ENC_PIC_PARAMS_VER as i64, 4043702284, "NV_ENC_PIC_PARAMS_VER");+ assert_eq!(NV_ENC_LOCK_BITSTREAM_VER as i64, 4043374604, "NV_ENC_LOCK_BITSTREAM_VER");+ assert_eq!(NV_ENC_LOCK_INPUT_BUFFER_VER as i64, 1895890956, "NV_ENC_LOCK_INPUT_BUFFER_VER");+ assert_eq!(NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER as i64, 1895890956, "NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER");+ assert_eq!(NVENCAPI_VERSION as i64, 16777228, "NVENCAPI_VERSION");+}++#[test]+fn guids_match_the_header() {+ assert_eq!(NV_ENC_CODEC_H264_GUID.to_u128(), 0x6bc827624e634ca4aa851e50f321f6bfu128, "NV_ENC_CODEC_H264_GUID");+ assert_eq!(NV_ENC_H264_PROFILE_BASELINE_GUID.to_u128(), 0x0727bcaa78c44c838c2fef3dff267c6au128, "NV_ENC_H264_PROFILE_BASELINE_GUID");+ assert_eq!(NV_ENC_H264_PROFILE_MAIN_GUID.to_u128(), 0x60b5c1d467fe479094d5c4726d7b6e6du128, "NV_ENC_H264_PROFILE_MAIN_GUID");+ assert_eq!(NV_ENC_H264_PROFILE_HIGH_GUID.to_u128(), 0xe7cbc3094f7a4b89af2ad537c92be310u128, "NV_ENC_H264_PROFILE_HIGH_GUID");+ assert_eq!(NV_ENC_PRESET_P4_GUID.to_u128(), 0x90a7b826df064862b9d2cd6d73a08681u128, "NV_ENC_PRESET_P4_GUID");+ assert_eq!(NV_ENC_PRESET_P5_GUID.to_u128(), 0x21c6e6b4297a4cba998fb6cbde72ade3u128, "NV_ENC_PRESET_P5_GUID");+}diff --git a/crates/platform/src/nvenc/export.rs b/crates/platform/src/nvenc/export.rsnew file mode 100644index 000000000..43bf4d389--- /dev/null+++ b/crates/platform/src/nvenc/export.rs@@ -0,0 +1,129 @@+//! 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()+ }+}++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)+ }++ fn timescale(&self) -> u32 {+ self.rate.num as u32+ }++ 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)+ }+}++/// 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 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 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),+ }+}diff --git a/crates/platform/src/nvenc/ffi.rs b/crates/platform/src/nvenc/ffi.rsnew file mode 100644index 000000000..ca536503a--- /dev/null+++ b/crates/platform/src/nvenc/ffi.rs@@ -0,0 +1,473 @@+//! 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 `tests/nvenc_abi.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 --git a/crates/platform/src/nvenc/mod.rs b/crates/platform/src/nvenc/mod.rsnew file mode 100644index 000000000..18b25c47e--- /dev/null+++ b/crates/platform/src/nvenc/mod.rs@@ -0,0 +1,308 @@+//! 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(¶ms, 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) })+ }+}++/// 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()));+ for (row, dst) in y.chunks_exact(w).zip(luma.chunks_exact_mut(pitch)).take(h) {+ dst[..w].copy_from_slice(row);+ }+ let cw = w / 2;+ 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;+ }+ }+}++/// 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 {+ 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);+ // trailing zero bytes belong to the next start code (4-byte form) or are padding+ while e > s && data[e - 1] == 0 {+ e -= 1;+ }+ if e > s {+ out.push(&data[s..e]);+ }+ }+ 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) {+ 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());+ 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]);+ }+}diff --git a/crates/platform/src/nvenc/session.rs b/crates/platform/src/nvenc/session.rsnew file mode 100644index 000000000..054b13cd7--- /dev/null+++ b/crates/platform/src/nvenc/session.rs@@ -0,0 +1,493 @@+//! 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.+ 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));+ }+ 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));+ }+ 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 --git a/crates/platform/tests/nvenc.rs b/crates/platform/tests/nvenc.rsnew file mode 100644index 000000000..e72638af0--- /dev/null+++ b/crates/platform/tests/nvenc.rs@@ -0,0 +1,106 @@+//! NVENC H.264 encoding (Windows, NVIDIA GPU): the stream decodes with our own decoder to pictures+//! close to the source, keyframes and timestamps are right, and Export takes it only when asked.+//! Skips without an NVIDIA GPU / driver with NVENC.+#![cfg(target_os = "windows")]++use filmcraft_isobmff::{AvcConfig, SampleEntry};+use filmcraft_platform::nvenc::{Config, NvencH264, Packet, Profile};++/// A moving test picture: gradient background, a moving box, a little texture.+fn rgba(w: usize, h: usize, i: usize) -> Vec<u8> {+ let mut v = vec![0u8; w * h * 4];+ for y in 0..h {+ for x in 0..w {+ let o = (y * w + x) * 4;+ let (bx, by) = ((i * 7) % (w - 64), (i * 3) % (h - 64));+ let in_box = x >= bx && x < bx + 64 && y >= by && y < by + 64;+ let tex = ((x * 31 + y * 17 + i * 5) % 23) as u8;+ v[o] = if in_box { 230 } else { (x * 200 / w) as u8 + tex };+ v[o + 1] = if in_box { 40 } else { (y * 200 / h) as u8 + tex };+ v[o + 2] = if in_box { 60 } else { 90 + tex };+ v[o + 3] = 255;+ }+ }+ v+}++fn config(w: u32, h: u32) -> Config {+ Config {+ width: w,+ height: h,+ fps: (24, 1),+ bitrate_kbps: 6000,+ max_bitrate_kbps: 9000,+ cbr: false,+ keyint: 24,+ profile: Profile::High,+ level: None,+ sar: None,+ bframes: true,+ }+}++fn encode_all(cfg: &Config, frames: usize) -> Option<(NvencH264, Vec<Packet>, Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>)> {+ let mut enc = match NvencH264::new(cfg) {+ Ok(e) => e,+ Err(why) => {+ eprintln!("SKIPPED: {why}");+ return None;+ }+ };+ let (w, h) = (cfg.width as usize, cfg.height as usize);+ let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());+ let (mut packets, mut sources) = (Vec::new(), Vec::new());+ for i in 0..frames {+ filmcraft_export::rgba_to_yuv420_8(&rgba(w, h, i), w, h, &mut y, &mut u, &mut v);+ sources.push((y.clone(), u.clone(), v.clone()));+ packets.extend(enc.encode(&y, &u, &v, i as u64).unwrap());+ }+ packets.extend(enc.flush().unwrap());+ Some((enc, packets, sources))+}++fn psnr(a: &[u8], b: &[u8]) -> f64 {+ let mse = a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(*y)).powi(2)).sum::<f64>() / a.len() as f64;+ if mse == 0.0 { 99.0 } else { 10.0 * (255.0f64 * 255.0 / mse).log10() }+}++#[test]+fn the_stream_decodes_to_the_source() {+ let (w, h) = (1280u32, 720u32);+ let Some((enc, packets, sources)) = encode_all(&config(w, h), 72) else { return };+ assert_eq!(packets.len(), 72, "one packet per picture");++ // timestamps: decoding order, presentation = frame number, dts = k - delay+ let delay = i64::from(enc.delay());+ for (k, p) in packets.iter().enumerate() {+ assert_eq!(p.dts, k as i64 - delay, "dts of packet {k}");+ assert!(p.pts >= p.dts, "pts {} before dts {}", p.pts, p.dts);+ }+ let mut pts: Vec<i64> = packets.iter().map(|p| p.pts).collect();+ pts.sort_unstable();+ assert_eq!(pts, (0..72).collect::<Vec<_>>(), "every picture once");+ // keyframes every 24 pictures (IDR), nothing else flagged+ let keys: Vec<i64> = packets.iter().filter(|p| p.key).map(|p| p.pts).collect();+ assert_eq!(keys, vec![0, 24, 48], "IDR pictures");++ // the avcC parses and our decoder decodes the samples+ let (sps, pps) = enc.parameter_sets();+ let entry = SampleEntry::avc(AvcConfig::new(vec![sps.to_vec()], vec![pps.to_vec()], 4), w as u16, h as u16);+ let mut dec = filmcraft_codecs::software_video_decoder(&entry).unwrap();+ let mut out = Vec::new();+ for p in &packets {+ out.extend(dec.decode(&p.data, p.pts).unwrap());+ }+ out.extend(dec.flush());+ assert_eq!(out.len(), 72);+ let mut worst = 99.0f64;+ for f in &out {+ let src = &sources[f.pts as usize];+ let filmcraft_frame::PixelData::Yuv8 { planes, .. } = &f.frame.data else { panic!("8-bit planes") };+ worst = worst.min(psnr(&planes[0], &src.0));+ assert!(psnr(&planes[1], &src.1) > 33.0 && psnr(&planes[2], &src.2) > 33.0, "chroma of picture {}", f.pts);+ }+ assert!(worst > 34.0, "luma PSNR {worst:.1} dB");+ eprintln!("worst luma PSNR {worst:.1} dB, {} bytes", packets.iter().map(|p| p.data.len()).sum::<usize>());+}diff --git a/crates/platform/tests/nvenc_export.rs b/crates/platform/tests/nvenc_export.rsnew file mode 100644index 000000000..be82040c8--- /dev/null+++ b/crates/platform/tests/nvenc_export.rs@@ -0,0 +1,143 @@+//! Export with Hardware encoding (NVENC) against the software encoder, through the real export+//! pipeline: the same frames, a file both decode, counters showing which encoder ran, and what NVENC+//! declines (hardware encoding Off, two-pass, MXF...) going to the software encoder. Its own test+//! binary: the encoder registry is process-wide. Skips without an NVIDIA GPU with NVENC.+#![cfg(target_os = "windows")]++use std::sync::Arc;++use filmcraft_export::{BitrateMode, ExportSettings, Format, HardwareEncoding, Progress, export, hw_encode_stats};+use filmcraft_media::generators::GeneratorSource;+use filmcraft_media::{DemoScene, FrameRequest, Generator, MediaSource};+use filmcraft_project::{ItemKind, Label, MediaClip, MediaRef, Project, SequenceSettings, TrackKind};+use filmcraft_render::SourceMap;+use filmcraft_time::{FrameRate, Tick, TimeRange};++/// The encoder counters are process-wide: one test at a time.+static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());++fn project(w: u32, h: u32, frames: i64) -> (Arc<Project>, filmcraft_project::ItemId, SourceMap) {+ let rate = FrameRate::FPS_24;+ let mut p = Project::new("x");+ let g = GeneratorSource::new(Generator::Demo(DemoScene::OceanSunset), w, h, rate, rate.tick_of(frames));+ let info = g.info().clone();+ let clip = p.add_item(+ &info.name.clone(),+ Label::Iris,+ ItemKind::Media(MediaClip {+ media: MediaRef::Generator(g.generator.clone()),+ info,+ interpret: Default::default(),+ mark_in: None,+ mark_out: None,+ markers: vec![],+ offline: false,+ proxy: None,+ identity: None,+ }),+ None,+ );+ let seq = p.new_sequence("s", SequenceSettings { width: w, height: h, frame_rate: rate, ..Default::default() }, 1, 1, None);+ let v = p.make_track_item(clip, TrackKind::Video, Tick::ZERO, TimeRange::new(Tick::ZERO, rate.tick_of(frames)), rate).unwrap();+ p.sequence_mut(seq).unwrap().video_tracks[0].items.push(v);+ let mut m = SourceMap::default();+ m.0.insert(clip, Arc::new(g));+ (Arc::new(p), seq, m)+}++fn tmp(name: &str) -> String {+ let d = std::env::temp_dir().join(format!("fc-nvenc-{}", std::process::id()));+ std::fs::create_dir_all(&d).unwrap();+ d.join(name).to_string_lossy().to_string()+}++fn decode(path: &str) -> Vec<Arc<filmcraft_frame::VideoFrame>> {+ let bytes: Arc<[u8]> = std::fs::read(path).unwrap().into();+ let src = filmcraft_codecs::open_bytes(path, bytes).unwrap();+ let rate = src.info().frame_rate();+ let n = rate.frame_at(src.info().duration);+ (0..n).map(|i| src.video_frame(FrameRequest::full(rate.tick_of(i))).unwrap()).collect()+}++fn luma_psnr(a: &filmcraft_frame::VideoFrame, b: &filmcraft_frame::VideoFrame) -> f64 {+ let (x, y) = (a.luma8(), b.luma8());+ let mse = x.iter().zip(&y).map(|(p, q)| (f64::from(*p) - f64::from(*q)).powi(2)).sum::<f64>() / x.len() as f64;+ if mse == 0.0 { 99.0 } else { 10.0 * (255.0f64 * 255.0 / mse).log10() }+}++fn settings(path: String, hw: HardwareEncoding) -> ExportSettings {+ ExportSettings {+ format: Format::H264,+ path,+ include_audio: false,+ bitrate_kbps: 4000,+ bitrate_mode: BitrateMode::Vbr1Pass,+ hardware_encoding: hw,+ ..Default::default()+ }+}++#[test]+fn hardware_export_matches_the_software_export() {+ let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ filmcraft_platform::register();+ let (p, seq, m) = project(1280, 720, 72);+ let soft_path = tmp("soft.mp4");+ export(&p, seq, &settings(soft_path.clone(), HardwareEncoding::Off), &m, &Progress::default()).unwrap();+ assert_eq!(hw_encode_stats().sessions, 0, "Off: no hardware encoder");++ let hw_path = tmp("hw.mp4");+ let before = hw_encode_stats();+ let report = export(&p, seq, &settings(hw_path.clone(), HardwareEncoding::Auto), &m, &Progress::default()).unwrap();+ let after = hw_encode_stats();+ if after.sessions == before.sessions {+ eprintln!("SKIPPED: no NVENC here (declined {})", after.declined - before.declined);+ return;+ }+ assert_eq!(report.frames, 72);+ assert_eq!(after.frames - before.frames, 72, "every picture went through NVENC");++ let (soft, hard) = (decode(&soft_path), decode(&hw_path));+ assert_eq!((soft.len(), hard.len()), (72, 72), "frame counts");+ let worst = soft.iter().zip(&hard).map(|(a, b)| luma_psnr(a, b)).fold(99.0, f64::min);+ assert!(worst > 30.0, "hardware export differs from the software one: {worst:.1} dB");+ let size = |p: &str| std::fs::metadata(p).unwrap().len();+ eprintln!("software {} bytes, hardware {} bytes, worst luma PSNR between them {worst:.1} dB", size(&soft_path), size(&hw_path));++ // the file plays: ffmpeg decodes it without errors (external oracle only)+ if let Some(ff) = filmcraft_testkit::ffmpeg() {+ let out = std::process::Command::new(ff).args(["-v", "error", "-i", &hw_path, "-f", "null", "-"]).output().unwrap();+ assert!(out.stderr.is_empty(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));+ }+}++#[test]+fn what_nvenc_does_not_take_goes_to_the_software_encoder() {+ let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ filmcraft_platform::register();+ let (p, seq, m) = project(640, 360, 24);+ let run = |name: &str, f: &dyn Fn(&mut ExportSettings)| {+ let mut s = settings(tmp(name), HardwareEncoding::Auto);+ f(&mut s);+ let before = hw_encode_stats();+ export(&p, seq, &s, &m, &Progress::default()).unwrap();+ let after = hw_encode_stats();+ (after.frames - before.frames, after.declined - before.declined)+ };+ // two-pass VBR is a software feature (both passes ask, both are declined)+ assert_eq!(run("two_pass.mp4", &|s| s.bitrate_mode = BitrateMode::Vbr2Pass), (0, 2));+ // MXF H.264 is an Annex B stream with in-band parameter sets: the software encoder's+ assert_eq!(+ run("mxf.mxf", &|s| {+ s.format = Format::MxfOp1a;+ s.mxf_video_codec = filmcraft_export::MxfVideoCodec::H264;+ }),+ (0, 1)+ );+ // an odd frame size is rounded to even by the pipeline, so NVENC still takes it+ assert_eq!(run("odd.mp4", &|s| s.frame_size = Some((641, 359))), (24, 0));+ // Off never touches the hardware encoder+ assert_eq!(run("off.mp4", &|s| s.hardware_encoding = HardwareEncoding::Off), (0, 0));+ // the decoded file of a declined export is fine+ assert_eq!(decode(&tmp("odd.mp4")).len(), 24);+}diff --git a/crates/ui-egui/examples/bench/main.rs b/crates/ui-egui/examples/bench/main.rsindex ffae87dea..1729745b2 100644--- a/crates/ui-egui/examples/bench/main.rs+++ b/crates/ui-egui/examples/bench/main.rs@@ -331,6 +331,7 @@ pub fn section_markdown(v: &Value) -> String {("realtime", "× real time"),("cpu_ms_per_frame", "CPU ms/frame"),("mbytes", "MB"),+ ("hw_frames", "hw frames"),("load", "load"),],2,diff --git a/crates/ui-egui/examples/bench/sections.rs b/crates/ui-egui/examples/bench/sections.rsindex 97ea0521e..9d0465ee2 100644--- a/crates/ui-egui/examples/bench/sections.rs+++ b/crates/ui-egui/examples/bench/sections.rs@@ -442,6 +442,7 @@ pub fn export(o: &Opts) -> Vec<Value> {let mut cpu = Vec::new();let mut bytes = 0u64;let mut frames = 0i64;+ let hw0 = filmcraft_engine::export::hw_encode_stats();for _ in 0..o.repeat {let mut s = Session::default();let a = playback::import(&mut s, &path);@@ -459,7 +460,9 @@ pub fn export(o: &Opts) -> Vec<Value> {frames = s.project.sequence(seq).map(|q| q.settings.frame_rate.frame_at(q.duration())).unwrap_or(0);let out = dir.join(format!("out.{ext}"));let (t0, c0) = (Instant::now(), cpu_now());- let r = s.execute("file.exportMedia", json!({"path": out.to_string_lossy(), "format": format, "wait": true}));+ // `--hw auto`: the hardware encoder too (NVENC H.264 on Windows); `--hw off`: ours+ let hardware = if o.hw == "off" { "off" } else { "auto" };+ let r = s.execute("file.exportMedia", json!({"path": out.to_string_lossy(), "format": format, "hardwareEncoding": hardware, "wait": true}));let dt = t0.elapsed().as_secs_f64();if let Err(e) = r {eprintln!("export {format}: {e}");@@ -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,}));}let _ = std::fs::remove_dir_all(&dir);diff --git a/crates/ui-egui/src/panels/export_mode.rs b/crates/ui-egui/src/panels/export_mode.rsindex c9446a7fe..3087cf0ce 100644--- a/crates/ui-egui/src/panels/export_mode.rs+++ b/crates/ui-egui/src/panels/export_mode.rs@@ -22,8 +22,8 @@use egui::{Align2, Color32, Rect, Sense, pos2, vec2};use filmcraft_engine::export::presets::{DEFAULT_PRESET, preset_key};use filmcraft_engine::export::{- AudioCodec, BitrateMode, ExportSettings, FieldOrder, Format, H264Profile, Multiplexer, MxfVideoCodec, Placement, Scaling, TextOverlay, builtin_presets,- format_bytes,+ AudioCodec, BitrateMode, ExportSettings, FieldOrder, Format, H264Profile, HardwareEncoding, Multiplexer, MxfVideoCodec, Placement, Scaling, TextOverlay,+ builtin_presets, format_bytes,};use filmcraft_engine::time::{FrameRate, Tick};use serde::{Deserialize, Serialize};@@ -617,6 +617,14 @@ fn video_section(ui: &mut egui::Ui, reg: &mut Reg, s: &mut ExportSettings, t: &Ts.bitrate_mode = o[i];}});+ row(ui, t, "Hardware Encoding", |ui| {+ // the GPU's video encoder (NVENC on NVIDIA GPUs, Windows) where there is one and it+ // takes these settings; two-pass VBR, HDR and MXF always use our encoder+ let mut on = s.hardware_encoding == HardwareEncoding::Auto;+ if check(ui, reg, "export.video.hardwareEncoding", &mut on, "Use the GPU when available") {+ s.hardware_encoding = if on { HardwareEncoding::Auto } else { HardwareEncoding::Off };+ }+ });if let Some(bpp) = s.adaptive_bitrate {row(ui, t, "Target Bitrate", |ui| {ui.label(egui::RichText::new(format!("Adaptive ({bpp} bits per pixel)")).size(12.0));