Skip to content
Closed
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
18 changes: 18 additions & 0 deletions crates/enc-ffmpeg/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ pub struct EncoderBase {
/// capture gap that lands on a fragment cut, playing post-gap content
/// during the gap. The bool records whether the duration was synthesized.
held_packet: Option<(Packet, bool)>,
/// Pts (encoder ticks) and key flag of each encoded packet, for
/// recording encoders that place keyframes on capture time.
packet_keys: Option<Vec<(i64, bool)>>,
}

impl EncoderBase {
Expand All @@ -110,9 +113,21 @@ impl EncoderBase {
stream_index,
last_written_dts: None,
held_packet: None,
packet_keys: None,
}
}

pub(crate) fn record_packet_keys(&mut self) {
self.packet_keys = Some(Vec::new());
}

pub(crate) fn take_packet_keys(&mut self) -> Vec<(i64, bool)> {
self.packet_keys
.as_mut()
.map(std::mem::take)
.unwrap_or_default()
}

pub fn set_packet_stats(&mut self, stats: Arc<EncodedPacketStats>) {
self.packet_stats = Some(stats);
}
Expand Down Expand Up @@ -202,6 +217,9 @@ impl EncoderBase {
encoder: &mut encoder::encoder::Encoder,
) -> Result<(), ffmpeg::Error> {
while packet_available(encoder.receive_packet(&mut self.packet))? {
if let (Some(keys), Some(pts)) = (&mut self.packet_keys, self.packet.pts()) {
keys.push((pts, self.packet.is_key()));
}
self.packet.set_stream(self.stream_index);
self.packet.rescale_ts(
encoder.time_base(),
Expand Down
88 changes: 70 additions & 18 deletions crates/enc-ffmpeg/src/video/h264.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use tracing::{debug, error, info, trace, warn};

use crate::base::EncoderBase;
use crate::video::h264_packet::H264PacketEncoder;
use crate::video::keyframe_cadence::KeyframeCadence;
#[cfg(target_os = "macos")]
use crate::video::videotoolbox_hw::VideoToolboxHwFrames;
use std::sync::Arc;
Expand Down Expand Up @@ -236,7 +237,7 @@ impl H264EncoderBuilder {
);
}
}
return Ok(encoder);
return Ok(encoder.with_recording_keyframes(self.is_export));
}
Err(err) => {
debug!("Encoder {} init failed: {:?}", codec_name, err);
Expand Down Expand Up @@ -298,6 +299,7 @@ impl H264EncoderBuilder {
input_width,
input_height,
converted_frame_pool,
keyframes: None,
#[cfg(target_os = "macos")]
videotoolbox_hw: None,
})
Expand Down Expand Up @@ -421,6 +423,7 @@ impl H264EncoderBuilder {
"Selected hardware H264 encoder with zero-copy VideoToolbox input"
);

let is_export = self.is_export;
Ok(H264Encoder {
base: EncoderBase::new(stream_index),
encoder,
Expand All @@ -432,8 +435,10 @@ impl H264EncoderBuilder {
input_width: input_config.width,
input_height: input_config.height,
converted_frame_pool: None,
keyframes: None,
videotoolbox_hw: Some(Arc::new(hw_frames)),
})
}
.with_recording_keyframes(is_export))
}

