Repository navigation
Conversation
|
Thanks for this PR. We're using it (backported onto 1. The NVIDIA MFT rejects
With the Baseline profile the NVIDIA MFT returns hr = SetCodecApiUInt32(codec_api_.Get(), CODECAPI_AVEncMPVDefaultBPictureCount, 0);
if (FAILED(hr)) {
RTC_LOG(LS_WARNING) << "Encoder MFT rejected B-frame count (baseline has none): "
<< HResultToString(hr);
}2. A frame with a size different from The size check in if (static_cast<int>(configuration_.width) != frame_buffer->width() ||
static_cast<int>(configuration_.height) != frame_buffer->height()) {
RTC_LOG(LS_WARNING) << "Frame size " << frame_buffer->width() << "x"
<< frame_buffer->height() << " != encoder "
<< configuration_.width << "x" << configuration_.height
<< "; dropping frame.";
return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
}Not a bug, just a note: a driver crash can't be caught in-process. Some kind of opt-out (we use an environment variable checked in We haven't tested AMD or Intel yet. We'll report back here if those show problems. |
Adds a Windows hardware H264 backend using the Media Foundation transform registered by the GPU driver, covering Intel QuickSync, AMD VCN and NVIDIA NVENC through a single implementation with no third-party dependencies (system libraries only: mfplat, mfuuid, mf, dxguid). Follows the src/nvidia/ backend layout: - mf_encoder_factory: MFTEnumEx(HARDWARE) probe with an activation check (registration alone does not guarantee a working driver), registered under the generic VideoEncoderBackend::Hardware like the Jetson/Android backends. Advertises the H264 level the MFT actually accepts (4.2 -> 4.0 -> 3.1 via MFT_SET_TYPE_TEST_ONLY) instead of a hardcoded 42e01f, so 1080p can be negotiated. - h264_encoder_impl: webrtc::VideoEncoder over the async hardware MFT with a bounded synchronous event pump (no extra threads). CBR via ICodecAPI, B-frames disabled, effectively-infinite GOP (webrtc drives IDRs), low-latency mode, runtime bitrate updates with a re-init-plus-hysteresis fallback for drivers that reject them, and cached-SPS/PPS prepend for MFTs that do not inline the sequence header on IDR frames. - mf_decoder_factory + h264_decoder_impl: the inbox CLSID_CMSH264DecoderMFT fronting DXVA for all vendors when given a D3D11 device manager; NV12 texture output is copied back through a staging texture into pooled I420 buffers. Falls back to (and reports) software decode when no video-capable D3D11 device exists; handles MF_E_TRANSFORM_STREAM_CHANGE and the 1088-line coded-height display aperture. Windows previously compiled no hardware video factory at all; failures at any point fall back to OpenH264/FFmpeg through the existing dispatch layer. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Validated on a Windows 10 box with Intel HD Graphics (Ivy Bridge i5-3470, QSV driver 10.18.10.5161): cargo build -p webrtc-sys and the livekit-ffi cdylib link both pass under MSVC 14.44 / SDK 10.0.26100, and video_encoder_backend_list() lists Hardware at runtime (the QSV encoder MFT enumerates and activates through MFVideoEncoderFactory::IsSupported). - async MFTs re-signal METransformHaveOutput after MF_E_TRANSFORM_STREAM_CHANGE; an inline ProcessOutput retry returns E_UNEXPECTED on Intel QSV. Wait for the re-signal instead (sync MFTs keep the inline retry). - include d3d10_1.h, not d3d10.h, for ID3D10Multithread (d3d10.h before d3d10_1.h is a hard error on current SDKs due to SAL ordering). - GUID_NULL needs cguid.h; use zero-initialization instead. - fix ProbeTransform call sites left behind by the probe-cleanup refactor. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
aa0c41a to
6090b75
Compare
There was a problem hiding this comment.
Devin Review found 6 new potential issues.
4 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)
| if (pending_bitrate_reinit_) { | ||
| int32_t ret = ReinitTransform(); | ||
| if (ret != WEBRTC_VIDEO_CODEC_OK) { | ||
| ReportError(); | ||
| return ret; | ||
| } |
There was a problem hiding this comment.
🔴 Encoder fallback aborts debug builds
When an Auto H264 sender fails to rebuild after a bitrate change, Encode requests a WebRTC encoder switch. The default switch passes no format and disallows default fallback, which trips ApplyEncoderSwitch’s assertion when checks are enabled.
Learn more
ApplyBitrate schedules a rebuild when a driver rejects a runtime bitrate update and the target moves by more than 20%. ReinitTransform releases the old encoder before creating and configuring the replacement. The pinned WebRTC release treats WEBRTC_VIDEO_CODEC_ENCODER_FAILURE as a request to switch encoders. Auto mode clears the sender’s encoder selector, so the default codec-preference path calls the switch callback with std::nullopt and allow_default_fallback = false. WebRtcVideoSendChannel::ApplyEncoderSwitch asserts format.has_value() || allow_default_fallback before handling the request. The Windows build script supports debug builds, where that assertion terminates the process.
Example: An Auto H264 sender increases its bitrate from 1 Mbps to 1.5 Mbps. If the driver rejects the live update and then refuses to configure the replacement, a build with WebRTC assertions enabled aborts before trying another encoder.
Recommended fix: Give Auto Media Foundation H264 a same-format software fallback in the encoder factory, and signal WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE to that wrapper when the rebuild fails. Preserve the explicitly selected backend policy, and exercise the failed-rebuild path with WebRTC assertions enabled.
Was this helpful? React with 👍 or 👎 to provide feedback.
| if (is_async_) { | ||
| need_input_credits_--; | ||
| // Collect whatever the MFT already produced; block only when too many | ||
| // frames are in flight so encoder latency stays bounded. | ||
| return PumpEvents(kOutputWaitTimeoutMs, /*until_need_input=*/false, | ||
| /*until_pending_at_most=*/kMaxPendingFrames); | ||
| } |
There was a problem hiding this comment.
🔴 Last video update stays unsent
When an app stops submitting frames, Encode can return before the hardware finishes its last update. Nothing reads the output event until another frame arrives, so viewers never see that update.
Learn more
NativeVideoSource::capture_frame lets an application submit raw frames on demand. Once a real frame arrives, the keepalive task stops supplying black frames. PumpEvents returns immediately when there is no event ready and the pending-count limit is satisfied. An asynchronous transform can post METransformHaveOutput after that return. No consumer runs again until another Encode call.
Example: A source publishes a new slide, then waits for the next slide change. The GPU finishes encoding just after the nonblocking poll, leaving viewers on the previous slide for the entire pause.
Recommended fix: Collect hardware output independently of future input calls, using a serialized event consumer with deterministic shutdown. If keeping a synchronous design, wait for output only under a transform contract that guarantees progress without additional input.
Was this helpful? React with 👍 or 👎 to provide feedback.
| MFSetAttributeSize(output_type.Get(), MF_MT_FRAME_SIZE, configuration_.width, | ||
| configuration_.height); | ||
| MFSetAttributeRatio(output_type.Get(), MF_MT_FRAME_RATE, fps, 1); | ||
| output_type->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive); | ||
| output_type->SetUINT32(MF_MT_MPEG2_PROFILE, H264ProfileToMFProfile(profile_)); | ||
| output_type->SetUINT32(MF_MT_MPEG2_LEVEL, H264LevelToMFLevel(level_)); | ||
|
|
||
| hr = transform_->SetOutputType(output_stream_id_, output_type.Get(), 0); | ||
| if (FAILED(hr)) { | ||
| // Some drivers reject an explicit level; let the MFT derive it. | ||
| output_type->DeleteItem(MF_MT_MPEG2_LEVEL); | ||
| hr = transform_->SetOutputType(output_stream_id_, output_type.Get(), 0); |
There was a problem hiding this comment.
🟡 H.264 output exceeds negotiated level
For 1080p30 negotiated at level 3.1, ConfigureTransform keeps the source dimensions and drops the level constraint if rejected. The resulting stream exceeds the receiver’s negotiated decoding limit.
Learn more
The encoder parses the negotiated profile and level in MFH264EncoderImpl. WebRTC can select this factory for the same H.264 profile and packetization mode at a lower peer-advertised level; FormatSupportedByBackendFactory matches using IsSameCodec, which does not compare H.264 levels. The configuration forwards the source dimensions and frame rate without enforcing the negotiated limit, and a rejected level is removed on retry.
Example: A Windows publisher captures 1920×1080 at 30 fps and selects constrained baseline against a receiver advertising 42e01f. A transform accepting the unrestricted retry can emit level 4.0 video, even though the receiver only advertised level 3.1. A 1080p picture alone exceeds level 3.1’s macroblocks-per-frame limit.
Recommended fix: Enforce the negotiated level’s picture size, processing rate, and bitrate limits before opening the transform. Arrange for compliant input adaptation or select a compliant fallback rather than retrying with an unrestricted type.
Was this helpful? React with 👍 or 👎 to provide feedback.
…up, and add LK_DISABLE_MF
6090b75 to
1f68486
Compare
…d verwalter changeset
1f68486 to
6f67812
Compare
|
Thanks @wemerson-silva-kz for testing this on an RTX 4060 Ti and reporting those two issues! I've rebased the PR onto current Fixes & Updates
Regarding the two remaining Devin Review notes:
@cloudwebrtc All 34 CI checks are now green (including |
PR description
Adds a hardware H264 encoder + decoder backend for Windows, using Media Foundation.
I need to run LiveKit with hardware acceleration for video en/decoding if at all possible,
and found this was not possible on Windows. Without prior experience in LiveKit dev, I
attempted to fill in this gap using LLMs: this PR was created through guided steps with Fable 5.
Windows currently compiles no hardware video factory at all — the NVENC backend
is Linux-only (it dlopens
libnvidia-encode.so.1), and thevaapi-windowsexperiment in
build.rsis commented out. On a typical Intel- or AMD-iGPUworkstation, H264 therefore runs on OpenH264/FFmpeg in software.
This PR adds an encoder and decoder built on the Media Foundation transform
(MFT) registered by the GPU driver. One implementation covers Intel
QuickSync, AMD VCN, and NVIDIA — NVIDIA's Windows driver registers an encoder
MFT like the other vendors, so it is included even though the NVENC backend
isn't available on this platform. It links only static Windows GUID libraries
(
mfuuid,dxguid) and loadsmfplat.dlldynamically from System32 at runtime:no third-party dependencies, nothing downloaded, no custom libwebrtc build, and
Windows N editions without the Media Feature Pack still load cleanly and fall
back to software.
Layout (mirrors
webrtc-sys/src/nvidia/)Integration is three small edits:
AddMfFactoryunder#if defined(USE_MF_VIDEO_CODEC)invideo_encoder_factory.cpp(registered asthe generic
VideoEncoderBackend::Hardwareafter NVENC/VAAPI, like theJetson/Android backends, so there are no cxx bridge changes), one
push_backinvideo_decoder_factory.cpp, and five files +/DUSE_MF_VIDEO_CODEC=1+ staticGUID libs (
mfuuid,dxguid) in thebuild.rs"windows"arm. Every failurepath falls through to the existing software fallback, and
LK_DISABLE_MFdisables the backend at runtime.
Design notes
Encode()runs a boundedsynchronous event pump — no extra threads, at most 4 frames in flight. CBR via
ICodecAPI, B-frames disabled (warning-only under Baseline for drivers likeNVIDIA's MFT that reject
CODECAPI_AVEncMPVDefaultBPictureCount),effectively-infinite GOP (webrtc drives IDRs through
AVEncVideoForceKeyFrame),AVLowLatencyMode. Bitrate is updated at runtime where the driver accepts it,otherwise by re-init behind a >20% hysteresis. A cached
MF_MT_MPEG_SEQUENCE_HEADERis prepended to IDRs for vendor MFTs that don'tinline SPS/PPS. Annex-B output feeds the same NALU-scan /
H264BitstreamParserpost-processing as the NVENC implementation.accepts (
MFT_SET_TYPE_TEST_ONLY, 4.2 → 4.0 → 3.1) rather than hardcoding42e01f, so 1080p can be negotiated. Constrained Baseline only, matching theexisting default interop posture.
CLSID_CMSH264DecoderMFTfronts DXVA for every vendorwhen given a D3D11 device manager. Without one it silently decodes on the CPU,
which would be strictly worse than the existing decoder path — so the factory
only registers when a video-capable D3D11 device exists. Handles
MF_E_TRANSFORM_STREAM_CHANGEand the coded-size display aperture (1080parrives as 1920×1088). NV12 texture → staging texture → pooled I420.
mfplat.dll.mfplat.dllis loaded dynamically from System32 onfirst MF probe/use; COM is initialized per-thread (MTA, STA-tolerant), since
webrtc calls in on its own task queues;
MFStartupis process-wide start-once.Known limitations
physical hardware (no machine available). Intel QuickSync and NVIDIA
(reported by
@wemerson-silva-kzon an RTX 4060 Ti, 1920×1032@60fps +simulcast) have been validated on real hardware.
i.e. the same copy costs as the NVENC backend. Zero-copy is a possible
follow-up.
Breaking changes
None. The change is additive and Windows-only: new files under
webrtc-sys/src/mf/, two guarded dispatch registrations, and abuild.rs"windows"arm. There are no Rust or FFI API changes, no cxx bridge changes andno new dependencies. On every other platform the diff compiles to nothing, and
on Windows the backend only registers when
mfplat.dlland a hardware MFT (and,for decode, a video-capable D3D11 device) are actually present and
LK_DISABLE_MFis unset — otherwise behaviour is unchanged.
MSRV
Unchanged. No Rust language or dependency changes; the only Rust touched is
build.rslink/source declarations.Async
No async Rust is involved — this is C++ inside
webrtc-sys, called on webrtc'sown encoder/decoder task queues. Nothing in
livekit-runtimeis used or needed,and no Tokio dependency is introduced. The MFT event pump is synchronous and
bounded, and holds no locks shared with application threads.
Testing
I want to be straight about this: there are no unit tests in this PR, and I
don't think there is an honest way to add meaningful ones. The code under test
is a driver-registered hardware transform — there is nothing to assert against
without a GPU, and a test that mocked the MFT away would only be asserting that
the mock behaves like the mock. CI has no GPU on the
windows-latestrunners,so anything I added would either be skipped there or would emulate exactly the
happy path the contributing guidelines ask us not to emulate. This matches the
existing NVENC, VAAPI and Jetson backends, which likewise ship without unit
tests.
What I did instead was validate on real hardware, deliberately choosing a
worst-case old machine — a Dell OptiPlex 7010: i5-3470, Ivy Bridge HD 2500,
driver 10.18.10.5161 (2020, the final Ivy Bridge branch), Windows 10. If it
works there, the driver floor is Ivy Bridge and up.
Standalone probe (a small
cl.exeexecutable driving the MFTs directly):ICodecAPIok)TEST_ONLY)profile_idc=66,level_idc=40ForceKeyFrame→ IDRBuild and runtime (same machine, MSVC 14.44 / SDK 10.0.26100, stable Rust):
cargo build -p webrtc-sys— clean.cargo build -p livekit-ffi— fulllivekit_ffi.dllcdylib link clean, whichis what validates the CODECAPI GUID instantiation and System32 dynamic
mfplat.dllloading.video_encoder_backend_list()returns[Auto, Software, Hardware], i.e.MFVideoEncoderFactory::IsSupported()enumerated and activated the QSV MFT through the real dispatch path.
End to end: a live session between a macOS client and a Windows client, both
built on this SDK with H264 selected, camera video flowing in both directions.
Process-module snapshots confirm the Intel hardware encoder MFT
(
mfx_mft_h264ve_64.dll+libmfxhw64.dll) and the inbox decoder(
msmpeg2vdec.dll) are loaded in-process on the Windows side for the duration.Additionally,
@wemerson-silva-kzverified the branch on Windows 11 with anNVIDIA RTX 4060 Ti (driver 610.88) encoding 1920×1032@60fps with simulcast.
Three hardware behaviours were only discovered by running on a real GPU, and are
now baked into the code:
METransformHaveOutputafterMF_E_TRANSFORM_STREAM_CHANGE— an inlineProcessOutputretry returnsE_UNEXPECTEDon QSV. The encoder now waits for the re-signal; synchronousMFTs keep the inline retry. Without this the first frame would have dropped
the whole backend to software.
d3d10.hbefored3d10_1.his a hard error on current SDKs (SAL ordering) —include
d3d10_1.hforID3D10Multithread.GUID_NULLrequirescguid.h; zero-initialization is used instead.Windows ARM64 (
aarch64-pc-windows-msvc): CI now builds and passes foraarch64-pc-windows-msvcas well asx86_64-pc-windows-msvc. There is noarchitecture-specific code in
webrtc-sys/src/mf/, though runtime execution onphysical Windows ARM64 hardware has not been tested. Happy to gate it to
x86_64if preferred.Notes for review
A few questions I expect, answered up front:
LIVEKIT_PREFERRED_HW_ENCODERsupport? It parsesnvenc|vaapionly, and MF registers as the generic
Hardwarebackend after NVENC/VAAPI(so native NVENC takes precedence if also compiled on Windows). Worth
extending if needed.
posture. High profile is a straightforward follow-up — the
eAVEncH264VProfile_Highmapping already exists in the implementation.decodes on the CPU, which is strictly worse than the built-in decoder path, so
registering unconditionally would be a silent regression.
main(webrtc-a545de4/verwalter) and all CI checks pass.