From b8b357a00a606b9ca28bc328907532fde006a960 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 02:10:43 +0300 Subject: [PATCH] voelin-media: keep the audio of a recording's first moment A recording and a clip start at a video keyframe, and dropped all audio that came before it. But the video encoder is behind the audio: by the time the keyframe of a moment arrives, the audio of that moment and of the encoder's whole delay has already gone by. With a hardware H.264 encoder starting up, a recording's audio began 285 ms after its picture. The recorder now keeps the last two seconds of audio while it waits and, once the keyframe is written, writes the part not older than it. The replay buffer keeps waiting audio the same way, and when it trims to a keyframe it keeps the audio of the keyframe's time that arrived before it; a clip feeds everything to a recorder, which skips video up to its first keyframe. The same recording now starts its audio 10 ms after the picture (one Opus frame). Co-Authored-By: Claude Opus 5.5 --- .../voelin-media/src/studio/output/record.rs | 73 +++++++++++++++--- .../voelin-media/src/studio/output/replay.rs | 76 ++++++++++++++++--- 2 files changed, 129 insertions(+), 20 deletions(-) diff --git a/crates/voelin-media/src/studio/output/record.rs b/crates/voelin-media/src/studio/output/record.rs index 1237273..29c5cb1 100644 --- a/crates/voelin-media/src/studio/output/record.rs +++ b/crates/voelin-media/src/studio/output/record.rs @@ -2,10 +2,12 @@ //! //! The recorder waits for the first keyframe of the layer it records (a file //! that starts mid-picture is useless), then writes an [`ebml`] file and -//! every packet after it. The audio track is declared from the start, so -//! audio that arrives before the first keyframe is simply dropped rather -//! than shifting the file's clock. +//! every packet after it. The video encoder's delay means that keyframe +//! arrives after the audio of the same moment, so the last [`BACKLOG`] of +//! audio is kept while waiting and what of it is not older than the keyframe +//! is written too: the recording's audio starts with its picture. +use std::collections::VecDeque; use std::fs::File; use std::io::BufWriter; use std::path::{Path, PathBuf}; @@ -18,6 +20,10 @@ use crate::studio::output::ebml::{self, Track as MkvTrack, TrackKind, Writer}; use crate::studio::output::{OutputSink, Packet, Track}; use crate::{Error, Result}; +/// How much audio is kept while waiting for the first keyframe: more than +/// any encoder's delay. +pub const BACKLOG: Duration = Duration::from_secs(2); + /// The container a recording is written in. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Format { @@ -65,6 +71,8 @@ pub struct Recorder { /// H.264 frames are rewritten length-prefixed. scratch: Vec, video: Option, + /// Audio (90 kHz time, bytes) that came while waiting for the keyframe. + backlog: VecDeque<(u64, Vec)>, } impl Recorder { @@ -90,6 +98,7 @@ impl Recorder { waiting: true, scratch: Vec::new(), video: None, + backlog: VecDeque::new(), }) } @@ -169,9 +178,20 @@ impl OutputSink for Recorder { Track::Video { .. } => return Ok(()), Track::Audio { .. } => (1, None), }; - if self.writer.is_none() { - // Nothing before the first keyframe of the recorded layer. - let Some(codec) = codec.filter(|_| packet.keyframe) else { return Ok(()) }; + let opening = self.writer.is_none(); + if opening { + // No video before the first keyframe of the recorded layer; the + // audio waits for it. + let Some(codec) = codec.filter(|_| packet.keyframe) else { + if codec.is_none() { + let keep = BACKLOG.as_millis() as u64 * 90; + self.backlog.push_back((packet.pts_90khz, packet.data.to_vec())); + while self.backlog.front().is_some_and(|(t, _)| t + keep < packet.pts_90khz) { + self.backlog.pop_front(); + } + } + return Ok(()); + }; self.open(packet, codec)?; } let Some(writer) = &mut self.writer else { return Ok(()) }; @@ -186,12 +206,18 @@ impl OutputSink for Recorder { } if codec == Some(Codec::H264) { ebml::to_length_prefixed(packet.data, &mut self.scratch); - let scratch = std::mem::take(&mut self.scratch); - let result = writer.write(index, packet.ms(), packet.keyframe, &scratch); - self.scratch = scratch; - return result; + writer.write(index, packet.ms(), packet.keyframe, &self.scratch)?; + } else { + writer.write(index, packet.ms(), packet.keyframe, packet.data)?; } - writer.write(index, packet.ms(), packet.keyframe, packet.data) + if opening { + for (time, data) in self.backlog.drain(..) { + if time >= packet.pts_90khz { + writer.write(1, time * 1000 / 90_000, true, &data)?; + } + } + } + Ok(()) } fn finish(&mut self) -> Result<()> { @@ -284,6 +310,31 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + #[test] + fn audio_of_the_keyframes_moment_is_kept_while_waiting() { + let dir = dir("backlog"); + let mut recorder = Recorder::start(dir.join("clip.webm"), 0, 2).unwrap(); + let audio = |ms: u64| Packet { + track: Track::Audio { channels: 2 }, + pts_90khz: ms * 90, + keyframe: true, + width: 0, + height: 0, + data: &[7, 7], + }; + // The encoder is slow: audio up to 200 ms is here before the keyframe + // of the picture at 100 ms. + for ms in (0..=200).step_by(20) { + recorder.write(&audio(ms)).unwrap(); + } + recorder.write(&video(0, 100, true, &[1, 2, 3])).unwrap(); + // The keyframe, then the audio from 100 ms on: 100, 120, ... 200. + assert_eq!(recorder.writer.as_ref().unwrap().blocks(), 1 + 6); + assert!(recorder.backlog.is_empty()); + recorder.finish().unwrap(); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn a_codec_change_stops_the_recording() { let dir = dir("codec-change"); diff --git a/crates/voelin-media/src/studio/output/replay.rs b/crates/voelin-media/src/studio/output/replay.rs index 2f475a2..f431ff9 100644 --- a/crates/voelin-media/src/studio/output/replay.rs +++ b/crates/voelin-media/src/studio/output/replay.rs @@ -23,7 +23,7 @@ use std::time::Duration; use tracing::debug; use crate::codec::Codec; -use crate::studio::output::record::Recorder; +use crate::studio::output::record::{BACKLOG, Recorder}; use crate::studio::output::{OutputSink, Packet, Track}; use crate::{Error, Result}; @@ -188,6 +188,16 @@ impl ReplayBuffer { .rfind(|(_, e)| e.keyframe && e.track.is_video() && e.pts_90khz <= cutoff) .map(|(i, _)| i); let Some(keep) = keep else { return }; + // Audio that arrived before the keyframe but belongs after it (the + // video encoder's delay) stays with it; the older video between is + // harmless, a clip skips video up to its first keyframe. + let key = self.entries[keep].pts_90khz; + let keep = self + .entries + .iter() + .take(keep) + .position(|e| !e.track.is_video() && e.pts_90khz >= key) + .unwrap_or(keep); let dropped: Vec = self.entries.drain(..keep).map(|e| e.data).collect(); for data in &dropped { self.release(data); @@ -293,13 +303,14 @@ impl ReplayBuffer { "the replay buffer is off (studio.replay_seconds is 0)".into(), )); } - let start = - self.entries.iter().position(|e| e.keyframe && e.track.is_video()).ok_or_else( - || Error::InvalidFrame("the replay buffer holds no keyframe yet".into()), - )?; + if !self.entries.iter().any(|e| e.keyframe && e.track.is_video()) { + return Err(Error::InvalidFrame("the replay buffer holds no keyframe yet".into())); + } + // Everything, from the start: the recorder skips video up to the + // first keyframe and keeps the audio of its moment. let mut recorder = Recorder::start(path, self.layer, self.channels)?; let mut bytes = Vec::new(); - for index in start..self.entries.len() { + for index in 0..self.entries.len() { self.read(index, &mut bytes)?; let entry = &self.entries[index]; recorder.write(&Packet { @@ -353,9 +364,18 @@ impl OutputSink for ReplayBuffer { self.last_keyframe = packet.pts_90khz; } } - // Nothing before the first keyframe: a clip has to start at one. - if self.entries.is_empty() && !(packet.keyframe && packet.track.is_video()) { - return Ok(()); + // No video before the first keyframe: a clip has to start at one. The + // audio waits for it, the last [`BACKLOG`] of it. + if self.needs_keyframe { + if packet.track.is_video() && !packet.keyframe { + return Ok(()); + } + let keep = BACKLOG.as_millis() as u64 * 90; + while self.entries.front().is_some_and(|e| e.pts_90khz + keep < packet.pts_90khz) { + if let Some(entry) = self.entries.pop_front() { + self.release(&entry.data); + } + } } self.entries.push_back(Entry { track: packet.track, @@ -511,6 +531,44 @@ mod tests { assert!(buffer.wants(Track::Video { codec: Codec::Vp8, layer: 0 })); } + #[test] + fn audio_ahead_of_a_late_keyframe_stays_with_it() { + let mut buffer = ReplayBuffer::new(Duration::from_secs(1), 64, 0, 2); + let audio = |buffer: &mut ReplayBuffer, ms: u64| { + let track = Track::Audio { channels: 2 }; + let packet = Packet { + track, + pts_90khz: ms * 90, + keyframe: true, + width: 0, + height: 0, + data: &[7], + }; + buffer.write(&packet).unwrap(); + }; + // The encoder is 100 ms behind the audio: each keyframe arrives after + // the audio of the next 100 ms. + for ms in (0..=200).step_by(20) { + audio(&mut buffer, ms); + } + push(&mut buffer, 100, true, 10); + for ms in (220..3000).step_by(20) { + audio(&mut buffer, ms); + if ms % 100 == 0 { + push(&mut buffer, ms - 100, (ms - 100) % 1000 == 0, 10); + } + } + // The window starts at the keyframe of 1000 ms (the last one at or + // before 2900 - 1000 ms), with the audio from 1000 ms on that came + // before it. + let first = buffer.entries.front().unwrap(); + assert!(!first.track.is_video()); + assert_eq!(first.pts_90khz, 1000 * 90); + assert!(buffer.entries.iter().all(|e| e.track.is_video() || e.pts_90khz >= 1000 * 90)); + let key = buffer.entries.iter().find(|e| e.keyframe && e.track.is_video()).unwrap(); + assert_eq!(key.pts_90khz, 1000 * 90); + } + #[test] fn it_asks_for_keyframes_so_the_window_can_move() { let mut buffer = ReplayBuffer::new(Duration::from_secs(1), 64, 0, 2);