Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(enc-ffmpeg): add packet-level h264 encoder for OOP muxer

Richie McIlroy100838d256a3
diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs
index eb66d53fc..ae8f1da80 100644
--- a/crates/enc-ffmpeg/src/video/h264.rs
+++ b/crates/enc-ffmpeg/src/video/h264.rs
@@ -12,6 +12,7 @@ use ffmpeg::{
use tracing::{debug, error, trace, warn};
use crate::base::EncoderBase;
+use crate::video::h264_packet::H264PacketEncoder;
fn is_420(format: ffmpeg::format::Pixel) -> bool {
format
@@ -20,6 +21,7 @@ fn is_420(format: ffmpeg::format::Pixel) -> bool {
.unwrap_or(false)
}
+#[derive(Clone)]
pub struct H264EncoderBuilder {
bpp: f32,
input_config: VideoInfo,
@@ -110,6 +112,11 @@ impl H264EncoderBuilder {
self
}
+ pub fn with_encoder_priority_override(mut self, codecs: &'static [&'static str]) -> Self {
+ self.encoder_priority_override = Some(codecs);
+ self
+ }
+
pub fn build(
self,
output: &mut format::context::Output,
@@ -220,173 +227,378 @@ impl H264EncoderBuilder {
external_conversion: bool,
crf: Option<u8>,
) -> Result<H264Encoder, H264EncoderError> {
- 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 OpenedVideoEncoder {
+ encoder,
+ converter,
+ converted_frame_pool,
+ output_format,
+ output_width,
+ output_height,
+ input_format,
+ input_width,
+ input_height,
+ } = open_video_encoder(
+ codec,
+ encoder_options,
+ input_config,
+ output_width,
+ output_height,
+ bpp,
+ external_conversion,
+ crf,
+ )?;
- let output_format = if encoder_supports_input_format {
- input_config.pixel_format
- } else {
- needs_pixel_conversion = true;
- ffmpeg::format::Pixel::NV12
- };
+ let mut output_stream = output.add_stream(codec)?;
+ let stream_index = output_stream.index();
+ output_stream.set_time_base((1, H264Encoder::TIME_BASE));
+ output_stream.set_rate(input_config.frame_rate);
+ output_stream.set_parameters(&encoder);
- debug!(
- encoder = %codec.name(),
- input_format = ?input_config.pixel_format,
- output_format = ?output_format,
- needs_pixel_conversion = needs_pixel_conversion,
- external_conversion = external_conversion,
- "Encoder pixel format configuration"
- );
+ Ok(H264Encoder {
+ base: EncoderBase::new(stream_index),
+ encoder,
+ converter,
+ output_format,
+ output_width,
+ output_height,
+ input_format,
+ input_width,
+ input_height,
+ converted_frame_pool,
+ })
+ }
- if is_420(output_format)
- && (!output_width.is_multiple_of(2) || !output_height.is_multiple_of(2))
- {
- return Err(H264EncoderError::InvalidOutputDimensions {
- width: output_width,
- height: output_height,
- });
- }
+ pub fn build_standalone(self) -> Result<H264PacketEncoder, H264EncoderError> {
+ let input_config = self.input_config;
+ let (raw_width, raw_height) = self
+ .output_size
+ .unwrap_or((input_config.width, input_config.height));
- let needs_scaling =
- output_width != input_config.width || output_height != input_config.height;
+ let output_width = ensure_even(raw_width);
+ let output_height = ensure_even(raw_height);
- if needs_scaling && !external_conversion {
- debug!(
- "Scaling video frames for H264 encoding from {}x{} to {}x{}",
- input_config.width, input_config.height, output_width, output_height
+ if raw_width != output_width || raw_height != output_height {
+ warn!(
+ raw_width,
+ raw_height,
+ output_width,
+ output_height,
+ "Auto-adjusted odd dimensions to even for H264 encoding (standalone)"
);
}
- let converter = if external_conversion {
- debug!(
- output_format = ?output_format,
- output_width = output_width,
- output_height = output_height,
- "External conversion enabled, skipping internal converter"
- );
- 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,
+ let candidates = get_codec_and_options(
+ &input_config,
+ self.preset,
+ self.encoder_priority_override,
+ self.is_export,
+ self.crf,
+ );
+ if candidates.is_empty() {
+ return Err(H264EncoderError::CodecNotFound);
+ }
+
+ let mut last_error = None;
+
+ for (codec, encoder_options) in candidates {
+ let codec_name = codec.name().to_string();
+ match Self::build_standalone_with_codec(
+ codec,
+ encoder_options,
+ &input_config,
output_width,
output_height,
- flags,
+ self.bpp,
+ self.external_conversion,
+ self.crf,
) {
- Ok(context) => {
+ Ok(encoder) => {
+ let fps =
+ input_config.frame_rate.0 as f32 / input_config.frame_rate.1.max(1) as f32;
debug!(
- encoder = %codec.name(),
- src_format = ?input_config.pixel_format,
- src_size = %format!("{}x{}", input_config.width, input_config.height),
- dst_format = ?output_format,
- dst_size = %format!("{}x{}", output_width, output_height),
- needs_scaling = needs_scaling,
- "Created SOFTWARE scaler for pixel format conversion (CPU-intensive)"
+ encoder = %codec_name,
+ width = input_config.width,
+ height = input_config.height,
+ fps = fps,
+ "Selected standalone H264 encoder"
);
- Some(context)
+ return Ok(encoder);
}
- Err(e) => {
- if needs_pixel_conversion {
- error!(
- "Failed to create converter from {:?} to {:?}: {:?}",
- input_config.pixel_format, output_format, e
- );
- return Err(H264EncoderError::PixFmtNotSupported(
- input_config.pixel_format,
- ));
- }
-
- return Err(H264EncoderError::FFmpeg(e));
+ Err(err) => {
+ debug!("Standalone encoder {} init failed: {:?}", codec_name, err);
+ last_error = Some(err);
}
}
- } else {
- debug!(
- encoder = %codec.name(),
- "No pixel format conversion needed (zero-copy path)"
- );
- 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));
- encoder.set_colorspace(color::Space::BT709);
- encoder.set_color_range(color::Range::MPEG);
- unsafe {
- (*encoder.as_mut_ptr()).color_primaries =
- ffmpeg::ffi::AVColorPrimaries::AVCOL_PRI_BT709;
- (*encoder.as_mut_ptr()).color_trc =
- ffmpeg::ffi::AVColorTransferCharacteristic::AVCOL_TRC_BT709;
}
- if crf.is_some() {
- encoder.set_bit_rate(0);
- } else {
- 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 * 3 / 2);
- }
+ Err(last_error.unwrap_or(H264EncoderError::CodecNotFound))
+ }
- let encoder = encoder.open_with(encoder_options)?;
+ #[allow(clippy::too_many_arguments)]
+ fn build_standalone_with_codec(
+ codec: Codec,
+ encoder_options: Dictionary<'static>,
+ input_config: &VideoInfo,
+ output_width: u32,
+ output_height: u32,
+ bpp: f32,
+ external_conversion: bool,
+ crf: Option<u8>,
+ ) -> Result<H264PacketEncoder, H264EncoderError> {
+ let opened = open_video_encoder_with_flags(
+ codec,
+ encoder_options,
+ input_config,
+ output_width,
+ output_height,
+ bpp,
+ external_conversion,
+ crf,
+ true,
+ )?;
+ let codec_name = codec.name().to_string();
+ Ok(H264PacketEncoder::from_opened(
+ opened,
+ codec_name,
+ input_config.time_base,
+ input_config.frame_rate,
+ ))
+ }
+}
- let mut output_stream = output.add_stream(codec)?;
- let stream_index = output_stream.index();
- output_stream.set_time_base((1, H264Encoder::TIME_BASE));
- output_stream.set_rate(input_config.frame_rate);
- output_stream.set_parameters(&encoder);
+pub(crate) struct OpenedVideoEncoder {
+ pub encoder: encoder::Video,
+ pub converter: Option<ffmpeg::software::scaling::Context>,
+ pub converted_frame_pool: Option<frame::Video>,
+ pub output_format: format::Pixel,
+ pub output_width: u32,
+ pub output_height: u32,
+ pub input_format: format::Pixel,
+ pub input_width: u32,
+ pub input_height: u32,
+}
- let converted_frame_pool = if converter.is_some() {
- Some(frame::Video::new(
- output_format,
- output_width,
- output_height,
- ))
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn open_video_encoder(
+ codec: Codec,
+ encoder_options: Dictionary<'static>,
+ input_config: &VideoInfo,
+ output_width: u32,
+ output_height: u32,
+ bpp: f32,
+ external_conversion: bool,
+ crf: Option<u8>,
+) -> Result<OpenedVideoEncoder, H264EncoderError> {
+ open_video_encoder_inner(
+ codec,
+ encoder_options,
+ input_config,
+ output_width,
+ output_height,
+ bpp,
+ external_conversion,
+ crf,
+ false,
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn open_video_encoder_with_flags(
+ codec: Codec,
+ encoder_options: Dictionary<'static>,
+ input_config: &VideoInfo,
+ output_width: u32,
+ output_height: u32,
+ bpp: f32,
+ external_conversion: bool,
+ crf: Option<u8>,
+ global_header: bool,
+) -> Result<OpenedVideoEncoder, H264EncoderError> {
+ open_video_encoder_inner(
+ codec,
+ encoder_options,
+ input_config,
+ output_width,
+ output_height,
+ bpp,
+ external_conversion,
+ crf,
+ global_header,
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+fn open_video_encoder_inner(
+ codec: Codec,
+ encoder_options: Dictionary<'static>,
+ input_config: &VideoInfo,
+ output_width: u32,
+ output_height: u32,
+ bpp: f32,
+ external_conversion: bool,
+ crf: Option<u8>,
+ global_header: bool,
+) -> Result<OpenedVideoEncoder, H264EncoderError> {
+ 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;
+ ffmpeg::format::Pixel::NV12
+ };
+
+ debug!(
+ encoder = %codec.name(),
+ input_format = ?input_config.pixel_format,
+ output_format = ?output_format,
+ needs_pixel_conversion = needs_pixel_conversion,
+ external_conversion = external_conversion,
+ "Encoder pixel format configuration"
+ );
+
+ if is_420(output_format)
+ && (!output_width.is_multiple_of(2) || !output_height.is_multiple_of(2))
+ {
+ return Err(H264EncoderError::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 H264 encoding from {}x{} to {}x{}",
+ input_config.width, input_config.height, output_width, output_height
+ );
+ }
+
+ let converter = if external_conversion {
+ debug!(
+ output_format = ?output_format,
+ output_width = output_width,
+ output_height = output_height,
+ "External conversion enabled, skipping internal converter"
+ );
+ None
+ } else if needs_pixel_conversion || needs_scaling {
+ let flags = if needs_scaling {
+ ffmpeg::software::scaling::flag::Flags::BICUBIC
} else {
- None
+ ffmpeg::software::scaling::flag::Flags::FAST_BILINEAR
};
- Ok(H264Encoder {
- base: EncoderBase::new(stream_index),
- encoder,
- converter,
+ match ffmpeg::software::scaling::Context::get(
+ input_config.pixel_format,
+ input_config.width,
+ input_config.height,
output_format,
output_width,
output_height,
- input_format: input_config.pixel_format,
- input_width: input_config.width,
- input_height: input_config.height,
- converted_frame_pool,
- })
+ flags,
+ ) {
+ Ok(context) => {
+ debug!(
+ encoder = %codec.name(),
+ src_format = ?input_config.pixel_format,
+ src_size = %format!("{}x{}", input_config.width, input_config.height),
+ dst_format = ?output_format,
+ dst_size = %format!("{}x{}", output_width, output_height),
+ needs_scaling = needs_scaling,
+ "Created SOFTWARE scaler for pixel format conversion (CPU-intensive)"
+ );
+ Some(context)
+ }
+ Err(e) => {
+ if needs_pixel_conversion {
+ error!(
+ "Failed to create converter from {:?} to {:?}: {:?}",
+ input_config.pixel_format, output_format, e
+ );
+ return Err(H264EncoderError::PixFmtNotSupported(
+ input_config.pixel_format,
+ ));
+ }
+
+ return Err(H264EncoderError::FFmpeg(e));
+ }
+ }
+ } else {
+ debug!(
+ encoder = %codec.name(),
+ "No pixel format conversion needed (zero-copy path)"
+ );
+ 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));
+ encoder.set_colorspace(color::Space::BT709);
+ encoder.set_color_range(color::Range::MPEG);
+ unsafe {
+ (*encoder.as_mut_ptr()).color_primaries = ffmpeg::ffi::AVColorPrimaries::AVCOL_PRI_BT709;
+ (*encoder.as_mut_ptr()).color_trc =
+ ffmpeg::ffi::AVColorTransferCharacteristic::AVCOL_TRC_BT709;
+ if global_header {
+ (*encoder.as_mut_ptr()).flags |= ffmpeg::ffi::AV_CODEC_FLAG_GLOBAL_HEADER as i32;
+ }
}
+
+ if crf.is_some() {
+ encoder.set_bit_rate(0);
+ } else {
+ 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 * 3 / 2);
+ }
+
+ let encoder = encoder.open_with(encoder_options)?;
+
+ let converted_frame_pool = if converter.is_some() {
+ Some(frame::Video::new(
+ output_format,
+ output_width,
+ output_height,
+ ))
+ } else {
+ None
+ };
+
+ Ok(OpenedVideoEncoder {
+ encoder,
+ converter,
+ converted_frame_pool,
+ output_format,
+ output_width,
+ output_height,
+ input_format: input_config.pixel_format,
+ input_width: input_config.width,
+ input_height: input_config.height,
+ })
}
pub struct H264Encoder {
@@ -685,7 +897,7 @@ fn export_encoder_priority_override(
None
}
-pub const DEFAULT_KEYFRAME_INTERVAL_SECS: u32 = 3;
+pub const DEFAULT_KEYFRAME_INTERVAL_SECS: u32 = 2;
fn get_codec_and_options(
config: &VideoInfo,
diff --git a/crates/enc-ffmpeg/src/video/h264_packet.rs b/crates/enc-ffmpeg/src/video/h264_packet.rs
new file mode 100644
index 000000000..3a802feae
--- /dev/null
+++ b/crates/enc-ffmpeg/src/video/h264_packet.rs
@@ -0,0 +1,338 @@
+use std::time::Duration;
+
+use ffmpeg::{
+ Packet, Rational,
+ codec::encoder,
+ format::{self},
+ frame,
+};
+
+use crate::video::h264::OpenedVideoEncoder;
+
+pub struct H264PacketEncoder {
+ encoder: encoder::Video,
+ converter: Option<ffmpeg::software::scaling::Context>,
+ converted_frame_pool: Option<frame::Video>,
+ output_format: format::Pixel,
+ output_width: u32,
+ output_height: u32,
+ input_format: format::Pixel,
+ input_width: u32,
+ input_height: u32,
+ packet: Packet,
+ first_pts: Option<i64>,
+ last_written_dts: Option<i64>,
+ encoder_time_base: Rational,
+ frame_rate: Rational,
+ codec_name: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct EncodedPacket {
+ pub pts: i64,
+ pub dts: i64,
+ pub duration: i64,
+ pub is_keyframe: bool,
+ pub data: Vec<u8>,
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum EncodePacketError {
+ #[error("Converter: {0}")]
+ Converter(ffmpeg::Error),
+ #[error("Encode: {0}")]
+ Encode(ffmpeg::Error),
+}
+
+impl H264PacketEncoder {
+ pub(crate) fn from_opened(
+ opened: OpenedVideoEncoder,
+ codec_name: String,
+ encoder_time_base: Rational,
+ frame_rate: Rational,
+ ) -> Self {
+ Self {
+ encoder: opened.encoder,
+ converter: opened.converter,
+ converted_frame_pool: opened.converted_frame_pool,
+ output_format: opened.output_format,
+ output_width: opened.output_width,
+ output_height: opened.output_height,
+ input_format: opened.input_format,
+ input_width: opened.input_width,
+ input_height: opened.input_height,
+ packet: Packet::empty(),
+ first_pts: None,
+ last_written_dts: None,
+ encoder_time_base,
+ frame_rate,
+ codec_name,
+ }
+ }
+
+ pub fn codec_name(&self) -> &str {
+ &self.codec_name
+ }
+
+ pub fn time_base(&self) -> Rational {
+ self.encoder_time_base
+ }
+
+ pub fn frame_rate(&self) -> Rational {
+ self.frame_rate
+ }
+
+ pub fn output_width(&self) -> u32 {
+ self.output_width
+ }
+
+ pub fn output_height(&self) -> u32 {
+ self.output_height
+ }
+
+ pub fn output_format(&self) -> format::Pixel {
+ self.output_format
+ }
+
+ pub fn input_format(&self) -> format::Pixel {
+ self.input_format
+ }
+
+ pub fn input_width(&self) -> u32 {
+ self.input_width
+ }
+
+ pub fn input_height(&self) -> u32 {
+ self.input_height
+ }
+
+ pub fn needs_conversion(&self) -> bool {
+ self.converter.is_some()
+ }
+
+ pub fn extradata(&self) -> Vec<u8> {
+ unsafe {
+ let ctx = self.encoder.as_ptr();
+ let size = (*ctx).extradata_size;
+ let ptr = (*ctx).extradata;
+ if ptr.is_null() || size <= 0 {
+ return Vec::new();
+ }
+ std::slice::from_raw_parts(ptr, size as usize).to_vec()
+ }
+ }
+
+ pub fn encode_frame<F>(
+ &mut self,
+ mut frame: frame::Video,
+ timestamp: Duration,
+ on_packet: F,
+ ) -> Result<(), EncodePacketError>
+ where
+ F: FnMut(EncodedPacket) -> Result<(), EncodePacketError>,
+ {
+ self.update_pts(&mut frame, timestamp);
+
+ let frame_to_send = if let Some(converter) = &mut self.converter {
+ let pts = frame.pts();
+ let converted = self.converted_frame_pool.as_mut().expect(
+ "converted_frame_pool present whenever converter is Some (invariant preserved by from_opened)",
+ );
+ converter
+ .run(&frame, converted)
+ .map_err(EncodePacketError::Converter)?;
+ converted.set_pts(pts);
+ converted as &frame::Video
+ } else {
+ &frame
+ };
+
+ self.encoder
+ .send_frame(frame_to_send)
+ .map_err(EncodePacketError::Encode)?;
+
+ self.drain_packets(on_packet)
+ }
+
+ pub fn encode_frame_reusable<F>(
+ &mut self,
+ frame: &mut frame::Video,
+ converted_frame: &mut Option<frame::Video>,
+ timestamp: Duration,
+ on_packet: F,
+ ) -> Result<(), EncodePacketError>
+ where
+ F: FnMut(EncodedPacket) -> Result<(), EncodePacketError>,
+ {
+ self.update_pts(frame, timestamp);
+
+ let frame_to_send = if let Some(converter) = &mut self.converter {
+ let pts = frame.pts();
+ let converted = converted_frame.get_or_insert_with(|| {
+ frame::Video::new(self.output_format, self.output_width, self.output_height)
+ });
+ converter
+ .run(frame, converted)
+ .map_err(EncodePacketError::Converter)?;
+ converted.set_pts(pts);
+ converted as &frame::Video
+ } else {
+ frame as &frame::Video
+ };
+
+ self.encoder
+ .send_frame(frame_to_send)
+ .map_err(EncodePacketError::Encode)?;
+
+ self.drain_packets(on_packet)
+ }
+
+ pub fn flush<F>(&mut self, on_packet: F) -> Result<(), EncodePacketError>
+ where
+ F: FnMut(EncodedPacket) -> Result<(), EncodePacketError>,
+ {
+ self.encoder.send_eof().map_err(EncodePacketError::Encode)?;
+ self.drain_packets(on_packet)
+ }
+
+ fn update_pts(&mut self, frame: &mut frame::Video, timestamp: Duration) {
+ if timestamp != Duration::MAX {
+ let tb = self.encoder.time_base();
+ let rate = tb.denominator() as f64 / tb.numerator() as f64;
+ let pts = (timestamp.as_secs_f64() * rate).round() as i64;
+ let first_pts = self.first_pts.get_or_insert(pts);
+ frame.set_pts(Some(pts - *first_pts));
+ } else if let Some(pts) = frame.pts() {
+ let first_pts = self.first_pts.get_or_insert(pts);
+ frame.set_pts(Some(pts - *first_pts));
+ } else {
+ tracing::error!("Frame has no pts");
+ }
+ }
+
+ fn drain_packets<F>(&mut self, mut on_packet: F) -> Result<(), EncodePacketError>
+ where
+ F: FnMut(EncodedPacket) -> Result<(), EncodePacketError>,
+ {
+ while self.encoder.receive_packet(&mut self.packet).is_ok() {
+ if let (Some(dts), Some(last_dts)) = (self.packet.dts(), self.last_written_dts)
+ && dts <= last_dts
+ {
+ let fixed_dts = last_dts + 1;
+ self.packet.set_dts(Some(fixed_dts));
+ if let Some(pts) = self.packet.pts()
+ && pts < fixed_dts
+ {
+ self.packet.set_pts(Some(fixed_dts));
+ }
+ }
+
+ if let (Some(pts), Some(dts)) = (self.packet.pts(), self.packet.dts())
+ && pts < dts
+ {
+ self.packet.set_pts(Some(dts));
+ }
+
+ self.last_written_dts = self.packet.dts();
+
+ let pts = self.packet.pts().unwrap_or(0);
+ let dts = self.packet.dts().unwrap_or(pts);
+ let duration = self.packet.duration();
+ let is_keyframe = self.packet.is_key();
+ let data = self.packet.data().map(|d| d.to_vec()).unwrap_or_default();
+
+ on_packet(EncodedPacket {
+ pts,
+ dts,
+ duration,
+ is_keyframe,
+ data,
+ })?;
+ }
+
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::video::h264::{H264EncoderBuilder, H264Preset};
+ use cap_media_info::{Pixel, VideoInfo};
+
+ fn test_video_info() -> VideoInfo {
+ VideoInfo {
+ pixel_format: Pixel::NV12,
+ width: 320,
+ height: 240,
+ time_base: ffmpeg::Rational(1, 1_000_000),
+ frame_rate: ffmpeg::Rational(30, 1),
+ }
+ }
+
+ fn create_test_frame(width: u32, height: u32) -> frame::Video {
+ let mut frame = frame::Video::new(format::Pixel::NV12, width, height);
+ for plane_idx in 0..frame.planes() {
+ let data = frame.data_mut(plane_idx);
+ for byte in data.iter_mut() {
+ *byte = 128;
+ }
+ }
+ frame
+ }
+
+ #[test]
+ fn standalone_builder_opens_encoder_and_produces_extradata() {
+ ffmpeg::init().ok();
+
+ let encoder = H264EncoderBuilder::new(test_video_info())
+ .with_preset(H264Preset::Ultrafast)
+ .build_standalone()
+ .expect("standalone build succeeds");
+
+ assert!(!encoder.codec_name().is_empty());
+ let tb = encoder.time_base();
+ assert!(tb.numerator() >= 1);
+ assert!(tb.denominator() >= 1);
+
+ let extra = encoder.extradata();
+ assert!(
+ !extra.is_empty() || encoder.codec_name() == "h264_videotoolbox",
+ "expected extradata on open with GLOBAL_HEADER for {}",
+ encoder.codec_name()
+ );
+ }
+
+ #[test]
+ fn standalone_encoder_produces_packets_on_frames_and_flush() {
+ ffmpeg::init().ok();
+
+ let mut encoder = H264EncoderBuilder::new(test_video_info())
+ .with_preset(H264Preset::Ultrafast)
+ .build_standalone()
+ .expect("standalone build succeeds");
+
+ let mut packets_seen = 0u32;
+ for i in 0..10 {
+ let frame = create_test_frame(320, 240);
+ encoder
+ .encode_frame(frame, Duration::from_millis(i * 33), |_pkt| {
+ packets_seen += 1;
+ Ok(())
+ })
+ .expect("encode succeeds");
+ }
+
+ encoder
+ .flush(|_pkt| {
+ packets_seen += 1;
+ Ok(())
+ })
+ .expect("flush succeeds");
+
+ assert!(
+ packets_seen > 0,
+ "expected at least one packet after encoding 10 frames + flush"
+ );
+ }
+}
diff --git a/crates/enc-ffmpeg/src/video/mod.rs b/crates/enc-ffmpeg/src/video/mod.rs
index 1a2c14bdd..408015325 100644
--- a/crates/enc-ffmpeg/src/video/mod.rs
+++ b/crates/enc-ffmpeg/src/video/mod.rs
@@ -1,3 +1,4 @@
pub mod h264;
+pub mod h264_packet;
pub mod hevc;
pub mod prores;