Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/enc-ffmpeg/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ mod audio;
pub use audio::*;

mod video;
#[cfg(any(windows, test))]
pub use video::d3d11_format::capture_texel_feeds_nv12;
pub use video::*;

mod mux;
Expand Down
95 changes: 94 additions & 1 deletion crates/enc-ffmpeg/src/mux/segmented_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ pub struct SegmentedVideoEncoder {
pending_fallback: Option<EncoderFallback>,
unrecovered_codec_failure: Option<(String, ffmpeg::Error)>,
flush_failure: Option<EncoderFlushFailure>,
#[cfg(windows)]
d3d11_status: String,
}

struct SegmentMux {
Expand Down Expand Up @@ -334,6 +336,8 @@ pub struct SegmentedVideoEncoderConfig {
/// [`SegmentedVideoEncoder::queue_hw_pixel_buffer`]) before falling back
/// to the software-frame path. Ignored on other platforms.
pub prefer_videotoolbox_hw_input: bool,
/// Address of an `ID3D11Device` that must outlive the encoder. Windows only.
pub d3d11_device: Option<usize>,
}

impl Default for SegmentedVideoEncoderConfig {
Expand All @@ -344,10 +348,19 @@ impl Default for SegmentedVideoEncoderConfig {
bpp: H264EncoderBuilder::QUALITY_BPP,
output_size: None,
prefer_videotoolbox_hw_input: false,
d3d11_device: None,
}
}
}

#[cfg(windows)]
fn flush_video_encoder(
encoder: &mut H264Encoder,
mux: &mut MuxSink<SegmentMux>,
) -> Result<(), ffmpeg::Error> {
encoder.flush_to(mux)
}

