Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve H264 encoder selection and error handling

Richie McIlroyf0be72f7ba12
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index b565856ee..d8dec93d6 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -58,7 +58,21 @@
"Bash(cargo test:*)",
"Bash(/opt/homebrew/bin/ffmpeg:*)",
"Bash(RUST_LOG=info cargo run:*)",
- "Bash(RUST_LOG=warn cargo run:*)"
+ "Bash(RUST_LOG=warn cargo run:*)",
+ "Bash(CAP_MUXER_BUFFER_SIZE=240 RUST_LOG=info cargo run:*)",
+ "Bash(CAP_MUXER_BUFFER_SIZE=480 RUST_LOG=debug cargo run:*)",
+ "Bash(CAP_MUXER_BUFFER_SIZE=480 RUST_LOG=info cargo run:*)",
+ "Bash(RUST_LOG=debug cargo run:*)",
+ "Bash(RUST_LOG=info ./target/release/examples/synthetic-test-runner:*)",
+ "Bash(CAP_MUXER_BUFFER_SIZE=960 RUST_LOG=info cargo run:*)",
+ "Bash(CAP_MUXER_BUFFER_SIZE=1200 RUST_LOG=warn ./target/release/examples/synthetic-test-runner:*)",
+ "Bash(./target/release/examples/synthetic-test-runner:*)",
+ "Bash(CAP_VIDEO_SOURCE_BUFFER_SIZE=2400 CAP_MUXER_BUFFER_SIZE=2400 RUST_LOG=warn ./target/release/examples/synthetic-test-runner:*)",
+ "Bash(CAP_VIDEO_SOURCE_BUFFER_SIZE=2400 CAP_MUXER_BUFFER_SIZE=2400 RUST_LOG=info cargo run:*)",
+ "Bash(sysctl:*)",
+ "Bash(CAP_VIDEO_SOURCE_BUFFER_SIZE=4800 CAP_MUXER_BUFFER_SIZE=4800 RUST_LOG=warn cargo run:*)",
+ "Bash(RUST_LOG=cap_enc_ffmpeg::video::h264=debug cargo run:*)",
+ "Bash(CAP_VIDEO_SOURCE_BUFFER_SIZE=5400 CAP_MUXER_BUFFER_SIZE=5400 RUST_LOG=info cargo run:*)"
],
"deny": [],
"ask": []
diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs
index 6629f67d3..31a096390 100644
--- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs
+++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs
@@ -10,7 +10,9 @@ use std::{
};
use sysinfo::Disks;
-use crate::video::h264::{H264Encoder, H264EncoderBuilder, H264EncoderError, H264Preset};
+use crate::video::h264::{
+ DEFAULT_KEYFRAME_INTERVAL_SECS, H264Encoder, H264EncoderBuilder, H264EncoderError, H264Preset,
+};
const INIT_SEGMENT_NAME: &str = "init.mp4";
const DISK_SPACE_WARNING_THRESHOLD_MB: u64 = 500;
@@ -142,7 +144,7 @@ pub enum QueueFrameError {
FFmpeg(#[from] ffmpeg::Error),
#[error("Init: {0}")]
Init(#[from] InitError),
- #[error("Encode: {0}")]
+ #[error(transparent)]
Encode(#[from] crate::video::h264::QueueFrameError),
#[error("Init segment validation failed: {0}")]
InitSegmentInvalid(String),
@@ -164,7 +166,7 @@ pub struct SegmentedVideoEncoderConfig {
impl Default for SegmentedVideoEncoderConfig {
fn default() -> Self {
Self {
- segment_duration: Duration::from_secs(3),
+ segment_duration: Duration::from_secs(DEFAULT_KEYFRAME_INTERVAL_SECS as u64),
preset: H264Preset::Ultrafast,
bpp: H264EncoderBuilder::QUALITY_BPP,
output_size: None,
diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs
index 47cef1adc..aba2f45f8 100644
--- a/crates/enc-ffmpeg/src/video/h264.rs
+++ b/crates/enc-ffmpeg/src/video/h264.rs
@@ -28,11 +28,12 @@ pub struct H264EncoderBuilder {
external_conversion: bool,
}
-#[derive(Clone, Copy)]
+#[derive(Clone, Copy, Debug, PartialEq)]
pub enum H264Preset {
Slow,
Medium,
Ultrafast,
+ HighThroughput,
}
#[derive(thiserror::Error, Debug)]
@@ -125,18 +126,37 @@ impl H264EncoderBuilder {
codec_name.as_str(),
"h264_videotoolbox" | "h264_nvenc" | "h264_qsv" | "h264_amf" | "h264_mf"
);
+ let fps =
+ input_config.frame_rate.0 as f32 / input_config.frame_rate.1.max(1) as f32;
if is_hardware {
debug!(
encoder = %codec_name,
+ width = input_config.width,
+ height = input_config.height,
+ fps = fps,
"Selected hardware H264 encoder"
);
} else {
- warn!(
- encoder = %codec_name,
- input_width = input_config.width,
- input_height = input_config.height,
- "WARNING: Using SOFTWARE H264 encoder (high CPU usage expected)"
- );
+ let is_high_throughput =
+ requires_software_encoder(&input_config, self.preset);
+ if is_high_throughput {
+ warn!(
+ encoder = %codec_name,
+ width = input_config.width,
+ height = input_config.height,
+ fps = fps,
+ preset = ?self.preset,
+ "Using SOFTWARE encoder for high throughput (hardware cannot keep up at this resolution/fps)"
+ );
+ } else {
+ warn!(
+ encoder = %codec_name,
+ width = input_config.width,
+ height = input_config.height,
+ fps = fps,
+ "Using SOFTWARE H264 encoder (high CPU usage expected)"
+ );
+ }
}
return Ok(encoder);
}
@@ -292,7 +312,6 @@ impl H264EncoderBuilder {
);
encoder.set_bit_rate(bitrate);
- encoder.set_max_bit_rate(bitrate);
let encoder = encoder.open_with(encoder_options)?;
@@ -302,6 +321,16 @@ impl H264EncoderBuilder {
output_stream.set_rate(input_config.frame_rate);
output_stream.set_parameters(&encoder);
+ let converted_frame_pool = if converter.is_some() {
+ Some(frame::Video::new(
+ output_format,
+ output_width,
+ output_height,
+ ))
+ } else {
+ None
+ };
+
Ok(H264Encoder {
base: EncoderBase::new(stream_index),
encoder,
@@ -312,6 +341,7 @@ impl H264EncoderBuilder {
input_format: input_config.pixel_format,
input_width: input_config.width,
input_height: input_config.height,
+ converted_frame_pool,
})
}
}
@@ -326,6 +356,7 @@ pub struct H264Encoder {
input_format: format::Pixel,
input_width: u32,
input_height: u32,
+ converted_frame_pool: Option<frame::Video>,
}
pub struct ConversionRequirements {
@@ -377,19 +408,20 @@ impl H264Encoder {
self.base
.update_pts(&mut frame, timestamp, &mut self.encoder);
- if let Some(converter) = &mut self.converter {
+ let frame_to_send = 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);
+ let converted = self.converted_frame_pool.as_mut().unwrap();
converter
- .run(&frame, &mut converted)
+ .run(&frame, converted)
.map_err(QueueFrameError::Converter)?;
converted.set_pts(pts);
- frame = converted;
- }
+ converted as &frame::Video
+ } else {
+ &frame
+ };
self.base
- .send_frame(&frame, output, &mut self.encoder)
+ .send_frame(frame_to_send, output, &mut self.encoder)
.map_err(QueueFrameError::Encode)?;
Ok(())
@@ -456,7 +488,97 @@ impl H264Encoder {
}
}
-fn get_encoder_priority() -> &'static [&'static str] {
+const VIDEOTOOLBOX_4K_MAX_FPS: f64 = 55.0;
+const VIDEOTOOLBOX_1080P_MAX_FPS: f64 = 190.0;
+const NVENC_4K_MAX_FPS: f64 = 120.0;
+const NVENC_1080P_MAX_FPS: f64 = 500.0;
+const QSV_4K_MAX_FPS: f64 = 90.0;
+const QSV_1080P_MAX_FPS: f64 = 300.0;
+const AMF_4K_MAX_FPS: f64 = 100.0;
+const AMF_1080P_MAX_FPS: f64 = 350.0;
+
+const PIXELS_4K: f64 = 3840.0 * 2160.0;
+const PIXELS_1080P: f64 = 1920.0 * 1080.0;
+
+fn estimate_hw_encoder_max_fps(encoder_name: &str, width: u32, height: u32) -> f64 {
+ let pixels = (width as f64) * (height as f64);
+
+ let (max_fps_4k, max_fps_1080p) = match encoder_name {
+ "h264_videotoolbox" => (VIDEOTOOLBOX_4K_MAX_FPS, VIDEOTOOLBOX_1080P_MAX_FPS),
+ "h264_nvenc" => (NVENC_4K_MAX_FPS, NVENC_1080P_MAX_FPS),
+ "h264_qsv" => (QSV_4K_MAX_FPS, QSV_1080P_MAX_FPS),
+ "h264_amf" | "h264_mf" => (AMF_4K_MAX_FPS, AMF_1080P_MAX_FPS),
+ _ => return f64::MAX,
+ };
+
+ if pixels >= PIXELS_4K {
+ max_fps_4k
+ } else if pixels <= PIXELS_1080P {
+ max_fps_1080p
+ } else {
+ let ratio = (pixels - PIXELS_1080P) / (PIXELS_4K - PIXELS_1080P);
+ max_fps_1080p + (max_fps_4k - max_fps_1080p) * ratio
+ }
+}
+
+fn requires_software_encoder(config: &VideoInfo, preset: H264Preset) -> bool {
+ if preset == H264Preset::HighThroughput {
+ return true;
+ }
+
+ let fps = config.frame_rate.numerator() as f64 / config.frame_rate.denominator().max(1) as f64;
+
+ #[cfg(target_os = "macos")]
+ {
+ let max_hw_fps =
+ estimate_hw_encoder_max_fps("h264_videotoolbox", config.width, config.height);
+ let headroom_factor = 0.9;
+ if fps > max_hw_fps * headroom_factor {
+ debug!(
+ width = config.width,
+ height = config.height,
+ target_fps = fps,
+ hw_max_fps = max_hw_fps,
+ "Target FPS exceeds VideoToolbox capability, using software encoder"
+ );
+ return true;
+ }
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ use cap_frame_converter::{GpuVendor, detect_primary_gpu};
+
+ let encoder_name = match detect_primary_gpu().map(|info| info.vendor) {
+ Some(GpuVendor::Nvidia) => "h264_nvenc",
+ Some(GpuVendor::Amd) => "h264_amf",
+ Some(GpuVendor::Intel) => "h264_qsv",
+ _ => "h264_nvenc",
+ };
+
+ let max_hw_fps = estimate_hw_encoder_max_fps(encoder_name, config.width, config.height);
+ let headroom_factor = 0.9;
+ if fps > max_hw_fps * headroom_factor {
+ debug!(
+ width = config.width,
+ height = config.height,
+ target_fps = fps,
+ hw_max_fps = max_hw_fps,
+ encoder = encoder_name,
+ "Target FPS exceeds hardware encoder capability, using software encoder"
+ );
+ return true;
+ }
+ }
+
+ false
+}
+
+fn get_encoder_priority(config: &VideoInfo, preset: H264Preset) -> &'static [&'static str] {
+ if requires_software_encoder(config, preset) {
+ return &["libx264"];
+ }
+
#[cfg(target_os = "macos")]
{
&[
@@ -496,11 +618,13 @@ fn get_encoder_priority() -> &'static [&'static str] {
}
}
+pub const DEFAULT_KEYFRAME_INTERVAL_SECS: u32 = 3;
+
fn get_codec_and_options(
config: &VideoInfo,
preset: H264Preset,
) -> Vec<(Codec, Dictionary<'static>)> {
- let keyframe_interval_secs = 2;
+ let keyframe_interval_secs = DEFAULT_KEYFRAME_INTERVAL_SECS;
let denominator = config.frame_rate.denominator();
let frames_per_sec = config.frame_rate.numerator() as f64
/ if denominator == 0 { 1 } else { denominator } as f64;
@@ -509,7 +633,7 @@ fn get_codec_and_options(
.max(1.0) as i32;
let keyframe_interval_str = keyframe_interval.to_string();
- let encoder_priority = get_encoder_priority();
+ let encoder_priority = get_encoder_priority(config, preset);
let mut encoders = Vec::new();
@@ -524,6 +648,7 @@ fn get_codec_and_options(
"h264_videotoolbox" => {
options.set("realtime", "true");
options.set("prio_speed", "true");
+ options.set("profile", "baseline");
}
"h264_nvenc" => {
options.set("preset", "p4");
@@ -555,10 +680,10 @@ fn get_codec_and_options(
match preset {
H264Preset::Slow => "slow",
H264Preset::Medium => "medium",
- H264Preset::Ultrafast => "ultrafast",
+ H264Preset::Ultrafast | H264Preset::HighThroughput => "ultrafast",
},
);
- if let H264Preset::Ultrafast = preset {
+ if matches!(preset, H264Preset::Ultrafast | H264Preset::HighThroughput) {
options.set("tune", "zerolatency");
}
options.set("vsync", "1");
diff --git a/crates/recording/examples/synthetic-test-runner.rs b/crates/recording/examples/synthetic-test-runner.rs
index 1d8ca5267..99adeb18e 100644
--- a/crates/recording/examples/synthetic-test-runner.rs
+++ b/crates/recording/examples/synthetic-test-runner.rs
@@ -138,6 +138,12 @@ async fn main() {
let mut failed = 0;
let mut results = Vec::new();
+ if cli.output_dir.exists() {
+ if let Err(e) = std::fs::remove_dir_all(&cli.output_dir) {
+ tracing::warn!("Failed to clean output directory before tests: {}", e);
+ }
+ }
+
let start = Instant::now();
for (idx, config) in configs.iter().enumerate() {
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index 058db9940..e25fc4451 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -28,6 +28,14 @@ use tracing::*;
const CONSECUTIVE_ANOMALY_ERROR_THRESHOLD: u64 = 30;
const LARGE_BACKWARD_JUMP_SECS: f64 = 1.0;
const LARGE_FORWARD_JUMP_SECS: f64 = 5.0;
+const DEFAULT_VIDEO_SOURCE_CHANNEL_CAPACITY: usize = 128;
+
+fn get_video_source_channel_capacity() -> usize {
+ std::env::var("CAP_VIDEO_SOURCE_BUFFER_SIZE")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(DEFAULT_VIDEO_SOURCE_CHANNEL_CAPACITY)
+}
pub struct TimestampAnomalyTracker {
stream_name: &'static str,
@@ -647,7 +655,8 @@ async fn setup_video_source<TVideo: VideoSource>(
video_config: TVideo::Config,
setup_ctx: &mut SetupCtx,
) -> anyhow::Result<(TVideo, mpsc::Receiver<TVideo::Frame>)> {
- let (video_tx, video_rx) = mpsc::channel(128);
+ let capacity = get_video_source_channel_capacity();
+ let (video_tx, video_rx) = mpsc::channel(capacity);
let video_source = TVideo::setup(video_config, video_tx, setup_ctx).await?;
Ok((video_source, video_rx))
diff --git a/crates/recording/src/output_pipeline/ffmpeg.rs b/crates/recording/src/output_pipeline/ffmpeg.rs
index 7f6e9a4f6..b95f3b899 100644
--- a/crates/recording/src/output_pipeline/ffmpeg.rs
+++ b/crates/recording/src/output_pipeline/ffmpeg.rs
@@ -467,11 +467,28 @@ impl Muxer for SegmentedVideoMuxer {
trace!("Segmented encoder channel already closed during finish: {e}");
}
+ let mut encoder_thread_finished = false;
+
if let Some(handle) = state.encoder_handle.take() {
- let timeout = Duration::from_secs(5);
+ let fps =
+ self.video_config.frame_rate.0 as f32 / self.video_config.frame_rate.1 as f32;
+ let buffer_size = get_muxer_buffer_size();
+ let base_timeout_secs = 5u64;
+ let buffer_drain_time_secs = (buffer_size as f32 / fps.max(1.0)).ceil() as u64;
+ let total_timeout_secs = base_timeout_secs + buffer_drain_time_secs.min(30);
+ let timeout = Duration::from_secs(total_timeout_secs);
+
+ debug!(
+ fps = fps,
+ buffer_size = buffer_size,
+ timeout_secs = total_timeout_secs,
+ "Waiting for encoder thread to finish"
+ );
+
let start = std::time::Instant::now();
loop {
if handle.is_finished() {
+ encoder_thread_finished = true;
match handle.join() {
Err(panic_payload) => {
warn!(
@@ -488,19 +505,33 @@ impl Muxer for SegmentedVideoMuxer {
}
if start.elapsed() > timeout {
warn!(
- "Segmented encoder thread did not finish within {:?}, abandoning",
+ fps = fps,
+ buffer_size = buffer_size,
+ elapsed_secs = start.elapsed().as_secs(),
+ "Segmented encoder thread did not finish within {:?}, abandoning (encoder may be overwhelmed at this resolution/fps)",
timeout
);
break;
}
std::thread::sleep(Duration::from_millis(50));
}
+ } else {
+ encoder_thread_finished = true;
}
- if let Ok(mut encoder) = state.encoder.lock()
- && let Err(e) = encoder.finish_with_timestamp(timestamp)
- {
- warn!("Failed to finish segmented encoder: {e}");
+ if encoder_thread_finished {
+ if let Ok(mut encoder) = state.encoder.lock()
+ && let Err(e) = encoder.finish_with_timestamp(timestamp)
+ {
+ warn!("Failed to finish segmented encoder: {e}");
+ }
+ } else {
+ warn!("Skipping encoder finalization because encoder thread is still running");
+ if let Ok(mut encoder) = state.encoder.try_lock()
+ && let Err(e) = encoder.finish_with_timestamp(timestamp)
+ {
+ warn!("Failed to finish segmented encoder (non-blocking attempt): {e}");
+ }
}
}
@@ -542,6 +573,7 @@ impl SegmentedVideoMuxer {
}
let mut slow_encode_count = 0u32;
+ let mut encode_error_count = 0u32;
let mut total_frames = 0u64;
const SLOW_THRESHOLD_MS: u128 = 5;
@@ -551,7 +583,12 @@ impl SegmentedVideoMuxer {
if let Ok(mut encoder) = encoder_clone.lock()
&& let Err(e) = encoder.queue_frame(frame, timestamp)
{
- warn!("Failed to encode frame: {e}");
+ encode_error_count += 1;
+ if encode_error_count <= 3 {
+ warn!("Failed to encode frame: {e}");
+ } else if encode_error_count == 4 {
+ warn!("Suppressing further encode errors (too many failures)");
+ }
}
let encode_elapsed_ms = encode_start.elapsed().as_millis();
@@ -575,6 +612,7 @@ impl SegmentedVideoMuxer {
debug!(
total_frames = total_frames,
slow_encodes = slow_encode_count,
+ encode_errors = encode_error_count,
slow_encode_pct = format!(
"{:.1}%",
100.0 * slow_encode_count as f64 / total_frames as f64
@@ -583,6 +621,16 @@ impl SegmentedVideoMuxer {
);
}
+ if encode_error_count > 0 {
+ warn!(
+ encode_errors = encode_error_count,
+ total_frames = total_frames,
+ "Encoder finished with {} encode errors out of {} frames",
+ encode_error_count,
+ total_frames
+ );
+ }
+
Ok(())
})?;