feat(codec): encodage H.264 matériel sous Windows par Media Foundation
La transformée H.264 du pilote (Quick Sync, NVENC, AMF) derrière le trait VideoEncoder, comme VA-API sous Linux. Trouvée par MFTEnumEx, matérielle d'abord, réglée en basse latence (pas d'image B, débit constant, une image clé toutes les cinq secondes et sur demande par ICodecAPI), nourrie en NV12 converti par le processeur en BT.709. Les transformées asynchrones (matérielles) et synchrones (logicielles) sont pilotées toutes les deux. SPS et PPS sont remis devant une image clé qui arrive sans eux. Sans transformée matérielle, l'hôte retombe sur libvpx avec l'avertissement hardware_fallback, comme sous Linux. VP9 reste sur libvpx. Vérifié sous Wine 11, dont la transformée H.264 passe par GStreamer (x264enc): flux Annex B avec SPS, PPS et IDR, changement de taille, refus d'une image de mauvaise taille. Reste la mesure sur un vrai Windows avec GPU. Refs #95 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
78ac97903f
commit
222099d0ed
10 files changed
+1068
-13
No files matched your search
@@ -20,9 +20,10 @@ local `rustscreen.local` en mDNS, viewer React qui reprend seul après
|
||||
une coupure ou une veille, tourne l'image et suit le thème, coque desktop Tauri avec icône de
|
||||
barre système, réglages persistants, interface en français et en anglais, inhibition de veille,
|
||||
journal JSON local et archive de diagnostics.
|
||||
Ce qui manque: la capture Windows et l'encodeur matériel Windows. macOS est hors périmètre comme
|
||||
hôte (#90) (sous Linux, VA-API
|
||||
par GStreamer, fonctionnalité `vaapi`, ADR 0012). Les messages de l'hôte
|
||||
L'encodage matériel passe par VA-API et GStreamer sous Linux (fonctionnalité `vaapi`, ADR 0012), par
|
||||
Media Foundation sous Windows (#95). Ce qui manque: la duplication de bureau DXGI sous Windows
|
||||
(la capture y passe par GDI, #8), et tout le travail Windows reste à vérifier sur une vraie machine,
|
||||
il n'a tourné que sous Wine. macOS est hors périmètre comme hôte (#90). Les messages de l'hôte
|
||||
(erreurs, avertissements, refus de réglages) partent en codes (`Notice`) que la coque traduit sous
|
||||
`desktop.host` (#75); le test `notices` refuse un code sans traduction.
|
||||
|
||||
@@ -171,7 +172,9 @@ cargo run --release -p rs-session --features pipewire,vaapi --bin rustscreen-cli
|
||||
|
||||
Windows se compile depuis Linux (#93): le shell `.#windows` fournit un rustc pour la cible
|
||||
`x86_64-pc-windows-gnu`, mingw-w64 et une libvpx statique, et range sa cible sous `target/windows`.
|
||||
Wine fait tourner le `.exe` et les tests, sans machine Windows. La capture GDI (#8) s'y vérifie sur
|
||||
Wine fait tourner le `.exe` et les tests, sans machine Windows. Les tests de Media Foundation y
|
||||
passent par la transformée H.264 de Wine (GStreamer, `x264enc`), logicielle et sans basse latence:
|
||||
ils encodent assez d'images pour franchir sa file d'attente. La capture GDI (#8) s'y vérifie sur
|
||||
un Xvfb **à la taille d'un moniteur que Wine annonce** (1920 × 1080): plus petit, X refuse de lire
|
||||
la zone et l'image sort noire.
|
||||
|
||||
|
||||
Generated
+105
@@ -2028,6 +2028,7 @@ dependencies = [
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3178,12 +3179,107 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
|
||||
dependencies = [
|
||||
"windows-collections",
|
||||
"windows-core",
|
||||
"windows-future",
|
||||
"windows-numerics",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-collections"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-future"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
"windows-threading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
@@ -3218,6 +3314,15 @@ dependencies = [
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-threading"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
|
||||
@@ -23,6 +23,19 @@ gstreamer = { version = "0.25", optional = true }
|
||||
gstreamer-app = { version = "0.25", optional = true }
|
||||
gstreamer-video = { version = "0.25", optional = true }
|
||||
|
||||
# Windows (#95): Media Foundation, the H.264 encoder of the GPU (Quick Sync,
|
||||
# NVENC, AMF). COM interfaces: `windows`, not `windows-sys`. The `unsafe`
|
||||
# code lives in `src/media_foundation.rs`.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.62.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Media_MediaFoundation",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Com_StructuredStorage",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_Variant",
|
||||
] }
|
||||
|
||||
[features]
|
||||
vaapi = ["dep:gstreamer", "dep:gstreamer-app", "dep:gstreamer-video"]
|
||||
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
//!
|
||||
//! The hardware encoder ([`hardware`], `vaapi` feature, #57) sits behind the
|
||||
//! same trait: H.264 or VP9 on the GPU through VA-API, without touching the
|
||||
//! rest of the pipeline.
|
||||
//! rest of the pipeline. Under Windows, [`media_foundation`] does the same
|
||||
//! with the GPU's Media Foundation transform (#95).
|
||||
//!
|
||||
//! Build dependency: libvpx. See `scripts/build-libvpx.sh` and AGENTS.md.
|
||||
|
||||
@@ -17,6 +18,8 @@ pub mod frame;
|
||||
#[cfg(feature = "vaapi")]
|
||||
pub mod hardware;
|
||||
pub mod ivf;
|
||||
#[cfg(windows)]
|
||||
pub mod media_foundation;
|
||||
pub mod pipeline;
|
||||
mod vpx;
|
||||
|
||||
@@ -26,4 +29,6 @@ pub use frame::{FrameSource, SharedFrames, SharedMedia, SharedPlayback, Syntheti
|
||||
#[cfg(feature = "vaapi")]
|
||||
pub use hardware::HardwareEncoder;
|
||||
pub use ivf::{IvfError, IvfFile};
|
||||
#[cfg(windows)]
|
||||
pub use media_foundation::MediaFoundationEncoder;
|
||||
pub use pipeline::{LiveSource, LiveStats, SourceView};
|
||||
@@ -0,0 +1,910 @@
|
||||
//! Hardware encoding under Windows through Media Foundation (#95), H.264.
|
||||
//!
|
||||
//! The Windows counterpart of [`crate::hardware`] (VA-API): the GPU's encoder
|
||||
//! is a Media Foundation transform (MFT) registered by its driver, Intel Quick
|
||||
//! Sync, NVIDIA NVENC or AMD AMF. It is found by [`MFTEnumEx`], set to low
|
||||
//! latency (no B-frame, one output per input, constant bitrate), and fed NV12:
|
||||
//! the BGRA image is converted on the processor, in BT.709 like the libvpx
|
||||
//! path, then interleaved.
|
||||
//!
|
||||
//! Hardware transforms are asynchronous: they say when they want an image
|
||||
//! (`METransformNeedInput`) and when an access unit is ready
|
||||
//! (`METransformHaveOutput`). Software ones are synchronous: input, then output
|
||||
//! until they ask for more. Both are driven here, the second for the tests
|
||||
//! under Wine, whose H.264 transform runs on GStreamer, and for
|
||||
//! [`MediaFoundationEncoder::software`].
|
||||
//!
|
||||
//! Without a hardware transform, [`MediaFoundationEncoder::new`] fails
|
||||
//! cleanly, and the caller falls back on libvpx.
|
||||
|
||||
use std::mem::ManuallyDrop;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use windows::Win32::Foundation::VARIANT_BOOL;
|
||||
use windows::Win32::Media::MediaFoundation::{
|
||||
CODECAPI_AVEncCommonMeanBitRate, CODECAPI_AVEncCommonRateControlMode,
|
||||
CODECAPI_AVEncH264CABACEnable, CODECAPI_AVEncMPVDefaultBPictureCount, CODECAPI_AVEncMPVGOPSize,
|
||||
CODECAPI_AVEncVideoForceKeyFrame, CODECAPI_AVLowLatencyMode, ICodecAPI, IMFActivate,
|
||||
IMFMediaEventGenerator, IMFMediaType, IMFSample, IMFTransform, METransformHaveOutput,
|
||||
METransformNeedInput, MF_E_NO_EVENTS_AVAILABLE, MF_E_NOTACCEPTING,
|
||||
MF_E_TRANSFORM_NEED_MORE_INPUT, MF_E_TRANSFORM_STREAM_CHANGE, MF_EVENT_FLAG_NO_WAIT,
|
||||
MF_EVENT_TYPE, MF_LOW_LATENCY, MF_MT_AVG_BITRATE, MF_MT_FRAME_RATE, MF_MT_FRAME_SIZE,
|
||||
MF_MT_INTERLACE_MODE, MF_MT_MAJOR_TYPE, MF_MT_MPEG_SEQUENCE_HEADER, MF_MT_MPEG2_PROFILE,
|
||||
MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SUBTYPE, MF_MT_VIDEO_NOMINAL_RANGE, MF_MT_YUV_MATRIX,
|
||||
MF_TRANSFORM_ASYNC, MF_TRANSFORM_ASYNC_UNLOCK, MF_VERSION, MFCreateMediaType,
|
||||
MFCreateMemoryBuffer, MFCreateSample, MFMediaType_Video, MFNominalRange_16_235, MFSTARTUP_LITE,
|
||||
MFSampleExtension_CleanPoint, MFStartup, MFT_CATEGORY_VIDEO_ENCODER, MFT_ENUM_FLAG,
|
||||
MFT_ENUM_FLAG_HARDWARE, MFT_ENUM_FLAG_SORTANDFILTER, MFT_ENUM_FLAG_SYNCMFT,
|
||||
MFT_ENUM_HARDWARE_URL_Attribute, MFT_FRIENDLY_NAME_Attribute,
|
||||
MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, MFT_MESSAGE_NOTIFY_START_OF_STREAM, MFT_OUTPUT_DATA_BUFFER,
|
||||
MFT_OUTPUT_STREAM_PROVIDES_SAMPLES, MFT_REGISTER_TYPE_INFO, MFTEnumEx, MFVideoFormat_H264,
|
||||
MFVideoFormat_NV12, MFVideoInterlace_Progressive, MFVideoTransferMatrix_BT709,
|
||||
eAVEncCommonRateControlMode_CBR, eAVEncH264VProfile_Base, eAVEncH264VProfile_ConstrainedBase,
|
||||
};
|
||||
use windows::Win32::System::Com::{CoIncrementMTAUsage, CoTaskMemFree};
|
||||
use windows::Win32::System::Variant::{
|
||||
VARIANT, VARIANT_0, VARIANT_0_0, VARIANT_0_0_0, VT_BOOL, VT_UI4,
|
||||
};
|
||||
use windows::core::{GUID, Interface, PWSTR};
|
||||
|
||||
use crate::color::{BgraFrame, bgra_to_i420};
|
||||
use crate::encoder::{EncodeConfig, EncodeError, VideoCodec, VideoEncoder};
|
||||
|
||||
/// How long an image may take through the GPU before it counts as lost, as
|
||||
/// with VA-API: a frozen driver must not freeze the capture thread.
|
||||
const PULL_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Seconds between two periodic keyframes, as libvpx and VA-API do.
|
||||
const KEYFRAME_INTERVAL_S: u32 = 5;
|
||||
|
||||
/// Media Foundation time unit: 100 ns.
|
||||
const TICKS_PER_SECOND: i64 = 10_000_000;
|
||||
|
||||
pub struct MediaFoundationEncoder {
|
||||
activate: IMFActivate,
|
||||
transform: IMFTransform,
|
||||
/// Present for an asynchronous (hardware) transform.
|
||||
events: Option<IMFMediaEventGenerator>,
|
||||
/// Keyframes on request and rate control; some transforms lack it.
|
||||
codec_api: Option<ICodecAPI>,
|
||||
input_stream: u32,
|
||||
output_stream: u32,
|
||||
/// Output buffer we lend the transform, when it does not bring its own.
|
||||
output_sample: Option<IMFSample>,
|
||||
/// `METransformNeedInput` received and not yet answered.
|
||||
input_wanted: u32,
|
||||
/// SPS and PPS, put back before a keyframe that comes without them.
|
||||
sequence_header: Option<Vec<u8>>,
|
||||
config: EncodeConfig,
|
||||
software: bool,
|
||||
name: String,
|
||||
frames: u64,
|
||||
keyframe_requested: bool,
|
||||
i420: Vec<u8>,
|
||||
}
|
||||
|
||||
// SAFETY: COM runs in the process's multithreaded apartment (`com_ready`),
|
||||
// and the transforms Media Foundation hands out are free-threaded. The encoder
|
||||
// is used by one thread at a time: created by the session, then moved into
|
||||
// the encoding thread (`LiveSource::spawn`).
|
||||
unsafe impl Send for MediaFoundationEncoder {}
|
||||
|
||||
impl std::fmt::Debug for MediaFoundationEncoder {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("MediaFoundationEncoder")
|
||||
.field("name", &self.name)
|
||||
.field("asynchronous", &self.events.is_some())
|
||||
.field("config", &self.config)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl MediaFoundationEncoder {
|
||||
/// Opens the GPU's H.264 encoder. VP8 and VP9 are refused, like a machine
|
||||
/// without one: libvpx encodes them.
|
||||
pub fn new(config: EncodeConfig) -> Result<Self, EncodeError> {
|
||||
Self::open(config, false)
|
||||
}
|
||||
|
||||
/// The same, a software transform accepted when no GPU offers one
|
||||
/// (Microsoft's, or Wine's): for the tests and for comparisons, not for
|
||||
/// a share, where libvpx is the fallback.
|
||||
pub fn software(config: EncodeConfig) -> Result<Self, EncodeError> {
|
||||
Self::open(config, true)
|
||||
}
|
||||
|
||||
/// Tells whether this machine encodes `codec` on its GPU, without keeping
|
||||
/// anything open. For the diagnostics.
|
||||
pub fn available(codec: VideoCodec) -> bool {
|
||||
let probe = EncodeConfig {
|
||||
width: 64,
|
||||
height: 64,
|
||||
fps: 30,
|
||||
bitrate_kbps: 500,
|
||||
codec,
|
||||
};
|
||||
Self::new(probe).is_ok()
|
||||
}
|
||||
|
||||
/// The transform's name, as its driver registers it.
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn open(config: EncodeConfig, software: bool) -> Result<Self, EncodeError> {
|
||||
if config.codec != VideoCodec::H264 {
|
||||
return Err(EncodeError::Init(format!(
|
||||
"no Media Foundation encoder for {}: use libvpx",
|
||||
config.codec.rtp_name()
|
||||
)));
|
||||
}
|
||||
media_foundation_ready()?;
|
||||
let mut last_error = None;
|
||||
for activate in encoders(software)? {
|
||||
match Self::activate(activate, config, software) {
|
||||
Ok(encoder) => {
|
||||
tracing::info!(
|
||||
encoder = encoder.name,
|
||||
asynchronous = encoder.events.is_some(),
|
||||
"Media Foundation encoder opened"
|
||||
);
|
||||
return Ok(encoder);
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::debug!(%error, "Media Foundation encoder refused");
|
||||
last_error = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(last_error.unwrap_or_else(|| {
|
||||
EncodeError::Init(if software {
|
||||
"no H.264 encoder in Media Foundation".into()
|
||||
} else {
|
||||
"no hardware H.264 encoder in Media Foundation".into()
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
fn activate(
|
||||
activate: IMFActivate,
|
||||
config: EncodeConfig,
|
||||
software: bool,
|
||||
) -> Result<Self, EncodeError> {
|
||||
// SAFETY: plain COM calls on interfaces we own; every pointer passed
|
||||
// lives for the duration of the call.
|
||||
unsafe {
|
||||
let name = friendly_name(&activate);
|
||||
let transform: IMFTransform = activate.ActivateObject().map_err(init)?;
|
||||
let attributes = transform.GetAttributes().ok();
|
||||
let asynchronous = attributes
|
||||
.as_ref()
|
||||
.and_then(|a| a.GetUINT32(&MF_TRANSFORM_ASYNC).ok())
|
||||
== Some(1);
|
||||
if let Some(attributes) = &attributes {
|
||||
if asynchronous {
|
||||
// Without this, an asynchronous transform refuses every
|
||||
// call: it expects a caller that knows the model.
|
||||
attributes
|
||||
.SetUINT32(&MF_TRANSFORM_ASYNC_UNLOCK, 1)
|
||||
.map_err(init)?;
|
||||
}
|
||||
let _ = attributes.SetUINT32(&MF_LOW_LATENCY, 1);
|
||||
}
|
||||
let events = if asynchronous {
|
||||
Some(transform.cast::<IMFMediaEventGenerator>().map_err(init)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let codec_api = transform.cast::<ICodecAPI>().ok();
|
||||
if let Some(api) = &codec_api {
|
||||
// Each is a wish: a transform that ignores one still encodes.
|
||||
let fps = u32::from(config.fps.max(1));
|
||||
for (key, value) in [
|
||||
(CODECAPI_AVLowLatencyMode, variant_bool(true)),
|
||||
(
|
||||
CODECAPI_AVEncCommonRateControlMode,
|
||||
variant_u32(eAVEncCommonRateControlMode_CBR.0 as u32),
|
||||
),
|
||||
(
|
||||
CODECAPI_AVEncCommonMeanBitRate,
|
||||
variant_u32(config.bitrate_kbps.saturating_mul(1000)),
|
||||
),
|
||||
(
|
||||
CODECAPI_AVEncMPVGOPSize,
|
||||
variant_u32(fps * KEYFRAME_INTERVAL_S),
|
||||
),
|
||||
(CODECAPI_AVEncMPVDefaultBPictureCount, variant_u32(0)),
|
||||
(CODECAPI_AVEncH264CABACEnable, variant_bool(false)),
|
||||
] {
|
||||
if let Err(error) = api.SetValue(&key, &value) {
|
||||
tracing::debug!(?key, %error, "codec setting ignored");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (input_stream, output_stream) = stream_ids(&transform);
|
||||
// An encoder takes its output type first: the input it accepts
|
||||
// follows from it. Constrained baseline is what browsers prefer;
|
||||
// some drivers only know baseline, decoded the same way when
|
||||
// nothing beyond constrained is used, which encoders never do.
|
||||
let mut output_set = Err(EncodeError::Init("no H.264 profile accepted".into()));
|
||||
for profile in [
|
||||
eAVEncH264VProfile_ConstrainedBase.0,
|
||||
eAVEncH264VProfile_Base.0,
|
||||
] {
|
||||
let output = video_type(&MFVideoFormat_H264, &config)?;
|
||||
output
|
||||
.SetUINT32(&MF_MT_AVG_BITRATE, config.bitrate_kbps.saturating_mul(1000))
|
||||
.map_err(init)?;
|
||||
output
|
||||
.SetUINT32(&MF_MT_MPEG2_PROFILE, profile as u32)
|
||||
.map_err(init)?;
|
||||
output_set = transform
|
||||
.SetOutputType(output_stream, &output, 0)
|
||||
.map_err(init);
|
||||
if output_set.is_ok() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
output_set?;
|
||||
let input = video_type(&MFVideoFormat_NV12, &config)?;
|
||||
// The colors of `bgra_to_i420`: BT.709, studio range.
|
||||
let _ = input.SetUINT32(&MF_MT_YUV_MATRIX, MFVideoTransferMatrix_BT709.0 as u32);
|
||||
let _ = input.SetUINT32(&MF_MT_VIDEO_NOMINAL_RANGE, MFNominalRange_16_235.0 as u32);
|
||||
transform
|
||||
.SetInputType(input_stream, &input, 0)
|
||||
.map_err(init)?;
|
||||
|
||||
let info = transform.GetOutputStreamInfo(output_stream).map_err(init)?;
|
||||
let output_sample = if info.dwFlags & MFT_OUTPUT_STREAM_PROVIDES_SAMPLES.0 as u32 != 0 {
|
||||
None
|
||||
} else {
|
||||
// The size it asks for, or room for an uncompressed image: a
|
||||
// keyframe never comes close.
|
||||
let raw = config.width * config.height * 3 / 2;
|
||||
Some(new_sample(info.cbSize.max(raw)).map_err(init)?)
|
||||
};
|
||||
transform
|
||||
.ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)
|
||||
.map_err(init)?;
|
||||
transform
|
||||
.ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0)
|
||||
.map_err(init)?;
|
||||
let sequence_header = sequence_header(&transform, output_stream);
|
||||
Ok(Self {
|
||||
activate,
|
||||
transform,
|
||||
events,
|
||||
codec_api,
|
||||
input_stream,
|
||||
output_stream,
|
||||
output_sample,
|
||||
input_wanted: 0,
|
||||
sequence_header,
|
||||
config,
|
||||
software,
|
||||
name,
|
||||
frames: 0,
|
||||
keyframe_requested: false,
|
||||
i420: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The image as an NV12 sample with its timestamp.
|
||||
fn input_sample(&mut self, frame: &BgraFrame) -> Result<IMFSample, EncodeError> {
|
||||
bgra_to_i420(frame, &mut self.i420);
|
||||
let (width, height) = (frame.width, frame.height);
|
||||
let luma = width * height;
|
||||
let chroma = luma / 4;
|
||||
let size = luma + 2 * chroma;
|
||||
let fps = i64::from(self.config.fps.max(1));
|
||||
// SAFETY: the buffer is locked for `size` bytes, written within them,
|
||||
// then unlocked before anyone else sees it.
|
||||
unsafe {
|
||||
// A new buffer per image: an asynchronous transform may hold the
|
||||
// previous one until its output.
|
||||
let buffer = MFCreateMemoryBuffer(size as u32).map_err(encode)?;
|
||||
let mut data = std::ptr::null_mut();
|
||||
buffer.Lock(&mut data, None, None).map_err(encode)?;
|
||||
let out = std::slice::from_raw_parts_mut(data, size);
|
||||
let (y, uv) = out.split_at_mut(luma);
|
||||
y.copy_from_slice(&self.i420[..luma]);
|
||||
let (u, v) = self.i420[luma..].split_at(chroma);
|
||||
for ((pair, u), v) in uv.as_chunks_mut::<2>().0.iter_mut().zip(u).zip(v) {
|
||||
*pair = [*u, *v];
|
||||
}
|
||||
buffer.Unlock().map_err(encode)?;
|
||||
buffer.SetCurrentLength(size as u32).map_err(encode)?;
|
||||
let sample = MFCreateSample().map_err(encode)?;
|
||||
sample.AddBuffer(&buffer).map_err(encode)?;
|
||||
let time = self.frames as i64 * TICKS_PER_SECOND / fps;
|
||||
sample.SetSampleTime(time).map_err(encode)?;
|
||||
sample
|
||||
.SetSampleDuration(TICKS_PER_SECOND / fps)
|
||||
.map_err(encode)?;
|
||||
Ok(sample)
|
||||
}
|
||||
}
|
||||
|
||||
fn force_keyframe(&self) {
|
||||
let Some(api) = &self.codec_api else {
|
||||
// The next periodic keyframe will do, within five seconds.
|
||||
tracing::debug!("keyframe requested from an encoder without ICodecAPI");
|
||||
return;
|
||||
};
|
||||
// SAFETY: COM call with a value that outlives it.
|
||||
if let Err(error) =
|
||||
unsafe { api.SetValue(&CODECAPI_AVEncVideoForceKeyFrame, &variant_u32(1)) }
|
||||
{
|
||||
tracing::debug!(%error, "keyframe request refused");
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronous transform: the image in, then every unit it gives.
|
||||
fn encode_sync(&mut self, sample: &IMFSample) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
let mut packets = Vec::new();
|
||||
// SAFETY: COM call on a sample we own.
|
||||
let accepted = unsafe { self.transform.ProcessInput(self.input_stream, sample, 0) };
|
||||
match accepted {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.code() == MF_E_NOTACCEPTING => {
|
||||
// It still holds output: take it, then try again once.
|
||||
self.drain(&mut packets)?;
|
||||
// SAFETY: as above.
|
||||
unsafe { self.transform.ProcessInput(self.input_stream, sample, 0) }
|
||||
.map_err(encode)?;
|
||||
}
|
||||
Err(error) => return Err(encode(error)),
|
||||
}
|
||||
self.drain(&mut packets)?;
|
||||
Ok(packets)
|
||||
}
|
||||
|
||||
/// Asynchronous transform: wait for it to want an image, give it, wait
|
||||
/// for the unit, take whatever else is ready.
|
||||
fn encode_async(&mut self, sample: &IMFSample) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
let mut packets = Vec::new();
|
||||
let deadline = Instant::now() + PULL_TIMEOUT;
|
||||
while self.input_wanted == 0 {
|
||||
if !self.next_event(Some(deadline), &mut packets)? {
|
||||
return Err(EncodeError::Encode(
|
||||
"Media Foundation: the encoder asks for no image".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// SAFETY: COM call on a sample we own.
|
||||
unsafe { self.transform.ProcessInput(self.input_stream, sample, 0) }.map_err(encode)?;
|
||||
self.input_wanted -= 1;
|
||||
let deadline = Instant::now() + PULL_TIMEOUT;
|
||||
while packets.is_empty() && self.next_event(Some(deadline), &mut packets)? {}
|
||||
while self.next_event(None, &mut packets)? {}
|
||||
Ok(packets)
|
||||
}
|
||||
|
||||
/// Handles one event of an asynchronous transform, waiting until
|
||||
/// `deadline` at most (not at all without one). False when none came.
|
||||
fn next_event(
|
||||
&mut self,
|
||||
deadline: Option<Instant>,
|
||||
packets: &mut Vec<Vec<u8>>,
|
||||
) -> Result<bool, EncodeError> {
|
||||
let Some(events) = self.events.clone() else {
|
||||
return Ok(false);
|
||||
};
|
||||
loop {
|
||||
// SAFETY: COM call; the event is ours once returned.
|
||||
let event = unsafe { events.GetEvent(MF_EVENT_FLAG_NO_WAIT) };
|
||||
match event {
|
||||
Ok(event) => {
|
||||
// SAFETY: as above.
|
||||
let (kind, status) = unsafe { (event.GetType(), event.GetStatus()) };
|
||||
if let Ok(status) = status {
|
||||
status.ok().map_err(encode)?;
|
||||
}
|
||||
let kind = MF_EVENT_TYPE(kind.map_err(encode)? as i32);
|
||||
if kind == METransformNeedInput {
|
||||
self.input_wanted += 1;
|
||||
} else if kind == METransformHaveOutput
|
||||
&& let Some(packet) = self.take_output()?
|
||||
{
|
||||
packets.push(packet);
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
Err(error) if error.code() == MF_E_NO_EVENTS_AVAILABLE => {
|
||||
match deadline {
|
||||
Some(deadline) if Instant::now() < deadline => {
|
||||
// `GetEvent` either blocks forever or not at all:
|
||||
// poll instead, a quarter of a millisecond is
|
||||
// nothing next to a frame.
|
||||
std::thread::sleep(Duration::from_micros(250));
|
||||
}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
}
|
||||
Err(error) => return Err(encode(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes every unit a synchronous transform has ready.
|
||||
fn drain(&mut self, packets: &mut Vec<Vec<u8>>) -> Result<(), EncodeError> {
|
||||
while let Some(packet) = self.take_output()? {
|
||||
packets.push(packet);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One access unit, or `None` when the transform wants more input.
|
||||
fn take_output(&mut self) -> Result<Option<Vec<u8>>, EncodeError> {
|
||||
loop {
|
||||
if let Some(sample) = &self.output_sample {
|
||||
// SAFETY: COM calls on a sample we own.
|
||||
unsafe {
|
||||
sample
|
||||
.GetBufferByIndex(0)
|
||||
.and_then(|b| b.SetCurrentLength(0))
|
||||
}
|
||||
.map_err(encode)?;
|
||||
}
|
||||
let mut buffers = [MFT_OUTPUT_DATA_BUFFER {
|
||||
dwStreamID: self.output_stream,
|
||||
pSample: ManuallyDrop::new(self.output_sample.clone()),
|
||||
dwStatus: 0,
|
||||
pEvents: ManuallyDrop::new(None),
|
||||
}];
|
||||
let mut status = 0;
|
||||
// SAFETY: the transform fills `buffers`, whose references we take
|
||||
// back right after, success or not, so that none leaks.
|
||||
let result = unsafe { self.transform.ProcessOutput(0, &mut buffers, &mut status) };
|
||||
let (sample, _events) = unsafe {
|
||||
(
|
||||
ManuallyDrop::take(&mut buffers[0].pSample),
|
||||
ManuallyDrop::take(&mut buffers[0].pEvents),
|
||||
)
|
||||
};
|
||||
match result {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.code() == MF_E_TRANSFORM_NEED_MORE_INPUT => return Ok(None),
|
||||
Err(error) if error.code() == MF_E_TRANSFORM_STREAM_CHANGE => {
|
||||
// The transform settled its output type: take the one it
|
||||
// proposes, and ask again.
|
||||
// SAFETY: COM calls on the transform we own.
|
||||
unsafe {
|
||||
let proposed = self
|
||||
.transform
|
||||
.GetOutputAvailableType(self.output_stream, 0)
|
||||
.map_err(encode)?;
|
||||
self.transform
|
||||
.SetOutputType(self.output_stream, &proposed, 0)
|
||||
.map_err(encode)?;
|
||||
}
|
||||
self.sequence_header = sequence_header(&self.transform, self.output_stream);
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(encode(error)),
|
||||
}
|
||||
let Some(sample) = sample else {
|
||||
return Ok(None);
|
||||
};
|
||||
// SAFETY: the buffer is locked for its current length, copied,
|
||||
// then unlocked.
|
||||
let (mut unit, keyframe) = unsafe {
|
||||
let buffer = sample.ConvertToContiguousBuffer().map_err(encode)?;
|
||||
let mut data = std::ptr::null_mut();
|
||||
let mut length = 0;
|
||||
buffer
|
||||
.Lock(&mut data, None, Some(&mut length))
|
||||
.map_err(encode)?;
|
||||
let unit = std::slice::from_raw_parts(data, length as usize).to_vec();
|
||||
buffer.Unlock().map_err(encode)?;
|
||||
let keyframe = sample.GetUINT32(&MFSampleExtension_CleanPoint) == Ok(1);
|
||||
(unit, keyframe)
|
||||
};
|
||||
if unit.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if keyframe
|
||||
&& !nal_types(&unit).contains(&7)
|
||||
&& let Some(header) = &self.sequence_header
|
||||
{
|
||||
// A browser joining on this keyframe needs SPS and PPS.
|
||||
unit.splice(0..0, header.iter().copied());
|
||||
}
|
||||
return Ok(Some(unit));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoEncoder for MediaFoundationEncoder {
|
||||
fn encode(&mut self, frame: &BgraFrame) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
let expected = self.config.width as usize * self.config.height as usize * 4;
|
||||
if frame.data.len() < expected
|
||||
|| frame.width != self.config.width as usize
|
||||
|| frame.height != self.config.height as usize
|
||||
{
|
||||
return Err(EncodeError::Encode(format!(
|
||||
"{}x{} image for a {}x{} encoder",
|
||||
frame.width, frame.height, self.config.width, self.config.height
|
||||
)));
|
||||
}
|
||||
if std::mem::take(&mut self.keyframe_requested) {
|
||||
self.force_keyframe();
|
||||
}
|
||||
let sample = self.input_sample(frame)?;
|
||||
self.frames += 1;
|
||||
let packets = if self.events.is_some() {
|
||||
self.encode_async(&sample)?
|
||||
} else {
|
||||
self.encode_sync(&sample)?
|
||||
};
|
||||
if packets.is_empty() {
|
||||
return Err(EncodeError::NoFrame);
|
||||
}
|
||||
Ok(packets)
|
||||
}
|
||||
|
||||
fn request_keyframe(&mut self) {
|
||||
self.keyframe_requested = true;
|
||||
}
|
||||
|
||||
fn config(&self) -> EncodeConfig {
|
||||
self.config
|
||||
}
|
||||
|
||||
fn reconfigure(&mut self, width: u32, height: u32) -> Result<(), EncodeError> {
|
||||
// A new transform at the new size, opened before the old one goes: a
|
||||
// failure leaves the stream as it was. Its first image is a keyframe.
|
||||
let config = EncodeConfig {
|
||||
width,
|
||||
height,
|
||||
..self.config
|
||||
};
|
||||
*self = Self::open(config, self.software)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MediaFoundationEncoder {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the transform is not used after this.
|
||||
let _ = unsafe { self.activate.ShutdownObject() };
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts COM in the multithreaded apartment for the whole process, and
|
||||
/// Media Foundation, once. Neither is ever stopped: an encoder can open at
|
||||
/// any time, on any thread.
|
||||
fn media_foundation_ready() -> Result<(), EncodeError> {
|
||||
static READY: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
READY
|
||||
.get_or_init(|| {
|
||||
// SAFETY: process-wide initializations, without arguments to keep
|
||||
// alive.
|
||||
unsafe {
|
||||
// Every thread that has not chosen an apartment joins this
|
||||
// one: the encoding thread does not have to.
|
||||
CoIncrementMTAUsage().map_err(|e| format!("COM: {e}"))?;
|
||||
MFStartup(MF_VERSION, MFSTARTUP_LITE).map_err(|e| format!("Media Foundation: {e}"))
|
||||
}
|
||||
})
|
||||
.clone()
|
||||
.map_err(EncodeError::Init)
|
||||
}
|
||||
|
||||
/// The H.264 encoders that take NV12, best first: hardware ones only, unless
|
||||
/// `software`.
|
||||
fn encoders(software: bool) -> Result<Vec<IMFActivate>, EncodeError> {
|
||||
let input = MFT_REGISTER_TYPE_INFO {
|
||||
guidMajorType: MFMediaType_Video,
|
||||
guidSubtype: MFVideoFormat_NV12,
|
||||
};
|
||||
let output = MFT_REGISTER_TYPE_INFO {
|
||||
guidMajorType: MFMediaType_Video,
|
||||
guidSubtype: MFVideoFormat_H264,
|
||||
};
|
||||
let mut flags = MFT_ENUM_FLAG_HARDWARE.0 | MFT_ENUM_FLAG_SORTANDFILTER.0;
|
||||
if software {
|
||||
flags |= MFT_ENUM_FLAG_SYNCMFT.0;
|
||||
}
|
||||
let mut list = std::ptr::null_mut();
|
||||
let mut count = 0;
|
||||
// SAFETY: Media Foundation allocates the array; we take each reference
|
||||
// out of it, then free it.
|
||||
unsafe {
|
||||
MFTEnumEx(
|
||||
MFT_CATEGORY_VIDEO_ENCODER,
|
||||
MFT_ENUM_FLAG(flags),
|
||||
Some(&input),
|
||||
Some(&output),
|
||||
&mut list,
|
||||
&mut count,
|
||||
)
|
||||
.map_err(init)?;
|
||||
if list.is_null() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let found = (0..count as usize)
|
||||
.filter_map(|i| std::ptr::read(list.add(i)))
|
||||
.collect::<Vec<_>>();
|
||||
CoTaskMemFree(Some(list as *const _));
|
||||
// Hardware first: the sort puts it there already, but not every
|
||||
// version of Windows sorts by it.
|
||||
let (mut hardware, other): (Vec<_>, Vec<_>) = found
|
||||
.into_iter()
|
||||
.partition(|a| a.GetStringLength(&MFT_ENUM_HARDWARE_URL_Attribute).is_ok());
|
||||
hardware.extend(other);
|
||||
Ok(hardware)
|
||||
}
|
||||
}
|
||||
|
||||
/// The registered name of an encoder, for the log.
|
||||
fn friendly_name(activate: &IMFActivate) -> String {
|
||||
let mut name = PWSTR::null();
|
||||
let mut length = 0;
|
||||
// SAFETY: Media Foundation allocates the string; we copy it, then free it.
|
||||
unsafe {
|
||||
if activate
|
||||
.GetAllocatedString(&MFT_FRIENDLY_NAME_Attribute, &mut name, &mut length)
|
||||
.is_err()
|
||||
{
|
||||
return "unnamed encoder".into();
|
||||
}
|
||||
let text = name.to_string().unwrap_or_default();
|
||||
CoTaskMemFree(Some(name.0 as *const _));
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream identifiers: most transforms have fixed streams numbered 0, and
|
||||
/// answer `E_NOTIMPL`.
|
||||
fn stream_ids(transform: &IMFTransform) -> (u32, u32) {
|
||||
let (mut input, mut output) = ([0u32], [0u32]);
|
||||
// SAFETY: two arrays of one identifier each, as announced.
|
||||
match unsafe { transform.GetStreamIDs(&mut input, &mut output) } {
|
||||
Ok(()) => (input[0], output[0]),
|
||||
Err(_) => (0, 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// A progressive video type of `subtype` at the configured size and rate.
|
||||
fn video_type(subtype: &GUID, config: &EncodeConfig) -> Result<IMFMediaType, EncodeError> {
|
||||
// SAFETY: COM calls on a type we just created.
|
||||
unsafe {
|
||||
let media = MFCreateMediaType().map_err(init)?;
|
||||
media
|
||||
.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)
|
||||
.map_err(init)?;
|
||||
media.SetGUID(&MF_MT_SUBTYPE, subtype).map_err(init)?;
|
||||
media
|
||||
.SetUINT64(
|
||||
&MF_MT_FRAME_SIZE,
|
||||
u64::from(config.width) << 32 | u64::from(config.height),
|
||||
)
|
||||
.map_err(init)?;
|
||||
media
|
||||
.SetUINT64(&MF_MT_FRAME_RATE, u64::from(config.fps.max(1)) << 32 | 1)
|
||||
.map_err(init)?;
|
||||
media
|
||||
.SetUINT64(&MF_MT_PIXEL_ASPECT_RATIO, 1 << 32 | 1)
|
||||
.map_err(init)?;
|
||||
media
|
||||
.SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)
|
||||
.map_err(init)?;
|
||||
Ok(media)
|
||||
}
|
||||
}
|
||||
|
||||
/// SPS and PPS of the current output type, when the transform gives them in
|
||||
/// Annex B (start codes); otherwise nothing, the stream carries them.
|
||||
fn sequence_header(transform: &IMFTransform, stream: u32) -> Option<Vec<u8>> {
|
||||
// SAFETY: the blob is copied into a buffer of the size announced.
|
||||
unsafe {
|
||||
let media = transform.GetOutputCurrentType(stream).ok()?;
|
||||
let size = media.GetBlobSize(&MF_MT_MPEG_SEQUENCE_HEADER).ok()?;
|
||||
let mut header = vec![0u8; size as usize];
|
||||
media
|
||||
.GetBlob(&MF_MT_MPEG_SEQUENCE_HEADER, &mut header, None)
|
||||
.ok()?;
|
||||
(header.starts_with(&[0, 0, 1]) || header.starts_with(&[0, 0, 0, 1])).then_some(header)
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty sample with a buffer of `size` bytes, lent to the transform.
|
||||
fn new_sample(size: u32) -> windows::core::Result<IMFSample> {
|
||||
// SAFETY: COM calls on objects we just created.
|
||||
unsafe {
|
||||
let sample = MFCreateSample()?;
|
||||
sample.AddBuffer(&MFCreateMemoryBuffer(size)?)?;
|
||||
Ok(sample)
|
||||
}
|
||||
}
|
||||
|
||||
/// NAL unit types of an Annex B access unit, in order.
|
||||
fn nal_types(unit: &[u8]) -> Vec<u8> {
|
||||
unit.windows(3)
|
||||
.enumerate()
|
||||
.filter(|(_, w)| *w == [0, 0, 1])
|
||||
.filter_map(|(i, _)| unit.get(i + 3).map(|b| b & 0x1f))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn variant_u32(value: u32) -> VARIANT {
|
||||
VARIANT {
|
||||
Anonymous: VARIANT_0 {
|
||||
Anonymous: ManuallyDrop::new(VARIANT_0_0 {
|
||||
vt: VT_UI4,
|
||||
wReserved1: 0,
|
||||
wReserved2: 0,
|
||||
wReserved3: 0,
|
||||
Anonymous: VARIANT_0_0_0 { ulVal: value },
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn variant_bool(value: bool) -> VARIANT {
|
||||
VARIANT {
|
||||
Anonymous: VARIANT_0 {
|
||||
Anonymous: ManuallyDrop::new(VARIANT_0_0 {
|
||||
vt: VT_BOOL,
|
||||
wReserved1: 0,
|
||||
wReserved2: 0,
|
||||
wReserved3: 0,
|
||||
Anonymous: VARIANT_0_0_0 {
|
||||
boolVal: VARIANT_BOOL(if value { -1 } else { 0 }),
|
||||
},
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn init(error: windows::core::Error) -> EncodeError {
|
||||
EncodeError::Init(format!("Media Foundation: {error}"))
|
||||
}
|
||||
|
||||
fn encode(error: windows::core::Error) -> EncodeError {
|
||||
EncodeError::Encode(format!("Media Foundation: {error}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn config(width: u32, height: u32) -> EncodeConfig {
|
||||
EncodeConfig {
|
||||
width,
|
||||
height,
|
||||
fps: 30,
|
||||
bitrate_kbps: 1000,
|
||||
codec: VideoCodec::H264,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bars that move, so that the encoder has something to say.
|
||||
fn image(width: usize, height: usize, shift: usize) -> Vec<u8> {
|
||||
let mut data = vec![0u8; width * height * 4];
|
||||
for (i, pixel) in data.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
let x = (i % width + shift) % width;
|
||||
pixel.copy_from_slice(&[(x * 255 / width) as u8, 128, 255 - (x as u8), 255]);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// Any H.264 transform: the GPU's on a real machine, Wine's (GStreamer,
|
||||
/// x264) under Wine. Skipped where neither exists.
|
||||
fn encoder(width: u32, height: u32) -> Option<MediaFoundationEncoder> {
|
||||
match MediaFoundationEncoder::software(config(width, height)) {
|
||||
Ok(encoder) => {
|
||||
eprintln!("encoder: {}", encoder.name());
|
||||
Some(encoder)
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("no Media Foundation H.264: {error}, test skipped");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Enough images to get past the lookahead of a software encoder.
|
||||
const IMAGES: usize = 90;
|
||||
|
||||
fn encode_all(
|
||||
encoder: &mut MediaFoundationEncoder,
|
||||
images: usize,
|
||||
width: usize,
|
||||
height: usize,
|
||||
) -> Vec<Vec<u8>> {
|
||||
let mut units = Vec::new();
|
||||
for i in 0..images {
|
||||
if i == images / 2 {
|
||||
encoder.request_keyframe();
|
||||
}
|
||||
let data = image(width, height, i * 7);
|
||||
let frame = BgraFrame {
|
||||
data: &data,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
match encoder.encode(&frame) {
|
||||
Ok(packets) => units.extend(packets),
|
||||
Err(EncodeError::NoFrame) => {}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
units
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn h264_comes_out_as_annex_b_with_its_parameters() {
|
||||
let Some(mut encoder) = encoder(320, 240) else {
|
||||
return;
|
||||
};
|
||||
// A GPU gives one unit per image; Wine's x264 keeps about forty in
|
||||
// its lookahead first, whatever the low-latency setting says.
|
||||
let units = encode_all(&mut encoder, IMAGES, 320, 240);
|
||||
assert!(
|
||||
units.len() >= IMAGES / 4,
|
||||
"{} access units for {IMAGES} images",
|
||||
units.len()
|
||||
);
|
||||
// SPS (7), PPS (8) and an IDR slice (5) in the first unit.
|
||||
let first = nal_types(&units[0]);
|
||||
assert!(
|
||||
first.contains(&7) && first.contains(&8) && first.contains(&5),
|
||||
"{first:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_size_gives_a_new_encoder_that_starts_on_a_keyframe() {
|
||||
let Some(mut encoder) = encoder(320, 240) else {
|
||||
return;
|
||||
};
|
||||
encode_all(&mut encoder, 3, 320, 240);
|
||||
encoder.reconfigure(640, 360).expect("new size");
|
||||
assert_eq!(encoder.config().width, 640);
|
||||
let units = encode_all(&mut encoder, IMAGES, 640, 360);
|
||||
assert!(!units.is_empty());
|
||||
assert!(nal_types(&units[0]).contains(&5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_of_the_wrong_size_is_refused() {
|
||||
let Some(mut encoder) = encoder(320, 240) else {
|
||||
return;
|
||||
};
|
||||
let data = image(160, 120, 0);
|
||||
let frame = BgraFrame {
|
||||
data: &data,
|
||||
width: 160,
|
||||
height: 120,
|
||||
};
|
||||
assert!(matches!(
|
||||
encoder.encode(&frame),
|
||||
Err(EncodeError::Encode(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vp8_and_vp9_are_left_to_libvpx() {
|
||||
for codec in [VideoCodec::Vp8, VideoCodec::Vp9] {
|
||||
let config = EncodeConfig {
|
||||
codec,
|
||||
..config(320, 240)
|
||||
};
|
||||
assert!(matches!(
|
||||
MediaFoundationEncoder::software(config),
|
||||
Err(EncodeError::Init(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nal_types_are_read_after_three_and_four_byte_start_codes() {
|
||||
let unit = [0, 0, 0, 1, 0x67, 9, 0, 0, 1, 0x68, 9, 0, 0, 1, 0x65, 1, 2];
|
||||
assert_eq!(nal_types(&unit), vec![7, 8, 5]);
|
||||
}
|
||||
}
|
||||
@@ -407,7 +407,7 @@ fn open_encoder(
|
||||
if encoding.hardware && config.codec != VideoCodec::Vp8 {
|
||||
match hardware_encoder(config) {
|
||||
Ok(encoder) => {
|
||||
tracing::info!(codec = config.codec.as_str(), "hardware encoder (VA-API)");
|
||||
tracing::info!(codec = config.codec.as_str(), "hardware encoder");
|
||||
return Ok((encoder, None));
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -437,7 +437,14 @@ fn hardware_encoder(config: EncodeConfig) -> Result<Box<dyn VideoEncoder>, rs_co
|
||||
Ok(Box::new(rs_codec::HardwareEncoder::new(config)?))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "vaapi"))]
|
||||
/// Windows: the GPU's H.264 through Media Foundation (#95); VP9 stays on
|
||||
/// libvpx.
|
||||
#[cfg(windows)]
|
||||
fn hardware_encoder(config: EncodeConfig) -> Result<Box<dyn VideoEncoder>, rs_codec::EncodeError> {
|
||||
Ok(Box::new(rs_codec::MediaFoundationEncoder::new(config)?))
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "vaapi", windows)))]
|
||||
fn hardware_encoder(_: EncodeConfig) -> Result<Box<dyn VideoEncoder>, rs_codec::EncodeError> {
|
||||
Err(rs_codec::EncodeError::Init(
|
||||
"this build has no hardware encoding (`vaapi` feature)".into(),
|
||||
|
||||
@@ -67,7 +67,7 @@ impl DiagnosticsContext {
|
||||
"vp9_exposed": true,
|
||||
// Asked to the GPU at export time only: opening it takes a
|
||||
// fraction of a second (#57).
|
||||
"hardware_built": cfg!(feature = "vaapi"),
|
||||
"hardware_built": cfg!(any(feature = "vaapi", windows)),
|
||||
"hardware": hardware_codecs(),
|
||||
"config": self.encode.map(|c| serde_json::json!({
|
||||
"width": c.width,
|
||||
@@ -102,7 +102,17 @@ fn hardware_codecs() -> Vec<&'static str> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "vaapi"))]
|
||||
/// The codecs this machine's GPU encodes through Media Foundation (#95).
|
||||
#[cfg(windows)]
|
||||
fn hardware_codecs() -> Vec<&'static str> {
|
||||
[rs_codec::VideoCodec::H264]
|
||||
.into_iter()
|
||||
.filter(|codec| rs_codec::MediaFoundationEncoder::available(*codec))
|
||||
.map(rs_codec::VideoCodec::as_str)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "vaapi", windows)))]
|
||||
fn hardware_codecs() -> Vec<&'static str> {
|
||||
Vec::new()
|
||||
}
|
||||
@@ -44,8 +44,10 @@ ne tient pas 30 i/s. Les GPU Intel et AMD récents encodent H.264 et VP9 en bass
|
||||
DMA-BUF des tampons PipeWire, sans copie.
|
||||
- Une dépendance de plus à la compilation (GStreamer, LGPL, liée dynamiquement) et à l'exécution
|
||||
(greffon `va`, pilote). Sans elles, rien ne casse: libvpx encode.
|
||||
- Windows demandera sa propre implémentation du même trait (Media Foundation), GStreamer n'étant
|
||||
pas là-bas un prérequis raisonnable. macOS est hors périmètre (#90).
|
||||
- Windows a sa propre implémentation du même trait (#95, `rs-codec::media_foundation`), GStreamer
|
||||
n'étant pas là-bas un prérequis raisonnable: la transformée H.264 du pilote (Quick Sync, NVENC,
|
||||
AMF), asynchrone, en basse latence, nourrie en NV12 converti par le processeur. VP9 y reste sur
|
||||
libvpx. macOS est hors périmètre (#90).
|
||||
|
||||
## Alternatives écartées
|
||||
|
||||
|
||||
+1
-1
@@ -169,7 +169,7 @@
|
||||
"codec": "Video codec",
|
||||
"codecHelp": "VP9 keeps the same picture for less bitrate. H.264 and VP9 are encoded by the graphics card when it can, which frees the processor; H.264 falls back on VP8 without it.",
|
||||
"hardwareEncoding": "Encode on the graphics card when possible",
|
||||
"hardwareEncodingHelp": "VA-API (Intel, AMD). Off: everything is encoded by the processor.",
|
||||
"hardwareEncodingHelp": "VA-API on Linux (Intel, AMD), Media Foundation on Windows (Intel, NVIDIA, AMD). Off: everything is encoded by the processor.",
|
||||
"codecs": {
|
||||
"vp8": "VP8 (light, decoded everywhere)",
|
||||
"vp9": "VP9 (less bitrate)",
|
||||
|
||||
+1
-1
@@ -169,7 +169,7 @@
|
||||
"codec": "Codec vidéo",
|
||||
"codecHelp": "VP9 garde la même image pour moins de débit. H.264 et VP9 sont encodés par la carte graphique quand elle sait le faire, ce qui libère le processeur ; sans elle, H.264 retombe en VP8.",
|
||||
"hardwareEncoding": "Encoder sur la carte graphique quand c’est possible",
|
||||
"hardwareEncodingHelp": "VA-API (Intel, AMD). Décoché : tout est encodé par le processeur.",
|
||||
"hardwareEncodingHelp": "VA-API sous Linux (Intel, AMD), Media Foundation sous Windows (Intel, NVIDIA, AMD). Décoché : tout est encodé par le processeur.",
|
||||
"codecs": {
|
||||
"vp8": "VP8 (léger, décodé partout)",
|
||||
"vp9": "VP9 (moins de débit)",
|
||||
|
||||
Reference in new issue
Block a user