Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add HEVC encoder support to FFmpeg and MediaFoundation

Richie McIlroyc0d7ba1a20b8
diff --git a/Cargo.lock b/Cargo.lock
index 48c6d25ef..10649ea5f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1328,6 +1328,7 @@ dependencies = [
name = "cap-enc-ffmpeg"
version = "0.1.0"
dependencies = [
+ "cap-frame-converter",
"cap-media-info",
"ffmpeg-next",
"serde",
diff --git a/crates/enc-ffmpeg/Cargo.toml b/crates/enc-ffmpeg/Cargo.toml
index cf0244afa..0c010bcee 100644
--- a/crates/enc-ffmpeg/Cargo.toml
+++ b/crates/enc-ffmpeg/Cargo.toml
@@ -13,5 +13,8 @@ thiserror.workspace = true
tracing.workspace = true
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+[target.'cfg(target_os = "windows")'.dependencies]
+cap-frame-converter = { path = "../frame-converter" }
+
[lints]
workspace = true
diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs
index 8f8614da4..fa440c6f9 100644
--- a/crates/enc-ffmpeg/src/video/h264.rs
+++ b/crates/enc-ffmpeg/src/video/h264.rs
@@ -382,6 +382,46 @@ impl H264Encoder {
}
}
+fn get_encoder_priority() -> &'static [&'static str] {
+ #[cfg(target_os = "macos")]
+ {
+ &[
+ "h264_videotoolbox",
+ "h264_qsv",
+ "h264_nvenc",
+ "h264_amf",
+ "h264_mf",
+ "libx264",
+ ]
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ use cap_frame_converter::{GpuVendor, detect_primary_gpu};
+
+ static ENCODER_PRIORITY_NVIDIA: &[&str] =
+ &["h264_nvenc", "h264_mf", "h264_qsv", "h264_amf", "libx264"];
+ static ENCODER_PRIORITY_AMD: &[&str] =
+ &["h264_amf", "h264_mf", "h264_nvenc", "h264_qsv", "libx264"];
+ static ENCODER_PRIORITY_INTEL: &[&str] =
+ &["h264_qsv", "h264_mf", "h264_nvenc", "h264_amf", "libx264"];
+ static ENCODER_PRIORITY_DEFAULT: &[&str] =
+ &["h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", "libx264"];
+
+ match detect_primary_gpu().map(|info| info.vendor) {
+ Some(GpuVendor::Nvidia) => ENCODER_PRIORITY_NVIDIA,
+ Some(GpuVendor::Amd) => ENCODER_PRIORITY_AMD,
+ Some(GpuVendor::Intel) => ENCODER_PRIORITY_INTEL,
+ _ => ENCODER_PRIORITY_DEFAULT,
+ }
+ }
+
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
+ {
+ &["libx264"]
+ }
+}
+
fn get_codec_and_options(
config: &VideoInfo,
preset: H264Preset,
@@ -395,18 +435,7 @@ fn get_codec_and_options(
.max(1.0) as i32;
let keyframe_interval_str = keyframe_interval.to_string();
- let encoder_priority: &[&str] = if cfg!(target_os = "macos") {
- &[
- "h264_videotoolbox",
- "h264_qsv",
- "h264_nvenc",
- "h264_amf",
- "h264_mf",
- "libx264",
- ]
- } else {
- &["h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", "libx264"]
- };
+ let encoder_priority = get_encoder_priority();
let mut encoders = Vec::new();
@@ -422,15 +451,21 @@ fn get_codec_and_options(
options.set("realtime", "true");
}
"h264_nvenc" => {
- options.set("preset", "fast");
+ options.set("preset", "p4");
+ options.set("tune", "ll");
+ options.set("rc", "vbr");
+ options.set("spatial-aq", "1");
+ options.set("temporal-aq", "1");
options.set("g", &keyframe_interval_str);
}
"h264_qsv" => {
- options.set("preset", "fast");
+ options.set("preset", "faster");
+ options.set("look_ahead", "1");
options.set("g", &keyframe_interval_str);
}
"h264_amf" => {
- options.set("quality", "speed");
+ options.set("quality", "balanced");
+ options.set("rc", "vbr_latency");
options.set("g", &keyframe_interval_str);
}
"h264_mf" => {
diff --git a/crates/enc-ffmpeg/src/video/hevc.rs b/crates/enc-ffmpeg/src/video/hevc.rs
new file mode 100644
index 000000000..f9548959b
--- /dev/null
+++ b/crates/enc-ffmpeg/src/video/hevc.rs
@@ -0,0 +1,507 @@
+use std::{thread, time::Duration};
+
+use cap_media_info::{Pixel, VideoInfo};
+use ffmpeg::{
+ Dictionary,
+ codec::{codec::Codec, context, encoder},
+ format::{self},
+ frame,
+ threading::Config,
+};
+use tracing::{debug, error, trace};
+
+use crate::base::EncoderBase;
+
+fn is_420(format: ffmpeg::format::Pixel) -> bool {
+ format
+ .descriptor()
+ .map(|desc| desc.log2_chroma_w() == 1 && desc.log2_chroma_h() == 1)
+ .unwrap_or(false)
+}
+
+pub struct HevcEncoderBuilder {
+ bpp: f32,
+ input_config: VideoInfo,
+ preset: HevcPreset,
+ output_size: Option<(u32, u32)>,
+ external_conversion: bool,
+}
+
+#[derive(Clone, Copy)]
+pub enum HevcPreset {
+ Slow,
+ Medium,
+ Ultrafast,
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum HevcEncoderError {
+ #[error("{0:?}")]
+ FFmpeg(#[from] ffmpeg::Error),
+ #[error("Codec not found")]
+ CodecNotFound,
+ #[error("Pixel format {0:?} not supported")]
+ PixFmtNotSupported(Pixel),
+ #[error("Invalid output dimensions {width}x{height}; expected non-zero even width and height")]
+ InvalidOutputDimensions { width: u32, height: u32 },
+}
+
+impl HevcEncoderBuilder {
+ pub const QUALITY_BPP: f32 = 0.2;
+
+ pub fn new(input_config: VideoInfo) -> Self {
+ Self {
+ input_config,
+ bpp: Self::QUALITY_BPP,
+ preset: HevcPreset::Ultrafast,
+ output_size: None,
+ external_conversion: false,
+ }
+ }
+
+ pub fn with_preset(mut self, preset: HevcPreset) -> Self {
+ self.preset = preset;
+ self
+ }
+
+ pub fn with_bpp(mut self, bpp: f32) -> Self {
+ self.bpp = bpp;
+ self
+ }
+
+ pub fn with_output_size(mut self, width: u32, height: u32) -> Result<Self, HevcEncoderError> {
+ if width == 0 || height == 0 {
+ return Err(HevcEncoderError::InvalidOutputDimensions { width, height });
+ }
+
+ self.output_size = Some((width, height));
+ Ok(self)
+ }
+
+ pub fn with_external_conversion(mut self) -> Self {
+ self.external_conversion = true;
+ self
+ }
+
+ pub fn build(
+ self,
+ output: &mut format::context::Output,
+ ) -> Result<HevcEncoder, HevcEncoderError> {
+ let input_config = self.input_config;
+ let (output_width, output_height) = self
+ .output_size
+ .unwrap_or((input_config.width, input_config.height));
+
+ if output_width == 0 || output_height == 0 {
+ return Err(HevcEncoderError::InvalidOutputDimensions {
+ width: output_width,
+ height: output_height,
+ });
+ }
+
+ let candidates = get_codec_and_options(&input_config, self.preset);
+ if candidates.is_empty() {
+ return Err(HevcEncoderError::CodecNotFound);
+ }
+
+ let mut last_error = None;
+
+ for (codec, encoder_options) in candidates {
+ let codec_name = codec.name().to_string();
+
+ match Self::build_with_codec(
+ codec,
+ encoder_options,
+ &input_config,
+ output,
+ output_width,
+ output_height,
+ self.bpp,
+ self.external_conversion,
+ ) {
+ Ok(encoder) => {
+ debug!("Using HEVC encoder {}", codec_name);
+ return Ok(encoder);
+ }
+ Err(err) => {
+ debug!("HEVC encoder {} init failed: {:?}", codec_name, err);
+ last_error = Some(err);
+ }
+ }
+ }
+
+ Err(last_error.unwrap_or(HevcEncoderError::CodecNotFound))
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn build_with_codec(
+ codec: Codec,
+ encoder_options: Dictionary<'static>,
+ input_config: &VideoInfo,
+ output: &mut format::context::Output,
+ output_width: u32,
+ output_height: u32,
+ bpp: f32,
+ external_conversion: bool,
+ ) -> Result<HevcEncoder, HevcEncoderError> {
+ let encoder_supports_input_format = codec
+ .video()
+ .ok()
+ .and_then(|codec_video| codec_video.formats())
+ .is_some_and(|mut formats| formats.any(|f| f == input_config.pixel_format));
+
+ let mut needs_pixel_conversion = false;
+
+ let output_format = if encoder_supports_input_format {
+ input_config.pixel_format
+ } else {
+ needs_pixel_conversion = true;
+ let format = ffmpeg::format::Pixel::NV12;
+ if !external_conversion {
+ debug!(
+ "Converting from {:?} to {:?} for HEVC encoding",
+ input_config.pixel_format, format
+ );
+ }
+ format
+ };
+
+ if is_420(output_format)
+ && (!output_width.is_multiple_of(2) || !output_height.is_multiple_of(2))
+ {
+ return Err(HevcEncoderError::InvalidOutputDimensions {
+ width: output_width,
+ height: output_height,
+ });
+ }
+
+ let needs_scaling =
+ output_width != input_config.width || output_height != input_config.height;
+
+ if needs_scaling && !external_conversion {
+ debug!(
+ "Scaling video frames for HEVC encoding from {}x{} to {}x{}",
+ input_config.width, input_config.height, output_width, output_height
+ );
+ }
+
+ let converter = if external_conversion {
+ debug!(
+ "External conversion enabled, skipping internal converter. Expected input: {:?} {}x{}",
+ output_format, output_width, output_height
+ );
+ None
+ } else if needs_pixel_conversion || needs_scaling {
+ let flags = if needs_scaling {
+ ffmpeg::software::scaling::flag::Flags::BICUBIC
+ } else {
+ ffmpeg::software::scaling::flag::Flags::FAST_BILINEAR
+ };
+
+ match ffmpeg::software::scaling::Context::get(
+ input_config.pixel_format,
+ input_config.width,
+ input_config.height,
+ output_format,
+ output_width,
+ output_height,
+ flags,
+ ) {
+ Ok(context) => Some(context),
+ Err(e) => {
+ if needs_pixel_conversion {
+ error!(
+ "Failed to create converter from {:?} to {:?}: {:?}",
+ input_config.pixel_format, output_format, e
+ );
+ return Err(HevcEncoderError::PixFmtNotSupported(
+ input_config.pixel_format,
+ ));
+ }
+
+ return Err(HevcEncoderError::FFmpeg(e));
+ }
+ }
+ } else {
+ None
+ };
+
+ let mut encoder_ctx = context::Context::new_with_codec(codec);
+
+ let thread_count = thread::available_parallelism()
+ .map(|v| v.get())
+ .unwrap_or(1);
+ encoder_ctx.set_threading(Config::count(thread_count));
+ let mut encoder = encoder_ctx.encoder().video()?;
+
+ encoder.set_width(output_width);
+ encoder.set_height(output_height);
+ encoder.set_format(output_format);
+ encoder.set_time_base(input_config.time_base);
+ encoder.set_frame_rate(Some(input_config.frame_rate));
+
+ let bitrate = get_bitrate(
+ output_width,
+ output_height,
+ input_config.frame_rate.0 as f32 / input_config.frame_rate.1 as f32,
+ bpp,
+ );
+
+ encoder.set_bit_rate(bitrate);
+ encoder.set_max_bit_rate(bitrate);
+
+ let encoder = encoder.open_with(encoder_options)?;
+
+ let mut output_stream = output.add_stream(codec)?;
+ let stream_index = output_stream.index();
+ output_stream.set_time_base((1, HevcEncoder::TIME_BASE));
+ output_stream.set_rate(input_config.frame_rate);
+ output_stream.set_parameters(&encoder);
+
+ Ok(HevcEncoder {
+ base: EncoderBase::new(stream_index),
+ encoder,
+ converter,
+ output_format,
+ output_width,
+ output_height,
+ input_format: input_config.pixel_format,
+ input_width: input_config.width,
+ input_height: input_config.height,
+ })
+ }
+}
+
+pub struct HevcEncoder {
+ base: EncoderBase,
+ encoder: encoder::Video,
+ converter: Option<ffmpeg::software::scaling::Context>,
+ output_format: format::Pixel,
+ output_width: u32,
+ output_height: u32,
+ input_format: format::Pixel,
+ input_width: u32,
+ input_height: u32,
+}
+
+pub struct ConversionRequirements {
+ pub input_format: format::Pixel,
+ pub input_width: u32,
+ pub input_height: u32,
+ pub output_format: format::Pixel,
+ pub output_width: u32,
+ pub output_height: u32,
+ pub needs_conversion: bool,
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum QueueFrameError {
+ #[error("Converter: {0}")]
+ Converter(ffmpeg::Error),
+ #[error("Encode: {0}")]
+ Encode(ffmpeg::Error),
+}
+
+impl HevcEncoder {
+ const TIME_BASE: i32 = 90000;
+
+ pub fn builder(input_config: VideoInfo) -> HevcEncoderBuilder {
+ HevcEncoderBuilder::new(input_config)
+ }
+
+ pub fn conversion_requirements(&self) -> ConversionRequirements {
+ let needs_conversion = self.input_format != self.output_format
+ || self.input_width != self.output_width
+ || self.input_height != self.output_height;
+ ConversionRequirements {
+ input_format: self.input_format,
+ input_width: self.input_width,
+ input_height: self.input_height,
+ output_format: self.output_format,
+ output_width: self.output_width,
+ output_height: self.output_height,
+ needs_conversion,
+ }
+ }
+
+ pub fn queue_frame(
+ &mut self,
+ mut frame: frame::Video,
+ timestamp: Duration,
+ output: &mut format::context::Output,
+ ) -> Result<(), QueueFrameError> {
+ self.base
+ .update_pts(&mut frame, timestamp, &mut self.encoder);
+
+ if let Some(converter) = &mut self.converter {
+ let pts = frame.pts();
+ let mut converted =
+ frame::Video::new(self.output_format, self.output_width, self.output_height);
+ converter
+ .run(&frame, &mut converted)
+ .map_err(QueueFrameError::Converter)?;
+ converted.set_pts(pts);
+ frame = converted;
+ }
+
+ self.base
+ .send_frame(&frame, output, &mut self.encoder)
+ .map_err(QueueFrameError::Encode)?;
+
+ Ok(())
+ }
+
+ pub fn queue_preconverted_frame(
+ &mut self,
+ mut frame: frame::Video,
+ timestamp: Duration,
+ output: &mut format::context::Output,
+ ) -> Result<(), QueueFrameError> {
+ trace!(
+ "Encoding pre-converted frame: format={:?}, size={}x{}, expected={:?} {}x{}",
+ frame.format(),
+ frame.width(),
+ frame.height(),
+ self.output_format,
+ self.output_width,
+ self.output_height
+ );
+
+ self.base
+ .update_pts(&mut frame, timestamp, &mut self.encoder);
+
+ self.base
+ .send_frame(&frame, output, &mut self.encoder)
+ .map_err(QueueFrameError::Encode)?;
+
+ Ok(())
+ }
+
+ pub fn flush(&mut self, output: &mut format::context::Output) -> Result<(), ffmpeg::Error> {
+ self.base.process_eof(output, &mut self.encoder)
+ }
+}
+
+fn get_encoder_priority() -> &'static [&'static str] {
+ #[cfg(target_os = "macos")]
+ {
+ &[
+ "hevc_videotoolbox",
+ "hevc_qsv",
+ "hevc_nvenc",
+ "hevc_amf",
+ "hevc_mf",
+ "libx265",
+ ]
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ use cap_frame_converter::{GpuVendor, detect_primary_gpu};
+
+ static ENCODER_PRIORITY_NVIDIA: &[&str] =
+ &["hevc_nvenc", "hevc_mf", "hevc_qsv", "hevc_amf", "libx265"];
+ static ENCODER_PRIORITY_AMD: &[&str] =
+ &["hevc_amf", "hevc_mf", "hevc_nvenc", "hevc_qsv", "libx265"];
+ static ENCODER_PRIORITY_INTEL: &[&str] =
+ &["hevc_qsv", "hevc_mf", "hevc_nvenc", "hevc_amf", "libx265"];
+ static ENCODER_PRIORITY_DEFAULT: &[&str] =
+ &["hevc_nvenc", "hevc_qsv", "hevc_amf", "hevc_mf", "libx265"];
+
+ match detect_primary_gpu().map(|info| info.vendor) {
+ Some(GpuVendor::Nvidia) => ENCODER_PRIORITY_NVIDIA,
+ Some(GpuVendor::Amd) => ENCODER_PRIORITY_AMD,
+ Some(GpuVendor::Intel) => ENCODER_PRIORITY_INTEL,
+ _ => ENCODER_PRIORITY_DEFAULT,
+ }
+ }
+
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
+ {
+ &["libx265"]
+ }
+}
+
+fn get_codec_and_options(
+ config: &VideoInfo,
+ preset: HevcPreset,
+) -> Vec<(Codec, Dictionary<'static>)> {
+ let keyframe_interval_secs = 2;
+ let denominator = config.frame_rate.denominator();
+ let frames_per_sec = config.frame_rate.numerator() as f64
+ / if denominator == 0 { 1 } else { denominator } as f64;
+ let keyframe_interval = (keyframe_interval_secs as f64 * frames_per_sec)
+ .round()
+ .max(1.0) as i32;
+ let keyframe_interval_str = keyframe_interval.to_string();
+
+ let encoder_priority = get_encoder_priority();
+
+ let mut encoders = Vec::new();
+
+ for encoder_name in encoder_priority {
+ let Some(codec) = encoder::find_by_name(encoder_name) else {
+ continue;
+ };
+
+ let mut options = Dictionary::new();
+
+ match *encoder_name {
+ "hevc_videotoolbox" => {
+ options.set("realtime", "true");
+ }
+ "hevc_nvenc" => {
+ options.set("preset", "p4");
+ options.set("tune", "ll");
+ options.set("rc", "vbr");
+ options.set("spatial-aq", "1");
+ options.set("temporal-aq", "1");
+ options.set("tier", "main");
+ options.set("g", &keyframe_interval_str);
+ }
+ "hevc_qsv" => {
+ options.set("preset", "faster");
+ options.set("look_ahead", "1");
+ options.set("g", &keyframe_interval_str);
+ }
+ "hevc_amf" => {
+ options.set("quality", "balanced");
+ options.set("rc", "vbr_latency");
+ options.set("g", &keyframe_interval_str);
+ }
+ "hevc_mf" => {
+ options.set("hw_encoding", "true");
+ options.set("scenario", "4");
+ options.set("quality", "1");
+ options.set("g", &keyframe_interval_str);
+ }
+ "libx265" => {
+ options.set(
+ "preset",
+ match preset {
+ HevcPreset::Slow => "slow",
+ HevcPreset::Medium => "medium",
+ HevcPreset::Ultrafast => "ultrafast",
+ },
+ );
+ if let HevcPreset::Ultrafast = preset {
+ options.set("tune", "zerolatency");
+ }
+ options.set("g", &keyframe_interval_str);
+ }
+ _ => {}
+ }
+
+ encoders.push((codec, options));
+ }
+
+ encoders
+}
+
+fn get_bitrate(width: u32, height: u32, frame_rate: f32, bpp: f32) -> usize {
+ let frame_rate_multiplier = ((frame_rate as f64 - 30.0).max(0.0) * 0.6) + 30.0;
+ let area = (width as f64) * (height as f64);
+ let pixels_per_second = area * frame_rate_multiplier;
+
+ (pixels_per_second * bpp as f64) as usize
+}
diff --git a/crates/enc-ffmpeg/src/video/mod.rs b/crates/enc-ffmpeg/src/video/mod.rs
index f61e79694..3429498fe 100644
--- a/crates/enc-ffmpeg/src/video/mod.rs
+++ b/crates/enc-ffmpeg/src/video/mod.rs
@@ -1 +1,2 @@
pub mod h264;
+pub mod hevc;
diff --git a/crates/enc-mediafoundation/src/video/h264.rs b/crates/enc-mediafoundation/src/video/h264.rs
index 4fae2c189..dd371989c 100644
--- a/crates/enc-mediafoundation/src/video/h264.rs
+++ b/crates/enc-mediafoundation/src/video/h264.rs
@@ -476,5 +476,6 @@ impl H264Encoder {
}
fn calculate_bitrate(width: u32, height: u32, fps: u32, multiplier: f32) -> u32 {
- ((width * height * ((fps - 30) / 2 + 30)) as f32 * multiplier) as u32
+ let frame_rate_factor = (fps as f32 - 30.0).max(0.0) / 2.0 + 30.0;
+ (width as f32 * height as f32 * frame_rate_factor * multiplier) as u32
}
diff --git a/crates/enc-mediafoundation/src/video/hevc.rs b/crates/enc-mediafoundation/src/video/hevc.rs
new file mode 100644
index 000000000..2b4a72ec0
--- /dev/null
+++ b/crates/enc-mediafoundation/src/video/hevc.rs
@@ -0,0 +1,450 @@
+use crate::{
+ media::{MFSetAttributeRatio, MFSetAttributeSize},
+ mft::EncoderDevice,
+ video::{NewVideoProcessorError, VideoProcessor},
+};
+use std::sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+};
+use windows::{
+ Foundation::TimeSpan,
+ Graphics::SizeInt32,
+ Win32::{
+ Foundation::E_NOTIMPL,
+ Graphics::{
+ Direct3D11::{ID3D11Device, ID3D11Texture2D},
+ Dxgi::Common::{DXGI_FORMAT, DXGI_FORMAT_NV12},
+ },
+ Media::MediaFoundation::{
+ self, IMFAttributes, IMFDXGIDeviceManager, IMFMediaEventGenerator, IMFMediaType,
+ IMFSample, IMFTransform, MF_E_INVALIDMEDIATYPE, MF_E_NO_MORE_TYPES,
+ MF_E_TRANSFORM_TYPE_NOT_SET, MF_EVENT_FLAG_NONE, MF_EVENT_TYPE,
+ MF_MT_ALL_SAMPLES_INDEPENDENT, MF_MT_AVG_BITRATE, MF_MT_FRAME_RATE, MF_MT_FRAME_SIZE,
+ MF_MT_INTERLACE_MODE, MF_MT_MAJOR_TYPE, MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SUBTYPE,
+ MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, MF_TRANSFORM_ASYNC_UNLOCK,
+ MFCreateDXGIDeviceManager, MFCreateDXGISurfaceBuffer, MFCreateMediaType,
+ MFCreateSample, MFMediaType_Video, MFT_ENUM_FLAG, MFT_ENUM_FLAG_HARDWARE,
+ MFT_ENUM_FLAG_TRANSCODE_ONLY, MFT_MESSAGE_COMMAND_FLUSH,
+ MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, MFT_MESSAGE_NOTIFY_END_OF_STREAM,
+ MFT_MESSAGE_NOTIFY_END_STREAMING, MFT_MESSAGE_NOTIFY_START_OF_STREAM,
+ MFT_MESSAGE_SET_D3D_MANAGER, MFT_OUTPUT_DATA_BUFFER, MFT_SET_TYPE_TEST_ONLY,
+ MFVideoFormat_HEVC, MFVideoFormat_NV12, MFVideoInterlace_Progressive,
+ },
+ },
+ core::{Error, Interface},
+};
+
+const MAX_CONSECUTIVE_EMPTY_SAMPLES: u8 = 20;
+
+pub struct HevcEncoder {
+ _d3d_device: ID3D11Device,
+ _media_device_manager: IMFDXGIDeviceManager,
+ _device_manager_reset_token: u32,
+
+ video_processor: VideoProcessor,
+
+ transform: IMFTransform,
+ event_generator: IMFMediaEventGenerator,
+ input_stream_id: u32,
+ output_stream_id: u32,
+ output_type: IMFMediaType,
+ bitrate: u32,
+}
+
+#[derive(Clone, Debug, thiserror::Error)]
+pub enum NewHevcEncoderError {
+ #[error("NoVideoEncoderDevice")]
+ NoVideoEncoderDevice,
+ #[error("EncoderTransform: {0}")]
+ EncoderTransform(windows::core::Error),
+ #[error("VideoProcessor: {0}")]
+ VideoProcessor(NewVideoProcessorError),
+ #[error("DeviceManager: {0}")]
+ DeviceManager(windows::core::Error),
+ #[error("EventGenerator: {0}")]
+ EventGenerator(windows::core::Error),
+ #[error("ConfigureStreams: {0}")]
+ ConfigureStreams(windows::core::Error),
+ #[error("OutputType: {0}")]
+ OutputType(windows::core::Error),
+ #[error("InputType: {0}")]
+ InputType(windows::core::Error),
+}
+
+unsafe impl Send for HevcEncoder {}
+
+impl HevcEncoder {
+ #[allow(clippy::too_many_arguments)]
+ fn new_with_scaled_output_with_flags(
+ d3d_device: &ID3D11Device,
+ format: DXGI_FORMAT,
+ input_resolution: SizeInt32,
+ output_resolution: SizeInt32,
+ frame_rate: u32,
+ bitrate_multipler: f32,
+ flags: MFT_ENUM_FLAG,
+ enable_hardware_transforms: bool,
+ ) -> Result<Self, NewHevcEncoderError> {
+ let bitrate = calculate_bitrate(
+ output_resolution.Width as u32,
+ output_resolution.Height as u32,
+ frame_rate,
+ bitrate_multipler,
+ );
+
+ let transform =
+ EncoderDevice::enumerate_with_flags(MFMediaType_Video, MFVideoFormat_HEVC, flags)
+ .map_err(|_| NewHevcEncoderError::NoVideoEncoderDevice)?
+ .first()
+ .cloned()
+ .ok_or(NewHevcEncoderError::NoVideoEncoderDevice)?
+ .create_transform()
+ .map_err(NewHevcEncoderError::EncoderTransform)?;
+
+ let video_processor = VideoProcessor::new(
+ d3d_device.clone(),
+ format,
+ input_resolution,
+ DXGI_FORMAT_NV12,
+ output_resolution,
+ frame_rate,
+ )
+ .map_err(NewHevcEncoderError::VideoProcessor)?;
+
+ let mut device_manager_reset_token: u32 = 0;
+ let media_device_manager = {
+ let mut media_device_manager = None;
+ unsafe {
+ MFCreateDXGIDeviceManager(
+ &mut device_manager_reset_token,
+ &mut media_device_manager,
+ )
+ .map_err(NewHevcEncoderError::DeviceManager)?
+ };
+ media_device_manager.expect("Device manager unexpectedly None")
+ };
+ unsafe {
+ media_device_manager
+ .ResetDevice(d3d_device, device_manager_reset_token)
+ .map_err(NewHevcEncoderError::DeviceManager)?
+ };
+
+ let event_generator: IMFMediaEventGenerator = transform
+ .cast()
+ .map_err(NewHevcEncoderError::EventGenerator)?;
+ let attributes = unsafe {
+ transform
+ .GetAttributes()
+ .map_err(NewHevcEncoderError::EventGenerator)?
+ };
+ unsafe {
+ attributes
+ .SetUINT32(&MF_TRANSFORM_ASYNC_UNLOCK, 1)
+ .map_err(NewHevcEncoderError::EventGenerator)?;
+ attributes
+ .SetUINT32(
+ &MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS,
+ enable_hardware_transforms as u32,
+ )
+ .map_err(NewHevcEncoderError::EventGenerator)?;
+ };
+
+ let mut number_of_input_streams = 0;
+ let mut number_of_output_streams = 0;
+ unsafe {
+ transform
+ .GetStreamCount(&mut number_of_input_streams, &mut number_of_output_streams)
+ .map_err(NewHevcEncoderError::EventGenerator)?
+ };
+ let (input_stream_ids, output_stream_ids) = {
+ let mut input_stream_ids = vec![0u32; number_of_input_streams as usize];
+ let mut output_stream_ids = vec![0u32; number_of_output_streams as usize];
+ let result =
+ unsafe { transform.GetStreamIDs(&mut input_stream_ids, &mut output_stream_ids) };
+ match result {
+ Ok(_) => {}
+ Err(error) => {
+ if error.code() == E_NOTIMPL {
+ for i in 0..number_of_input_streams {
+ input_stream_ids[i as usize] = i;
+ }
+ for i in 0..number_of_output_streams {
+ output_stream_ids[i as usize] = i;
+ }
+ } else {
+ return Err(NewHevcEncoderError::ConfigureStreams(error));
+ }
+ }
+ }
+ (input_stream_ids, output_stream_ids)
+ };
+ let input_stream_id = input_stream_ids[0];
+ let output_stream_id = output_stream_ids[0];
+
+ unsafe {
+ let temp = media_device_manager.clone();
+ transform
+ .ProcessMessage(
+ MFT_MESSAGE_SET_D3D_MANAGER,
+ std::mem::transmute::<IMFDXGIDeviceManager, usize>(temp),
+ )
+ .map_err(NewHevcEncoderError::EncoderTransform)?;
+ };
+
+ let output_type = (|| unsafe {
+ let output_type = MFCreateMediaType()?;
+ let attributes: IMFAttributes = output_type.cast()?;
+ output_type.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)?;
+ output_type.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_HEVC)?;
+ output_type.SetUINT32(&MF_MT_AVG_BITRATE, bitrate)?;
+ MFSetAttributeSize(
+ &attributes,
+ &MF_MT_FRAME_SIZE,
+ output_resolution.Width as u32,
+ output_resolution.Height as u32,
+ )?;
+ MFSetAttributeRatio(&attributes, &MF_MT_FRAME_RATE, frame_rate, 1)?;
+ MFSetAttributeRatio(&attributes, &MF_MT_PIXEL_ASPECT_RATIO, 1, 1)?;
+ output_type.SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)?;
+ output_type.SetUINT32(&MF_MT_ALL_SAMPLES_INDEPENDENT, 1)?;
+ transform.SetOutputType(output_stream_id, &output_type, 0)?;
+ Ok(output_type)
+ })()
+ .map_err(NewHevcEncoderError::OutputType)?;
+
+ let input_type: Option<IMFMediaType> = (|| unsafe {
+ let mut count = 0;
+ loop {
+ let result = transform.GetInputAvailableType(input_stream_id, count);
+ if let Err(error) = &result
+ && error.code() == MF_E_NO_MORE_TYPES
+ {
+ break Ok(None);
+ }
+
+ let input_type = result?;
+ let attributes: IMFAttributes = input_type.cast()?;
+ input_type.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)?;
+ input_type.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_NV12)?;
+ MFSetAttributeSize(
+ &attributes,
+ &MF_MT_FRAME_SIZE,
+ output_resolution.Width as u32,
+ output_resolution.Height as u32,
+ )?;
+ MFSetAttributeRatio(&attributes, &MF_MT_FRAME_RATE, frame_rate, 1)?;
+ let result = transform.SetInputType(
+ input_stream_id,
+ &input_type,
+ MFT_SET_TYPE_TEST_ONLY.0 as u32,
+ );
+ if let Err(error) = &result
+ && error.code() == MF_E_INVALIDMEDIATYPE
+ {
+ count += 1;
+ continue;
+ }
+ result?;
+ break Ok(Some(input_type));
+ }
+ })()
+ .map_err(NewHevcEncoderError::InputType)?;
+ if let Some(input_type) = input_type {
+ unsafe { transform.SetInputType(input_stream_id, &input_type, 0) }
+ .map_err(NewHevcEncoderError::InputType)?;
+ } else {
+ return Err(NewHevcEncoderError::InputType(Error::new(
+ MF_E_TRANSFORM_TYPE_NOT_SET,
+ "No suitable input type found! Try a different set of encoding settings.",
+ )));
+ }
+
+ Ok(Self {
+ _d3d_device: d3d_device.clone(),
+ _media_device_manager: media_device_manager,
+ _device_manager_reset_token: device_manager_reset_token,
+
+ video_processor,
+
+ transform,
+ event_generator,
+ input_stream_id,
+ output_stream_id,
+ bitrate,
+
+ output_type,
+ })
+ }
+
+ pub fn new_with_scaled_output(
+ d3d_device: &ID3D11Device,
+ format: DXGI_FORMAT,
+ input_resolution: SizeInt32,
+ output_resolution: SizeInt32,
+ frame_rate: u32,
+ bitrate_multipler: f32,
+ ) -> Result<Self, NewHevcEncoderError> {
+ Self::new_with_scaled_output_with_flags(
+ d3d_device,
+ format,
+ input_resolution,
+ output_resolution,
+ frame_rate,
+ bitrate_multipler,
+ MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_TRANSCODE_ONLY,
+ true,
+ )
+ }
+
+ pub fn new_with_scaled_output_software(
+ d3d_device: &ID3D11Device,
+ format: DXGI_FORMAT,
+ input_resolution: SizeInt32,
+ output_resolution: SizeInt32,
+ frame_rate: u32,
+ bitrate_multipler: f32,
+ ) -> Result<Self, NewHevcEncoderError> {
+ Self::new_with_scaled_output_with_flags(
+ d3d_device,
+ format,
+ input_resolution,
+ output_resolution,
+ frame_rate,
+ bitrate_multipler,
+ MFT_ENUM_FLAG_TRANSCODE_ONLY,
+ false,
+ )
+ }
+
+ pub fn new(
+ d3d_device: &ID3D11Device,
+ format: DXGI_FORMAT,
+ resolution: SizeInt32,
+ frame_rate: u32,
+ bitrate_multipler: f32,
+ ) -> Result<Self, NewHevcEncoderError> {
+ Self::new_with_scaled_output(
+ d3d_device,
+ format,
+ resolution,
+ resolution,
+ frame_rate,
+ bitrate_multipler,
+ )
+ }
+
+ pub fn new_software(
+ d3d_device: &ID3D11Device,
+ format: DXGI_FORMAT,
+ resolution: SizeInt32,
+ frame_rate: u32,
+ bitrate_multipler: f32,
+ ) -> Result<Self, NewHevcEncoderError> {
+ Self::new_with_scaled_output_software(
+ d3d_device,
+ format,
+ resolution,
+ resolution,
+ frame_rate,
+ bitrate_multipler,
+ )
+ }
+
+ pub fn bitrate(&self) -> u32 {
+ self.bitrate
+ }
+
+ pub fn output_type(&self) -> &IMFMediaType {
+ &self.output_type
+ }
+
+ pub fn run(
+ &mut self,
+ should_stop: Arc<AtomicBool>,
+ mut get_frame: impl FnMut() -> windows::core::Result<Option<(ID3D11Texture2D, TimeSpan)>>,
+ mut on_sample: impl FnMut(IMFSample) -> windows::core::Result<()>,
+ ) -> windows::core::Result<()> {
+ unsafe {
+ self.transform
+ .ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0)?;
+ self.transform
+ .ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)?;
+ self.transform
+ .ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0)?;
+
+ let mut consecutive_empty_samples = 0;
+ let mut should_exit = false;
+ while !should_exit {
+ let event = self.event_generator.GetEvent(MF_EVENT_FLAG_NONE)?;
+
+ let event_type = MF_EVENT_TYPE(event.GetType()? as i32);
+ match event_type {
+ MediaFoundation::METransformNeedInput => {
+ should_exit = true;
+ if !should_stop.load(Ordering::SeqCst)
+ && let Some((texture, timestamp)) = get_frame()?
+ {
+ self.video_processor.process_texture(&texture)?;
+ let input_buffer = {
+ MFCreateDXGISurfaceBuffer(
+ &ID3D11Texture2D::IID,
+ self.video_processor.output_texture(),
+ 0,
+ false,
+ )?
+ };
+ let mf_sample = MFCreateSample()?;
+ mf_sample.AddBuffer(&input_buffer)?;
+ mf_sample.SetSampleTime(timestamp.Duration)?;
+ self.transform
+ .ProcessInput(self.input_stream_id, &mf_sample, 0)?;
+ should_exit = false;
+ }
+ }
+ MediaFoundation::METransformHaveOutput => {
+ let mut status = 0;
+ let output_buffer = MFT_OUTPUT_DATA_BUFFER {
+ dwStreamID: self.output_stream_id,
+ ..Default::default()
+ };
+
+ let mut output_buffers = [output_buffer];
+ self.transform
+ .ProcessOutput(0, &mut output_buffers, &mut status)?;
+
+ if let Some(sample) = output_buffers[0].pSample.take() {
+ consecutive_empty_samples = 0;
+ on_sample(sample)?;
+ } else {
+ consecutive_empty_samples += 1;
+ if consecutive_empty_samples > MAX_CONSECUTIVE_EMPTY_SAMPLES {
+ return Err(windows::core::Error::new(
+ windows::core::HRESULT(0),
+ "Too many consecutive empty samples",
+ ));
+ }
+ }
+ }
+ _ => {
+ panic!("Unknown media event type: {}", event_type.0);
+ }
+ }
+ }
+
+ self.transform
+ .ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0)?;
+ self.transform
+ .ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0)?;
+ self.transform
+ .ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0)?;
+ }
+
+ Ok(())
+ }
+}
+
+fn calculate_bitrate(width: u32, height: u32, fps: u32, multiplier: f32) -> u32 {
+ let frame_rate_factor = (fps as f32 - 30.0).max(0.0) / 2.0 + 30.0;
+ (width as f32 * height as f32 * frame_rate_factor * multiplier * 0.6) as u32
+}
diff --git a/crates/enc-mediafoundation/src/video/mod.rs b/crates/enc-mediafoundation/src/video/mod.rs
index 273711713..b6376900b 100644
--- a/crates/enc-mediafoundation/src/video/mod.rs
+++ b/crates/enc-mediafoundation/src/video/mod.rs
@@ -1,5 +1,7 @@
mod h264;
+mod hevc;
mod video_processor;
pub use h264::*;
+pub use hevc::*;
pub use video_processor::*;
diff --git a/crates/frame-converter/Cargo.toml b/crates/frame-converter/Cargo.toml
index a69a81dbb..37cdc886c 100644
--- a/crates/frame-converter/Cargo.toml
+++ b/crates/frame-converter/Cargo.toml
@@ -24,6 +24,7 @@ windows = { workspace = true, features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D11",
+ "Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
"Win32_Media_MediaFoundation",
] }
diff --git a/crates/frame-converter/src/d3d11.rs b/crates/frame-converter/src/d3d11.rs
index 60eaaefd4..767756ca1 100644
--- a/crates/frame-converter/src/d3d11.rs
+++ b/crates/frame-converter/src/d3d11.rs
@@ -4,7 +4,10 @@ use parking_lot::Mutex;
use std::{
mem::ManuallyDrop,
ptr,
- sync::atomic::{AtomicBool, AtomicU64, Ordering},
+ sync::{
+ OnceLock,
+ atomic::{AtomicBool, AtomicU64, Ordering},
+ },
};
use windows::{
Win32::{
@@ -25,7 +28,7 @@ use windows::{
},
Dxgi::{
Common::{DXGI_FORMAT, DXGI_FORMAT_NV12, DXGI_FORMAT_YUY2},
- IDXGIAdapter, IDXGIDevice,
+ CreateDXGIFactory1, IDXGIAdapter, IDXGIDevice, IDXGIFactory1,
},
},
},
@@ -80,6 +83,53 @@ impl GpuInfo {
}
}
+static DETECTED_GPU: OnceLock<Option<GpuInfo>> = OnceLock::new();
+
+pub fn detect_primary_gpu() -> Option<&'static GpuInfo> {
+ DETECTED_GPU
+ .get_or_init(|| {
+ let result = detect_primary_gpu_inner();
+ if let Some(ref info) = result {
+ tracing::debug!(
+ "Detected primary GPU: {} (Vendor: {}, VendorID: 0x{:04X}, VRAM: {} MB)",
+ info.description,
+ info.vendor_name(),
+ info.vendor_id,
+ info.dedicated_video_memory / (1024 * 1024)
+ );
+ } else {
+ tracing::debug!("No GPU detected via DXGI, using default encoder order");
+ }
+ result
+ })
+ .as_ref()
+}
+
+fn detect_primary_gpu_inner() -> Option<GpuInfo> {
+ unsafe {
+ let factory: IDXGIFactory1 = CreateDXGIFactory1().ok()?;
+ let adapter: IDXGIAdapter = factory.EnumAdapters(0).ok()?;
+ let desc = adapter.GetDesc().ok()?;
+
+ let description = String::from_utf16_lossy(
+ &desc
+ .Description
+ .iter()
+ .take_while(|&&c| c != 0)
+ .copied()
+ .collect::<Vec<_>>(),
+ );
+
+ Some(GpuInfo {
+ vendor: GpuVendor::from_id(desc.VendorId),
+ vendor_id: desc.VendorId,
+ device_id: desc.DeviceId,
+ description,
+ dedicated_video_memory: desc.DedicatedVideoMemory as u64,
+ })
+ }
+}
+
struct D3D11Resources {
#[allow(dead_code)]
device: ID3D11Device,