Skip to content

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

M-HW: NVENC takes the export's RGBA and converts it on the GPU (#30)

MasakatsuFunaki5001d6bf2948
diff --git a/crates/platform/README.md b/crates/platform/README.md
index 58df2f6ea..8170e6292 100644
--- a/crates/platform/README.md
+++ b/crates/platform/README.md
@@ -65,14 +65,18 @@ let availability = filmcraft_platform::register(); // Available("VideoToolbox")
`nvEncodeAPI64.dll` (Windows) or `libnvidia-encode.so.1` (Linux), API 12.1, is loaded at run time,
so machines without NVIDIA still start. Windows uses a Direct3D 11 device; Linux retains a primary
CUDA context through the runtime-loaded `libcuda.so.1`, released after the encoder is destroyed.
- No SDK, CUDA toolkit or NVIDIA binaries are bundled or required at build time. RGBA is converted with the software encoder's own BT.709 limited conversion into NV12
- input buffers (a ring of eight); the encoder runs preset P5 with high-quality tuning, CABAC (CAVLC
+ No SDK, CUDA toolkit or NVIDIA binaries are bundled or required at build time. 8-bit pictures go
+ in as the export's RGBA (ABGR input buffers, a ring of eight) and NVENC converts them to BT.709
+ limited 4:2:0 on the GPU, with the same codes as the software encoder's own conversion; a driver
+ that refuses RGB input gets that CPU conversion into NV12 instead. The conversion used to run on
+ the encode thread, where it competed with the render of the next frames for the thread pool and
+ held NVENC back. The encoder runs preset P5 with high-quality tuning, CABAC (CAVLC
for Baseline), one B-frame when the profile and GPU allow it, and an IDR at every keyframe
distance; the parameter sets go into `avcC`. Export ▸ Hardware encoding (off by default) selects it.
It declines two-pass VBR, HDR, MXF, interlaced output, sizes outside NVENC's limits and systems
without an NVIDIA GPU or driver, and the software encoder runs instead. A failure during an export
ends it with an error, since a hardware stream cannot be finished in software. The same session,
- ring and NV12 path encode H.265, see [Hardware H.265 (HEVC) encoding (Windows,
+ ring and input path encode H.265, see [Hardware H.265 (HEVC) encoding (Windows,
NVENC)](#hardware-h265-hevc-encoding-windows-nvenc).
- **Linux: VA-API, H.264 (`avcC`) and HEVC (`hvcC`)**: H.264 8-bit 4:2:0 progressive, Constrained
Baseline / Main / High; HEVC Main, Main 10 and Main Still Picture, 4:2:0 8- and 10-bit (`vaapi/`), on Intel (iHD, i965), AMD and other Mesa drivers. `libva.so.2` and `libva-drm.so.2`
@@ -281,6 +285,7 @@ level 4 High tier, which many hardware decoders refuse; it is now level 4.1 Main
| `tests/nvenc_export.rs` (Windows / Linux; fallback also tested without NVIDIA) | Export with hardware encoding against the software encoder through the export pipeline: the two decoded files at worst 54.8 dB luma PSNR; ffmpeg decodes the file without errors; declined cases go to the software encoder; the counters |
| `tests/nvenc_hevc.rs` (Windows, NVIDIA with HEVC) | HEVC from NVENC (1280×720, 6 Mbps, 72 frames, keyframe every 24) decodes with our HEVC decoder at worst 48.9 dB luma / 51.0 dB chroma PSNR; IDR at 0, 24, 48; dts strictly increasing, pts a permutation, `sps_max_num_reorder_pics` within the dts shift; no parameter sets in the samples; the `hvcC`'s profile / tier / level bytes are the SPS's own; VUI BT.709 limited and timing `(1, 24)`; hostile configurations, sizes, planes and encoders dropped mid-stream give errors, never panics; keyframes every 1–2 pictures without B-frames |
| `tests/nvenc_hevc_export.rs` (Windows, NVIDIA with HEVC) | H.265 export through the real pipeline, MP4 and QuickTime, toggle Auto and Off: counters (72 frames, 1 session, 0 declined), our decoder against the software H.264 export at worst 54.8 dB luma PSNR, ffprobe `codec_name=hevc`, `profile=Main`, `codec_tag_string=hvc1`, `pix_fmt=yuv420p`, BT.709 limited, 72 frames, 24/1, keyframes at 0 and 48, start 0, `ffmpeg -xerror` clean; with AAC audio; 1920×1080 and 642×362 cropped back from the coded size; every decline (HDR, analysis pass, two-pass, interlaced, non-square pixels, MXF, sizes over 65535, odd sizes, sizes outside the GPU's limits) an error naming NVENC, counted once; H.264 with hardware encoding Off never touches NVENC |
+| `tests/nvenc_rgba_input.rs` (Windows, NVIDIA) | RGBA input, HEVC Main and H.264 High, 1280×720: solid red, green, blue, white, black and grey decode (our decoder) to the exact BT.709 limited codes of `rgba_to_yuv420_8`, within 2; a moving picture at worst 47.7 dB luma / 50.7 dB chroma PSNR against that conversion; Main 10 has no RGBA input; short pictures and planar / RGBA pictures for the other kind of encoder are errors |
| `tests/nvenc_hevc_probe.rs` (Windows) | the HEVC probe in a fresh process: its cost, the cached answer, `available(Hevc)` following it after `register()` (twice) |
| `tests/nvenc_hevc_warm.rs` (Windows) | `register()` answers the HEVC and the Main 10 questions on a thread of its own, before anyone asks; the answers are kept and `hdr_available(Hevc)` follows the Main 10 probe |
| `tests/nvenc_hevc_main10.rs` (Windows, NVIDIA with 10-bit HEVC) | HEVC Main 10 in process, PQ and HLG: a float picture (grey ramp to peak white, a moving box, saturated BT.2020 bars) is converted with `rgbf_to_yuv420_10`, encoded and decoded with our HEVC decoder (`Yuv16`, 10 bits, codes below 1024): worst 71.1 dB luma / 70.6 dB chroma PSNR on the 10-bit scale, 803 distinct luma levels on a ramp row, peak code 940 survives; IDR at 0 and 24; the VUI is BT.2020 / 16 or 18 / BT.2020 NCL / limited; the IDR samples carry two prefix SEI NAL units whose messages are byte-for-byte the expected 137 / 144 payloads (HLG: none; other pictures: none); Main and Main 10 refuse each other's pictures; hostile sizes, bitrates, signals, huge or empty SEI payloads, encoders dropped with SEI in flight |
diff --git a/crates/platform/src/nvenc/abi_tests.rs b/crates/platform/src/nvenc/abi_tests.rs
index 1d6980fb4..270108a58 100644
--- a/crates/platform/src/nvenc/abi_tests.rs
+++ b/crates/platform/src/nvenc/abi_tests.rs
@@ -444,6 +444,7 @@ fn constants_match_the_header() {
assert_eq!(NV_ENC_LEVEL_HEVC_62 as i64, 186, "NV_ENC_LEVEL_HEVC_62");
assert_eq!(NVENCAPI_VERSION as i64, 16777228, "NVENCAPI_VERSION");
assert_eq!(NV_ENC_BUFFER_FORMAT_YUV420_10BIT as i64, 65536, "NV_ENC_BUFFER_FORMAT_YUV420_10BIT");
+ assert_eq!(NV_ENC_BUFFER_FORMAT_ABGR as i64, 268435456, "NV_ENC_BUFFER_FORMAT_ABGR");
assert_eq!(NV_ENC_CAPS_SUPPORT_10BIT_ENCODE as i64, 39, "NV_ENC_CAPS_SUPPORT_10BIT_ENCODE");
assert_eq!(NV_ENC_VUI_COLOR_PRIMARIES_BT2020 as i64, 9, "NV_ENC_VUI_COLOR_PRIMARIES_BT2020");
assert_eq!(NV_ENC_VUI_TRANSFER_CHARACTERISTIC_SMPTE2084 as i64, 16, "NV_ENC_VUI_TRANSFER_CHARACTERISTIC_SMPTE2084");
diff --git a/crates/platform/src/nvenc/export.rs b/crates/platform/src/nvenc/export.rs
index 2acd3ab2d..a63b6a0ec 100644
--- a/crates/platform/src/nvenc/export.rs
+++ b/crates/platform/src/nvenc/export.rs
@@ -120,6 +120,8 @@ impl VideoEncoder for NvencEncoder {
}
(true, None) => return Err(ExportError::Unsupported("NVENC Main 10 needs the HDR picture (EncoderFrame::hdr)".into())),
(false, Some(_)) => return Err(ExportError::Unsupported("NVENC Main (8-bit) does not take HDR pictures".into())),
+ // the GPU converts the RGBA picture itself (BT.709 limited range, the same codes as `rgba_to_yuv420_8`)
+ (false, None) if self.enc.takes_rgba() => self.enc.encode_rgba(f.rgba, f.index).map_err(|e| ExportError::Encode(format!("NVENC: {e}{hint}")))?,
(false, None) => {
filmcraft_export::timed(filmcraft_export::Stage::Convert, || {
filmcraft_export::rgba_to_yuv420_8(f.rgba, w, h, &mut self.y, &mut self.u, &mut self.v)
@@ -209,7 +211,21 @@ pub fn factory(format: Format, w: u32, h: u32, rate: FrameRate, s: &ExportSettin
// H.265 through NVENC is Windows-only for now; on Linux this backend takes H.264 only
return if cfg!(target_os = "windows") { hevc_factory(w, h, rate, s) } else { None };
}
- factory_with(format, w, h, rate, s, Nvenc::new)
+ factory_with(format, w, h, rate, s, |cfg| open(cfg, &Signal::default()))
+}
+
+/// Open the encoder for `cfg`. An 8-bit one takes the export's RGBA pictures as they are and converts
+/// them on the GPU, which keeps the RGB → 4:2:0 conversion off the CPU (where it competes with the
+/// render of the next frames); where the driver refuses RGB input, it takes the CPU's 4:2:0 as before.
+/// Main 10 takes its 10-bit planes.
+fn open(cfg: &Config, signal: &Signal) -> std::result::Result<Nvenc, String> {
+ if cfg.profile == Profile::HevcMain10 {
+ return Nvenc::with_signal(cfg, signal);
+ }
+ Nvenc::with_rgba_input(cfg, signal).or_else(|why| {
+ log::info!("NVENC RGBA input declined ({why}): converting to 4:2:0 on the CPU");
+ Nvenc::with_signal(cfg, signal)
+ })
}
/// The H.264 side of [`factory`], with the driver call (`open`) passed in so tests can stand in for it.
@@ -254,7 +270,7 @@ fn hevc_factory(w: u32, h: u32, rate: FrameRate, s: &ExportSettings) -> Option<R
Ok(c) => c,
Err(why) => return declined(&why),
};
- match Nvenc::with_signal(&cfg, &nvenc_signal(&s.signal)) {
+ match open(&cfg, &nvenc_signal(&s.signal)) {
Ok(enc) => {
filmcraft_export::note_hw_encode_session();
Some(Ok(Box::new(new_encoder(enc, w, h, rate, s.signal))))
diff --git a/crates/platform/src/nvenc/ffi.rs b/crates/platform/src/nvenc/ffi.rs
index c3e479f42..dd348cff5 100644
--- a/crates/platform/src/nvenc/ffi.rs
+++ b/crates/platform/src/nvenc/ffi.rs
@@ -94,6 +94,8 @@ pub const NV_ENC_MEMORY_HEAP_SYSMEM_CACHED: u32 = 2;
pub const NV_ENC_BUFFER_FORMAT_NV12: u32 = 0x1;
/// P010: 10-bit 4:2:0, 16-bit little-endian samples with the value in the high 10 bits.
pub const NV_ENC_BUFFER_FORMAT_YUV420_10BIT: u32 = 0x10000;
+/// ABGR: 8-bit packed, one 32-bit little-endian word per pixel with R in the lowest byte (bytes R, G, B, A).
+pub const NV_ENC_BUFFER_FORMAT_ABGR: u32 = 0x10000000;
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;
diff --git a/crates/platform/src/nvenc/mod.rs b/crates/platform/src/nvenc/mod.rs
index e03ed0cfa..f97adc5fb 100644
--- a/crates/platform/src/nvenc/mod.rs
+++ b/crates/platform/src/nvenc/mod.rs
@@ -11,8 +11,11 @@
//! only encoder of the H.265 format (which has no 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 / hvcC
+//! RGBA (the export pipeline) ──► ABGR input buffer ──NVENC (BT.709 limited 4:2:0 on the GPU)──►
+//! Annex B ──► length-prefixed samples + avcC / hvcC
+//!
+//! where the driver refuses RGB input (`Nvenc::with_rgba_input` fails), as before:
+//! RGBA ──► BT.709 limited 4:2:0 (the software encoder's conversion) ──► NV12 input buffer ──NVENC──► …
//!
//! HDR (PQ / HLG) HEVC Main 10:
//! encoded BT.2020 R'G'B' floats ──► 10-bit limited 4:2:0 (`filmcraft_export::rgbf_to_yuv420_10`)
@@ -120,6 +123,8 @@ pub struct Nvenc {
size: (u32, u32),
/// Main 10: pictures go in as 10-bit P010 ([`Nvenc::encode_10`]), otherwise as 8-bit NV12 ([`Nvenc::encode`]).
ten_bit: bool,
+ /// Pictures go in as packed RGBA ([`Nvenc::encode_rgba`]) and the GPU converts them to 4:2:0.
+ rgba_input: bool,
}
/// The H.264 encoder (the name it had before HEVC joined it).
@@ -231,6 +236,19 @@ impl Nvenc {
/// on every IDR picture), or say why NVENC does not take this configuration. H.264 takes the
/// default signal only.
pub fn with_signal(cfg: &Config, signal: &Signal) -> Result<Self, String> {
+ Self::open(cfg, signal, false)
+ }
+
+ /// Open an 8-bit encoder that takes straight RGBA8 pictures ([`Nvenc::encode_rgba`]) and converts
+ /// them to 4:2:0 on the GPU, or say why not (Main 10, or a driver that refuses RGB input).
+ pub fn with_rgba_input(cfg: &Config, signal: &Signal) -> Result<Self, String> {
+ if cfg.profile == Profile::HevcMain10 {
+ return Err("RGBA input is 8-bit only".into());
+ }
+ Self::open(cfg, signal, true)
+ }
+
+ fn open(cfg: &Config, signal: &Signal, rgba_input: bool) -> 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"));
@@ -278,6 +296,7 @@ impl Nvenc {
Profile::High => 2,
},
ten_bit,
+ rgba_input,
signal: signal.clone(),
level,
sar: cfg.sar,
@@ -312,6 +331,7 @@ impl Nvenc {
emitted: 0,
size: (w, h),
ten_bit,
+ rgba_input,
})
}
@@ -345,6 +365,25 @@ impl Nvenc {
self.ten_bit
}
+ /// Whether this encoder takes packed RGBA pictures ([`Nvenc::encode_rgba`]) instead of planar ones.
+ pub fn takes_rgba(&self) -> bool {
+ self.rgba_input
+ }
+
+ /// Encode picture `index` from straight RGBA8 (`w * 4` bytes per row, alpha ignored); NVENC
+ /// converts it to 4:2:0 with the stream's matrix. The pictures that came out, as for
+ /// [`Nvenc::encode`]. An error for an encoder opened without [`Nvenc::with_rgba_input`].
+ pub fn encode_rgba(&mut self, rgba: &[u8], index: u64) -> Result<Vec<Packet>, String> {
+ if !self.rgba_input {
+ return Err("an RGBA picture for a planar-input encoder".into());
+ }
+ let (w, h) = (self.size.0 as usize, self.size.1 as usize);
+ if rgba.len() < w.saturating_mul(h).saturating_mul(4) {
+ return Err("the picture is smaller than the encoder's size".into());
+ }
+ self.submit_picture(index, |l| fill_rgba(l, rgba, w, h))
+ }
+
/// Encode picture `index` from planar 8-bit 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). An error
/// for a Main 10 encoder.
@@ -352,6 +391,9 @@ impl Nvenc {
if self.ten_bit {
return Err("an 8-bit picture for a Main 10 encoder".into());
}
+ if self.rgba_input {
+ return Err("a planar picture for an RGBA-input encoder".into());
+ }
let (w, h) = (self.size.0 as usize, self.size.1 as usize);
let (luma, chroma) = (w.saturating_mul(h), (w / 2).saturating_mul(h / 2));
if y.len() < luma || u.len() < chroma || v.len() < chroma {
@@ -455,6 +497,20 @@ fn fill_nv12(l: Locked<'_>, y: &[u8], u: &[u8], v: &[u8], w: usize, h: usize) {
}
}
+/// Copy straight RGBA8 rows into an ABGR input buffer (the same byte order: R, G, B, A). A row the
+/// pitch cannot hold is skipped, never overrun.
+fn fill_rgba(l: Locked<'_>, rgba: &[u8], w: usize, h: usize) {
+ let row = w.saturating_mul(4);
+ if row == 0 || l.pitch == 0 {
+ return;
+ }
+ for (src, dst) in rgba.chunks_exact(row).zip(l.data.chunks_mut(l.pitch)).take(h) {
+ if let Some(d) = dst.get_mut(..row) {
+ d.copy_from_slice(src);
+ }
+ }
+}
+
/// Copy planar 10-bit 4:2:0 into a P010 input buffer: each sample is a little-endian `u16` with the
/// 10-bit code in its high bits (`code << 6`), the chroma plane interleaved (Cb, Cr) after the luma rows,
/// `pitch` in bytes. Codes above 10 bits are masked; a row the pitch cannot hold is skipped, never overrun.
diff --git a/crates/platform/src/nvenc/session.rs b/crates/platform/src/nvenc/session.rs
index 1791c017c..b19691f71 100644
--- a/crates/platform/src/nvenc/session.rs
+++ b/crates/platform/src/nvenc/session.rs
@@ -150,6 +150,8 @@ pub struct Params {
pub profile: u8,
/// HEVC Main 10: 10-bit 4:2:0 pictures (P010), otherwise 8-bit (NV12).
pub ten_bit: bool,
+ /// 8-bit only: pictures go in as packed RGBA (ABGR) and NVENC converts them to 4:2:0 on the GPU.
+ pub rgba_input: bool,
/// HEVC: the VUI colour description and the SEI messages of every IDR picture (H.264 keeps BT.709).
pub signal: Signal,
/// The codec's own level code: `level × 10` for H.264, `level × 30` for HEVC.
@@ -160,7 +162,7 @@ pub struct Params {
}
/// An input buffer locked for writing: NV12 (or P010) rows go to `data` at `pitch` bytes per row, the
-/// chroma plane after `pitch * height` bytes.
+/// chroma plane after `pitch * height` bytes; packed RGBA (ABGR) has `height` rows and no chroma plane.
pub struct Locked<'a> {
pub data: &'a mut [u8],
pub pitch: usize,
@@ -315,8 +317,14 @@ impl Session {
if !p.signal.sei.is_empty() && p.codec != Codec::Hevc {
return Err("SEI messages are written for HEVC only".into());
}
- self.fmt = if p.ten_bit { NV_ENC_BUFFER_FORMAT_YUV420_10BIT } else { NV_ENC_BUFFER_FORMAT_NV12 };
- self.bytes_per_sample = if p.ten_bit { 2 } else { 1 };
+ if p.ten_bit && p.rgba_input {
+ return Err("RGBA input is 8-bit only".into());
+ }
+ (self.fmt, self.bytes_per_sample) = match (p.ten_bit, p.rgba_input) {
+ (true, _) => (NV_ENC_BUFFER_FORMAT_YUV420_10BIT, 2),
+ (false, true) => (NV_ENC_BUFFER_FORMAT_ABGR, 4),
+ (false, false) => (NV_ENC_BUFFER_FORMAT_NV12, 1),
+ };
self.gop = u64::from(p.gop.max(1));
self.submitted = 0;
// the SEI payloads: heap blocks that outlive every picture (see the field documentation)
@@ -516,7 +524,8 @@ impl Session {
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 or P010: luma rows then chroma rows, the pitch
- // in bytes) that stays valid until `UnlockInputBuffer`; the slice borrows it only inside `fill`.
+ // in bytes), or `pitch * h` bytes (ABGR: packed rows only), 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;
@@ -531,7 +540,8 @@ impl Session {
let _ = unlock(self.enc, input);
return Err(format!("the driver returned an input pitch of {} bytes for {w}-pixel rows of {}-byte samples", l.pitch, self.bytes_per_sample));
}
- let len = (l.pitch as usize).saturating_mul(h as usize).saturating_mul(3) / 2;
+ let rows = (l.pitch as usize).saturating_mul(h as usize);
+ let len = if self.fmt == NV_ENC_BUFFER_FORMAT_ABGR { rows } else { rows.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 {
diff --git a/crates/platform/tests/nvenc_rgba_input.rs b/crates/platform/tests/nvenc_rgba_input.rs
new file mode 100644
index 000000000..4009f3e68
--- /dev/null
+++ b/crates/platform/tests/nvenc_rgba_input.rs
@@ -0,0 +1,157 @@
+//! NVENC with packed RGBA input (Windows, NVIDIA GPU): the GPU's RGB → 4:2:0 conversion matches the
+//! export's own BT.709 limited-range conversion (`filmcraft_export::rgba_to_yuv420_8`), for HEVC Main
+//! and H.264. Skips without an NVIDIA GPU / driver.
+#![cfg(target_os = "windows")]
+
+use filmcraft_isobmff::{AvcConfig, SampleEntry};
+use filmcraft_platform::nvenc::{Codec, Config, Nvenc, Packet, Profile, Signal, available, hevc_available};
+
+/// NVENC sessions are a limited resource on consumer GPUs: one test at a time.
+static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+/// A moving test picture: gradient background, a moving box, a little texture.
+fn moving(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 solid(w: usize, h: usize, rgb: [u8; 3]) -> Vec<u8> {
+ [rgb[0], rgb[1], rgb[2], 255].repeat(w * h)
+}
+
+fn config(w: u32, h: u32, profile: Profile) -> Config {
+ Config {
+ width: w,
+ height: h,
+ fps: (30, 1),
+ bitrate_kbps: 8000,
+ max_bitrate_kbps: 12000,
+ cbr: false,
+ keyint: 30,
+ profile,
+ level: None,
+ sar: None,
+ bframes: true,
+ }
+}
+
+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() }
+}
+
+fn mean(p: &[u8]) -> f64 {
+ p.iter().map(|v| f64::from(*v)).sum::<f64>() / p.len() as f64
+}
+
+/// Encode `frames` through the RGBA input, decode with our own decoder: the decoded planes by picture.
+fn round_trip(profile: Profile, w: usize, h: usize, frames: &[Vec<u8>]) -> Vec<[Vec<u8>; 3]> {
+ let mut enc =
+ Nvenc::with_rgba_input(&config(w as u32, h as u32, profile), &Signal::default()).unwrap_or_else(|e| panic!("{profile:?} with RGBA input: {e}"));
+ assert!(enc.takes_rgba());
+ assert!(enc.encode(&[0; 4], &[0; 1], &[0; 1], 0).is_err(), "planar pictures are refused");
+ let mut packets: Vec<Packet> = Vec::new();
+ for (i, f) in frames.iter().enumerate() {
+ packets.extend(enc.encode_rgba(f, i as u64).unwrap());
+ }
+ packets.extend(enc.flush().unwrap());
+ assert_eq!(packets.len(), frames.len(), "one packet per picture");
+ let entry = match enc.codec() {
+ Codec::Hevc => SampleEntry::hevc(enc.hevc_config().expect("an hvcC record").clone(), w as u16, h as u16),
+ Codec::H264 => {
+ let (sps, pps) = enc.parameter_sets();
+ 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());
+ out.sort_by_key(|f| f.pts);
+ assert_eq!(out.len(), frames.len());
+ out.into_iter()
+ .map(|f| {
+ let filmcraft_frame::PixelData::Yuv8 { planes, .. } = &f.frame.data else { panic!("8-bit planes") };
+ [planes[0].to_vec(), planes[1].to_vec(), planes[2].to_vec()]
+ })
+ .collect()
+}
+
+fn check(profile: Profile) {
+ let (w, h) = (1280usize, 720usize);
+ // solid colours: the decoded means are the BT.709 limited-range codes of the export's own conversion
+ let colours: [[u8; 3]; 6] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255], [0, 0, 0], [128, 128, 128]];
+ let mut frames: Vec<Vec<u8>> = colours.iter().map(|c| solid(w, h, *c)).collect();
+ frames.extend((0..24).map(|i| moving(w, h, i)));
+ let decoded = round_trip(profile, w, h, &frames);
+ let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());
+ for (k, c) in colours.iter().enumerate() {
+ filmcraft_export::rgba_to_yuv420_8(&frames[k], w, h, &mut y, &mut u, &mut v);
+ let want = [f64::from(y[0]), f64::from(u[0]), f64::from(v[0])];
+ let got = [mean(&decoded[k][0]), mean(&decoded[k][1]), mean(&decoded[k][2])];
+ eprintln!("{profile:?} {c:?}: Y/Cb/Cr {got:.1?}, BT.709 limited {want:?}");
+ for (g, e) in got.iter().zip(want) {
+ assert!((g - e).abs() <= 2.0, "{profile:?} {c:?}: decoded {got:.1?}, expected {want:?}");
+ }
+ }
+ // a moving picture: close to the export's own conversion encoded the planar way
+ let (mut worst, mut worst_chroma) = (99.0f64, 99.0f64);
+ for (k, f) in frames.iter().enumerate().skip(colours.len()) {
+ filmcraft_export::rgba_to_yuv420_8(f, w, h, &mut y, &mut u, &mut v);
+ worst = worst.min(psnr(&decoded[k][0], &y));
+ worst_chroma = worst_chroma.min(psnr(&decoded[k][1], &u)).min(psnr(&decoded[k][2], &v));
+ }
+ eprintln!("{profile:?}: worst luma PSNR {worst:.1} dB, chroma {worst_chroma:.1} dB");
+ assert!(worst > 40.0, "{profile:?} luma PSNR {worst:.1} dB");
+ assert!(worst_chroma > 40.0, "{profile:?} chroma PSNR {worst_chroma:.1} dB");
+}
+
+#[test]
+fn hevc_rgba_input_converts_like_the_export() {
+ let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !hevc_available() {
+ eprintln!("SKIPPED: no NVENC HEVC encoder");
+ return;
+ }
+ check(Profile::HevcMain);
+}
+
+#[test]
+fn h264_rgba_input_converts_like_the_export() {
+ let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !available() {
+ eprintln!("SKIPPED: no NVENC");
+ return;
+ }
+ check(Profile::High);
+}
+
+#[test]
+fn main10_has_no_rgba_input_and_short_pictures_are_errors() {
+ let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !hevc_available() {
+ eprintln!("SKIPPED: no NVENC HEVC encoder");
+ return;
+ }
+ assert!(Nvenc::with_rgba_input(&config(640, 360, Profile::HevcMain10), &Signal::default()).is_err());
+ let mut enc = Nvenc::with_rgba_input(&config(640, 360, Profile::HevcMain), &Signal::default()).unwrap();
+ assert!(enc.encode_rgba(&[], 0).is_err());
+ assert!(enc.encode_rgba(&vec![0; 640 * 360 * 4 - 1], 0).is_err());
+ let mut planar = Nvenc::new(&config(640, 360, Profile::HevcMain)).unwrap();
+ assert!(!planar.takes_rgba());
+ assert!(planar.encode_rgba(&solid(640, 360, [1, 2, 3]), 0).is_err(), "RGBA pictures for a planar encoder");
+}
diff --git a/docs/testing.md b/docs/testing.md
index 1b64781ce..7e16e8d48 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -73,7 +73,8 @@ are never linked or shipped ([AGENTS.md](../AGENTS.md) §2).
without a Direct3D 11 video device or the HEVC / VP9 / AV1 codec extensions of the Microsoft Store. The VP9 and
AV1 fixtures (libvpx-vp9, libaom-av1; 360p, 1080p, 2160p, hidden alt-ref frames, two GOPs) need an ffmpeg with those encoders.
-The NVENC tests (`crates/platform/tests/nvenc.rs` and `nvenc_export.rs` for H.264, `nvenc_hevc.rs`,
+The NVENC tests (`crates/platform/tests/nvenc.rs` and `nvenc_export.rs` for H.264, `nvenc_rgba_input.rs` for
+the GPU's RGB → 4:2:0 conversion, `nvenc_hevc.rs`,
`nvenc_hevc_export.rs`, `nvenc_hevc_probe.rs` and `nvenc_hevc_warm.rs` for H.265, `nvenc_hevc_main10.rs` and
`nvenc_hevc_hdr_export.rs` for Main 10 HDR; Windows only) skip, printing `SKIPPED`, without an NVIDIA GPU
with NVENC (H.265: when the HEVC probe says there is no HEVC encoder; Main 10: when the Main 10 probe says