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
141 changes: 139 additions & 2 deletions crates/enc-ffmpeg/src/mux/segmented_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ pub struct SegmentedVideoEncoder {
segment_tx: SegmentSender,

segment_duration: Duration,
segment_keyframes: Option<SegmentKeyframes>,

disk_space_callback: Option<DiskSpaceCallback>,

Expand All @@ -194,6 +195,41 @@ pub struct SegmentedVideoEncoder {
flush_failure: Option<EncoderFlushFailure>,
}

const SPARSE_SEGMENT_SCAN_INTERVAL: Duration = Duration::from_secs(1);

struct SegmentKeyframes {
segment_duration: Duration,
encoder_interval: u32,
last: Option<Duration>,
frames_since: u32,
}

impl SegmentKeyframes {
fn new(segment_duration: Duration, video_config: &VideoInfo) -> Self {
Self {
segment_duration,
encoder_interval: crate::video::h264::keyframe_interval_frames(video_config) as u32,
last: None,
frames_since: 0,
}
}

fn must_force(&mut self, timestamp: Duration) -> bool {
let Some(last) = self.last else {
self.last = Some(timestamp);
return false;
};
self.frames_since += 1;
let encoder_due = self.frames_since >= self.encoder_interval;
let overdue = timestamp.saturating_sub(last) >= self.segment_duration;
if encoder_due || overdue {
self.last = Some(timestamp);
self.frames_since = 0;
}
overdue && !encoder_due
}
}

struct SegmentMux {
base_path: PathBuf,
output: format::context::Output,
Expand All @@ -203,6 +239,7 @@ struct SegmentMux {
completed_segments: Vec<VideoSegmentInfo>,

frames_since_segment_scan: u32,
last_segment_scan: std::time::Instant,

codec_info: CodecInfo,

Expand Down Expand Up @@ -232,8 +269,11 @@ impl MuxTarget for SegmentMux {
self.try_notify_init_segment();

self.frames_since_segment_scan += 1;
if self.frames_since_segment_scan >= 10 {
if self.frames_since_segment_scan >= 10
|| self.last_segment_scan.elapsed() >= SPARSE_SEGMENT_SCAN_INTERVAL
{
self.frames_since_segment_scan = 0;
self.last_segment_scan = std::time::Instant::now();
self.flush_pending_segments();
}
}
Expand Down Expand Up @@ -507,6 +547,7 @@ impl SegmentedVideoEncoder {
current_index: 1,
completed_segments: Vec::new(),
frames_since_segment_scan: 0,
last_segment_scan: std::time::Instant::now(),
codec_info,
segment_tx: SegmentSender::default(),
init_notified: false,
Expand All @@ -521,6 +562,8 @@ impl SegmentedVideoEncoder {
mux: MuxSink::Direct(mux),
segment_tx,
segment_duration: config.segment_duration,
segment_keyframes: (!timed_fragments)
.then(|| SegmentKeyframes::new(config.segment_duration, &video_config)),
disk_space_callback: None,
runtime_fallback: RUNTIME_SOFTWARE_FALLBACK,
codec_failures: CodecFailureHistory::default(),
Expand Down Expand Up @@ -585,9 +628,18 @@ impl SegmentedVideoEncoder {

pub fn queue_frame(
&mut self,
frame: frame::Video,
mut frame: frame::Video,
timestamp: Duration,
) -> Result<(), QueueFrameError> {
// Keyframes cut the segments, and the encoder places them by frame
// count. A source that only delivers on change falls behind that
// count, so a keyframe is forced once a segment's worth of time has
// passed since the last one.
if let Some(keyframes) = &mut self.segment_keyframes
&& keyframes.must_force(timestamp)
{
frame.set_kind(ffmpeg::picture::Type::I);
}
// Encode with the frame's real capture-derived timestamp. The encoder
// anchors pts at the first frame, so capture gaps (static content,
// stream restarts, dropped frames) stay in the timeline instead of
Expand Down Expand Up @@ -2001,6 +2053,91 @@ mod tests {
assert!(crate::remux::probe_video_can_decode(&remuxed_path).unwrap_or(false));
}

fn sparse_segment_durations(timestamps: &[Duration]) -> Vec<f64> {
ffmpeg::init().ok();
let temp = tempfile::tempdir().unwrap();
let base_path = temp.path().to_path_buf();
let mut video_info = test_video_info();
video_info.pixel_format = cap_media_info::Pixel::BGRA;
let mut encoder = SegmentedVideoEncoder::init(
base_path.clone(),
video_info,
SegmentedVideoEncoderConfig::default(),
)
.unwrap();
for &timestamp in timestamps {
let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, 320, 240);
frame.data_mut(0).fill(128);
encoder.queue_frame(frame, timestamp).unwrap();
}
encoder.finish().unwrap();
std::fs::read_to_string(base_path.join("media_0.m3u8"))
.unwrap()
.lines()
.filter_map(|line| line.strip_prefix("#EXTINF:"))
.map(|line| line.trim_end_matches(',').parse().unwrap())
.collect()
}

#[test]
fn a_static_source_refreshed_once_per_segment_still_cuts_every_segment() {
let refresh = Duration::from_secs(2) + Duration::from_secs(1) / 30;
let timestamps: Vec<Duration> = (0..6).map(|index| refresh * index).collect();
let durations = sparse_segment_durations(&timestamps);
assert!(durations.len() >= 5, "segments: {durations:?}");
for duration in &durations[..durations.len() - 1] {
assert!((2.0..2.1).contains(duration), "segments: {durations:?}");
}
}

#[test]
fn a_static_source_publishes_each_segment_without_waiting_for_ten_frames() {
ffmpeg::init().ok();
let temp = tempfile::tempdir().unwrap();
let mut encoder = SegmentedVideoEncoder::init(
temp.path().to_path_buf(),
test_video_info(),
SegmentedVideoEncoderConfig::default(),
)
.unwrap();
let (tx, rx) = mpsc::channel();
encoder.set_segment_callback(tx);
let refresh = Duration::from_secs(2) + Duration::from_secs(1) / 30;
for index in 0..4 {
if index == 3 {
std::thread::sleep(SPARSE_SEGMENT_SCAN_INTERVAL);
}
encoder
.queue_frame(create_test_frame(320, 240), refresh * index)
.unwrap();
}
let published = rx.try_iter().filter(|event| !event.is_init).count();
assert!(published >= 1, "no segment published after four frames");
encoder.finish().unwrap();
}

#[test]
fn a_sparse_source_cuts_segments_by_time_instead_of_frame_count() {
let timestamps: Vec<Duration> = (0..80)
.map(|index| Duration::from_millis(125) * index)
.collect();
let durations = sparse_segment_durations(&timestamps);
assert!(durations.len() >= 4, "segments: {durations:?}");
for duration in &durations[..durations.len() - 1] {
assert!((2.0..2.2).contains(duration), "segments: {durations:?}");
}
}

#[test]
fn a_full_rate_source_leaves_keyframes_to_the_encoder() {
let mut keyframes = SegmentKeyframes::new(Duration::from_secs(2), &test_video_info());
for index in 0..600u32 {
let jitter = Duration::from_millis(u64::from(index % 3));
let timestamp = Duration::from_secs(1) * index / 30 + jitter;
assert!(!keyframes.must_force(timestamp), "forced frame {index}");
}
}

fn recorded_track(base_path: &Path) -> PathBuf {
let mut segment_paths: Vec<PathBuf> = std::fs::read_dir(base_path)
.unwrap()
Expand Down
19 changes: 11 additions & 8 deletions crates/enc-ffmpeg/src/video/h264.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1284,6 +1284,7 @@ impl H264Encoder {
super::convert_or_scale(&frame, converted, converter)
.map_err(QueueFrameError::Converter)?;
converted.set_pts(pts);
converted.set_kind(frame.kind());
converted as &frame::Video
} else {
&frame
Expand Down Expand Up @@ -1655,21 +1656,23 @@ fn export_encoder_priority_override(

pub const DEFAULT_KEYFRAME_INTERVAL_SECS: u32 = 2;

pub(crate) fn keyframe_interval_frames(config: &VideoInfo) -> i32 {
let denominator = config.frame_rate.denominator();
let frames_per_sec = config.frame_rate.numerator() as f64
/ if denominator == 0 { 1 } else { denominator } as f64;
(DEFAULT_KEYFRAME_INTERVAL_SECS as f64 * frames_per_sec)
.round()
.max(1.0) as i32
}

fn get_codec_and_options(
config: &VideoInfo,
preset: H264Preset,
encoder_priority_override: Option<&'static [&'static str]>,
is_export: bool,
crf: Option<u8>,
) -> Vec<(Codec, Dictionary<'static>)> {
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;
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 keyframe_interval_str = keyframe_interval_frames(config).to_string();

let encoder_priority = if crf.is_some() {
&["libx264"] as &[&str]
Expand Down
2 changes: 1 addition & 1 deletion crates/recording/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ ashpd = { version = "0.11.0", default-features = false, features = ["tokio"] }
glow = "0.16"
khronos-egl = { version = "6", features = ["dynamic"] }
pipewire = "0.10.0"
x11rb = { version = "0.13.2", features = ["composite", "shm", "xfixes"] }
x11rb = { version = "0.13.2", features = ["composite", "damage", "shm", "xfixes"] }

[dev-dependencies]
tempfile = "3.20.0"
Expand Down
Loading
Loading