diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index bbc6c937f..30e466f06 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -175,6 +175,7 @@ the original copyright and permission notice in its header. | File | Author | Source | Licence | |---|---|---|---| +| `crates/platform/src/amf/ffi.rs` | Advanced Micro Devices, Inc. (AMF SDK headers); FilmCraft contributors (Rust transcription) | Vtables (`AMFFactory`, `AMFContext`, `AMFComponent`, `AMFSurface`, `AMFPlane`, `AMFBuffer`), `AMFVariantStruct`, `AMFHDRMetadata`, component ids, result / memory / surface / variant codes and the colour-profile, primaries, transfer and output-type constants, transcribed from `amf/public/include` of the AMF SDK v1.5.3 (https://github.com/GPUOpen-LibrariesAndSDKs/AMF, commit 57ee0cfb0e1a); property names in `amf/session.rs` come from the same headers | MIT (Copyright (c) 2018-2026 Advanced Micro Devices, Inc.; notice kept in the file header) | | `crates/platform/src/nvenc/ffi.rs` | NVIDIA Corporation (`nvEncodeAPI.h`); FilmCraft contributors (Rust transcription) | Structures (including `NV_ENC_CONFIG_HEVC` and its bit-field masks, `NV_ENC_PIC_PARAMS_HEVC`, `NV_ENC_SEI_PAYLOAD`, `NV_ENC_TIME_CODE`), function table, codec / profile GUIDs (H.264, HEVC Main, HEVC Main 10) and constants (`NV_ENC_LEVEL_HEVC_*`, tier, CU size, `NV_ENC_BUFFER_FORMAT_YUV420_10BIT`, `NV_ENC_CAPS_SUPPORT_10BIT_ENCODE`, BT.2020 / PQ / HLG VUI codes) transcribed from `nvEncodeAPI.h`, NVIDIA Video Codec SDK, API 12.1 (https://developer.nvidia.com/video-codec-sdk) | MIT (Copyright (c) 2010-2023 NVIDIA Corporation; notice kept in the file header) | ## Downloaded at runtime diff --git a/crates/platform/README.md b/crates/platform/README.md index c79268f85..7a058c35e 100644 --- a/crates/platform/README.md +++ b/crates/platform/README.md @@ -80,6 +80,17 @@ let availability = filmcraft_platform::register(); // Available("VideoToolbox") ends it with an error, since a hardware stream cannot be finished in software. The same session, ring and input path encode H.265, see [Hardware H.265 (HEVC) encoding (Windows, NVENC)](#hardware-h265-hevc-encoding-windows-nvenc). +- **Windows: AMD AMF H.264 and H.265 (HEVC Main / Main 10) encoding** (`amf/`, #880) for Export + (AV1 export is deferred to a follow-up PR). + `amfrt64.dll`, installed with AMD's driver, is loaded from System32 at run time (no SDK is linked + or bundled), so machines without an AMD GPU start as before. Pictures go in as host NV12 (8-bit) or + P010 (10-bit) surfaces from the CPU's 4:2:0 conversion. HEVC streams carry their colour + description (BT.709, or BT.2020 with PQ / HLG) and, for PQ, the HDR10 static metadata the `mdcv` / + `clli` boxes carry. H.264 is used + with Export ▸ Hardware encoding on (Auto); H.265 needs no opt-in. The factory declines what + NVENC declines (CRF, all-intra H.264, two-pass, non-square pixels, interlacing, other colour + signals, odd or zero sizes), and leaves H.264 and H.265 to NVENC where an NVIDIA GPU has it. The bindings are private (`amf::ffi`, + `amf::session`); see the AMF addendum of [ADR 0001](../../docs/adr/0001-platform-ffi.md). - **Linux: NVDEC, H.264 (`avcC`) and HEVC (`hvcC`)** on NVIDIA's proprietary driver (`nvdec/`): H.264 8-bit and HEVC 8- / 10-bit, 4:2:0 progressive. `libnvcuvid.so.1` and `libcuda.so.1` are loaded at run time; without them (or without a device) nothing is registered. NVIDIA's own parser takes the diff --git a/crates/platform/src/amf/abi_tests.rs b/crates/platform/src/amf/abi_tests.rs new file mode 100644 index 000000000..91f7a3ccf --- /dev/null +++ b/crates/platform/src/amf/abi_tests.rs @@ -0,0 +1,132 @@ +//! The AMF FFI declarations against the C compiler's view of AMD's AMF SDK headers (v1.5.3, commit +//! `57ee0cfb0e1a08d9041f77435653794c1b012be0`): sizes, alignments, the offsets of every vtable entry +//! this backend calls and the constants it uses. Generated by a C program, built +//! with MSVC (`cl /std:c11 /TC`, Windows x64) against the MIT-licensed headers in +//! `amf/public/include`, that prints `sizeof` / `_Alignof` / `offsetof` and the constants; the +//! headers are not in this repository. To regenerate, put that folder on the include path of a +//! program printing the same facts and update the numbers here. +//! +//! The vtables are tables of function pointers, so an entry's offset is eight times its index: a +//! missing or extra entry before it moves every later one, which is what these tests catch. + +use super::ffi::*; +use std::mem::{align_of, offset_of, size_of}; + +#[test] +fn amf_variant_struct_layout_matches_the_header() { + // a 4-byte type tag, then a 16-byte union that its amf_int64 / double / pointer members align to 8 + assert_eq!((size_of::(), align_of::()), (24, 8), "AMFVariantStruct"); + assert_eq!(offset_of!(AmfVariant, var_type), 0, "AMFVariantStruct.type"); + assert_eq!(offset_of!(AmfVariant, val), 8, "AMFVariantStruct.int64Value"); +} + +#[test] +fn amf_hdr_metadata_layout_matches_the_header() { + assert_eq!((size_of::(), align_of::()), (28, 4), "AMFHDRMetadata"); + assert_eq!(offset_of!(AmfHdrMetadata, red_primary), 0); + assert_eq!(offset_of!(AmfHdrMetadata, green_primary), 4); + assert_eq!(offset_of!(AmfHdrMetadata, blue_primary), 8); + assert_eq!(offset_of!(AmfHdrMetadata, white_point), 12); + assert_eq!(offset_of!(AmfHdrMetadata, max_mastering_luminance), 16); + assert_eq!(offset_of!(AmfHdrMetadata, min_mastering_luminance), 20); + assert_eq!(offset_of!(AmfHdrMetadata, max_content_light_level), 24); + assert_eq!(offset_of!(AmfHdrMetadata, max_frame_average_light_level), 26); +} + +#[test] +fn amf_factory_vtbl_layout_matches_the_header() { + assert_eq!((size_of::(), align_of::()), (56, 8), "AMFFactoryVtbl"); + assert_eq!(offset_of!(AmfFactoryVtbl, create_context), 0, "AMFFactoryVtbl.CreateContext"); + assert_eq!(offset_of!(AmfFactoryVtbl, create_component), 8, "AMFFactoryVtbl.CreateComponent"); +} + +#[test] +fn amf_context_vtbl_layout_matches_the_header() { + assert_eq!(offset_of!(AmfContextVtbl, release), 8, "AMFContextVtbl.Release"); + assert_eq!(offset_of!(AmfContextVtbl, terminate), 104, "AMFContextVtbl.Terminate"); + assert_eq!(offset_of!(AmfContextVtbl, init_dx11), 144, "AMFContextVtbl.InitDX11"); + assert_eq!(offset_of!(AmfContextVtbl, alloc_buffer), 344, "AMFContextVtbl.AllocBuffer"); + assert_eq!(offset_of!(AmfContextVtbl, alloc_surface), 352, "AMFContextVtbl.AllocSurface"); +} + +#[test] +fn amf_component_vtbl_layout_matches_the_header() { + assert_eq!(offset_of!(AmfComponentVtbl, release), 8, "AMFComponentVtbl.Release"); + assert_eq!(offset_of!(AmfComponentVtbl, set_property), 24, "AMFComponentVtbl.SetProperty"); + assert_eq!(offset_of!(AmfComponentVtbl, get_property), 32, "AMFComponentVtbl.GetProperty"); + assert_eq!(offset_of!(AmfComponentVtbl, init), 136, "AMFComponentVtbl.Init"); + assert_eq!(offset_of!(AmfComponentVtbl, terminate), 152, "AMFComponentVtbl.Terminate"); + assert_eq!(offset_of!(AmfComponentVtbl, drain), 160, "AMFComponentVtbl.Drain"); + assert_eq!(offset_of!(AmfComponentVtbl, flush), 168, "AMFComponentVtbl.Flush"); + assert_eq!(offset_of!(AmfComponentVtbl, submit_input), 176, "AMFComponentVtbl.SubmitInput"); + assert_eq!(offset_of!(AmfComponentVtbl, query_output), 184, "AMFComponentVtbl.QueryOutput"); +} + +#[test] +fn amf_plane_vtbl_layout_matches_the_header() { + assert_eq!(offset_of!(AmfPlaneVtbl, release), 8, "AMFPlaneVtbl.Release"); + assert_eq!(offset_of!(AmfPlaneVtbl, get_native), 32, "AMFPlaneVtbl.GetNative"); + assert_eq!(offset_of!(AmfPlaneVtbl, get_hpitch), 80, "AMFPlaneVtbl.GetHPitch"); + assert_eq!(offset_of!(AmfPlaneVtbl, get_vpitch), 88, "AMFPlaneVtbl.GetVPitch"); + assert_eq!(offset_of!(AmfPlaneVtbl, is_tiled), 96, "AMFPlaneVtbl.IsTiled"); +} + +#[test] +fn amf_surface_vtbl_layout_matches_the_header() { + assert_eq!(offset_of!(AmfSurfaceVtbl, release), 8, "AMFSurfaceVtbl.Release"); + assert_eq!(offset_of!(AmfSurfaceVtbl, set_pts), 152, "AMFSurfaceVtbl.SetPts"); + assert_eq!(offset_of!(AmfSurfaceVtbl, get_pts), 160, "AMFSurfaceVtbl.GetPts"); + assert_eq!(offset_of!(AmfSurfaceVtbl, set_duration), 168, "AMFSurfaceVtbl.SetDuration"); + assert_eq!(offset_of!(AmfSurfaceVtbl, get_duration), 176, "AMFSurfaceVtbl.GetDuration"); + assert_eq!(offset_of!(AmfSurfaceVtbl, get_plane_at), 200, "AMFSurfaceVtbl.GetPlaneAt"); +} + +#[test] +fn amf_buffer_vtbl_layout_matches_the_header() { + assert_eq!(offset_of!(AmfBufferVtbl, release), 8, "AMFBufferVtbl.Release"); + assert_eq!(offset_of!(AmfBufferVtbl, get_property), 32, "AMFBufferVtbl.GetProperty"); + assert_eq!(offset_of!(AmfBufferVtbl, get_pts), 160, "AMFBufferVtbl.GetPts"); + assert_eq!(offset_of!(AmfBufferVtbl, get_size), 192, "AMFBufferVtbl.GetSize"); + assert_eq!(offset_of!(AmfBufferVtbl, get_native), 200, "AMFBufferVtbl.GetNative"); +} + +#[test] +fn amf_constants_match_the_header() { + assert_eq!((AMF_OK, AMF_FAIL, AMF_NOT_SUPPORTED, AMF_EOF, AMF_REPEAT, AMF_INPUT_FULL), (0, 1, 10, 23, 24, 25), "AMF_RESULT"); + assert_eq!((AMF_MEMORY_HOST, AMF_MEMORY_DX11), (1, 3), "AMF_MEMORY_TYPE"); + assert_eq!((AMF_SURFACE_NV12, AMF_SURFACE_RGBA, AMF_SURFACE_P010), (1, 5, 10), "AMF_SURFACE_FORMAT"); + assert_eq!(AMF_DX11_1, 111, "AMF_DX_VERSION"); + assert_eq!( + (AMF_VARIANT_BOOL, AMF_VARIANT_INT64, AMF_VARIANT_DOUBLE, AMF_VARIANT_RECT, AMF_VARIANT_SIZE, AMF_VARIANT_POINT, AMF_VARIANT_RATE, AMF_VARIANT_RATIO), + (1, 2, 3, 4, 5, 6, 7, 8), + "AMF_VARIANT_TYPE" + ); + assert_eq!(AMF_VARIANT_INTERFACE, 12, "AMF_VARIANT_INTERFACE"); + assert_eq!((AMF_VIDEO_CONVERTER_COLOR_PROFILE_709, AMF_VIDEO_CONVERTER_COLOR_PROFILE_2020), (1, 2), "AMF_VIDEO_CONVERTER_COLOR_PROFILE_ENUM"); + assert_eq!((AMF_COLOR_PRIMARIES_BT709, AMF_COLOR_PRIMARIES_BT2020), (1, 9), "AMF_COLOR_PRIMARIES_ENUM"); + assert_eq!( + (AMF_COLOR_TRANSFER_CHARACTERISTIC_BT709, AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084, AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67), + (1, 16, 18), + "AMF_COLOR_TRANSFER_CHARACTERISTIC_ENUM" + ); + assert_eq!( + ( + AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR, + AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_I, + AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_P, + AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_B + ), + (0, 1, 2, 3) + ); + assert_eq!((AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_IDR, AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_I, AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_P), (0, 1, 2)); + assert_eq!( + ( + AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_KEY, + AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_INTRA_ONLY, + AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_INTER, + AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_SWITCH, + AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_SHOW_EXISTING + ), + (0, 1, 2, 3, 4) + ); +} diff --git a/crates/platform/src/amf/export.rs b/crates/platform/src/amf/export.rs new file mode 100644 index 000000000..42c778e31 --- /dev/null +++ b/crates/platform/src/amf/export.rs @@ -0,0 +1,538 @@ +//! AMD AMF integration with FilmCraft export pipeline. + +use filmcraft_export::{ + BitrateMode, ColorSignal, EncodedPacket, EncoderFrame, ExportError, ExportSettings, FieldOrder, Format, H264Pass, H264Profile, HardwareEncoding, Result, + VideoEncoder, +}; +use filmcraft_isobmff::{Av1Config, AvcConfig, HevcConfig, SampleEntry}; +use filmcraft_time::FrameRate; + +use super::{Codec, Config, Profile, Session}; + +pub fn factory(format: Format, w: u32, h: u32, rate: FrameRate, s: &ExportSettings) -> Option>> { + // AMF opens its device on the default adapter. Where an NVIDIA GPU with NVENC is present, it + // takes H.264 and H.265 (an AMD iGPU as the default adapter must not get them). + // The NVENC probe is cached, and warmed when the platform registers. + if matches!(format, Format::H264 | Format::Hevc) && crate::nvenc::hevc_available() { + return None; + } + factory_with(format, w, h, rate, s, Session::open) +} + +/// AMF export factory without the dual-GPU handoff to NVENC (for testing AMF directly on AMD+NVIDIA hosts). +#[doc(hidden)] +pub fn direct_factory(format: Format, w: u32, h: u32, rate: FrameRate, s: &ExportSettings) -> Option>> { + factory_with(format, w, h, rate, s, Session::open) +} + +/// [`factory`] with the session open replaced, so what it declines is tested without the hardware. +fn factory_with( + format: Format, + w: u32, + h: u32, + rate: FrameRate, + s: &ExportSettings, + open: impl FnOnce(&Config) -> std::result::Result, +) -> Option>> { + let cfg = match config(format, w, h, rate, s) { + Ok(Some(cfg)) => cfg, + Ok(None) => return None, + Err(why) => { + log::info!("AMD AMF declined the {format:?} export: {why}"); + return None; + } + }; + let codec = cfg.profile.codec(); + let session = match open(&cfg) { + Ok(s) => s, + Err(why) => { + log::info!("AMD AMF {:?} encoding declined: {why}", codec); + return None; + } + }; + + filmcraft_export::note_hw_encode_session(); + Some(Ok(Box::new(AmfEncoder { + session, + w, + h, + rate, + signal: s.signal, + sps: Vec::new(), + pps: Vec::new(), + vps: Vec::new(), + hvcc: None, + av1c: None, + y: Vec::new(), + u: Vec::new(), + v: Vec::new(), + y16: Vec::new(), + u16: Vec::new(), + v16: Vec::new(), + }))) +} + +/// The session for this export: `Ok(None)` when it is not one AMF handles at all (another format, +/// or H.264 with Hardware encoding off), `Err` with the reason when AMF would encode something other +/// than what was asked. The same declines as NVENC's (`nvenc::export::config`), for AV1 too. +fn config(format: Format, w: u32, h: u32, rate: FrameRate, s: &ExportSettings) -> std::result::Result, String> { + let codec = match format { + Format::H264 if s.hardware_encoding == HardwareEncoding::Auto && !s.signal.is_hdr() => Codec::H264, + Format::Hevc => Codec::Hevc, + _ => return Ok(None), + }; + if s.format.is_mxf() { + return Err("MXF".into()); + } + let hdr = s.signal.is_hdr(); + // BT.709 SDR, or BT.2020 NCL with PQ / HLG: the colour descriptions the session writes + if hdr && (s.signal.primaries != 9 || s.signal.matrix != 9) || !hdr && s.signal != ColorSignal::default() { + return Err(format!("the colour signal {:?} (AMF here writes BT.709, or BT.2020 with PQ / HLG)", s.signal)); + } + if s.bitrate_mode == BitrateMode::Vbr2Pass || !matches!(s.h264_pass, H264Pass::Single) { + return Err("two-pass VBR".into()); + } + if s.bitrate_mode == BitrateMode::Crf { + return Err("CRF (constant quality)".into()); + } + if codec == Codec::H264 && s.h264_intra_only { + return Err("all-intra H.264".into()); + } + // the session writes no aspect ratio, for any codec + if s.pixel_aspect.is_some_and(|(n, d)| n != d) { + return Err("non-square pixels".into()); + } + if s.field_order != FieldOrder::Progressive { + return Err("interlaced output".into()); + } + if w == 0 || h == 0 || !w.is_multiple_of(2) || !h.is_multiple_of(2) { + return Err(format!("AMF needs nonzero even dimensions, not {w}x{h}")); + } + if w > u32::from(u16::MAX) || h > u32::from(u16::MAX) { + return Err(format!("{w}x{h} does not fit an MP4 sample entry")); + } + let (Ok(timescale), Ok(frame_duration)) = (u32::try_from(rate.num), u32::try_from(rate.den)) else { + return Err("frame rate".into()); + }; + if timescale == 0 || frame_duration == 0 { + return Err("frame rate".into()); + } + let fps_val = f64::from(timescale) / f64::from(frame_duration); + let keyint = s.keyframe_distance.filter(|&k| k > 0).unwrap_or_else(|| (fps_val * 2.0).round().max(1.0) as u32); + let kbps = s.bitrate_kbps.max(100); + let max_kbps = s.max_bitrate_kbps.filter(|&m| m >= kbps).unwrap_or(kbps.saturating_mul(3) / 2); + let profile = match codec { + Codec::H264 => match s.h264_profile { + H264Profile::Baseline => Profile::H264Baseline, + H264Profile::Main => Profile::H264Main, + H264Profile::High => Profile::H264High, + H264Profile::High10 => return Err("H.264 High 10".into()), + }, + Codec::Hevc if hdr => Profile::HevcMain10, + Codec::Hevc => Profile::HevcMain, + Codec::Av1 if hdr => Profile::Av1Main10, + Codec::Av1 => Profile::Av1Main, + }; + Ok(Some(Config { + width: w, + height: h, + fps: (timescale, frame_duration), + bitrate_kbps: kbps, + max_bitrate_kbps: max_kbps, + cbr: s.bitrate_mode == BitrateMode::Cbr, + keyint, + profile, + signal: s.signal, + })) +} + +struct AmfEncoder { + session: Session, + w: u32, + h: u32, + rate: FrameRate, + signal: ColorSignal, + sps: Vec, + pps: Vec, + vps: Vec, + hvcc: Option, + av1c: Option, + y: Vec, + u: Vec, + v: Vec, + y16: Vec, + u16: Vec, + v16: Vec, +} + +impl AmfEncoder { + fn process_raw_packets(&mut self, packets: Vec) -> Result> { + let duration = u32::try_from(self.rate.den).unwrap_or(u32::MAX); + let mut out = Vec::new(); + + for p in packets { + filmcraft_export::note_hw_encode_frame(); + let codec = self.session.codec(); + let is_av1 = codec == Codec::Av1; + + if !is_av1 { + // Parse parameter sets from keyframe Annex B if not parsed yet + if self.sps.is_empty() { + // the sample entry is built from the first keyframe's parameter sets, and they are + // stripped from the samples: without them the file would not decode + let sets = parameter_sets(codec, p.key, &p.data, (self.w, self.h), self.session.is_ten_bit()).map_err(ExportError::Encode)?; + self.vps = sets.vps; + self.sps = sets.sps; + self.pps = sets.pps; + self.hvcc = sets.hvcc; + } + } else if self.av1c.is_none() { + // the `av1C` must match the stream's sequence header, which the first keyframe carries + self.av1c = Some(av1_config(p.key, &p.data).map_err(ExportError::Encode)?); + } + + let data = if is_av1 { + p.data + } else { + let nvenc_codec = match codec { + Codec::H264 => crate::nvenc::Codec::H264, + Codec::Hevc => crate::nvenc::Codec::Hevc, + Codec::Av1 => return Err(ExportError::Encode("unexpected AV1 Annex B conversion request".into())), + }; + crate::nvenc::annex_b_to_length_prefixed_for(nvenc_codec, &p.data) + .map_err(|e| ExportError::Encode(format!("AMD AMF Annex B conversion failed: {e}")))? + }; + + out.push(EncodedPacket { data, key: p.key, duration, composition_offset: 0 }); + } + Ok(out) + } +} + +impl VideoEncoder for AmfEncoder { + fn sample_entry(&self) -> SampleEntry { + let (w, h) = (u16::try_from(self.w).unwrap_or(u16::MAX), u16::try_from(self.h).unwrap_or(u16::MAX)); + match self.session.codec() { + Codec::H264 => SampleEntry::avc(AvcConfig::new(vec![self.sps.clone()], vec![self.pps.clone()], 4), w, h), + Codec::Hevc => { + let mut e = SampleEntry::hevc(self.hvcc.clone().unwrap_or_default(), w, h); + self.signal.apply_to(&mut e, false); + e + } + Codec::Av1 => { + let mut e = SampleEntry::av1(self.av1c.clone().unwrap_or_default(), w, h); + self.signal.apply_to(&mut e, false); + e + } + } + } + + fn timescale(&self) -> u32 { + u32::try_from(self.rate.num).unwrap_or(u32::MAX) + } + + fn hardware(&self) -> Option<&'static str> { + Some("AMD AMF") + } + + fn encode(&mut self, f: &EncoderFrame) -> Result> { + if f.width != self.w || f.height != self.h { + return Err(ExportError::Encode(format!("AMD AMF: picture size {}x{} does not match encoder {}x{}", f.width, f.height, self.w, self.h))); + } + + let pts = i64::try_from(f.index).unwrap_or(0).saturating_mul(self.rate.den); + let duration = self.rate.den; + + let raw = match (self.session.is_ten_bit(), f.hdr) { + (true, Some(rgb)) => { + let (kr, kb) = self.signal.kr_kb(); + filmcraft_export::timed(filmcraft_export::Stage::Convert, || { + filmcraft_export::rgbf_to_yuv420_10( + rgb, + self.w as usize, + self.h as usize, + filmcraft_export::Matrix::new(kr, kb), + &mut self.y16, + &mut self.u16, + &mut self.v16, + ) + })?; + self.session.encode_10bit(&self.y16, &self.u16, &self.v16, pts, duration) + } + (true, None) => return Err(ExportError::Unsupported("AMD AMF Main 10 needs the HDR picture (EncoderFrame::hdr)".into())), + (false, Some(_)) => return Err(ExportError::Unsupported("AMD AMF Main (8-bit) does not take HDR pictures".into())), + (false, None) => { + filmcraft_export::timed(filmcraft_export::Stage::Convert, || { + 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) + }); + self.session.encode_8bit(&self.y, &self.u, &self.v, pts, duration) + } + }; + + let packets = raw.map_err(|e| ExportError::Encode(format!("AMD AMF encode failed: {e}")))?; + self.process_raw_packets(packets) + } + + fn flush(&mut self) -> Result> { + let packets = self.session.drain().map_err(|e| ExportError::Encode(format!("AMD AMF drain failed: {e}")))?; + self.process_raw_packets(packets) + } +} + +/// The parameter sets of the first packet, from which the sample entry is written. +struct ParameterSets { + vps: Vec, + sps: Vec, + pps: Vec, + hvcc: Option, +} + +fn parameter_sets(codec: Codec, key: bool, data: &[u8], size: (u32, u32), ten_bit: bool) -> std::result::Result { + if !key { + return Err("AMD AMF: the first packet is not a keyframe, so it carries no parameter sets".into()); + } + match codec { + Codec::H264 => { + let (sps, pps) = crate::nvenc::split_parameter_sets(data).map_err(|e| format!("AMD AMF: the first keyframe has no usable SPS/PPS: {e}"))?; + Ok(ParameterSets { vps: Vec::new(), sps, pps, hvcc: None }) + } + Codec::Hevc => { + let (vps, sps, pps) = + crate::nvenc::split_hevc_parameter_sets(data).map_err(|e| format!("AMD AMF: the first keyframe has no usable VPS/SPS/PPS: {e}"))?; + let hvcc = crate::nvenc::hevc::hevc_config(&vps, &sps, &pps, size, if ten_bit { 10 } else { 8 }) + .map_err(|e| format!("AMD AMF: the first keyframe's HEVC parameter sets are unusable: {e}"))?; + Ok(ParameterSets { vps, sps, pps, hvcc: Some(hvcc) }) + } + Codec::Av1 => Err("AMD AMF: AV1 has no Annex B parameter sets".into()), + } +} + +/// The OBUs of a temporal unit (each with a size field, as AMF writes them): `(type, whole OBU, payload)`. +fn av1_obus(data: &[u8]) -> Vec<(u8, &[u8], &[u8])> { + let mut out = Vec::new(); + let mut pos = 0usize; + while pos < data.len() { + let start = pos; + let b0 = data[pos]; + let (obu_type, extension, has_size) = ((b0 >> 3) & 0x0f, (b0 >> 2) & 1 == 1, (b0 >> 1) & 1 == 1); + pos += 1 + usize::from(extension); + if !has_size { + break; + } + let mut len = 0usize; + let mut shift = 0; + loop { + let Some(&b) = data.get(pos) else { return out }; + pos += 1; + len |= usize::from(b & 0x7f) << shift; + shift += 7; + if b & 0x80 == 0 { + break; + } + if shift > 56 { + return out; + } + } + let Some(end) = pos.checked_add(len).filter(|&e| e <= data.len()) else { return out }; + out.push((obu_type, &data[start..end], &data[pos..end])); + pos = end; + } + out +} + +/// `seq_tier[0]` of a sequence header OBU's payload (AV1 §5.5.1): coded only for a level above 3.3. +fn av1_tier_0(payload: &[u8]) -> Option { + let mut r = Bits { data: payload, pos: 0 }; + r.read(3)?; // seq_profile + r.read(1)?; // still_picture + if r.read(1)? == 1 { + // reduced_still_picture_header: one level, Main tier + return Some(false); + } + if r.read(1)? == 1 { + // timing_info: num_units_in_display_tick, time_scale, equal_picture_interval + r.read(32)?; + r.read(32)?; + if r.read(1)? == 1 { + r.uvlc()?; // num_ticks_per_picture_minus_1 + } + if r.read(1)? == 1 { + // decoder_model_info: buffer_delay_length_minus_1, num_units_in_decoding_tick, + // buffer_removal_time_length_minus_1, frame_presentation_time_length_minus_1 + r.read(5)?; + r.read(32)?; + r.read(5)?; + r.read(5)?; + } + } + r.read(1)?; // initial_display_delay_present_flag + r.read(5)?; // operating_points_cnt_minus_1 + r.read(12)?; // operating_point_idc[0] + let level = r.read(5)?; + Some(level > 7 && r.read(1)? == 1) +} + +/// An MSB-first bit reader over a byte slice. +struct Bits<'a> { + data: &'a [u8], + pos: usize, +} + +impl Bits<'_> { + fn read(&mut self, n: u32) -> Option { + let mut v = 0u32; + for _ in 0..n { + let byte = *self.data.get(self.pos / 8)?; + v = (v << 1) | u32::from((byte >> (7 - self.pos % 8)) & 1); + self.pos += 1; + } + Some(v) + } + + fn uvlc(&mut self) -> Option { + let mut zeros = 0; + while self.read(1)? == 0 { + zeros += 1; + if zeros >= 32 { + return Some(u32::MAX); + } + } + Some(self.read(zeros)?.saturating_add((1u32 << zeros) - 1)) + } +} + +/// The `av1C` of the stream, from the sequence header OBU of the first packet (AV1-ISOBMFF §2.3: its +/// fields restate the sequence header's, and `configOBUs` carries the header itself). +fn av1_config(key: bool, data: &[u8]) -> std::result::Result { + if !key { + return Err("AMD AMF: the first AV1 packet is not a keyframe, so it carries no sequence header".into()); + } + let (obu, payload) = + av1_obus(data).into_iter().find(|(t, ..)| *t == 1).map(|(_, o, p)| (o, p)).ok_or("AMD AMF: the first AV1 keyframe has no sequence header")?; + let seq = craft_video::av1::decode::SequenceHeader::parse(payload).map_err(|e| format!("AMD AMF: the AV1 sequence header is unusable: {e}"))?; + let c = &seq.color; + Ok(Av1Config { + seq_profile: seq.profile, + seq_level_idx_0: seq.seq_level_idx[0], + // the decoder's parser reads seq_tier but does not keep it + seq_tier_0: av1_tier_0(payload).ok_or("AMD AMF: the AV1 sequence header ends before its first operating point")?, + high_bitdepth: c.bit_depth > 8, + twelve_bit: c.bit_depth == 12, + monochrome: c.mono_chrome, + chroma_subsampling_x: c.subsampling_x == 1, + chroma_subsampling_y: c.subsampling_y == 1, + chroma_sample_position: c.chroma_sample_position, + initial_presentation_delay_minus_one: None, + config_obus: obu.to_vec(), + }) +} + +#[cfg(test)] +mod parameter_set_tests { + use super::*; + + #[test] + fn a_first_keyframe_without_parameter_sets_fails_the_export() { + // an IDR slice alone: no SPS or PPS to build the sample entry from + let idr_only = [0, 0, 0, 1, 0x65, 0x88, 0x84, 0x00]; + assert!(parameter_sets(Codec::H264, true, &idr_only, (64, 64), false).is_err()); + assert!(parameter_sets(Codec::Hevc, true, &[0, 0, 0, 1, 0x26, 0x01, 0xaf], (64, 64), false).is_err()); + } + + #[test] + fn a_first_packet_that_is_not_a_keyframe_fails_the_export() { + assert!(parameter_sets(Codec::H264, false, &[0, 0, 0, 1, 0x41, 0x9a], (64, 64), false).is_err()); + } + + #[test] + fn the_first_keyframe_gives_its_sps_and_pps() { + let data = [0, 0, 0, 1, 0x67, 0x64, 0x00, 0x1f, 0, 0, 0, 1, 0x68, 0xee, 0x3c, 0x80, 0, 0, 0, 1, 0x65, 0x88]; + let sets = parameter_sets(Codec::H264, true, &data, (64, 64), false).unwrap(); + assert_eq!(sets.sps, [0x67, 0x64, 0x00, 0x1f]); + assert_eq!(sets.pps, [0x68, 0xee, 0x3c, 0x80]); + } +} + +#[cfg(test)] +mod factory_tests { + use super::*; + use std::cell::Cell; + + const RATE: FrameRate = FrameRate { num: 30, den: 1 }; + + fn auto() -> ExportSettings { + ExportSettings { hardware_encoding: HardwareEncoding::Auto, ..ExportSettings::default() } + } + + /// Whether the factory got as far as opening a session (stubbed to fail, so nothing is encoded). + fn opens(format: Format, w: u32, h: u32, s: &ExportSettings) -> bool { + let opened = Cell::new(false); + let r = factory_with(format, w, h, RATE, s, |_| { + opened.set(true); + Err("stub".into()) + }); + assert!(r.is_none(), "a failed open declines"); + opened.get() + } + + #[test] + fn exports_amf_would_encode_differently_are_declined_before_a_session_opens() { + for (what, format, s) in [ + ("H.264 CRF", Format::H264, ExportSettings { bitrate_mode: BitrateMode::Crf, ..auto() }), + ("H.265 CRF", Format::Hevc, ExportSettings { bitrate_mode: BitrateMode::Crf, ..auto() }), + ("all-intra H.264", Format::H264, ExportSettings { h264_intra_only: true, ..auto() }), + ("two-pass VBR", Format::Hevc, ExportSettings { bitrate_mode: BitrateMode::Vbr2Pass, ..auto() }), + ("non-square pixels, H.265", Format::Hevc, ExportSettings { pixel_aspect: Some((4, 3)), ..auto() }), + ("interlaced", Format::Hevc, ExportSettings { field_order: FieldOrder::UpperFirst, ..auto() }), + ("BT.601 SDR", Format::Hevc, ExportSettings { signal: ColorSignal { primaries: 6, transfer: 6, matrix: 6 }, ..auto() }), + ("PQ with BT.709 primaries", Format::Hevc, ExportSettings { signal: ColorSignal { primaries: 1, transfer: 16, matrix: 1 }, ..auto() }), + ("H.264 with Hardware encoding off", Format::H264, ExportSettings::default()), + ("AV1 deferred to follow-up", Format::Av1, auto()), + ] { + assert!(!opens(format, 1920, 1080, &s), "{what}: declined"); + } + for (w, h) in [(0, 1080), (1920, 0), (1921, 1080), (1920, 1081), (70_000, 1080)] { + assert!(!opens(Format::Hevc, w, h, &auto()), "{w}x{h}: declined"); + } + assert!(!opens(Format::ProRes, 1920, 1080, &auto()), "not a format AMF encodes"); + } + + #[test] + fn exports_amf_encodes_as_asked_open_a_session() { + assert!(opens(Format::H264, 1920, 1080, &auto())); + assert!(opens(Format::H264, 1920, 1080, &ExportSettings { bitrate_mode: BitrateMode::Cbr, pixel_aspect: Some((1, 1)), ..auto() })); + assert!(opens(Format::Hevc, 1920, 1080, &ExportSettings::default()), "H.265 needs no opt-in"); + assert!(opens(Format::Hevc, 3840, 2160, &ExportSettings { signal: ColorSignal::PQ, ..auto() })); + let cfg = config(Format::Hevc, 3840, 2160, RATE, &ExportSettings { signal: ColorSignal::PQ, ..auto() }).unwrap().unwrap(); + assert_eq!((cfg.profile, cfg.signal), (Profile::HevcMain10, ColorSignal::PQ), "Main 10 with the export's colour"); + } + + /// A 1080p 10-bit PQ sequence header OBU as libaom writes it: level 4.0 (8), Main tier. + const SEQUENCE_HEADER: [u8; 16] = [0x0a, 0x0e, 0x00, 0x00, 0x00, 0x42, 0xab, 0xbf, 0xc3, 0x73, 0x2b, 0xe5, 0x40, 0x80, 0x82, 0x41]; + + #[test] + fn the_av1c_restates_the_first_keyframes_sequence_header() { + // a temporal delimiter, the sequence header, then (a stand-in for) a frame OBU + let mut tu = vec![0x12, 0x00]; + tu.extend_from_slice(&SEQUENCE_HEADER); + tu.extend_from_slice(&[0x32, 0x01, 0x10]); + let c = av1_config(true, &tu).unwrap(); + assert_eq!((c.seq_profile, c.seq_level_idx_0, c.seq_tier_0), (0, 8, false)); + assert!(c.high_bitdepth && !c.twelve_bit && !c.monochrome); + assert!(c.chroma_subsampling_x && c.chroma_subsampling_y); + assert_eq!(c.config_obus, SEQUENCE_HEADER, "configOBUs carries the sequence header OBU"); + assert!(av1_config(false, &tu).is_err(), "not a keyframe"); + assert!(av1_config(true, &[0x12, 0x00, 0x32, 0x01, 0x10]).is_err(), "no sequence header"); + } + + #[test] + fn the_tier_is_read_where_the_level_codes_it() { + // seq_profile 0, flags 0, operating_points_cnt_minus_1 0, idc 0, level 13 (5.1), tier 1 + let high = [0x00, 0x00, 0x00, 0b0110_1100]; + assert_eq!(av1_tier_0(&high), Some(true)); + // level 4 (3.0) codes no tier: the next bit is not read as one + let low = [0x00, 0x00, 0x00, 0b0010_0100]; + assert_eq!(av1_tier_0(&low), Some(false)); + assert_eq!(av1_tier_0(&[0x00]), None, "truncated"); + } +} diff --git a/crates/platform/src/amf/ffi.rs b/crates/platform/src/amf/ffi.rs new file mode 100644 index 000000000..e4b350749 --- /dev/null +++ b/crates/platform/src/amf/ffi.rs @@ -0,0 +1,440 @@ +// The declarations in this file are transcribed from AMD's AMF SDK headers (`amf/public/include`, +// AMF SDK v1.5.3, https://github.com/GPUOpen-LibrariesAndSDKs/AMF, commit 57ee0cfb0e1a), which +// carry this notice: +// +// Copyright (c) 2018-2026 Advanced Micro Devices, Inc. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +//! AMD's Advanced Media Framework (AMF) as the driver's `amfrt64.dll` expects it: the structures, +//! vtables and constants this backend uses, from the AMF SDK v1.5.3 headers (`core/Factory.h`, +//! `core/Context.h`, `core/Surface.h`, `core/Plane.h`, `core/Buffer.h`, `core/Variant.h`, +//! `components/Component.h`, `components/ColorSpace.h`, `components/VideoEncoderVCE.h`, +//! `components/VideoEncoderHEVC.h`, `components/VideoEncoderAV1.h`). Written from the public +//! headers; sizes, offsets and constants are checked against a C compiler's by `abi_tests.rs`. +//! `amfrt64.dll` is loaded at run time; no AMD SDK is linked or bundled. `AMFInit` is asked for +//! interface version 1.4.0. + +#![allow(dead_code)] + +use std::ffi::c_void; +use std::sync::OnceLock; +use windows::Win32::Foundation::HMODULE; +use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; +use windows::core::{PCSTR, w}; + +pub const AMF_OK: i32 = 0; +pub const AMF_FAIL: i32 = 1; +pub const AMF_EOF: i32 = 23; +pub const AMF_REPEAT: i32 = 24; +pub const AMF_INPUT_FULL: i32 = 25; +pub const AMF_NOT_SUPPORTED: i32 = 10; + +pub const AMF_MEMORY_HOST: u32 = 1; +pub const AMF_MEMORY_DX11: u32 = 3; + +pub const AMF_SURFACE_NV12: u32 = 1; +pub const AMF_SURFACE_P010: u32 = 10; +pub const AMF_SURFACE_RGBA: u32 = 5; + +pub const AMF_DX11_1: u32 = 111; + +pub const AMF_VARIANT_BOOL: i32 = 1; +pub const AMF_VARIANT_INT64: i32 = 2; +pub const AMF_VARIANT_DOUBLE: i32 = 3; +pub const AMF_VARIANT_RECT: i32 = 4; +pub const AMF_VARIANT_SIZE: i32 = 5; +pub const AMF_VARIANT_POINT: i32 = 6; +pub const AMF_VARIANT_RATE: i32 = 7; +pub const AMF_VARIANT_RATIO: i32 = 8; +pub const AMF_VARIANT_INTERFACE: i32 = 12; + +// AMF_VIDEO_CONVERTER_COLOR_PROFILE_ENUM +pub const AMF_VIDEO_CONVERTER_COLOR_PROFILE_709: i64 = 1; +pub const AMF_VIDEO_CONVERTER_COLOR_PROFILE_2020: i64 = 2; + +// AMF_COLOR_PRIMARIES_ENUM and AMF_COLOR_TRANSFER_CHARACTERISTIC_ENUM take the H.273 code points +pub const AMF_COLOR_PRIMARIES_BT709: i64 = 1; +pub const AMF_COLOR_PRIMARIES_BT2020: i64 = 9; +pub const AMF_COLOR_TRANSFER_CHARACTERISTIC_BT709: i64 = 1; +pub const AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084: i64 = 16; +pub const AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67: i64 = 18; + +/// `AMFHDRMetadata`: the HDR10 static metadata (chromaticities in 0.00002, luminance in 0.0001 cd/m²). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct AmfHdrMetadata { + pub red_primary: [u16; 2], + pub green_primary: [u16; 2], + pub blue_primary: [u16; 2], + pub white_point: [u16; 2], + pub max_mastering_luminance: u32, + pub min_mastering_luminance: u32, + pub max_content_light_level: u16, + pub max_frame_average_light_level: u16, +} + +// H.264 Output Data Type (AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_ENUM) +pub const AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR: i64 = 0; +pub const AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_I: i64 = 1; +pub const AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_P: i64 = 2; +pub const AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_B: i64 = 3; + +// HEVC Output Data Type (AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_ENUM) +pub const AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_IDR: i64 = 0; +pub const AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_I: i64 = 1; +pub const AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_P: i64 = 2; + +// AV1 Output Frame Type (AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_ENUM) +pub const AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_KEY: i64 = 0; +pub const AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_INTRA_ONLY: i64 = 1; +pub const AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_INTER: i64 = 2; +pub const AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_SWITCH: i64 = 3; +pub const AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_SHOW_EXISTING: i64 = 4; + +pub const AMF_VIDEO_ENCODER_VCE_AVC: windows::core::PCWSTR = windows::core::w!("AMFVideoEncoderVCE_AVC"); +pub const AMF_VIDEO_ENCODER_HW_HEVC: windows::core::PCWSTR = windows::core::w!("AMFVideoEncoderHW_HEVC"); +pub const AMF_VIDEO_ENCODER_HW_AV1: windows::core::PCWSTR = windows::core::w!("AMFVideoEncoderHW_AV1"); + +pub type AmfInitFn = unsafe extern "C" fn(u64, *mut *mut AmfFactory) -> i32; +pub type AmfQueryVersionFn = unsafe extern "C" fn(*mut u64) -> i32; + +/// `AMFVariantStruct`: the type tag, then a 16-byte union (its largest members are `AMFRect` and +/// `AMFFloatVector4D`) that its `amf_int64`, `amf_double` and pointer members make 8-byte aligned. +#[repr(C, align(8))] +#[derive(Clone, Copy)] +pub struct AmfVariant { + pub var_type: i32, + pub _pad: u32, + pub val: [u8; 16], +} + +impl AmfVariant { + pub fn int64(v: i64) -> Self { + let mut s = Self { var_type: AMF_VARIANT_INT64, _pad: 0, val: [0; 16] }; + s.val[..8].copy_from_slice(&v.to_ne_bytes()); + s + } + + pub fn bool_val(v: bool) -> Self { + let mut s = Self { var_type: AMF_VARIANT_BOOL, _pad: 0, val: [0; 16] }; + s.val[0] = if v { 1 } else { 0 }; + s + } + + pub fn rate(num: u32, den: u32) -> Self { + let mut s = Self { var_type: AMF_VARIANT_RATE, _pad: 0, val: [0; 16] }; + s.val[..4].copy_from_slice(&num.to_ne_bytes()); + s.val[4..8].copy_from_slice(&den.to_ne_bytes()); + s + } + + pub fn ratio(num: u32, den: u32) -> Self { + let mut s = Self { var_type: AMF_VARIANT_RATIO, _pad: 0, val: [0; 16] }; + s.val[..4].copy_from_slice(&num.to_ne_bytes()); + s.val[4..8].copy_from_slice(&den.to_ne_bytes()); + s + } + + pub fn size(width: i32, height: i32) -> Self { + let mut s = Self { var_type: AMF_VARIANT_SIZE, _pad: 0, val: [0; 16] }; + s.val[..4].copy_from_slice(&width.to_ne_bytes()); + s.val[4..8].copy_from_slice(&height.to_ne_bytes()); + s + } + + /// An `AMFInterface*` (here an `AMFBuffer`); the receiver takes its own reference. + pub fn interface(p: *mut c_void) -> Self { + let mut s = Self { var_type: AMF_VARIANT_INTERFACE, _pad: 0, val: [0; 16] }; + s.val[..size_of::()].copy_from_slice(&(p as usize).to_ne_bytes()); + s + } + + pub fn as_int64(&self) -> Option { + if self.var_type == AMF_VARIANT_INT64 { + let bytes = <[u8; 8]>::try_from(&self.val[..8]).ok()?; + Some(i64::from_ne_bytes(bytes)) + } else { + None + } + } +} + +#[repr(C)] +pub struct AmfFactoryVtbl { + pub create_context: unsafe extern "system" fn(*mut AmfFactory, *mut *mut AmfContext) -> i32, + pub create_component: unsafe extern "system" fn(*mut AmfFactory, *mut AmfContext, *const u16, *mut *mut AmfComponent) -> i32, + pub set_cache_folder: *const c_void, + pub get_cache_folder: *const c_void, + pub get_debug: *const c_void, + pub get_trace: *const c_void, + pub get_programs: *const c_void, +} + +#[repr(C)] +pub struct AmfFactory { + pub vtbl: *const AmfFactoryVtbl, +} + +#[repr(C)] +pub struct AmfContextVtbl { + pub acquire: *const c_void, + pub release: unsafe extern "system" fn(*mut AmfContext) -> i32, + pub query_interface: *const c_void, + + pub set_property: *const c_void, + pub get_property: *const c_void, + pub has_property: *const c_void, + pub get_property_count: *const c_void, + pub get_property_at: *const c_void, + pub clear: *const c_void, + pub add_to: *const c_void, + pub copy_to: *const c_void, + pub add_observer: *const c_void, + pub remove_observer: *const c_void, + + pub terminate: unsafe extern "system" fn(*mut AmfContext) -> i32, + + pub init_dx9: *const c_void, + pub get_dx9_device: *const c_void, + pub lock_dx9: *const c_void, + pub unlock_dx9: *const c_void, + + pub init_dx11: unsafe extern "system" fn(*mut AmfContext, *mut c_void, u32) -> i32, + pub get_dx11_device: *const c_void, + pub lock_dx11: *const c_void, + pub unlock_dx11: *const c_void, + + pub init_opencl: *const c_void, + pub get_opencl_context: *const c_void, + pub get_opencl_command_queue: *const c_void, + pub get_opencl_device_id: *const c_void, + pub get_opencl_compute_factory: *const c_void, + pub init_opencl_ex: *const c_void, + pub lock_opencl: *const c_void, + pub unlock_opencl: *const c_void, + + pub init_opengl: *const c_void, + pub get_opengl_context: *const c_void, + pub get_opengl_drawable: *const c_void, + pub lock_opengl: *const c_void, + pub unlock_opengl: *const c_void, + + pub init_xv: *const c_void, + pub get_xv_device: *const c_void, + pub lock_xv: *const c_void, + pub unlock_xv: *const c_void, + + pub init_gralloc: *const c_void, + pub get_gralloc_device: *const c_void, + pub lock_gralloc: *const c_void, + pub unlock_gralloc: *const c_void, + + pub alloc_buffer: unsafe extern "system" fn(*mut AmfContext, u32, usize, *mut *mut AmfBuffer) -> i32, + pub alloc_surface: unsafe extern "system" fn(*mut AmfContext, u32, u32, i32, i32, *mut *mut AmfSurface) -> i32, +} + +#[repr(C)] +pub struct AmfContext { + pub vtbl: *const AmfContextVtbl, +} + +#[repr(C)] +pub struct AmfComponentVtbl { + pub acquire: *const c_void, + pub release: unsafe extern "system" fn(*mut AmfComponent) -> i32, + pub query_interface: *const c_void, + + pub set_property: unsafe extern "system" fn(*mut AmfComponent, *const u16, AmfVariant) -> i32, + pub get_property: unsafe extern "system" fn(*mut AmfComponent, *const u16, *mut AmfVariant) -> i32, + pub has_property: *const c_void, + pub get_property_count: *const c_void, + pub get_property_at: *const c_void, + pub clear: *const c_void, + pub add_to: *const c_void, + pub copy_to: *const c_void, + pub add_observer: *const c_void, + pub remove_observer: *const c_void, + + pub get_properties_info_count: *const c_void, + pub get_property_info_at: *const c_void, + pub get_property_info: *const c_void, + pub validate_property: *const c_void, + + pub init: unsafe extern "system" fn(*mut AmfComponent, u32, i32, i32) -> i32, + pub reinit: *const c_void, + pub terminate: unsafe extern "system" fn(*mut AmfComponent) -> i32, + pub drain: unsafe extern "system" fn(*mut AmfComponent) -> i32, + pub flush: unsafe extern "system" fn(*mut AmfComponent) -> i32, + pub submit_input: unsafe extern "system" fn(*mut AmfComponent, *mut c_void) -> i32, + pub query_output: unsafe extern "system" fn(*mut AmfComponent, *mut *mut c_void) -> i32, +} + +#[repr(C)] +pub struct AmfComponent { + pub vtbl: *const AmfComponentVtbl, +} + +#[repr(C)] +pub struct AmfPlaneVtbl { + pub acquire: *const c_void, + pub release: unsafe extern "system" fn(*mut AmfPlane) -> i32, + pub query_interface: *const c_void, + + pub get_type: *const c_void, + pub get_native: unsafe extern "system" fn(*mut AmfPlane) -> *mut u8, + pub get_pixel_size_in_bytes: *const c_void, + pub get_offset_x: *const c_void, + pub get_offset_y: *const c_void, + pub get_width: *const c_void, + pub get_height: *const c_void, + pub get_hpitch: unsafe extern "system" fn(*mut AmfPlane) -> i32, + pub get_vpitch: unsafe extern "system" fn(*mut AmfPlane) -> i32, + pub is_tiled: *const c_void, +} + +#[repr(C)] +pub struct AmfPlane { + pub vtbl: *const AmfPlaneVtbl, +} + +#[repr(C)] +pub struct AmfSurfaceVtbl { + pub acquire: *const c_void, + pub release: unsafe extern "system" fn(*mut AmfSurface) -> i32, + pub query_interface: *const c_void, + + pub set_property: *const c_void, + pub get_property: *const c_void, + pub has_property: *const c_void, + pub get_property_count: *const c_void, + pub get_property_at: *const c_void, + pub clear: *const c_void, + pub add_to: *const c_void, + pub copy_to: *const c_void, + pub add_observer: *const c_void, + pub remove_observer: *const c_void, + + pub get_memory_type: *const c_void, + pub duplicate: *const c_void, + pub convert: *const c_void, + pub interop: *const c_void, + pub get_data_type: *const c_void, + pub is_reusable: *const c_void, + pub set_pts: unsafe extern "system" fn(*mut AmfSurface, i64), + pub get_pts: unsafe extern "system" fn(*mut AmfSurface) -> i64, + pub set_duration: unsafe extern "system" fn(*mut AmfSurface, i64), + pub get_duration: unsafe extern "system" fn(*mut AmfSurface) -> i64, + + pub get_format: *const c_void, + pub get_planes_count: *const c_void, + pub get_plane_at: unsafe extern "system" fn(*mut AmfSurface, usize) -> *mut AmfPlane, +} + +#[repr(C)] +pub struct AmfSurface { + pub vtbl: *const AmfSurfaceVtbl, +} + +#[repr(C)] +pub struct AmfBufferVtbl { + pub acquire: *const c_void, + pub release: unsafe extern "system" fn(*mut AmfBuffer) -> i32, + pub query_interface: *const c_void, + + pub set_property: *const c_void, + pub get_property: unsafe extern "system" fn(*mut AmfBuffer, *const u16, *mut AmfVariant) -> i32, + pub has_property: *const c_void, + pub get_property_count: *const c_void, + pub get_property_at: *const c_void, + pub clear: *const c_void, + pub add_to: *const c_void, + pub copy_to: *const c_void, + pub add_observer: *const c_void, + pub remove_observer: *const c_void, + + pub get_memory_type: *const c_void, + pub duplicate: *const c_void, + pub convert: *const c_void, + pub interop: *const c_void, + pub get_data_type: *const c_void, + pub is_reusable: *const c_void, + pub set_pts: unsafe extern "system" fn(*mut AmfBuffer, i64), + pub get_pts: unsafe extern "system" fn(*mut AmfBuffer) -> i64, + pub set_duration: unsafe extern "system" fn(*mut AmfBuffer, i64), + pub get_duration: unsafe extern "system" fn(*mut AmfBuffer) -> i64, + + pub set_size: *const c_void, + pub get_size: unsafe extern "system" fn(*mut AmfBuffer) -> usize, + pub get_native: unsafe extern "system" fn(*mut AmfBuffer) -> *mut u8, +} + +#[repr(C)] +pub struct AmfBuffer { + pub vtbl: *const AmfBufferVtbl, +} + +pub struct AmfRuntime { + _module: HMODULE, + factory: *mut AmfFactory, +} + +// SAFETY: AMF documents its factory as usable from any thread; the runtime only hands out the +// pointer and the DLL handle, and neither is freed while the process runs. +unsafe impl Send for AmfRuntime {} +// SAFETY: as for `Send`: the factory's methods may be called from several threads at once. +unsafe impl Sync for AmfRuntime {} + +static RUNTIME: OnceLock> = OnceLock::new(); + +pub fn runtime() -> Result<&'static AmfRuntime, String> { + RUNTIME.get_or_init(load_runtime).as_ref().map_err(Clone::clone) +} + +fn load_runtime() -> Result { + // SAFETY: a static NUL-terminated name, searched only in System32 (no DLL planting from the + // working directory); the module is never freed, so pointers into it stay valid. + let _module = unsafe { LoadLibraryExW(w!("amfrt64.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.map_err(|e| format!("amfrt64.dll not available: {e}"))?; + + // SAFETY: the module handle is live (above) and the name a static NUL-terminated string. + let p_init = unsafe { GetProcAddress(_module, PCSTR(c"AMFInit".as_ptr().cast())) }.ok_or_else(|| "amfrt64.dll lacks AMFInit symbol".to_string())?; + + // SAFETY: `AMFInit` is declared in AMF's `Factory.h` as + // `AMF_RESULT AMF_CDECL_CALL AMFInit(amf_uint64 version, amf::AMFFactory **ppFactory)`, which + // `AmfInitFn` matches (on x64 there is one calling convention). + let init_fn: AmfInitFn = unsafe { std::mem::transmute(p_init) }; + + let mut factory = std::ptr::null_mut(); + // AMF_FULL_VERSION for 1.4.0: (1 << 48) | (4 << 32) + let full_version = (1u64 << 48) | (4u64 << 32); + // SAFETY: the function resolved above, with a version constant and a local out-pointer, checked + // for null below. + let res = unsafe { init_fn(full_version, &mut factory) }; + if res != AMF_OK || factory.is_null() { + return Err(format!("AMFInit failed with code {res}")); + } + + Ok(AmfRuntime { _module, factory }) +} + +impl AmfRuntime { + pub fn factory(&self) -> *mut AmfFactory { + self.factory + } +} diff --git a/crates/platform/src/amf/mod.rs b/crates/platform/src/amf/mod.rs new file mode 100644 index 000000000..cbc45861e --- /dev/null +++ b/crates/platform/src/amf/mod.rs @@ -0,0 +1,144 @@ +//! AMD AMF hardware video encoding integration (Windows). +//! +//! Provides H.264, HEVC (Main / Main 10 HDR), and AV1 (RDNA 3+) encoding on AMD Radeon graphics. + +#[cfg(test)] +mod abi_tests; +pub mod export; +// The FFI stays inside this module (ADR 0001 rule 3): only the safe session types are exported. +#[allow(unsafe_code)] +mod ffi; +#[allow(unsafe_code)] +mod session; + +use std::sync::{Once, OnceLock}; + +use filmcraft_export::ColorSignal; + +pub use session::{Codec, Config, Packet, Profile, Session}; + +static HEVC_AVAILABLE: OnceLock = OnceLock::new(); +static HEVC_HDR_AVAILABLE: OnceLock = OnceLock::new(); +static AV1_AVAILABLE: OnceLock = OnceLock::new(); +static AV1_HDR_AVAILABLE: OnceLock = OnceLock::new(); + +/// Whether AMD AMF hardware encoding is available on this system. +pub fn is_available() -> bool { + hevc_available() || av1_available() +} + +/// Whether this system has an AMD GPU with hardware HEVC encoding. +pub fn hevc_available() -> bool { + *HEVC_AVAILABLE.get_or_init(|| { + let probe = Config { + width: 640, + height: 360, + fps: (30, 1), + bitrate_kbps: 2000, + max_bitrate_kbps: 3000, + cbr: false, + keyint: 30, + profile: Profile::HevcMain, + signal: ColorSignal::default(), + }; + let res = Session::open(&probe); + if let Err(why) = &res { + log::info!("no AMD AMF HEVC encoder: {why}"); + } + res.is_ok() + }) +} + +/// Whether this system has an AMD GPU with hardware HEVC Main 10 (HDR) encoding. +pub fn hevc_hdr_available() -> bool { + *HEVC_HDR_AVAILABLE.get_or_init(|| { + let probe = Config { + width: 640, + height: 360, + fps: (30, 1), + bitrate_kbps: 2000, + max_bitrate_kbps: 3000, + cbr: false, + keyint: 30, + profile: Profile::HevcMain10, + signal: ColorSignal::PQ, + }; + let res = Session::open(&probe); + if let Err(why) = &res { + log::info!("no AMD AMF HEVC Main 10 encoder: {why}"); + } + res.is_ok() + }) +} + +/// Whether this system has an AMD GPU with hardware AV1 encoding. +pub fn av1_available() -> bool { + *AV1_AVAILABLE.get_or_init(|| { + let probe = Config { + width: 640, + height: 360, + fps: (30, 1), + bitrate_kbps: 2000, + max_bitrate_kbps: 3000, + cbr: false, + keyint: 30, + profile: Profile::Av1Main, + signal: ColorSignal::default(), + }; + let res = Session::open(&probe); + if let Err(why) = &res { + log::info!("no AMD AMF AV1 encoder: {why}"); + } + res.is_ok() + }) +} + +/// Whether this system has an AMD GPU with hardware AV1 Main 10 (HDR) encoding. +pub fn av1_hdr_available() -> bool { + *AV1_HDR_AVAILABLE.get_or_init(|| { + let probe = Config { + width: 640, + height: 360, + fps: (30, 1), + bitrate_kbps: 2000, + max_bitrate_kbps: 3000, + cbr: false, + keyint: 30, + profile: Profile::Av1Main10, + signal: ColorSignal::PQ, + }; + let res = Session::open(&probe); + if let Err(why) = &res { + log::info!("no AMD AMF AV1 Main 10 encoder: {why}"); + } + res.is_ok() + }) +} + +/// Warm the HEVC probes ahead of time in a background thread. +pub fn warm_hevc_probe() { + static STARTED: Once = Once::new(); + STARTED.call_once(|| { + let spawned = std::thread::Builder::new().name("amf-hevc-probe".into()).spawn(|| { + let _ = std::panic::catch_unwind(hevc_available); + let _ = std::panic::catch_unwind(hevc_hdr_available); + }); + if let Err(e) = spawned { + log::info!("AMD AMF HEVC probe thread not started: {e}"); + } + }); +} + +/// Warm the AV1 probes ahead of time in a background thread. +pub fn warm_av1_probe() { + static STARTED: Once = Once::new(); + STARTED.call_once(|| { + let spawned = std::thread::Builder::new().name("amf-av1-probe".into()).spawn(|| { + let _ = std::panic::catch_unwind(av1_available); + let _ = std::panic::catch_unwind(av1_hdr_available); + }); + if let Err(e) = spawned { + log::info!("AMD AMF AV1 probe thread not started: {e}"); + } + }); +} diff --git a/crates/platform/src/amf/session.rs b/crates/platform/src/amf/session.rs new file mode 100644 index 000000000..4a734fbaa --- /dev/null +++ b/crates/platform/src/amf/session.rs @@ -0,0 +1,767 @@ +//! AMD AMF encoder session management. + +use std::ffi::c_void; +use std::time::{Duration, Instant}; + +use super::ffi::{ + AMF_COLOR_PRIMARIES_BT709, AMF_COLOR_PRIMARIES_BT2020, AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67, AMF_COLOR_TRANSFER_CHARACTERISTIC_BT709, + AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084, AMF_VIDEO_CONVERTER_COLOR_PROFILE_709, AMF_VIDEO_CONVERTER_COLOR_PROFILE_2020, +}; +use super::ffi::{ + AMF_DX11_1, AMF_EOF, AMF_INPUT_FULL, AMF_MEMORY_HOST, AMF_OK, AMF_REPEAT, AMF_SURFACE_NV12, AMF_SURFACE_P010, AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_KEY, + AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_IDR, AMF_VIDEO_ENCODER_HW_AV1, AMF_VIDEO_ENCODER_HW_HEVC, AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR, + AMF_VIDEO_ENCODER_VCE_AVC, AmfBuffer, AmfComponent, AmfContext, AmfHdrMetadata, AmfSurface, AmfVariant, runtime, +}; +use filmcraft_export::ColorSignal; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Codec { + H264, + Hevc, + Av1, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Profile { + H264Baseline, + H264Main, + H264High, + HevcMain, + HevcMain10, + Av1Main, + Av1Main10, +} + +impl Profile { + pub fn codec(self) -> Codec { + match self { + Profile::H264Baseline | Profile::H264Main | Profile::H264High => Codec::H264, + Profile::HevcMain | Profile::HevcMain10 => Codec::Hevc, + Profile::Av1Main | Profile::Av1Main10 => Codec::Av1, + } + } + + pub fn is_ten_bit(self) -> bool { + matches!(self, Profile::HevcMain10 | Profile::Av1Main10) + } +} + +pub struct Config { + pub width: u32, + pub height: u32, + pub fps: (u32, u32), + pub bitrate_kbps: u32, + pub max_bitrate_kbps: u32, + pub cbr: bool, + pub keyint: u32, + pub profile: Profile, + /// The colour the stream says it is (BT.709 SDR, or BT.2020 with PQ / HLG for Main 10). + pub signal: ColorSignal, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Packet { + pub data: Vec, + pub key: bool, + pub pts: i64, + pub dts: i64, +} + +pub struct Session { + context: *mut AmfContext, + component: *mut AmfComponent, + codec: Codec, + ten_bit: bool, + width: u32, + height: u32, +} + +// SAFETY: the context and component are owned by the session alone (nothing else holds them), and +// every call on them takes `&mut self`, so moving the session to another thread never makes two +// threads use them at once; AMF objects are not tied to the thread that created them. +unsafe impl Send for Session {} + +impl Session { + pub fn open(cfg: &Config) -> Result { + // the plane copies below rely on a nonzero even size; AMF takes it as `amf_int32` + if cfg.width == 0 || cfg.height == 0 || !cfg.width.is_multiple_of(2) || !cfg.height.is_multiple_of(2) { + return Err(format!("AMF needs a nonzero even picture size, not {}x{}", cfg.width, cfg.height)); + } + let (Ok(w), Ok(h)) = (i32::try_from(cfg.width), i32::try_from(cfg.height)) else { + return Err(format!("{}x{} is too large for AMF", cfg.width, cfg.height)); + }; + if cfg.fps.0 == 0 || cfg.fps.1 == 0 { + return Err("AMF needs a nonzero frame rate".into()); + } + let rt = runtime()?; + let factory = rt.factory(); + + let mut context: *mut AmfContext = std::ptr::null_mut(); + // SAFETY: `factory` is the non-null factory AMFInit returned, alive for the process (the DLL is + // never unloaded); the out-pointer is a local, checked for null below. + let res = unsafe { ((*(*factory).vtbl).create_context)(factory, &mut context) }; + if res != AMF_OK || context.is_null() { + return Err(format!("AMF CreateContext failed ({res})")); + } + + // SAFETY: `context` was just created and checked non-null. A null device asks AMF to create its + // own D3D11 device on the default adapter; no pointer of ours is retained. + let res = unsafe { ((*(*context).vtbl).init_dx11)(context, std::ptr::null_mut(), AMF_DX11_1) }; + if res != AMF_OK { + // SAFETY: our one reference to the context, released once; it is not used afterwards. + unsafe { ((*(*context).vtbl).release)(context) }; + return Err(format!("AMF InitDX11 failed ({res})")); + } + + let codec = cfg.profile.codec(); + let component_id = match codec { + Codec::H264 => AMF_VIDEO_ENCODER_VCE_AVC, + Codec::Hevc => AMF_VIDEO_ENCODER_HW_HEVC, + Codec::Av1 => AMF_VIDEO_ENCODER_HW_AV1, + }; + + let mut component: *mut AmfComponent = std::ptr::null_mut(); + // SAFETY: `factory` and `context` are live (above); the component id is a static NUL-terminated + // wide string, and the out-pointer is a local, checked for null below. + let res = unsafe { ((*(*factory).vtbl).create_component)(factory, context, component_id.as_ptr(), &mut component) }; + if res != AMF_OK || component.is_null() { + // SAFETY: the initialised context, terminated and its one reference released; not used after. + unsafe { + ((*(*context).vtbl).terminate)(context); + ((*(*context).vtbl).release)(context); + } + return Err(format!("AMF CreateComponent for {:?} failed ({res})", codec)); + } + + let ten_bit = cfg.profile.is_ten_bit(); + let target_bps = i64::from(cfg.bitrate_kbps.max(100)).saturating_mul(1000); + let peak_bps = i64::from(cfg.max_bitrate_kbps.max(cfg.bitrate_kbps)).saturating_mul(1000); + let rate_control = match (codec, cfg.cbr) { + (Codec::H264, true) => 1, + (Codec::H264, false) => 2, + (Codec::Hevc | Codec::Av1, true) => 3, + (Codec::Hevc | Codec::Av1, false) => 2, + }; + + let mut prop_res = AMF_OK; + let mut set = |name: *const u16, val: AmfVariant| { + if prop_res == AMF_OK { + // SAFETY: `component` is live and not yet initialised; `name` is a static NUL-terminated + // wide string and the variant is passed by value (AMF copies it). + let r = unsafe { ((*(*component).vtbl).set_property)(component, name, val) }; + if r != AMF_OK { + prop_res = r; + } + } + }; + + match codec { + Codec::H264 => { + let prof_val = match cfg.profile { + Profile::H264Baseline => 66, + Profile::H264Main => 77, + _ => 100, + }; + set(windows::core::w!("Usage").as_ptr(), AmfVariant::int64(0)); + set(windows::core::w!("Profile").as_ptr(), AmfVariant::int64(prof_val)); + set(windows::core::w!("FrameSize").as_ptr(), AmfVariant::size(w, h)); + set(windows::core::w!("FrameRate").as_ptr(), AmfVariant::rate(cfg.fps.0, cfg.fps.1)); + set(windows::core::w!("TargetBitrate").as_ptr(), AmfVariant::int64(target_bps)); + set(windows::core::w!("PeakBitrate").as_ptr(), AmfVariant::int64(peak_bps)); + set(windows::core::w!("RateControlMethod").as_ptr(), AmfVariant::int64(rate_control)); + // the AVC encoder places IDR frames by IDRPeriod (240 by default); it has no GOP-size + // property (`VideoEncoderVCE.h`) + set(windows::core::w!("IDRPeriod").as_ptr(), AmfVariant::int64(i64::from(cfg.keyint.max(1)))); + } + Codec::Hevc => { + let prof_val = if ten_bit { 2 } else { 1 }; + set(windows::core::w!("HevcUsage").as_ptr(), AmfVariant::int64(0)); + set(windows::core::w!("HevcProfile").as_ptr(), AmfVariant::int64(prof_val)); + set(windows::core::w!("HevcFrameSize").as_ptr(), AmfVariant::size(w, h)); + set(windows::core::w!("HevcFrameRate").as_ptr(), AmfVariant::rate(cfg.fps.0, cfg.fps.1)); + set(windows::core::w!("HevcTargetBitrate").as_ptr(), AmfVariant::int64(target_bps)); + set(windows::core::w!("HevcPeakBitrate").as_ptr(), AmfVariant::int64(peak_bps)); + set(windows::core::w!("HevcRateControlMethod").as_ptr(), AmfVariant::int64(rate_control)); + set(windows::core::w!("HevcGOPSize").as_ptr(), AmfVariant::int64(i64::from(cfg.keyint.max(1)))); + if ten_bit { + set(windows::core::w!("HevcColorBitDepth").as_ptr(), AmfVariant::int64(10)); + set(windows::core::w!("HevcNominalRange").as_ptr(), AmfVariant::int64(0)); + } + } + Codec::Av1 => { + set(windows::core::w!("Av1Usage").as_ptr(), AmfVariant::int64(0)); + set(windows::core::w!("Av1Profile").as_ptr(), AmfVariant::int64(1)); + set(windows::core::w!("Av1FrameSize").as_ptr(), AmfVariant::size(w, h)); + set(windows::core::w!("Av1FrameRate").as_ptr(), AmfVariant::rate(cfg.fps.0, cfg.fps.1)); + set(windows::core::w!("Av1TargetBitrate").as_ptr(), AmfVariant::int64(target_bps)); + set(windows::core::w!("Av1PeakBitrate").as_ptr(), AmfVariant::int64(peak_bps)); + set(windows::core::w!("Av1RateControlMethod").as_ptr(), AmfVariant::int64(rate_control)); + set(windows::core::w!("Av1GOPSize").as_ptr(), AmfVariant::int64(i64::from(cfg.keyint.max(1)))); + if ten_bit { + set(windows::core::w!("Av1ColorBitDepth").as_ptr(), AmfVariant::int64(10)); + } + } + } + + // The colour description the stream carries (VUI / sequence header). Left unset, AMF writes + // BT.709 even into a PQ stream, so for HDR a runtime that refuses it fails the session; for + // SDR the request only restates AMF's default. + if let Some(props) = color_properties(codec) { + let hdr = cfg.signal.is_hdr(); + let profile = if hdr { AMF_VIDEO_CONVERTER_COLOR_PROFILE_2020 } else { AMF_VIDEO_CONVERTER_COLOR_PROFILE_709 }; + let primaries = if hdr { AMF_COLOR_PRIMARIES_BT2020 } else { AMF_COLOR_PRIMARIES_BT709 }; + let transfer = match cfg.signal.transfer { + 16 => AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084, + 18 => AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67, + _ => AMF_COLOR_TRANSFER_CHARACTERISTIC_BT709, + }; + // the input planes are already in the output's colour: the same description on both + // sides, so AMF converts nothing + for (name, value) in [ + (props.in_profile, profile), + (props.in_transfer, transfer), + (props.in_primaries, primaries), + (props.out_profile, profile), + (props.out_transfer, transfer), + (props.out_primaries, primaries), + ] { + if hdr { + set(name.as_ptr(), AmfVariant::int64(value)); + } else { + // SAFETY: setting a property on the live component before Init; the name is a + // static NUL-terminated wide string. + let _ = unsafe { ((*(*component).vtbl).set_property)(component, name.as_ptr(), AmfVariant::int64(value)) }; + } + } + if let Some((md, (max_cll, max_fall))) = cfg.signal.static_metadata() + && prop_res == AMF_OK + { + let meta = AmfHdrMetadata { + // ST 2086 lists the primaries green, blue, red + green_primary: [md.primaries[0].0, md.primaries[0].1], + blue_primary: [md.primaries[1].0, md.primaries[1].1], + red_primary: [md.primaries[2].0, md.primaries[2].1], + white_point: [md.white_point.0, md.white_point.1], + max_mastering_luminance: md.max_luminance, + min_mastering_luminance: md.min_luminance, + max_content_light_level: max_cll, + max_frame_average_light_level: max_fall, + }; + if let Err(e) = set_hdr_metadata(context, component, props.hdr_metadata, &meta) { + prop_res = e; + } + } + } + + // CBR with the HRD model enforced, as AMD's rate-control developers recommend (#880). A + // runtime without the property keeps the encoder rather than failing the export. + if cfg.cbr { + let hrd = match codec { + Codec::H264 => windows::core::w!("EnforceHRD"), + Codec::Hevc => windows::core::w!("HevcEnforceHRD"), + Codec::Av1 => windows::core::w!("Av1EnforceHRD"), + }; + // SAFETY: as for `set` above. + let _ = unsafe { ((*(*component).vtbl).set_property)(component, hrd.as_ptr(), AmfVariant::bool_val(true)) }; + } + + if prop_res != AMF_OK { + // SAFETY: the live component and context, each terminated and its one reference released + // once, component first; neither is used afterwards. + unsafe { + ((*(*component).vtbl).terminate)(component); + ((*(*component).vtbl).release)(component); + ((*(*context).vtbl).terminate)(context); + ((*(*context).vtbl).release)(context); + } + return Err(format!("AMF SetProperty failed ({prop_res})")); + } + + let surface_format = if ten_bit { AMF_SURFACE_P010 } else { AMF_SURFACE_NV12 }; + // SAFETY: the live, configured component; format and size are plain values (the size was + // checked to fit `amf_int32` at the top of `open`). + let res = unsafe { ((*(*component).vtbl).init)(component, surface_format, w, h) }; + if res != AMF_OK { + // SAFETY: as above, on the Init failure. + unsafe { + ((*(*component).vtbl).terminate)(component); + ((*(*component).vtbl).release)(component); + ((*(*context).vtbl).terminate)(context); + ((*(*context).vtbl).release)(context); + } + return Err(format!("AMF Component Init failed ({res})")); + } + + Ok(Session { context, component, codec, ten_bit, width: cfg.width, height: cfg.height }) + } + + pub fn codec(&self) -> Codec { + self.codec + } + + pub fn is_ten_bit(&self) -> bool { + self.ten_bit + } + + /// Encode one 8-bit 4:2:0 picture: `y` is `width × height`, `u` and `v` are a quarter of that. + pub fn encode_8bit(&mut self, y: &[u8], u: &[u8], v: &[u8], pts: i64, duration: i64) -> Result, String> { + let (wu, hu) = (self.width as usize, self.height as usize); + check_planes(y.len(), u.len(), v.len(), wu, hu)?; + let surface = self.alloc_surface(AMF_SURFACE_NV12)?; + // NV12: a luma plane of `width` bytes per row, then interleaved U/V, `width` bytes per row at + // half the height + let filled = (|| -> Result<(), String> { + let (y_ptr, y_pitch) = plane(surface, 0, wu, hu)?; + let (uv_ptr, uv_pitch) = plane(surface, 1, wu, hu / 2)?; + let cwu = wu / 2; + for (r, row) in y.chunks_exact(wu).take(hu).enumerate() { + // SAFETY: `plane` checked that the plane holds `hu` rows of `y_pitch >= wu` bytes and + // `r < hu`; the source row is `wu` bytes of a Rust slice, which cannot overlap AMF's memory. + unsafe { std::ptr::copy_nonoverlapping(row.as_ptr(), y_ptr.add(r * y_pitch), wu) }; + } + for (r, (ur, vr)) in u.chunks_exact(cwu).zip(v.chunks_exact(cwu)).take(hu / 2).enumerate() { + for (i, (&u_val, &v_val)) in ur.iter().zip(vr).enumerate() { + // SAFETY: `plane` checked `hu / 2` rows of `uv_pitch >= wu` bytes, `r < hu / 2`, and + // `2 * i + 1 < 2 * cwu = wu`. + unsafe { + let dst = uv_ptr.add(r * uv_pitch); + *dst.add(i * 2) = u_val; + *dst.add(i * 2 + 1) = v_val; + } + } + } + Ok(()) + })(); + self.submit_filled(surface, filled, pts, duration) + } + + /// Encode one 10-bit 4:2:0 picture (values in the low 10 bits), laid out as for + /// [`Session::encode_8bit`]. + pub fn encode_10bit(&mut self, y: &[u16], u: &[u16], v: &[u16], pts: i64, duration: i64) -> Result, String> { + let (wu, hu) = (self.width as usize, self.height as usize); + check_planes(y.len(), u.len(), v.len(), wu, hu)?; + let surface = self.alloc_surface(AMF_SURFACE_P010)?; + // P010: 16-bit samples with the value in the high 10 bits, `width` samples per row + let filled = (|| -> Result<(), String> { + let (y_ptr, y_pitch) = plane(surface, 0, wu * 2, hu)?; + let (uv_ptr, uv_pitch) = plane(surface, 1, wu * 2, hu / 2)?; + let cwu = wu / 2; + for (r, row) in y.chunks_exact(wu).take(hu).enumerate() { + for (c, &val) in row.iter().enumerate() { + // SAFETY: `plane` checked `hu` rows of `y_pitch >= 2 * wu` bytes, `r < hu` and `c < wu`. + // The write is unaligned because AMF does not promise an even pitch. + unsafe { y_ptr.add(r * y_pitch + c * 2).cast::().write_unaligned((val & 0x3ff) << 6) }; + } + } + for (r, (ur, vr)) in u.chunks_exact(cwu).zip(v.chunks_exact(cwu)).take(hu / 2).enumerate() { + for (c, (&u_val, &v_val)) in ur.iter().zip(vr).enumerate() { + // SAFETY: `plane` checked `hu / 2` rows of `uv_pitch >= 2 * wu` bytes, `r < hu / 2`, and + // `4 * c + 3 < 4 * cwu = 2 * wu`. + unsafe { + let dst = uv_ptr.add(r * uv_pitch + c * 4); + dst.cast::().write_unaligned((u_val & 0x3ff) << 6); + dst.add(2).cast::().write_unaligned((v_val & 0x3ff) << 6); + } + } + } + Ok(()) + })(); + self.submit_filled(surface, filled, pts, duration) + } + + /// A host-memory surface of the session's size, holding one reference, which + /// [`Session::submit_filled`] releases. + fn alloc_surface(&mut self, format: u32) -> Result<*mut AmfSurface, String> { + let (w, h) = (self.width as i32, self.height as i32); + let mut surface: *mut AmfSurface = std::ptr::null_mut(); + // SAFETY: `self.context` is the live context `open` initialised; the out-pointer is a local. + let res = unsafe { ((*(*self.context).vtbl).alloc_surface)(self.context, AMF_MEMORY_HOST, format, w, h, &mut surface) }; + if res != AMF_OK || surface.is_null() { + return Err(format!("AMF AllocSurface failed ({res})")); + } + Ok(surface) + } + + /// Submit a surface whose planes were filled (`filled` is `Ok`), releasing it on every path. + fn submit_filled(&mut self, surface: *mut AmfSurface, filled: Result<(), String>, pts: i64, duration: i64) -> Result, String> { + let result = filled.and_then(|()| self.submit_surface(surface, pts, duration)); + // SAFETY: `surface` came from `alloc_surface` and our reference is still held; AMF takes its own + // reference to a surface it accepts, so ours is released here whether or not it was submitted. + unsafe { ((*(*surface).vtbl).release)(surface) }; + result + } + + fn submit_surface(&mut self, surface: *mut AmfSurface, pts: i64, duration: i64) -> Result, String> { + // SAFETY: `surface` is live until `submit_filled` releases it after this returns, and + // `self.component` is the initialised encoder. + let mut res = unsafe { + ((*(*surface).vtbl).set_pts)(surface, pts); + ((*(*surface).vtbl).set_duration)(surface, duration); + ((*(*self.component).vtbl).submit_input)(self.component, surface.cast::()) + }; + let mut packets = Vec::new(); + let start = Instant::now(); + while res == AMF_INPUT_FULL && start.elapsed() < Duration::from_millis(500) { + packets.append(&mut self.query_packets()?); + std::thread::sleep(Duration::from_millis(1)); + // SAFETY: as above. + res = unsafe { ((*(*self.component).vtbl).submit_input)(self.component, surface.cast::()) }; + } + if res != AMF_OK { + return Err(format!("AMF SubmitInput failed ({res})")); + } + packets.extend(self.query_packets()?); + Ok(packets) + } + + fn check_output_buffer_keyframe(&self, buf: *mut AmfBuffer, slice: &[u8]) -> bool { + let (prop_name, target_enum) = match self.codec { + Codec::H264 => (windows::core::w!("OutputDataType"), AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR), + Codec::Hevc => (windows::core::w!("HevcOutputDataType"), AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_IDR), + Codec::Av1 => (windows::core::w!("Av1OutputFrameType"), AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_KEY), + }; + let mut var = AmfVariant { var_type: 0, _pad: 0, val: [0; 16] }; + // SAFETY: `buf` is the live output buffer `poll_output` holds a reference to; the name is a + // static NUL-terminated wide string and `var` a local the call writes. + let hr = unsafe { ((*(*buf).vtbl).get_property)(buf, prop_name.as_ptr(), &mut var) }; + if hr == AMF_OK + && let Some(val) = var.as_int64() + { + val == target_enum + } else { + is_keyframe(self.codec, slice) + } + } + + fn poll_output(&mut self, wait: bool) -> Result<(Vec, bool), String> { + let mut packets = Vec::new(); + let mut out_data: *mut c_void = std::ptr::null_mut(); + let mut repeats = 0; + let mut eof = false; + + // SAFETY: `self.component` is the initialised encoder. A buffer from QueryOutput holds one + // reference, ours, released after its bytes are copied (or on the error path); its pointer and + // size come from that buffer, and the slice is used only before the release. + unsafe { + loop { + let res = ((*(*self.component).vtbl).query_output)(self.component, &mut out_data); + if res == AMF_OK && !out_data.is_null() { + repeats = 0; + let buf = out_data.cast::(); + out_data = std::ptr::null_mut(); + let size = ((*(*buf).vtbl).get_size)(buf); + let ptr = ((*(*buf).vtbl).get_native)(buf); + let pts = ((*(*buf).vtbl).get_pts)(buf); + // `from_raw_parts` needs a non-null pointer even for an empty slice + let data: &[u8] = if size == 0 { + &[] + } else if ptr.is_null() { + ((*(*buf).vtbl).release)(buf); + return Err("AMF QueryOutput gave a buffer with no memory".into()); + } else { + std::slice::from_raw_parts(ptr, size) + }; + let is_key = self.check_output_buffer_keyframe(buf, data); + packets.push(Packet { data: data.to_vec(), key: is_key, pts, dts: pts }); + ((*(*buf).vtbl).release)(buf); + } else if res == AMF_REPEAT { + if !wait { + break; + } + repeats += 1; + if repeats > 20 { + break; + } + std::thread::sleep(Duration::from_millis(1)); + } else if res == AMF_EOF { + eof = true; + break; + } else { + return Err(format!("AMF QueryOutput failed ({res})")); + } + } + } + Ok((packets, eof)) + } + + fn query_packets(&mut self) -> Result, String> { + self.poll_output(false).map(|(pkts, _)| pkts) + } + + pub fn drain(&mut self) -> Result, String> { + // SAFETY: `self.component` is the initialised encoder, used only through `&mut self`. + unsafe { + let res = ((*(*self.component).vtbl).drain)(self.component); + if res != AMF_OK { + return Err(format!("AMF Drain failed ({res})")); + } + } + + Self::drain_loop(Duration::from_secs(5), || self.poll_output(true)) + } + + pub(crate) fn drain_loop(timeout: Duration, mut poller: F) -> Result, String> + where + F: FnMut() -> Result<(Vec, bool), String>, + { + let mut packets = Vec::new(); + let start = Instant::now(); + let mut eof_reached = false; + loop { + let (chunk, eof) = poller()?; + packets.extend(chunk); + if eof { + eof_reached = true; + break; + } + if start.elapsed() > timeout { + break; + } + std::thread::sleep(Duration::from_millis(2)); + } + if !eof_reached { + return Err("AMF drain timed out before receiving EOF".to_string()); + } + Ok(packets) + } +} + +impl Drop for Session { + fn drop(&mut self) { + // SAFETY: the session holds the only reference to each; they are terminated and released once, + // component before context, and the session is not used again. + unsafe { + if !self.component.is_null() { + ((*(*self.component).vtbl).terminate)(self.component); + ((*(*self.component).vtbl).release)(self.component); + } + if !self.context.is_null() { + ((*(*self.context).vtbl).terminate)(self.context); + ((*(*self.context).vtbl).release)(self.context); + } + } + } +} + +/// The names of an encoder's colour-description properties. +struct ColorProperties { + in_profile: windows::core::PCWSTR, + in_transfer: windows::core::PCWSTR, + in_primaries: windows::core::PCWSTR, + out_profile: windows::core::PCWSTR, + out_transfer: windows::core::PCWSTR, + out_primaries: windows::core::PCWSTR, + hdr_metadata: windows::core::PCWSTR, +} + +/// The colour-description properties of the HEVC and AV1 encoders (`VideoEncoderHEVC.h`, +/// `VideoEncoderAV1.h`). H.264 here is SDR only and keeps AMF's BT.709 default. +fn color_properties(codec: Codec) -> Option { + use windows::core::w; + match codec { + Codec::H264 => None, + Codec::Hevc => Some(ColorProperties { + in_profile: w!("HevcInColorProfile"), + in_transfer: w!("HevcInColorTransferChar"), + in_primaries: w!("HevcInColorPrimaries"), + out_profile: w!("HevcOutColorProfile"), + out_transfer: w!("HevcOutColorTransferChar"), + out_primaries: w!("HevcOutColorPrimaries"), + hdr_metadata: w!("HevcInHDRMetadata"), + }), + Codec::Av1 => Some(ColorProperties { + in_profile: w!("Av1InputColorProfile"), + in_transfer: w!("Av1InputColorTransferChar"), + in_primaries: w!("Av1InputColorPrimaries"), + out_profile: w!("Av1OutputColorProfile"), + out_transfer: w!("Av1OutputColorTransferChar"), + out_primaries: w!("Av1OutputColorPrimaries"), + hdr_metadata: w!("Av1InHDRMetadata"), + }), + } +} + +/// Hand the encoder its HDR10 static metadata: an `AMFBuffer` holding an `AMFHDRMetadata`, which +/// the encoder writes as SEI (HEVC) or metadata OBUs (AV1). Returns the failing AMF result. +fn set_hdr_metadata(context: *mut AmfContext, component: *mut AmfComponent, name: windows::core::PCWSTR, meta: &AmfHdrMetadata) -> Result<(), i32> { + let mut buf: *mut AmfBuffer = std::ptr::null_mut(); + let size = std::mem::size_of::(); + // SAFETY: `context` is the live, initialised context; the out-pointer is a local. + let res = unsafe { ((*(*context).vtbl).alloc_buffer)(context, AMF_MEMORY_HOST, size, &mut buf) }; + if res != AMF_OK || buf.is_null() { + return Err(if res == AMF_OK { super::ffi::AMF_FAIL } else { res }); + } + // SAFETY: `buf` is the buffer just allocated, holding our one reference. Its memory is checked + // to be non-null and at least `size` bytes before the unaligned write of `meta`; the component + // takes its own reference to the buffer in SetProperty, so ours is released on every path. + unsafe { + let mem = ((*(*buf).vtbl).get_native)(buf); + let res = if mem.is_null() || ((*(*buf).vtbl).get_size)(buf) < size { + super::ffi::AMF_FAIL + } else { + mem.cast::().write_unaligned(*meta); + ((*(*component).vtbl).set_property)(component, name.as_ptr(), AmfVariant::interface(buf.cast::())) + }; + ((*(*buf).vtbl).release)(buf); + if res == AMF_OK { Ok(()) } else { Err(res) } + } +} + +/// The input planes hold a `w × h` picture and its two quarter-size chroma planes. +fn check_planes(y: usize, u: usize, v: usize, w: usize, h: usize) -> Result<(), String> { + let (luma, chroma) = (w * h, (w / 2) * (h / 2)); + if y < luma || u < chroma || v < chroma { + return Err(format!("AMF: the picture's planes ({y}, {u}, {v} samples) are smaller than {w}x{h} 4:2:0 needs ({luma}, {chroma}, {chroma})")); + } + Ok(()) +} + +/// Plane `index` of a host surface: its memory and row pitch in bytes, checked to hold `rows` rows +/// of `row_bytes` bytes, so the copies into it stay inside it. +fn plane(surface: *mut AmfSurface, index: usize, row_bytes: usize, rows: usize) -> Result<(*mut u8, usize), String> { + // SAFETY: `surface` is a live surface from `alloc_surface`. The plane it returns belongs to the + // surface (we hold no reference to release) and is called only after its null check. + let (ptr, hpitch, vpitch) = unsafe { + let p = ((*(*surface).vtbl).get_plane_at)(surface, index); + if p.is_null() { + return Err(format!("AMF surface has no plane {index}")); + } + (((*(*p).vtbl).get_native)(p), ((*(*p).vtbl).get_hpitch)(p), ((*(*p).vtbl).get_vpitch)(p)) + }; + if ptr.is_null() { + return Err(format!("AMF plane {index} has no host memory")); + } + let pitch = usize::try_from(hpitch) + .ok() + .filter(|&p| p >= row_bytes) + .ok_or_else(|| format!("AMF plane {index}: pitch {hpitch} is narrower than a row ({row_bytes} bytes)"))?; + if usize::try_from(vpitch).ok().is_none_or(|v| v < rows) { + return Err(format!("AMF plane {index}: {vpitch} rows, {rows} needed")); + } + Ok((ptr, pitch)) +} + +fn is_keyframe(codec: Codec, data: &[u8]) -> bool { + // AV1 output is a sequence of OBUs, with no Annex B start codes to split on + if codec == Codec::Av1 { + return av1_is_keyframe(data); + } + for n in crate::nvenc::annex_b_nals(data) { + match codec { + Codec::H264 => { + if let Some(&b) = n.first() { + let nal_type = b & 0x1f; + if nal_type == 5 { + return true; + } + } + } + Codec::Hevc => { + if n.len() >= 2 { + let nal_type = (n[0] >> 1) & 0x3f; + if matches!(nal_type, 19..=21) { + return true; + } + } + } + Codec::Av1 => {} + } + } + false +} + +/// Whether a temporal unit's OBUs hold a sequence header or the frame header of a shown key frame. +fn av1_is_keyframe(data: &[u8]) -> bool { + // Parse OBUs: check for sequence header (1) or key frame in frame header (3, 6) + let mut pos = 0usize; + while pos < data.len() { + let b0 = data[pos]; + if (b0 >> 7) & 1 != 0 { + break; + } + let obu_type = (b0 >> 3) & 0x0F; + let extension_flag = (b0 >> 2) & 1; + let has_size = (b0 >> 1) & 1; + pos += 1; + if extension_flag != 0 { + if pos >= data.len() { + break; + } + pos += 1; + } + let payload_start = if has_size != 0 { + let mut payload_len = 0usize; + let mut shift = 0; + let mut valid = false; + while pos < data.len() { + let b = data[pos]; + pos += 1; + payload_len |= ((b & 0x7F) as usize) << shift; + shift += 7; + if (b & 0x80) == 0 { + valid = true; + break; + } + } + if !valid { + break; + } + let start = pos; + pos = pos.saturating_add(payload_len); + start + } else { + let start = pos; + pos = data.len(); + start + }; + + if obu_type == 1 { + return true; + } + if (obu_type == 3 || obu_type == 6) + && let Some(&p0) = data.get(payload_start) + { + let show_existing_frame = (p0 >> 7) & 1; + let frame_type = (p0 >> 5) & 3; + if show_existing_frame == 0 && frame_type == 0 { + return true; + } + } + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn drain_loop_fails_on_timeout_without_eof() { + let res = Session::drain_loop(Duration::from_millis(20), || Ok((vec![], false))); + assert!(res.is_err()); + assert!(res.unwrap_err().contains("timed out before receiving EOF")); + } + + #[test] + fn drain_loop_succeeds_on_eof() { + let mut count = 0; + let res = Session::drain_loop(Duration::from_millis(100), || { + count += 1; + if count == 3 { Ok((vec![Packet { data: vec![1, 2, 3], key: true, pts: 0, dts: 0 }], true)) } else { Ok((vec![], false)) } + }); + assert!(res.is_ok()); + let packets = res.unwrap(); + assert_eq!(packets.len(), 1); + assert_eq!(packets[0].data, vec![1, 2, 3]); + } + + #[test] + fn av1_keyframes_are_found_without_start_codes() { + // a temporal delimiter, then a sequence header OBU + assert!(is_keyframe(Codec::Av1, &[0x12, 0x00, 0x0a, 0x01, 0x00])); + // a temporal delimiter, then a frame OBU for a shown key frame + assert!(is_keyframe(Codec::Av1, &[0x12, 0x00, 0x32, 0x01, 0x00])); + // a temporal delimiter, then a frame OBU for an inter frame + assert!(!is_keyframe(Codec::Av1, &[0x12, 0x00, 0x32, 0x01, 0x20])); + } +} diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rs index b33d857ba..ddbcef084 100644 --- a/crates/platform/src/lib.rs +++ b/crates/platform/src/lib.rs @@ -30,6 +30,8 @@ // Used by the Windows (and, for `biplanar`, Linux) decoders; compiled everywhere so their tests run // on every system. +#[cfg(target_os = "windows")] +pub mod amf; #[cfg_attr(not(target_os = "windows"), allow(dead_code))] mod annexb; #[cfg_attr(not(any(target_os = "windows", target_os = "linux")), allow(dead_code))] @@ -73,7 +75,9 @@ pub enum Availability { /// using FilmCraft's own decoders. pub fn register() -> Availability { #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - filmcraft_export::register_encoder(nvenc::export::factory); + { + filmcraft_export::register_encoder(nvenc::export::factory); + } #[cfg(target_os = "macos")] { filmcraft_codecs::register_video_decoder(videotoolbox_factory); @@ -91,23 +95,30 @@ pub fn register() -> Availability { filmcraft_codecs::hw::set_hw_backend("VideoToolbox"); Availability::Available("VideoToolbox") } - // Export ▸ H.265: NVENC is FilmCraft's only HEVC encoder on Windows, so the format is available - // when a small HEVC session opens. That takes about half a second, so it is asked on a thread of - // its own now rather than by the first draw of the format list. + // Export ▸ H.265: NVENC and AMD AMF are FilmCraft's hardware encoders on Windows + // (AMD AMF AV1 export is deferred to a follow-up pending RDNA 3/4 hardware verification). #[cfg(target_os = "windows")] { filmcraft_export::register_format_probe(filmcraft_export::Format::Hevc, nvenc::hevc_available); - // HDR sequences export as HEVC Main 10 (PQ / HLG) only where NVENC has a 10-bit encoder; elsewhere - // (and on macOS, whose VideoToolbox path is 8-bit) they are tone-mapped to SDR, as before + filmcraft_export::register_format_probe(filmcraft_export::Format::Hevc, amf::hevc_available); + // HDR sequences export as HEVC Main 10 (PQ / HLG) only where an encoder has a 10-bit encoder filmcraft_export::register_hdr_probe(filmcraft_export::Format::Hevc, nvenc::hevc_hdr_available); + filmcraft_export::register_hdr_probe(filmcraft_export::Format::Hevc, amf::hevc_hdr_available); nvenc::warm_hevc_probe(); + amf::warm_hevc_probe(); } #[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)); + // Hardware encoders in front of the software encoder. Each registration goes in front of + // the ones before it, so AMF is asked first; it steps aside for H.264 and H.265 where NVENC + // is present (`amf::export::factory`), so a machine with an AMD iGPU as its default adapter + // and an NVIDIA card encodes on the card. Asking NVENC first instead would count its + // "no NVIDIA GPU" answer as a declined hardware export on every AMD machine. + ENCODERS.call_once(|| { + filmcraft_export::register_encoder(nvenc::export::factory); + filmcraft_export::register_encoder(amf::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/tests/amf_export.rs b/crates/platform/tests/amf_export.rs new file mode 100644 index 000000000..5eb13a120 --- /dev/null +++ b/crates/platform/tests/amf_export.rs @@ -0,0 +1,279 @@ +//! Export using AMD AMF hardware encoder through FilmCraft's real export pipeline. +#![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_platform::amf::{av1_available, hevc_available}; +use filmcraft_project::{ItemKind, Label, MediaClip, MediaRef, Project, SequenceSettings, TrackKind}; +use filmcraft_render::SourceMap; +use filmcraft_time::{FrameRate, Tick, TimeRange}; + +static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn project(w: u32, h: u32, frames: i64) -> (Arc, filmcraft_project::ItemId, SourceMap) { + project_in(w, h, frames, filmcraft_color::ColorPipeline::REC709) +} + +/// A sequence in the given colour pipeline (an HDR working space makes the export HDR). +fn project_in(w: u32, h: u32, frames: i64, color: filmcraft_color::ColorPipeline) -> (Arc, filmcraft_project::ItemId, SourceMap) { + let rate = FrameRate::FPS_24; + let mut p = Project::new("amd_proj"); + 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(Box::new(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, color, ..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-amf-test-{}", std::process::id())); + let _ = std::fs::create_dir_all(&d); + d.join(name).to_string_lossy().to_string() +} + +fn decode(path: &str) -> Vec> { + 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() +} + +/// The payload of the first `fourcc` box in a file (enough for the sample-entry boxes asked about here). +fn box_payload<'a>(file: &'a [u8], fourcc: &[u8; 4]) -> Option<&'a [u8]> { + let at = file.windows(4).position(|w| w == fourcc)?; + let size = u32::from_be_bytes(file.get(at.checked_sub(4)?..at)?.try_into().ok()?) as usize; + file.get(at + 4..(at - 4).checked_add(size)?) +} + +/// #880: an HDR H.265 export from AMF says it is BT.2020 with PQ / HLG in its SPS VUI, not only in +/// the `colr` box (AMF writes BT.709 when its colour properties are not set), and a PQ export carries +/// the HDR10 mastering display in the stream as well as in the `mdcv` box. +#[test] +fn test_amf_hevc_hdr_export_signals_its_colour_in_the_stream() { + let _lock = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if !filmcraft_platform::amf::hevc_hdr_available() { + eprintln!("No AMD AMF HEVC Main 10 encoder on this system, skipping test."); + return; + } + // the HDR probe as well as the AMF encoder: without the probe an HDR sequence exports + // tone-mapped to SDR; use `direct_factory` + AMF HDR probe rather than `register()` so NVENC + // does not intercept HEVC on dual-GPU AMD+NVIDIA test hosts. + filmcraft_export::register_encoder(filmcraft_platform::amf::export::direct_factory); + filmcraft_export::register_hdr_probe(Format::Hevc, filmcraft_platform::amf::hevc_hdr_available); + use filmcraft_color::{ColorPipeline, WorkingSpace}; + for (name, working, signal) in + [("pq", WorkingSpace::Rec2100Pq, filmcraft_export::ColorSignal::PQ), ("hlg", WorkingSpace::Rec2100Hlg, filmcraft_export::ColorSignal::HLG)] + { + // the export's colour comes from the sequence's working space + let (p, seq, m) = project_in(640, 360, 12, ColorPipeline { working, ..ColorPipeline::REC709 }); + let out_path = tmp(&format!("amf_test_hevc_{name}.mp4")); + let settings = ExportSettings { + format: Format::Hevc, + path: out_path.clone(), + include_audio: false, + bitrate_kbps: 2000, + bitrate_mode: BitrateMode::Vbr1Pass, + hardware_encoding: HardwareEncoding::Auto, + ..Default::default() + }; + let report = export(&p, seq, &settings, &m, &Progress::default()).expect("AMF HEVC HDR export failed"); + assert_eq!(report.encoder.as_deref(), Some("AMD AMF"), "{name}"); + let file = std::fs::read(&out_path).unwrap(); + let hvcc = filmcraft_isobmff::HevcConfig::parse(box_payload(&file, b"hvcC").expect("an hvcC")).unwrap(); + let sps = hvcc.arrays.iter().flat_map(|a| &a.nalus).find(|n| n.first().is_some_and(|h| (h >> 1) & 0x3f == 33)).expect("an SPS"); + let sps = craft_video::hevc::decode::params::Sps::parse(&filmcraft_bitstream::unescape_rbsp(&sps[2..])).unwrap(); + let vui = sps.vui.expect("the SPS has a VUI"); + assert_eq!( + (vui.colour_primaries, vui.transfer_characteristics, vui.matrix_coefficients), + (signal.primaries, signal.transfer, signal.matrix), + "{name}: the VUI's colour description" + ); + if let Some((md, _)) = signal.static_metadata() { + // the same primaries and white point in the `mdcv` box and in the stream's mastering-display + // SEI (the first 16 of its 24 bytes: the luminances that follow hold `00 00` runs, which + // the stream escapes with emulation-prevention bytes) + let bytes = md.to_bytes(); + let bytes = &bytes[..16]; + let n = file.windows(bytes.len()).filter(|w| *w == bytes).count(); + assert!(n >= 2, "{name}: the mastering display is in the stream as well as in mdcv ({n} copies)"); + } + assert_eq!(decode(&out_path).len(), 12, "{name}: decodes"); + let _ = std::fs::remove_file(&out_path); + } +} + +#[test] +fn test_amf_hevc_export_and_decode() { + let _lock = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if !hevc_available() { + eprintln!("No AMD AMF HEVC encoder on this system, skipping test."); + return; + } + + filmcraft_export::register_encoder(filmcraft_platform::amf::export::direct_factory); + + // Match the capability probe: some AMD runtimes reject smaller HEVC pictures. + let (p, seq, m) = project(640, 360, 24); + let out_path = tmp("amf_test_hevc.mp4"); + let settings = ExportSettings { + format: Format::Hevc, + path: out_path.clone(), + include_audio: false, + bitrate_kbps: 1000, + bitrate_mode: BitrateMode::Vbr1Pass, + hardware_encoding: HardwareEncoding::Auto, + ..Default::default() + }; + + let before = hw_encode_stats(); + let report = export(&p, seq, &settings, &m, &Progress::default()).expect("AMF HEVC export failed"); + let after = hw_encode_stats(); + assert_eq!(report.encoder.as_deref(), Some("AMD AMF"), "the report names the encoder that ran"); + assert!(report.warnings.is_empty(), "no software-fallback warning: {:?}", report.warnings); + + assert!(after.sessions > before.sessions, "AMF session was not recorded"); + assert!(after.frames >= before.frames + 24, "AMF frames were not recorded"); + + let frames = decode(&out_path); + assert_eq!(frames.len(), 24, "Decoded frame count mismatch"); + assert_eq!(frames[0].width, 640); + assert_eq!(frames[0].height, 360); + + let _ = std::fs::remove_file(&out_path); +} + +#[test] +fn test_amf_h264_export_and_decode() { + let _lock = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let probe_cfg = filmcraft_platform::amf::Config { + width: 320, + height: 240, + fps: (24, 1), + bitrate_kbps: 1000, + max_bitrate_kbps: 1500, + cbr: false, + keyint: 24, + profile: filmcraft_platform::amf::Profile::H264High, + signal: Default::default(), + }; + if filmcraft_platform::amf::Session::open(&probe_cfg).is_err() { + eprintln!("No AMD AMF H.264 encoder on this system, skipping test."); + return; + } + + filmcraft_export::register_encoder(filmcraft_platform::amf::export::direct_factory); + + let (p, seq, m) = project(320, 240, 24); + let out_path = tmp("amf_test_h264.mp4"); + let settings = ExportSettings { + format: Format::H264, + path: out_path.clone(), + include_audio: false, + bitrate_kbps: 1000, + bitrate_mode: BitrateMode::Vbr1Pass, + hardware_encoding: HardwareEncoding::Auto, + ..Default::default() + }; + + let before = hw_encode_stats(); + let report = export(&p, seq, &settings, &m, &Progress::default()).expect("AMF H.264 export failed"); + let after = hw_encode_stats(); + assert_eq!(report.encoder.as_deref(), Some("AMD AMF"), "the report names the encoder that ran"); + assert!(report.warnings.is_empty(), "no software-fallback warning: {:?}", report.warnings); + + assert!(after.sessions > before.sessions, "AMF session was not recorded"); + assert!(after.frames >= before.frames + 24, "AMF frames were not recorded"); + + let frames = decode(&out_path); + assert_eq!(frames.len(), 24, "Decoded frame count mismatch"); + assert_eq!(frames[0].width, 320); + assert_eq!(frames[0].height, 240); + + let _ = std::fs::remove_file(&out_path); +} + +#[test] +#[ignore = "AMF AV1 export is deferred to a follow-up pending RDNA 3/4 hardware verification"] +fn test_amf_av1_export_and_decode() { + let _lock = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if !av1_available() { + eprintln!("No AMD AMF AV1 encoder on this system, skipping test."); + return; + } + + filmcraft_export::register_encoder(filmcraft_platform::amf::export::factory); + + // Cross two GOP boundaries so delayed output and later keyframes are exercised. + let (p, seq, m) = project(640, 360, 72); + let out_path = tmp("amf_test_av1.mp4"); + let settings = ExportSettings { + format: Format::Av1, + path: out_path.clone(), + include_audio: false, + bitrate_kbps: 2000, + bitrate_mode: BitrateMode::Vbr1Pass, + keyframe_distance: Some(24), + hardware_encoding: HardwareEncoding::Auto, + ..Default::default() + }; + + let before = hw_encode_stats(); + let report = export(&p, seq, &settings, &m, &Progress::default()).expect("AMF AV1 export failed"); + let after = hw_encode_stats(); + assert_eq!(report.frames, 72); + assert_eq!(report.encoder.as_deref(), Some("AMD AMF"), "the report names the encoder that ran"); + assert!(report.warnings.is_empty(), "no software-fallback warning: {:?}", report.warnings); + assert_eq!(after.sessions - before.sessions, 1, "AV1 must use one AMF session"); + assert_eq!(after.frames - before.frames, 72, "Every AV1 picture must go through AMF"); + + let frames = decode(&out_path); + assert_eq!(frames.len(), 72, "Decoded AV1 frame count mismatch"); + assert!(frames.iter().all(|frame| frame.width == 640 && frame.height == 360)); + + let bytes: Arc<[u8]> = std::fs::read(&out_path).unwrap().into(); + let src = filmcraft_codecs::open_bytes(&out_path, bytes).unwrap(); + let rate = src.info().frame_rate(); + // A fresh source must also seek into later GOPs, rather than only decode from frame zero. + for index in [49, 25, 0, 71] { + let frame = src.video_frame(FrameRequest::full(rate.tick_of(index))).unwrap(); + assert_eq!((frame.width, frame.height), (640, 360)); + } + + std::fs::remove_file(&out_path).unwrap(); +} + +#[test] +fn test_amf_factory_defers_h264_and_hevc_to_nvenc_when_present() { + if !filmcraft_platform::nvenc::hevc_available() { + eprintln!("No NVENC on this system, skipping dual-GPU handoff check."); + return; + } + let rate = FrameRate::FPS_24; + let h264 = ExportSettings { format: Format::H264, hardware_encoding: HardwareEncoding::Auto, ..Default::default() }; + let hevc = ExportSettings { format: Format::Hevc, ..Default::default() }; + assert!(filmcraft_platform::amf::export::factory(Format::H264, 320, 240, rate, &h264).is_none()); + assert!(filmcraft_platform::amf::export::factory(Format::Hevc, 640, 360, rate, &hevc).is_none()); +} diff --git a/crates/platform/tests/amf_probe.rs b/crates/platform/tests/amf_probe.rs new file mode 100644 index 000000000..cc9a3b326 --- /dev/null +++ b/crates/platform/tests/amf_probe.rs @@ -0,0 +1,79 @@ +//! AMD AMF hardware encoder integration tests. +#![cfg(target_os = "windows")] + +use filmcraft_platform::amf::{Config, Profile, Session, av1_available, av1_hdr_available, hevc_available, hevc_hdr_available}; + +#[test] +fn test_amf_safe_session_h264() { + let cfg = Config { + width: 320, + height: 240, + fps: (30, 1), + bitrate_kbps: 1000, + max_bitrate_kbps: 1500, + cbr: false, + keyint: 30, + profile: Profile::H264High, + signal: Default::default(), + }; + let mut session = match Session::open(&cfg) { + Ok(s) => s, + Err(e) => { + eprintln!("AMF H.264 Session::open skipped/failed: {e}"); + return; + } + }; + let y = vec![128u8; 320 * 240]; + let u = vec![128u8; 160 * 120]; + let v = vec![128u8; 160 * 120]; + let mut total_packets = 0; + for i in 0..5 { + let pkts = session.encode_8bit(&y, &u, &v, i * 333_333, 333_333).unwrap(); + total_packets += pkts.len(); + } + let drain_pkts = session.drain().unwrap(); + total_packets += drain_pkts.len(); + println!("Total H.264 packets from safe AMF Session: {total_packets}"); + assert!(total_packets >= 5); +} + +#[test] +fn test_amf_safe_session_hevc() { + if !hevc_available() { + eprintln!("No AMD AMF HEVC encoder on this system, skipping test."); + return; + } + // Match the capability probe: some AMD runtimes reject smaller HEVC pictures. + let cfg = Config { + width: 640, + height: 360, + fps: (30, 1), + bitrate_kbps: 1000, + max_bitrate_kbps: 1500, + cbr: false, + keyint: 30, + profile: Profile::HevcMain, + signal: Default::default(), + }; + let mut session = Session::open(&cfg).expect("AMF HEVC session failed after a successful capability probe"); + let y = vec![128u8; 640 * 360]; + let u = vec![128u8; 320 * 180]; + let v = vec![128u8; 320 * 180]; + let mut total_packets = 0; + for i in 0..5 { + let pkts = session.encode_8bit(&y, &u, &v, i * 333_333, 333_333).unwrap(); + total_packets += pkts.len(); + } + let drain_pkts = session.drain().unwrap(); + total_packets += drain_pkts.len(); + println!("Total HEVC packets from safe AMF Session: {total_packets}"); + assert!(total_packets >= 5); +} + +#[test] +fn test_amf_probes() { + println!("AMF hevc_available: {}", hevc_available()); + println!("AMF hevc_hdr_available: {}", hevc_hdr_available()); + println!("AMF av1_available: {}", av1_available()); + println!("AMF av1_hdr_available: {}", av1_hdr_available()); +} diff --git a/crates/platform/tests/it/nvenc_export.rs b/crates/platform/tests/it/nvenc_export.rs index 3662dff61..56f02e720 100644 --- a/crates/platform/tests/it/nvenc_export.rs +++ b/crates/platform/tests/it/nvenc_export.rs @@ -146,7 +146,7 @@ fn what_nvenc_does_not_take_goes_to_the_software_encoder() { (0, 1) ); // an odd frame size is rounded to even by the pipeline, so NVENC still takes it - let hardware_available = filmcraft_platform::nvenc::available(); + let hardware_available = filmcraft_platform::nvenc::available() || amf_available(); let odd = run("odd.mp4", &|s| s.frame_size = Some((641, 359))); assert_eq!(odd, if hardware_available { (24, 0) } else { (0, 1) }); // Off never touches the hardware encoder @@ -154,3 +154,16 @@ fn what_nvenc_does_not_take_goes_to_the_software_encoder() { // the decoded file of a declined export is fine assert_eq!(decode(&tmp(&dir, "odd.mp4")).len(), 24); } + +/// AMD AMF encodes what NVENC would where there is no NVIDIA GPU (#880): either is the hardware +/// encoder for these exports. +fn amf_available() -> bool { + #[cfg(target_os = "windows")] + { + filmcraft_platform::amf::is_available() + } + #[cfg(not(target_os = "windows"))] + { + false + } +} diff --git a/crates/platform/tests/it/nvenc_hevc_export.rs b/crates/platform/tests/it/nvenc_hevc_export.rs index 61c6064e9..fce4c7282 100644 --- a/crates/platform/tests/it/nvenc_hevc_export.rs +++ b/crates/platform/tests/it/nvenc_hevc_export.rs @@ -114,7 +114,12 @@ fn delta(before: filmcraft_export::HwEncodeStats) -> (u64, u64, u64) { fn hevc_exports_play_everywhere() { let _one = crate::common::NVENC_SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); filmcraft_platform::register(); - assert_eq!(filmcraft_export::available(Format::Hevc), hevc_available(), "the format is available iff NVENC can encode HEVC"); + // AMD AMF encodes HEVC too (#880): the format is offered when either can + assert_eq!( + filmcraft_export::available(Format::Hevc), + hevc_available() || filmcraft_platform::amf::hevc_available(), + "the format is available iff NVENC or AMF can encode HEVC" + ); if !hevc_available() { eprintln!("SKIPPED: no NVENC HEVC here"); return; @@ -287,7 +292,7 @@ fn interlaced_output_is_refused_before_any_encoder_is_asked() { assert!(export(&p, seq, &s, &m, &Progress::default()).is_err()); assert_eq!(delta(before), (0, 0, 0)); - if !hevc_available() { + if !hevc_available() && !filmcraft_platform::amf::hevc_available() { // no HEVC encoder: the export's own "encoder not available" error, nothing written, no panic let err = export(&p, seq, &hevc(tmp("none.mp4")), &m, &Progress::default()).expect_err("no encoder").to_string(); assert!(err.contains("encoder not available"), "{err}"); diff --git a/crates/platform/tests/it/nvenc_hevc_probe.rs b/crates/platform/tests/it/nvenc_hevc_probe.rs index 9da9d58cf..18392f0c9 100644 --- a/crates/platform/tests/it/nvenc_hevc_probe.rs +++ b/crates/platform/tests/it/nvenc_hevc_probe.rs @@ -22,9 +22,11 @@ fn the_probe_runs_once_and_registers_the_format() { assert!(warm < Duration::from_millis(50), "the answer is cached: {warm:?}"); // `register` makes `available(Hevc)` follow the probe; registering again changes nothing - assert!(!filmcraft_export::available(Format::Hevc) || first); + // (AMD AMF registers HEVC too, #880) + let amf = filmcraft_platform::amf::hevc_available(); + assert!(!filmcraft_export::available(Format::Hevc) || first || amf); filmcraft_platform::register(); filmcraft_platform::register(); - assert_eq!(filmcraft_export::available(Format::Hevc), first); + assert_eq!(filmcraft_export::available(Format::Hevc), first || amf); assert!(filmcraft_export::available(Format::H264)); } diff --git a/crates/platform/tests/nvenc_hevc_hdr_export.rs b/crates/platform/tests/nvenc_hevc_hdr_export.rs index 5930c36ce..fc6d205ea 100644 --- a/crates/platform/tests/nvenc_hevc_hdr_export.rs +++ b/crates/platform/tests/nvenc_hevc_hdr_export.rs @@ -146,7 +146,8 @@ fn yuv16(f: &filmcraft_frame::VideoFrame) -> ([Arc>; 3], u32) { fn hdr_sequences_export_as_main_10() { let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); filmcraft_platform::register(); - assert_eq!(filmcraft_export::hdr_available(Format::Hevc), hevc_hdr_available(), "HDR H.265 is available iff NVENC can encode Main 10"); + // The global registry also includes AMD AMF; NVENC-specific checks still skip below without NVENC. + assert_eq!(filmcraft_export::hdr_available(Format::Hevc), hevc_hdr_available() || filmcraft_platform::amf::hevc_hdr_available()); if !hevc_hdr_available() { eprintln!("SKIPPED: no NVENC HEVC Main 10 here (hevc: {})", hevc_available()); return; diff --git a/crates/platform/tests/nvenc_hevc_warm.rs b/crates/platform/tests/nvenc_hevc_warm.rs index adc0ebb2b..62841376d 100644 --- a/crates/platform/tests/nvenc_hevc_warm.rs +++ b/crates/platform/tests/nvenc_hevc_warm.rs @@ -24,7 +24,8 @@ fn register_answers_the_hevc_question_in_the_background() { eprintln!("answered in the background after {:?}", t0.elapsed()); let hdr = hevc_hdr_available(); assert!(!hdr || hevc_available(), "Main 10 implies HEVC"); - assert_eq!(filmcraft_export::hdr_available(filmcraft_export::Format::Hevc), hdr); + // The global registry includes AMF, while this test's warm-up assertions are specific to NVENC. + assert_eq!(filmcraft_export::hdr_available(filmcraft_export::Format::Hevc), hdr || filmcraft_platform::amf::hevc_hdr_available()); // the answer is kept: asking and registering again change nothing let answer = hevc_available(); filmcraft_platform::register(); diff --git a/docs/adr/0001-platform-ffi.md b/docs/adr/0001-platform-ffi.md index 0095922c9..7bfff7c7e 100644 --- a/docs/adr/0001-platform-ffi.md +++ b/docs/adr/0001-platform-ffi.md @@ -69,6 +69,7 @@ remain in effect; implementation differences are not exceptions to those rules. | macOS | [`videotoolbox_encode`](../../crates/platform/src/videotoolbox_encode.rs) | VideoToolbox H.264/HEVC encoding and its output callback; `dlsym` resolves an optional VideoToolbox property. | | Windows | [`media_foundation::gpu`](../../crates/platform/src/media_foundation/gpu.rs), [`media_foundation::mft`](../../crates/platform/src/media_foundation/mft.rs) | COM, Media Foundation, D3D11 device setup and surface readback. | | Windows / 64-bit Linux | [`nvenc::ffi`](../../crates/platform/src/nvenc/ffi.rs), [`nvenc::session`](../../crates/platform/src/nvenc/session.rs), [`nvenc::device`](../../crates/platform/src/nvenc/device.rs) | NVENC declarations and calls, driver loading, D3D11 or CUDA device/context operations. | +| Windows | [`amf::ffi`](../../crates/platform/src/amf/ffi.rs), [`amf::session`](../../crates/platform/src/amf/session.rs) | AMD AMF declarations, `amfrt64.dll` loading, encoder sessions and host-surface writes (see the AMF addendum). | | 64-bit Linux | [`nvdec::cuvid`](../../crates/platform/src/nvdec/cuvid.rs) | NVDEC driver calls, parser callbacks and CUDA readback, using `nvenc::device`. | | Linux | [`vaapi::va`](../../crates/platform/src/vaapi/va.rs) | libva/libva-drm loading, displays, decoding, surface readback and logging. | | Windows | [`cursor::cursor_screen_position`](../../crates/platform/src/cursor.rs) (function only) | `GetCursorPos`; a non-media deviation, discussed below. | @@ -263,3 +264,27 @@ checked, so an error closes them all and none leaks. The driver's counts are cla and every plane's object index is checked. The public result (`SurfaceDmabuf`) is plain data and owned descriptors, no raw pointers. Nothing imports it yet, so the readback stays the only path and the fallback guarantee is unchanged. +## Addendum (2026-11-17): AMD AMF hardware encoding on Windows + +H.264 and H.265 (Main, Main 10) encoding on AMD GPUs through AMF (`amf/`, #880; AV1 export is +deferred to a follow-up PR). The rules +above hold: + +- **Two allowance scopes**, both private modules: `amf::ffi` (the declarations and the run-time + loading of `amfrt64.dll` from System32; no SDK is linked or bundled) and `amf::session` (the + encoder session: properties, host surfaces, output buffers). `amf::export`, the export factory, + is safe code. The public API is `amf::export::factory`, the availability probes and the safe + `Session` / `Config` / `Packet` types; no AMF type or raw pointer is public. +- **The declarations are transcribed from AMD's MIT-licensed AMF SDK headers** (the notice is kept in + `ffi.rs`, the version is named there and in `ATTRIBUTION.md`), and `amf/abi_tests.rs` checks their + sizes, alignments, offsets and constants against a C compiler's view of those headers, as for NVENC. +- **Driver results are checked before they are used:** plane pointers, pitches and row counts + before the host surface is written, buffer pointers before they become slices, and the size + (nonzero, even, within `amf_int32`) before a session opens. Every AMF object has one owner that + releases it on every path. +- **No callbacks:** AMF is driven synchronously (`SubmitInput` / `QueryOutput`), and registers no + Rust code. +- **The same factory rules as NVENC:** an export AMF would encode differently from what was asked + (CRF, all-intra H.264, two-pass, non-square pixels, interlacing, a colour other than BT.709 SDR or + BT.2020 PQ / HLG) is declined before a session opens, and on a machine with both, H.264 and + H.265 go to NVENC.