impl SegmentedVideoEncoder {
pub fn init(
base_path: PathBuf,
Expand Down Expand Up @@ -462,7 +475,27 @@ impl SegmentedVideoEncoder {
} else {
None
};
#[cfg(not(target_os = "macos"))]
#[cfg(target_os = "windows")]
let (hw_attempt, d3d11_status) = match config.d3d11_device {
Some(device) => {
let device = device as *mut std::ffi::c_void;
match unsafe { builder.clone().build_d3d11_hw_input(&mut output, device) } {
Ok(encoder) => {
let status = encoder.d3d11_sw_format_name().unwrap_or("nv12").to_string();
(Some(encoder), status)
}
Err(error) => {
tracing::info!(
%error,
"D3D11 texture input unavailable, using the CPU frame path"
);
(None, error.to_string())
}
}
}
None => (None, String::new()),
};
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
let hw_attempt: Option<H264Encoder> = None;

let encoder = match hw_attempt {
Expand Down Expand Up @@ -527,6 +560,8 @@ impl SegmentedVideoEncoder {
pending_fallback: None,
unrecovered_codec_failure: None,
flush_failure: None,
#[cfg(windows)]
d3d11_status,
};

if write_behind {
Expand Down Expand Up @@ -583,6 +618,64 @@ impl SegmentedVideoEncoder {
self.queue_frame(frame, timestamp)
}

#[cfg(windows)]
pub fn is_d3d11_hw_input(&self) -> bool {
self.encoder.is_d3d11_hw_input()
}

#[cfg(windows)]
pub fn d3d11_status(&self) -> &str {
&self.d3d11_status
}

pub fn codec_name(&self) -> String {
self.encoder.codec_name()
}

#[cfg(windows)]
pub fn abandon_d3d11_input(&mut self) -> bool {
if !self.encoder.is_d3d11_hw_input() {
return false;
}
let encoder_name = self.encoder.codec_name();
if let Err(error) = flush_video_encoder(&mut self.encoder, &mut self.mux) {
tracing::error!(
encoder = %encoder_name,
%error,
"D3D11 texture input stopped before its queued frames could be written; those frames are lost"
);
}
match self.encoder.replace_with_software() {
Ok(()) => {
tracing::warn!(
encoder = %encoder_name,
"D3D11 texture input stopped; later frames use the CPU path"
);
true
Comment on lines +648 to +654

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Fallback loses queued frames

abandon_d3d11_input drops the hardware encoder without first draining it. This also happens when texture conversion becomes unavailable, not just when the encoder fails. Valid frames still queued in a working encoder are then discarded.

Try flushing those packets into self.mux before replacing the encoder. If flushing fails, report the lost frames.

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/enc-ffmpeg/src/mux/segmented_stream.rs
Line: 632-635

Comment:
**Fallback loses queued frames**

`abandon_d3d11_input` drops the hardware encoder without first draining it. This also happens when texture conversion becomes unavailable, not just when the encoder fails. Valid frames still queued in a working encoder are then discarded.

Try flushing those packets into `self.mux` before replacing the encoder. If flushing fails, report the lost frames.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 84c28a4b9: abandon_d3d11_input now drains queued packets from the hardware encoder into the mux before falling back to libx264 (logging any flush error with the encoder name and continuing the CPU fallback).

}
Err(error) => {
tracing::error!(%error, "Could not leave the D3D11 texture path");
false
}
}
}

/// # Safety
/// `texture` must be an NV12 texture on the device passed at init, at the
/// encoder's width and height. `lifetime.free` runs once when the queued
/// frame is dropped.
#[cfg(windows)]
pub unsafe fn queue_d3d11_texture(
&mut self,
texture: *mut std::ffi::c_void,
timestamp: Duration,
lifetime: Option<crate::D3d11TextureLifetime>,
) -> Result<(), QueueFrameError> {
let frame = unsafe { self.encoder.wrap_d3d11_texture(texture, lifetime) }
.map_err(InitError::Encoder)?;
self.queue_frame(frame, timestamp)
}

pub fn queue_frame(
&mut self,
frame: frame::Video,
Expand Down
111 changes: 111 additions & 0 deletions crates/enc-ffmpeg/src/video/d3d11_format.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
//! Which D3D11 `sw_format` FFmpeg 7.1 will actually encode.
//!
//! `hwcontext_d3d11va.c` `supported_formats` accepts NV12 and BGRA and rejects
//! RGBA (`Unsupported pixel format`). `amfenc.c` `format_map` accepts NV12 and
//! has `BGR0`, not `BGRA`, so a BGRA frames context fails with
//! `Format of input frames context (bgra) is not supported by AMF`.
//! `ff_nvenc_pix_fmts` includes `AV_PIX_FMT_D3D11` and maps NV12 through.
//! `qsvenc_h264.c` lists only NV12 and QSV, so QSV is a derived `AV_PIX_FMT_QSV`
//! context on those same NV12 frames. `mfenc.c` lists NV12 and YUV420P and is
//! not a D3D11 texture input.

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum D3d11SwFormat {
Nv12,
}

impl D3d11SwFormat {
pub fn name(self) -> &'static str {
match self {
Self::Nv12 => "nv12",
}
}
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum D3d11TexturePath {
D3d11Nv12,
QsvFromD3d11Nv12,
}

pub fn d3d11_texture_path(encoder: &str) -> Option<D3d11TexturePath> {
match encoder {
"h264_amf" | "hevc_amf" | "av1_amf" | "h264_nvenc" | "hevc_nvenc" | "av1_nvenc" => {
Some(D3d11TexturePath::D3d11Nv12)
}
"h264_qsv" | "hevc_qsv" | "av1_qsv" => Some(D3d11TexturePath::QsvFromD3d11Nv12),
_ => None,
}
}

pub fn d3d11_sw_format(encoder: &str) -> Option<D3d11SwFormat> {
d3d11_texture_path(encoder).map(|_| D3d11SwFormat::Nv12)
}

pub fn shared_d3d11_sw_format(encoders: &[&str]) -> Option<D3d11SwFormat> {
let mut chosen = None;
for encoder in encoders {
let format = d3d11_sw_format(encoder)?;
match chosen {
None => chosen = Some(format),
Some(existing) if existing == format => {}
Some(_) => return None,
}
}
chosen
}

pub fn capture_texel_feeds_nv12(format_name: &str) -> bool {
matches!(format_name, "rgba" | "bgra" | "nv12")
}

pub const H264_TEXTURE_ENCODERS: &[&str] = &["h264_amf", "h264_nvenc", "h264_qsv"];

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn amf_and_nvenc_share_nv12_and_reject_rgba_and_bgra() {
assert_eq!(D3d11SwFormat::Nv12.name(), "nv12");
assert_eq!(d3d11_sw_format("h264_amf"), Some(D3d11SwFormat::Nv12));
assert_eq!(d3d11_sw_format("hevc_amf"), Some(D3d11SwFormat::Nv12));
assert_eq!(d3d11_sw_format("av1_amf"), Some(D3d11SwFormat::Nv12));
assert_eq!(
d3d11_texture_path("h264_nvenc"),
Some(D3d11TexturePath::D3d11Nv12)
);
assert_eq!(
d3d11_texture_path("hevc_nvenc"),
Some(D3d11TexturePath::D3d11Nv12)
);
assert_eq!(d3d11_sw_format("rgba"), None);
assert_eq!(d3d11_sw_format("bgra"), None);
assert_eq!(
shared_d3d11_sw_format(H264_TEXTURE_ENCODERS),
Some(D3d11SwFormat::Nv12)
);
}

#[test]
fn qsv_derives_from_nv12_and_mf_and_libx264_stay_off_the_texture_path() {
assert_eq!(
d3d11_texture_path("h264_qsv"),
Some(D3d11TexturePath::QsvFromD3d11Nv12)
);
assert_eq!(d3d11_sw_format("hevc_qsv"), Some(D3d11SwFormat::Nv12));
assert_eq!(d3d11_texture_path("h264_mf"), None);
assert_eq!(d3d11_texture_path("hevc_mf"), None);
assert_eq!(d3d11_texture_path("libx264"), None);
assert_eq!(shared_d3d11_sw_format(&["h264_amf", "libx264"]), None);
}

#[test]
fn rgba_and_bgra_capture_convert_to_nv12() {
assert!(capture_texel_feeds_nv12("rgba"));
assert!(capture_texel_feeds_nv12("bgra"));
assert!(capture_texel_feeds_nv12("nv12"));
assert!(!capture_texel_feeds_nv12("rgba64"));
assert!(!capture_texel_feeds_nv12("other"));
}
}
Loading
Loading