pub fn build_standalone(self) -> Result<H264PacketEncoder, H264EncoderError> {
Expand Down Expand Up @@ -513,7 +518,7 @@ impl H264EncoderBuilder {
fps = fps,
"Selected standalone H264 encoder"
);
return Ok(encoder);
return Ok(encoder.with_recording_keyframes(self.is_export));
}
Err(err) => {
debug!("Standalone encoder {} init failed: {:?}", codec_name, err);
Expand Down Expand Up @@ -821,6 +826,7 @@ pub struct H264Encoder {
input_width: u32,
input_height: u32,
converted_frame_pool: Option<frame::Video>,
keyframes: Option<KeyframeCadence>,
#[cfg(target_os = "macos")]
videotoolbox_hw: Option<Arc<VideoToolboxHwFrames>>,
}
Expand All @@ -846,6 +852,30 @@ pub enum QueueFrameError {
impl H264Encoder {
const TIME_BASE: i32 = 90000;

/// Recording encoders force a keyframe every
/// [`DEFAULT_KEYFRAME_INTERVAL_SECS`] of capture time (see
/// [`KeyframeCadence`]); exports keep the encoder's own cadence.
fn with_recording_keyframes(mut self, is_export: bool) -> Self {
if !is_export {
let gop_size = unsafe { (*self.encoder.as_ptr()).gop_size };
self.keyframes = Some(KeyframeCadence::new(
Duration::from_secs(u64::from(DEFAULT_KEYFRAME_INTERVAL_SECS)),
self.encoder.time_base(),
gop_size,
));
self.base.record_packet_keys();
}
self
}

fn observe_packets(&mut self) {
if let Some(keyframes) = &mut self.keyframes {
for (pts, is_key) in self.base.take_packet_keys() {
keyframes.observe(pts, is_key);
}
}
}

pub fn builder(input_config: VideoInfo) -> H264EncoderBuilder {
H264EncoderBuilder::new(input_config)
}
Expand Down Expand Up @@ -902,6 +932,7 @@ impl H264Encoder {
) -> Result<(), QueueFrameError> {
self.base
.update_pts(&mut frame, timestamp, &mut self.encoder);
let requested = frame.kind() == ffmpeg::picture::Type::I;

let frame_to_send = if let Some(converter) = &mut self.converter {
let pts = frame.pts();
Expand All @@ -910,14 +941,20 @@ impl H264Encoder {
.run(&frame, converted)
.map_err(QueueFrameError::Converter)?;
converted.set_pts(pts);
converted as &frame::Video
converted
} else {
&frame
&mut frame
};

self.base
.send_frame(frame_to_send, output, &mut self.encoder)
.map_err(QueueFrameError::Encode)?;
match &mut self.keyframes {
Some(keyframes) => keyframes.send(frame_to_send, requested, |frame| {
self.base.send_frame(frame, output, &mut self.encoder)
}),
None => self
.base
.send_frame(frame_to_send, output, &mut self.encoder),
}
.map_err(QueueFrameError::Encode)?;
self.observe_packets();

Ok(())
}
Expand All @@ -930,6 +967,7 @@ impl H264Encoder {
output: &mut format::context::Output,
) -> Result<(), QueueFrameError> {
self.base.update_pts(frame, timestamp, &mut self.encoder);
let requested = frame.kind() == ffmpeg::picture::Type::I;

let frame_to_send = if let Some(converter) = &mut self.converter {
let pts = frame.pts();
Expand All @@ -940,14 +978,20 @@ impl H264Encoder {
.run(frame, converted)
.map_err(QueueFrameError::Converter)?;
converted.set_pts(pts);
converted as &frame::Video
converted
} else {
frame as &frame::Video
frame
};

self.base
.send_frame(frame_to_send, output, &mut self.encoder)
.map_err(QueueFrameError::Encode)?;
match &mut self.keyframes {
Some(keyframes) => keyframes.send(frame_to_send, requested, |frame| {
self.base.send_frame(frame, output, &mut self.encoder)
}),
None => self
.base
.send_frame(frame_to_send, output, &mut self.encoder),
}
.map_err(QueueFrameError::Encode)?;
self.observe_packets();

Ok(())
}
Expand All @@ -970,10 +1014,16 @@ impl H264Encoder {

self.base
.update_pts(&mut frame, timestamp, &mut self.encoder);
let requested = frame.kind() == ffmpeg::picture::Type::I;

self.base
.send_frame(&frame, output, &mut self.encoder)
.map_err(QueueFrameError::Encode)?;
match &mut self.keyframes {
Some(keyframes) => keyframes.send(&mut frame, requested, |frame| {
self.base.send_frame(frame, output, &mut self.encoder)
}),
None => self.base.send_frame(&frame, output, &mut self.encoder),
}
.map_err(QueueFrameError::Encode)?;
self.observe_packets();

Ok(())
}
Expand Down Expand Up @@ -1254,6 +1304,7 @@ fn get_codec_and_options(
options.set("rc", "vbr");
options.set("spatial-aq", "1");
options.set("temporal-aq", "1");
options.set("forced-idr", "1");
}
options.set("g", &keyframe_interval_str);
}
Expand All @@ -1265,6 +1316,7 @@ fn get_codec_and_options(
} else {
options.set("preset", "faster");
options.set("look_ahead", "1");
options.set("forced_idr", "1");
}
options.set("g", &keyframe_interval_str);
}
Expand Down
Loading
Loading