voelin-media: record the studio and keep a replay buffer

Recording and the replay buffer must work whether or not a stream is live,
and neither may cost a second encode, so both are fed the packets the
streamer's encoders already produce. That makes them output sinks over one
small trait rather than pipelines of their own.

The container is an own EBML writer: Matroska and WebM need so little of the
format for this (a header, one Info, one Tracks, clusters of SimpleBlocks)
that a dependency would be the larger cost. The segment size stays unknown
and there are no cues, so a recording cut short by a crash still plays; only
the duration is written back at the end, because a file of unknown length is
a poor thing to hand a player. H.264 is stored the way Matroska wants it,
length-prefixed with its parameter sets in CodecPrivate, which is why the
header waits for the first keyframe.

The replay buffer keeps whole keyframe groups so a clip always starts where a
decoder can, and a window longer than memory allows spills its oldest packets
to a temporary file it drops again once they age out -- the length is a
setting with no maximum, so it cannot be bounded by what fits in RAM.

RTMP is a seam that says what it is waiting for (the muxing side of the
FFmpeg loader) instead of dropping a stream silently.

tests/studio_record.rs runs real VP8 frames through both and reads the files
back with ffprobe: codecs, size, duration, and every frame of a clip decoded.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5 committed 2026-09-29 23:32:23 +03:00
1 parent 5fb93dc33d
commit eb86ef9fba
7 files changed
+1703

No files matched your search

+3
View File
@@ -8,8 +8,11 @@
//! - [`source`]: the live input behind each of a scene's sources (colour,
//! text, image, screen, window, camera)
//! - [`camera`]: listing and capturing cameras
//! - [`output`]: what the encoded packets go to besides the stream
//! (recording, the replay buffer, WHIP)
pub mod camera;
pub mod compose;
pub mod output;
pub mod scene;
pub mod source;
@@ -0,0 +1,514 @@
//! A small Matroska / WebM writer, enough for what the studio records.
//!
//! Only what a recording needs is written: an EBML header, one `Info`, one
//! `Tracks` and a stream of `Cluster`s of `SimpleBlock`s. The `Segment` has
//! an unknown size and there are no `Cues`, so a recording that is cut short
//! (a crash, a full disk) still plays up to the last cluster; players seek by
//! scanning, which is what a live WebM stream needs anyway. The one thing
//! written back is the `Duration`, which is reserved in the header and filled
//! in on [`Writer::finish`] -- without it players show a file of unknown
//! length.
//!
//! Timestamps are milliseconds (`TimecodeScale` 1 ms); each cluster starts at
//! a keyframe, and blocks carry their offset from the cluster as a 16-bit
//! value, so a cluster never spans more than 32 seconds.
//!
//! H.264 has to be stored length-prefixed with its parameter sets in
//! `CodecPrivate` ([`avcc`]), which is why the header is written when the
//! first keyframe arrives rather than at the start.
use std::io::{Seek, SeekFrom, Write};
use crate::codec::Codec;
use crate::{Error, Result};
/// `Segment`, `Cluster` and the rest, as their full EBML ids.
mod id {
pub const EBML: u32 = 0x1A45_DFA3;
pub const EBML_VERSION: u32 = 0x4286;
pub const EBML_READ_VERSION: u32 = 0x42F7;
pub const EBML_MAX_ID_LENGTH: u32 = 0x42F2;
pub const EBML_MAX_SIZE_LENGTH: u32 = 0x42F3;
pub const DOC_TYPE: u32 = 0x4282;
pub const DOC_TYPE_VERSION: u32 = 0x4287;
pub const DOC_TYPE_READ_VERSION: u32 = 0x4285;
pub const SEGMENT: u32 = 0x1853_8067;
pub const INFO: u32 = 0x1549_A966;
pub const TIMECODE_SCALE: u32 = 0x002A_D7B1;
pub const DURATION: u32 = 0x4489;
pub const MUXING_APP: u32 = 0x4D80;
pub const WRITING_APP: u32 = 0x5741;
pub const TRACKS: u32 = 0x1654_AE6B;
pub const TRACK_ENTRY: u32 = 0xAE;
pub const TRACK_NUMBER: u32 = 0xD7;
pub const TRACK_UID: u32 = 0x73C5;
pub const TRACK_TYPE: u32 = 0x83;
pub const FLAG_LACING: u32 = 0x9C;
pub const CODEC_ID: u32 = 0x86;
pub const CODEC_PRIVATE: u32 = 0x63A2;
pub const LANGUAGE: u32 = 0x0022_B59C;
pub const VIDEO: u32 = 0xE0;
pub const PIXEL_WIDTH: u32 = 0xB0;
pub const PIXEL_HEIGHT: u32 = 0xBA;
pub const AUDIO: u32 = 0xE1;
pub const SAMPLING_FREQUENCY: u32 = 0xB5;
pub const CHANNELS: u32 = 0x9F;
pub const CLUSTER: u32 = 0x1F43_B675;
pub const TIMECODE: u32 = 0xE7;
pub const SIMPLE_BLOCK: u32 = 0xA3;
}
/// Append an element id (its bytes already carry their length).
fn put_id(out: &mut Vec<u8>, id: u32) {
let bytes = id.to_be_bytes();
let first = bytes.iter().position(|&b| b != 0).unwrap_or(3);
out.extend_from_slice(&bytes[first..]);
}
/// Append an EBML unsigned integer of `len` bytes (the length marker is the
/// top bit of the first byte).
fn put_size(out: &mut Vec<u8>, size: u64) {
// The shortest length whose value range holds `size` (all-ones is
// reserved for "unknown").
let mut len = 1;
while len < 8 && size >= (1u64 << (7 * len)) - 1 {
len += 1;
}
let marked = size | 1u64 << (7 * len);
out.extend_from_slice(&marked.to_be_bytes()[8 - len..]);
}
/// Append an element with `body` as its content.
fn element(out: &mut Vec<u8>, id: u32, body: &[u8]) {
put_id(out, id);
put_size(out, body.len() as u64);
out.extend_from_slice(body);
}
/// An unsigned integer element, in as few bytes as it fits.
fn uint(out: &mut Vec<u8>, id: u32, value: u64) {
let bytes = value.to_be_bytes();
let first = bytes.iter().position(|&b| b != 0).unwrap_or(7);
element(out, id, &bytes[first..]);
}
/// An IEEE-754 double element (Matroska stores frequencies as floats).
fn float(out: &mut Vec<u8>, id: u32, value: f64) {
element(out, id, &value.to_be_bytes());
}
fn text(out: &mut Vec<u8>, id: u32, value: &str) {
element(out, id, value.as_bytes());
}
/// What one track holds.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TrackKind {
Video {
codec: Codec,
width: u32,
height: u32,
},
/// Opus at 48 kHz.
Opus {
channels: u16,
},
}
/// One track of the file.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Track {
pub kind: TrackKind,
/// `CodecPrivate`: the Opus head, or H.264's `avcC`.
pub private: Vec<u8>,
}
impl TrackKind {
/// The Matroska codec id.
fn codec_id(&self) -> &'static str {
match self {
Self::Video { codec: Codec::Vp8, .. } => "V_VP8",
Self::Video { codec: Codec::Vp9, .. } => "V_VP9",
Self::Video { codec: Codec::Av1, .. } => "V_AV1",
Self::Video { codec: Codec::H264, .. } => "V_MPEG4/ISO/AVC",
Self::Video { codec: Codec::H265, .. } => "V_MPEGH/ISO/HEVC",
Self::Opus { .. } => "A_OPUS",
}
}
/// Whether WebM allows this codec (Matroska allows everything).
fn in_webm(&self) -> bool {
matches!(
self,
Self::Video { codec: Codec::Vp8 | Codec::Vp9 | Codec::Av1, .. } | Self::Opus { .. }
)
}
}
/// The `CodecPrivate` of an Opus track: an `OpusHead` for 48 kHz.
pub fn opus_head(channels: u16) -> Vec<u8> {
let mut head = Vec::with_capacity(19);
head.extend_from_slice(b"OpusHead");
head.push(1); // version
head.push(channels.clamp(1, 255) as u8);
head.extend_from_slice(&312u16.to_le_bytes()); // pre-skip
head.extend_from_slice(&48_000u32.to_le_bytes());
head.extend_from_slice(&0i16.to_le_bytes()); // output gain
head.push(0); // channel mapping family
head
}
/// The NAL units of an Annex B stream (start codes stripped).
pub fn annex_b_units(data: &[u8]) -> impl Iterator<Item = &[u8]> {
let mut rest = data;
std::iter::from_fn(move || {
// Skip to the first start code.
let start = (0..rest.len().saturating_sub(2)).find(|&i| rest[i..i + 3] == [0, 0, 1])?;
rest = &rest[start + 3..];
let end = (0..rest.len().saturating_sub(2))
.find(|&i| rest[i..i + 3] == [0, 0, 1])
.map_or(rest.len(), |i| if i > 0 && rest[i - 1] == 0 { i - 1 } else { i });
let (unit, tail) = rest.split_at(end);
rest = tail;
Some(unit)
})
.filter(|unit| !unit.is_empty())
}
/// The `avcC` record of an Annex B keyframe: the parameter sets Matroska
/// needs before any picture. `None` if the frame carries none.
pub fn avcc(keyframe: &[u8]) -> Option<Vec<u8>> {
let mut sps: Option<&[u8]> = None;
let mut pps: Option<&[u8]> = None;
for unit in annex_b_units(keyframe) {
match unit[0] & 0x1F {
7 => sps = sps.or(Some(unit)),
8 => pps = pps.or(Some(unit)),
_ => {}
}
}
let (sps, pps) = (sps?, pps?);
if sps.len() < 4 {
return None;
}
let mut record = vec![1, sps[1], sps[2], sps[3], 0xFF, 0xE1];
record.extend_from_slice(&(sps.len() as u16).to_be_bytes());
record.extend_from_slice(sps);
record.push(1);
record.extend_from_slice(&(pps.len() as u16).to_be_bytes());
record.extend_from_slice(pps);
Some(record)
}
/// An Annex B frame as the length-prefixed units Matroska stores.
pub fn to_length_prefixed(data: &[u8], out: &mut Vec<u8>) {
out.clear();
for unit in annex_b_units(data) {
// Access unit delimiters say nothing a container does not.
if unit[0] & 0x1F == 9 {
continue;
}
out.extend_from_slice(&(unit.len() as u32).to_be_bytes());
out.extend_from_slice(unit);
}
}
/// A cluster is closed at a keyframe, or once it reaches this many bytes or
/// this much time (a block's timestamp is 16 bits from the cluster's).
const CLUSTER_BYTES: usize = 4 << 20;
const CLUSTER_MS: u64 = 5_000;
/// Writes Matroska or WebM; see the [module docs](self).
pub struct Writer<W: Write + Seek> {
out: W,
/// Where the `Duration` value sits, to fill in at the end.
duration_at: u64,
tracks: Vec<Track>,
/// Timestamp of the open cluster, and its blocks.
cluster: Option<u64>,
buffer: Vec<u8>,
/// The first timestamp seen, so the file starts at zero.
origin: Option<u64>,
last_ms: u64,
bytes: u64,
blocks: u64,
}
impl<W: Write + Seek> Writer<W> {
/// Start a file with these tracks (track 1 first). `webm` writes the
/// WebM doc type, which only allows VP8, VP9, AV1 and Opus.
pub fn new(mut out: W, webm: bool, tracks: Vec<Track>) -> Result<Self> {
if tracks.is_empty() {
return Err(Error::InvalidFrame("a recording needs at least one track".into()));
}
if webm && let Some(track) = tracks.iter().find(|t| !t.kind.in_webm()) {
return Err(Error::InvalidFrame(format!(
"{} cannot go into WebM; record Matroska instead",
track.kind.codec_id()
)));
}
let mut head = Vec::new();
let mut body = Vec::new();
uint(&mut body, id::EBML_VERSION, 1);
uint(&mut body, id::EBML_READ_VERSION, 1);
uint(&mut body, id::EBML_MAX_ID_LENGTH, 4);
uint(&mut body, id::EBML_MAX_SIZE_LENGTH, 8);
text(&mut body, id::DOC_TYPE, if webm { "webm" } else { "matroska" });
uint(&mut body, id::DOC_TYPE_VERSION, 4);
uint(&mut body, id::DOC_TYPE_READ_VERSION, 2);
element(&mut head, id::EBML, &body);
// A segment of unknown size: nothing is ever written back.
put_id(&mut head, id::SEGMENT);
head.extend_from_slice(&[0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
body.clear();
uint(&mut body, id::TIMECODE_SCALE, 1_000_000);
text(&mut body, id::MUXING_APP, "Voelin Studio");
text(&mut body, id::WRITING_APP, "Voelin Studio");
// Reserved: the length is only known when the recording stops.
put_id(&mut body, id::DURATION);
put_size(&mut body, 8);
let duration_in_info = body.len();
body.extend_from_slice(&0f64.to_be_bytes());
element(&mut head, id::INFO, &body);
let duration_at = (head.len() - body.len() + duration_in_info) as u64;
body.clear();
for (i, track) in tracks.iter().enumerate() {
let mut entry = Vec::new();
let number = i as u64 + 1;
uint(&mut entry, id::TRACK_NUMBER, number);
uint(&mut entry, id::TRACK_UID, number);
uint(
&mut entry,
id::TRACK_TYPE,
match track.kind {
TrackKind::Video { .. } => 1,
TrackKind::Opus { .. } => 2,
},
);
uint(&mut entry, id::FLAG_LACING, 0);
text(&mut entry, id::LANGUAGE, "und");
text(&mut entry, id::CODEC_ID, track.kind.codec_id());
if !track.private.is_empty() {
element(&mut entry, id::CODEC_PRIVATE, &track.private);
}
match track.kind {
TrackKind::Video { width, height, .. } => {
let mut video = Vec::new();
uint(&mut video, id::PIXEL_WIDTH, u64::from(width.max(1)));
uint(&mut video, id::PIXEL_HEIGHT, u64::from(height.max(1)));
element(&mut entry, id::VIDEO, &video);
}
TrackKind::Opus { channels } => {
let mut audio = Vec::new();
float(&mut audio, id::SAMPLING_FREQUENCY, 48_000.0);
uint(&mut audio, id::CHANNELS, u64::from(channels.max(1)));
element(&mut entry, id::AUDIO, &audio);
}
}
element(&mut body, id::TRACK_ENTRY, &entry);
}
element(&mut head, id::TRACKS, &body);
out.write_all(&head)?;
Ok(Self {
out,
duration_at,
tracks,
cluster: None,
buffer: Vec::with_capacity(CLUSTER_BYTES / 4),
origin: None,
last_ms: 0,
bytes: head.len() as u64,
blocks: 0,
})
}
/// The tracks, in the order their numbers follow.
pub fn tracks(&self) -> &[Track] {
&self.tracks
}
/// Bytes written so far.
pub fn bytes(&self) -> u64 {
self.bytes + self.buffer.len() as u64
}
pub fn blocks(&self) -> u64 {
self.blocks
}
/// Length of the recording so far.
pub fn duration(&self) -> std::time::Duration {
std::time::Duration::from_millis(self.last_ms)
}
/// Add one frame of `track` (0-based) at `ms` from the start of the
/// stream. The first frame decides where the file's clock starts.
pub fn write(&mut self, track: usize, ms: u64, keyframe: bool, data: &[u8]) -> Result<()> {
if track >= self.tracks.len() {
return Err(Error::InvalidFrame(format!("no track {track} in this recording")));
}
if data.is_empty() {
return Ok(());
}
let origin = *self.origin.get_or_insert(ms);
let ms = ms.saturating_sub(origin);
self.last_ms = self.last_ms.max(ms);
let start = match self.cluster {
Some(start)
if !(keyframe && track == 0)
&& self.buffer.len() < CLUSTER_BYTES
&& ms.saturating_sub(start) < CLUSTER_MS =>
{
start
}
_ => {
self.flush_cluster()?;
self.cluster = Some(ms);
let mut head = Vec::new();
uint(&mut head, id::TIMECODE, ms);
self.buffer.extend_from_slice(&head);
ms
}
};
let offset = i64::try_from(ms).unwrap_or(i64::MAX) - i64::try_from(start).unwrap_or(0);
let offset = offset.clamp(i64::from(i16::MIN), i64::from(i16::MAX)) as i16;
put_id(&mut self.buffer, id::SIMPLE_BLOCK);
put_size(&mut self.buffer, data.len() as u64 + 4);
// Track number as a one-byte EBML varint (at most 127 tracks).
self.buffer.push(0x80 | (track as u8 + 1));
self.buffer.extend_from_slice(&offset.to_be_bytes());
self.buffer.push(if keyframe { 0x80 } else { 0 });
self.buffer.extend_from_slice(data);
self.blocks += 1;
Ok(())
}
fn flush_cluster(&mut self) -> Result<()> {
if self.cluster.take().is_none() || self.buffer.is_empty() {
self.buffer.clear();
return Ok(());
}
let mut head = Vec::new();
put_id(&mut head, id::CLUSTER);
put_size(&mut head, self.buffer.len() as u64);
self.out.write_all(&head)?;
self.out.write_all(&self.buffer)?;
self.bytes += (head.len() + self.buffer.len()) as u64;
self.buffer.clear();
Ok(())
}
/// Write out the open cluster, fill in the duration and return the sink.
pub fn finish(mut self) -> Result<W> {
self.flush_cluster()?;
let end = self.out.stream_position()?;
self.out.seek(SeekFrom::Start(self.duration_at))?;
self.out.write_all(&(self.last_ms as f64).to_be_bytes())?;
self.out.seek(SeekFrom::Start(end))?;
self.out.flush()?;
Ok(self.out)
}
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::*;
fn varint(size: u64) -> Vec<u8> {
let mut out = Vec::new();
put_size(&mut out, size);
out
}
#[test]
fn sizes_take_the_shortest_form() {
assert_eq!(varint(0), vec![0x80]);
assert_eq!(varint(1), vec![0x81]);
// 127 is the reserved "unknown" value of a one-byte size.
assert_eq!(varint(126), vec![0xFE]);
assert_eq!(varint(127), vec![0x40, 0x7F]);
assert_eq!(varint(0x3FFE), vec![0x7F, 0xFE]);
assert_eq!(varint(0x3FFF), vec![0x20, 0x3F, 0xFF], "the two-byte all-ones is reserved");
let mut out = Vec::new();
uint(&mut out, 0x83, 1);
assert_eq!(out, vec![0x83, 0x81, 1]);
out.clear();
uint(&mut out, 0x2AD7B1, 1_000_000);
assert_eq!(out, vec![0x2A, 0xD7, 0xB1, 0x83, 0x0F, 0x42, 0x40]);
}
#[test]
fn annex_b_is_split_and_converted() {
// SPS, PPS and an IDR, with three- and four-byte start codes.
let sps = [0x67u8, 0x42, 0x00, 0x1E, 0xAA];
let pps = [0x68u8, 0xCE, 0x3C, 0x80];
let idr = [0x65u8, 0x88, 0x84];
let mut stream = vec![0, 0, 0, 1];
stream.extend_from_slice(&sps);
stream.extend_from_slice(&[0, 0, 1]);
stream.extend_from_slice(&pps);
stream.extend_from_slice(&[0, 0, 0, 1]);
stream.extend_from_slice(&idr);
let units: Vec<&[u8]> = annex_b_units(&stream).collect();
assert_eq!(units, vec![&sps[..], &pps[..], &idr[..]]);
let record = avcc(&stream).expect("parameter sets");
assert_eq!(&record[..6], &[1, 0x42, 0x00, 0x1E, 0xFF, 0xE1]);
assert_eq!(&record[6..8], &(sps.len() as u16).to_be_bytes());
assert_eq!(&record[8..8 + sps.len()], &sps);
assert_eq!(record[8 + sps.len()], 1, "one PPS");
let mut prefixed = Vec::new();
to_length_prefixed(&stream, &mut prefixed);
assert_eq!(&prefixed[..4], &(sps.len() as u32).to_be_bytes());
assert_eq!(prefixed.len(), 12 + sps.len() + pps.len() + idr.len());
// A frame without parameter sets has no record.
assert!(avcc(&[0, 0, 1, 0x65, 1, 2]).is_none());
}
#[test]
fn a_file_has_a_header_tracks_and_clusters() {
let tracks = vec![
Track {
kind: TrackKind::Video { codec: Codec::Vp8, width: 320, height: 240 },
private: Vec::new(),
},
Track { kind: TrackKind::Opus { channels: 2 }, private: opus_head(2) },
];
let mut writer = Writer::new(Cursor::new(Vec::new()), true, tracks).unwrap();
writer.write(0, 1000, true, &[1, 2, 3]).unwrap();
writer.write(1, 1000, true, &[4, 5]).unwrap();
writer.write(0, 1033, false, &[6]).unwrap();
// A video keyframe opens a new cluster.
writer.write(0, 1066, true, &[7]).unwrap();
assert_eq!(writer.blocks(), 4);
assert_eq!(writer.duration(), std::time::Duration::from_millis(66));
let file = writer.finish().unwrap().into_inner();
// EBML header, "webm", two clusters.
assert_eq!(&file[..4], &[0x1A, 0x45, 0xDF, 0xA3]);
assert!(file.windows(4).any(|w| w == b"webm"));
assert!(file.windows(5).any(|w| w == b"V_VP8"));
assert!(file.windows(6).any(|w| w == b"A_OPUS"));
assert!(file.windows(8).any(|w| w == b"OpusHead"));
let clusters = file.windows(4).filter(|w| *w == [0x1F, 0x43, 0xB6, 0x75]).count();
assert_eq!(clusters, 2, "a keyframe starts a cluster");
// WebM refuses H.264; Matroska takes it.
let h264 = vec![Track {
kind: TrackKind::Video { codec: Codec::H264, width: 16, height: 16 },
private: vec![1, 2, 3],
}];
assert!(Writer::new(Cursor::new(Vec::new()), true, h264.clone()).is_err());
let mut writer = Writer::new(Cursor::new(Vec::new()), false, h264).unwrap();
writer.write(0, 0, true, &[9]).unwrap();
assert!(writer.write(1, 0, true, &[9]).is_err(), "no track 1");
let file = writer.finish().unwrap().into_inner();
assert!(file.windows(8).any(|w| w == b"matroska"));
assert!(file.windows(15).any(|w| w == b"V_MPEG4/ISO/AVC"));
assert!(Writer::new(Cursor::new(Vec::new()), false, Vec::new()).is_err());
}
}
@@ -0,0 +1,122 @@
//! Where the studio's encoded packets go besides the stream.
//!
//! The streamer already encodes every layer; an [`OutputSink`] is fed the
//! same packets, so recording, the replay buffer and WHIP cost no second
//! encode and work whether or not the stream is live.
//!
//! - [`record`]: a file, WebM or Matroska ([`ebml`])
//! - [`replay`]: the last few seconds in memory (spilling to disk), written
//! out as a clip without re-encoding
//! - `whip`: WHIP (WebRTC-HTTP ingestion) to a broadcast service
//! - [`rtmp`]: the seam for RTMP, which will go through the FFmpeg loader
//!
//! A sink never stalls the encoder: [`OutputSink::write`] returns an error
//! instead of blocking for long, and the studio drops the sink and reports
//! it.
use crate::Result;
use crate::codec::Codec;
pub mod ebml;
pub mod record;
pub mod replay;
pub mod rtmp;
/// Which stream a packet belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Track {
/// One simulcast layer's video.
Video { codec: Codec, layer: u32 },
/// The studio's audio: Opus, 48 kHz.
Audio { channels: u16 },
}
impl Track {
pub fn is_video(&self) -> bool {
matches!(self, Self::Video { .. })
}
pub fn layer(&self) -> u32 {
match self {
Self::Video { layer, .. } => *layer,
Self::Audio { .. } => u32::MAX,
}
}
}
/// One encoded packet on its way out of the studio.
#[derive(Clone, Copy, Debug)]
pub struct Packet<'a> {
pub track: Track,
/// Presentation time on the 90 kHz clock, as RTP carries it.
pub pts_90khz: u64,
/// Video: a frame that stands alone. Audio: always true.
pub keyframe: bool,
/// Size of the picture this packet belongs to (video only, 0 otherwise).
pub width: u32,
pub height: u32,
pub data: &'a [u8],
}
impl Packet<'_> {
/// The packet's time in milliseconds.
pub fn ms(&self) -> u64 {
self.pts_90khz * 1000 / 90_000
}
}
/// Something fed with the studio's encoded packets.
///
/// Every method runs on the encoder's thread, so none of them may block for
/// long; work that can wait belongs on the sink's own thread.
pub trait OutputSink: Send {
/// For logs, stats and the controller's events.
fn name(&self) -> &str;
/// Whether this sink wants `track` at all. A recording takes one layer;
/// WHIP may take another.
fn wants(&self, track: Track) -> bool {
let _ = track;
true
}
/// Whether the sink needs a keyframe now (it has just started, or it
/// dropped packets).
fn needs_keyframe(&mut self) -> bool {
false
}
/// Take one packet.
fn write(&mut self, packet: &Packet<'_>) -> Result<()>;
/// Close the file, tear the session down. Called once.
fn finish(&mut self) -> Result<()> {
Ok(())
}
/// Bytes written so far, for the stats.
fn bytes(&self) -> u64 {
0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn packet_times_and_tracks() {
let packet = Packet {
track: Track::Video { codec: Codec::Vp8, layer: 2 },
pts_90khz: 90_000 * 3 / 2,
keyframe: true,
width: 8,
height: 6,
data: &[1],
};
assert_eq!(packet.ms(), 1500);
assert!(packet.track.is_video());
assert_eq!(packet.track.layer(), 2);
assert!(!Track::Audio { channels: 2 }.is_video());
}
}
@@ -0,0 +1,305 @@
//! Recording the studio to a file, without re-encoding.
//!
//! 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.
use std::fs::File;
use std::io::BufWriter;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tracing::debug;
use crate::codec::Codec;
use crate::studio::output::ebml::{self, Track as MkvTrack, TrackKind, Writer};
use crate::studio::output::{OutputSink, Packet, Track};
use crate::{Error, Result};
/// The container a recording is written in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Format {
/// VP8, VP9, AV1 and Opus.
#[default]
WebM,
/// Also H.264 and H.265.
Matroska,
}
impl Format {
/// The format a file name asks for: `.webm`, or `.mkv` / `.mka`.
pub fn of_path(path: &Path) -> Result<Self> {
match path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {
Some("webm") => Ok(Self::WebM),
Some("mkv" | "mka" | "matroska") => Ok(Self::Matroska),
_ => Err(Error::InvalidFrame(format!(
"cannot tell the recording format of {}: use .webm or .mkv",
path.display()
))),
}
}
/// The format that can hold `codec`, preferring what `wanted` asks for.
pub fn for_codec(wanted: Self, codec: Codec) -> Self {
match codec {
Codec::Vp8 | Codec::Vp9 | Codec::Av1 => wanted,
// WebM has no place for these.
Codec::H264 | Codec::H265 => Self::Matroska,
}
}
}
/// Writes the studio's packets to a file; see the [module docs](self).
pub struct Recorder {
path: PathBuf,
name: String,
format: Format,
/// The layer recorded; other layers are ignored.
layer: u32,
channels: u16,
writer: Option<Writer<BufWriter<File>>>,
/// Set until the first keyframe opened the file.
waiting: bool,
/// H.264 frames are rewritten length-prefixed.
scratch: Vec<u8>,
video: Option<Codec>,
}
impl Recorder {
/// Start recording `layer` to `path`. The container comes from the file
/// name; a codec WebM cannot hold moves the recording to Matroska (and
/// the file keeps the name it was given).
pub fn start(path: impl Into<PathBuf>, layer: u32, channels: u16) -> Result<Self> {
let path = path.into();
let format = Format::of_path(&path)?;
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent)?;
}
// Fail now rather than at the first keyframe if the path is bad.
File::create(&path)?;
let name = path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());
Ok(Self {
path,
name,
format,
layer,
channels: channels.clamp(1, 8),
writer: None,
waiting: true,
scratch: Vec::new(),
video: None,
})
}
pub fn path(&self) -> &Path {
&self.path
}
/// What the file actually holds (a codec WebM cannot hold moved it).
pub fn format(&self) -> Format {
self.format
}
/// Whether the first keyframe arrived and the file is being written.
pub fn started(&self) -> bool {
self.writer.is_some()
}
/// Length of the recording so far.
pub fn duration(&self) -> Duration {
self.writer.as_ref().map_or(Duration::ZERO, Writer::duration)
}
/// Open the file on the first keyframe of the recorded layer.
fn open(&mut self, packet: &Packet<'_>, codec: Codec) -> Result<()> {
let private = if codec == Codec::H264 {
ebml::avcc(packet.data).ok_or_else(|| Error::Encoder {
codec,
message: "the keyframe carries no parameter sets to record".into(),
})?
} else {
Vec::new()
};
self.format = Format::for_codec(self.format, codec);
let tracks = vec![
MkvTrack {
kind: TrackKind::Video {
codec,
width: packet.width.max(2),
height: packet.height.max(2),
},
private,
},
MkvTrack {
kind: TrackKind::Opus { channels: self.channels },
private: ebml::opus_head(self.channels),
},
];
let file = BufWriter::new(File::create(&self.path)?);
let writer = Writer::new(file, self.format == Format::WebM, tracks)?;
debug!(path = %self.path.display(), %codec, format = ?self.format, "recording");
self.writer = Some(writer);
self.waiting = false;
self.video = Some(codec);
Ok(())
}
}
impl OutputSink for Recorder {
fn name(&self) -> &str {
&self.name
}
fn wants(&self, track: Track) -> bool {
match track {
Track::Video { layer, .. } => layer == self.layer,
Track::Audio { .. } => true,
}
}
fn needs_keyframe(&mut self) -> bool {
self.waiting
}
fn write(&mut self, packet: &Packet<'_>) -> Result<()> {
let (index, codec) = match packet.track {
Track::Video { codec, layer } if layer == self.layer => (0, Some(codec)),
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(()) };
self.open(packet, codec)?;
}
let Some(writer) = &mut self.writer else { return Ok(()) };
// A codec change mid-recording would need a new file.
if let Some(codec) = codec
&& self.video != Some(codec)
{
return Err(Error::Encoder {
codec,
message: "the codec changed while recording; stop and start again".into(),
});
}
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, packet.data)
}
fn finish(&mut self) -> Result<()> {
let Some(writer) = self.writer.take() else { return Ok(()) };
let blocks = writer.blocks();
let file = writer.finish()?;
drop(file);
debug!(path = %self.path.display(), blocks, "recording finished");
Ok(())
}
fn bytes(&self) -> u64 {
self.writer.as_ref().map_or(0, Writer::bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"voelin-studio-{name}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn video(layer: u32, ms: u64, keyframe: bool, data: &[u8]) -> Packet<'_> {
Packet {
track: Track::Video { codec: Codec::Vp8, layer },
pts_90khz: ms * 90,
keyframe,
width: 320,
height: 240,
data,
}
}
#[test]
fn formats_come_from_the_name_and_the_codec() {
assert_eq!(Format::of_path(Path::new("a.webm")).unwrap(), Format::WebM);
assert_eq!(Format::of_path(Path::new("a.MKV")).unwrap(), Format::Matroska);
assert!(Format::of_path(Path::new("a.mp4")).is_err());
assert!(Format::of_path(Path::new("a")).is_err());
assert_eq!(Format::for_codec(Format::WebM, Codec::Vp9), Format::WebM);
assert_eq!(Format::for_codec(Format::WebM, Codec::H264), Format::Matroska);
}
#[test]
fn recording_starts_at_a_keyframe() {
let dir = dir("record");
let path = dir.join("clip.webm");
let mut recorder = Recorder::start(&path, 0, 2).unwrap();
assert!(recorder.needs_keyframe());
// Before the first keyframe nothing is written.
recorder.write(&video(0, 0, false, &[1, 2])).unwrap();
recorder
.write(&Packet { track: Track::Audio { channels: 2 }, ..video(0, 0, true, &[9]) })
.unwrap();
assert!(!recorder.started());
// Another layer is ignored even when it is a keyframe.
assert!(!recorder.wants(Track::Video { codec: Codec::Vp8, layer: 1 }));
recorder.write(&video(1, 10, true, &[3])).unwrap();
assert!(!recorder.started());
recorder.write(&video(0, 100, true, &[1, 2, 3])).unwrap();
assert!(recorder.started() && !recorder.needs_keyframe());
for ms in (133..1000).step_by(33) {
recorder.write(&video(0, ms, false, &[4, 5])).unwrap();
recorder
.write(&Packet {
track: Track::Audio { channels: 2 },
pts_90khz: ms * 90,
keyframe: true,
width: 0,
height: 0,
data: &[7, 7, 7],
})
.unwrap();
}
// The file's clock starts at the first keyframe, not at zero.
assert!(recorder.duration() >= Duration::from_millis(800));
recorder.finish().unwrap();
let written = std::fs::read(&path).unwrap();
assert!(written.len() > 100, "{} bytes", written.len());
assert!(written.windows(4).any(|w| w == b"webm"));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_codec_change_stops_the_recording() {
let dir = dir("codec-change");
let path = dir.join("clip.mkv");
let mut recorder = Recorder::start(&path, 0, 2).unwrap();
recorder.write(&video(0, 0, true, &[1])).unwrap();
let mut other = video(0, 33, false, &[2]);
other.track = Track::Video { codec: Codec::Vp9, layer: 0 };
assert!(recorder.write(&other).is_err());
recorder.finish().unwrap();
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn an_unwritable_path_fails_at_once() {
assert!(Recorder::start("/nonexistent-root-dir/x/clip.webm", 0, 2).is_err());
assert!(Recorder::start("clip.mp4", 0, 2).is_err());
}
}
@@ -0,0 +1,488 @@
//! The replay buffer: the last few seconds, kept encoded.
//!
//! Every packet is kept until it falls out of the window
//! (`studio.replay_seconds`, no maximum), and the window always reaches back
//! to a keyframe, so [`ReplayBuffer::save_clip`] can write a playable file
//! without re-encoding anything.
//!
//! Long windows do not have to fit in memory: past
//! `studio.replay_memory_mb` the oldest packets are moved to a temporary
//! file and only their offsets stay in memory. The file is emptied again
//! whenever every packet in it has aged out, so a buffer that briefly
//! overflowed does not keep the disk space.
use std::collections::VecDeque;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;
use tracing::debug;
use crate::codec::Codec;
use crate::studio::output::record::Recorder;
use crate::studio::output::{OutputSink, Packet, Track};
use crate::{Error, Result};
/// Where a kept packet's bytes are.
enum Data {
Memory(Vec<u8>),
Spilled { offset: u64, len: u32 },
}
/// One kept packet.
struct Entry {
track: Track,
pts_90khz: u64,
keyframe: bool,
width: u32,
height: u32,
data: Data,
}
/// The temporary file holding packets that no longer fit in memory.
struct Spill {
path: PathBuf,
file: File,
/// Bytes written so far (the next offset).
end: u64,
/// Packets still in it.
entries: usize,
}
impl Drop for Spill {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
/// What the buffer holds right now.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ReplayStats {
pub packets: u64,
/// How far back the buffer reaches.
pub duration: Duration,
pub memory_bytes: u64,
pub spilled_bytes: u64,
/// Clips written.
pub clips: u64,
}
/// The rolling buffer of encoded packets; see the [module docs](self).
pub struct ReplayBuffer {
length: Duration,
memory_limit: u64,
layer: u32,
channels: u16,
entries: VecDeque<Entry>,
memory: u64,
spill: Option<Spill>,
/// Where the temporary file goes.
spill_dir: PathBuf,
codec: Option<Codec>,
clips: u64,
needs_keyframe: bool,
}
impl ReplayBuffer {
/// A buffer holding `length` of `layer` (0 turns it off) with at most
/// `memory_mb` megabytes in memory before it spills to disk.
pub fn new(length: Duration, memory_mb: u64, layer: u32, channels: u16) -> Self {
Self {
length,
memory_limit: memory_mb.saturating_mul(1 << 20),
layer,
channels: channels.clamp(1, 8),
entries: VecDeque::new(),
memory: 0,
spill: None,
spill_dir: std::env::temp_dir(),
codec: None,
clips: 0,
needs_keyframe: true,
}
}
/// Where the spill file goes (the system's temporary directory by
/// default).
pub fn with_spill_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.spill_dir = dir.into();
self
}
/// How far back the buffer keeps packets; 0 turns it off and frees what
/// it holds. There is no maximum.
pub fn set_length(&mut self, length: Duration) {
self.length = length;
if length.is_zero() {
self.clear();
} else {
self.trim();
}
}
pub fn length(&self) -> Duration {
self.length
}
/// Megabytes kept in memory before older packets go to disk.
pub fn set_memory_mb(&mut self, memory_mb: u64) {
self.memory_limit = memory_mb.saturating_mul(1 << 20);
let _ = self.spill_over_limit();
}
pub fn is_on(&self) -> bool {
!self.length.is_zero()
}
pub fn clear(&mut self) {
self.entries.clear();
self.memory = 0;
self.spill = None;
self.needs_keyframe = true;
}
pub fn stats(&self) -> ReplayStats {
let first = self.entries.front().map_or(0, |e| e.pts_90khz);
let last = self.entries.back().map_or(0, |e| e.pts_90khz);
ReplayStats {
packets: self.entries.len() as u64,
duration: Duration::from_micros(last.saturating_sub(first) * 1_000_000 / 90_000),
memory_bytes: self.memory,
spilled_bytes: self.spill.as_ref().map_or(0, |s| s.end),
clips: self.clips,
}
}
/// Drop packets older than the window, never past the keyframe the
/// window starts in.
fn trim(&mut self) {
let Some(newest) = self.entries.back().map(|e| e.pts_90khz) else { return };
let window = (self.length.as_micros() as u64).saturating_mul(90_000) / 1_000_000;
let cutoff = newest.saturating_sub(window);
// The last video keyframe at or before the cutoff: everything before
// it can go.
let keep = self
.entries
.iter()
.enumerate()
.rfind(|(_, e)| e.keyframe && e.track.is_video() && e.pts_90khz <= cutoff)
.map(|(i, _)| i);
let Some(keep) = keep else { return };
let dropped: Vec<Data> = self.entries.drain(..keep).map(|e| e.data).collect();
for data in &dropped {
self.release(data);
}
self.reset_spill();
}
/// Account for an entry that is gone.
fn release(&mut self, data: &Data) {
match data {
Data::Memory(bytes) => self.memory = self.memory.saturating_sub(bytes.len() as u64),
Data::Spilled { .. } => {
if let Some(spill) = &mut self.spill {
spill.entries -= 1;
}
}
}
}
/// Throw the spill file away once nothing in it is kept any more.
fn reset_spill(&mut self) {
if self.spill.as_ref().is_some_and(|s| s.entries == 0) {
self.spill = None;
}
}
/// Move the oldest in-memory packets to disk until memory is within the
/// limit.
fn spill_over_limit(&mut self) -> Result<()> {
if self.memory <= self.memory_limit {
return Ok(());
}
for index in 0..self.entries.len() {
if self.memory <= self.memory_limit {
break;
}
let Data::Memory(bytes) = &self.entries[index].data else { continue };
let len = bytes.len();
let spill = match &mut self.spill {
Some(spill) => spill,
None => {
let path = self.spill_dir.join(format!(
"voelin-replay-{}-{:?}.bin",
std::process::id(),
std::thread::current().id()
));
let file = File::options()
.create(true)
.truncate(true)
.read(true)
.write(true)
.open(&path)?;
debug!(path = %path.display(), "replay buffer spilling to disk");
self.spill.insert(Spill { path, file, end: 0, entries: 0 })
}
};
let offset = spill.end;
// Take the bytes out before writing, so a failed write drops the
// packet rather than leaving it counted twice.
let Data::Memory(bytes) = std::mem::replace(
&mut self.entries[index].data,
Data::Spilled { offset, len: len as u32 },
) else {
unreachable!("checked above")
};
spill.file.seek(SeekFrom::Start(offset))?;
spill.file.write_all(&bytes)?;
spill.end += len as u64;
spill.entries += 1;
self.memory -= len as u64;
}
Ok(())
}
/// The bytes of one kept packet, into `out`.
fn read(&mut self, index: usize, out: &mut Vec<u8>) -> Result<()> {
out.clear();
match &self.entries[index].data {
Data::Memory(bytes) => out.extend_from_slice(bytes),
Data::Spilled { offset, len } => {
let (offset, len) = (*offset, *len as usize);
let Some(spill) = &mut self.spill else {
return Err(Error::InvalidFrame("the replay spill file is gone".into()));
};
out.resize(len, 0);
spill.file.seek(SeekFrom::Start(offset))?;
spill.file.read_exact(out)?;
}
}
Ok(())
}
/// Write everything the buffer holds, from its first keyframe, to
/// `path`; the container comes from the file name. Returns how long the
/// clip is.
///
/// The buffer keeps its packets, so several clips can be saved from one
/// window.
pub fn save_clip(&mut self, path: impl AsRef<Path>) -> Result<Duration> {
let path = path.as_ref();
if !self.is_on() {
return Err(Error::InvalidFrame(
"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()),
)?;
let mut recorder = Recorder::start(path, self.layer, self.channels)?;
let mut bytes = Vec::new();
for index in start..self.entries.len() {
self.read(index, &mut bytes)?;
let entry = &self.entries[index];
recorder.write(&Packet {
track: entry.track,
pts_90khz: entry.pts_90khz,
keyframe: entry.keyframe,
width: entry.width,
height: entry.height,
data: &bytes,
})?;
}
let length = recorder.duration();
recorder.finish()?;
self.clips += 1;
debug!(path = %path.display(), ?length, "replay clip saved");
Ok(length)
}
}
impl OutputSink for ReplayBuffer {
fn name(&self) -> &str {
"replay"
}
fn wants(&self, track: Track) -> bool {
match track {
Track::Video { layer, .. } => layer == self.layer,
Track::Audio { .. } => true,
}
}
fn needs_keyframe(&mut self) -> bool {
self.is_on() && self.needs_keyframe
}
fn write(&mut self, packet: &Packet<'_>) -> Result<()> {
if !self.is_on() || !self.wants(packet.track) {
return Ok(());
}
if let Track::Video { codec, .. } = packet.track {
// A codec change makes everything before it unplayable.
if self.codec.is_some_and(|c| c != codec) {
self.clear();
}
self.codec = Some(codec);
if packet.keyframe {
self.needs_keyframe = false;
}
}
// 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(());
}
self.entries.push_back(Entry {
track: packet.track,
pts_90khz: packet.pts_90khz,
keyframe: packet.keyframe,
width: packet.width,
height: packet.height,
data: Data::Memory(packet.data.to_vec()),
});
self.memory += packet.data.len() as u64;
self.trim();
self.spill_over_limit()
}
fn bytes(&self) -> u64 {
self.memory + self.spill.as_ref().map_or(0, |s| s.end)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn video(ms: u64, keyframe: bool, len: usize) -> (Vec<u8>, u64, bool) {
(vec![(ms % 251) as u8; len], ms, keyframe)
}
fn push(buffer: &mut ReplayBuffer, ms: u64, keyframe: bool, len: usize) {
let (data, ms, keyframe) = video(ms, keyframe, len);
buffer
.write(&Packet {
track: Track::Video { codec: Codec::Vp8, layer: 0 },
pts_90khz: ms * 90,
keyframe,
width: 320,
height: 240,
data: &data,
})
.unwrap();
}
fn dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"voelin-replay-{name}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn it_starts_at_a_keyframe_and_keeps_the_window() {
let mut buffer = ReplayBuffer::new(Duration::from_secs(2), 64, 0, 2);
assert!(buffer.is_on() && buffer.needs_keyframe());
// Nothing before the first keyframe.
for ms in [0, 33, 66] {
push(&mut buffer, ms, false, 10);
}
assert_eq!(buffer.stats().packets, 0);
push(&mut buffer, 100, true, 100);
assert!(!buffer.needs_keyframe());
// Five seconds at 30 fps with a keyframe every second.
for n in 1..150u64 {
let ms = 100 + n * 33;
push(&mut buffer, ms, n.is_multiple_of(30), 10);
}
let stats = buffer.stats();
// The window reaches back to the keyframe that covers it: at most a
// keyframe interval more than the two seconds asked for.
assert!(
stats.duration >= Duration::from_secs(2) && stats.duration <= Duration::from_secs(3),
"{stats:?}"
);
assert_eq!(stats.spilled_bytes, 0, "everything fits in memory");
}
#[test]
fn it_spills_to_disk_and_comes_back() {
let dir = dir("spill");
// A tiny memory limit: almost everything goes to the file.
let mut buffer = ReplayBuffer::new(Duration::from_secs(4), 0, 0, 2).with_spill_dir(&dir);
push(&mut buffer, 0, true, 4096);
for n in 1..120u64 {
push(&mut buffer, n * 33, n.is_multiple_of(30), 4096);
}
let stats = buffer.stats();
assert!(stats.spilled_bytes > 0, "{stats:?}");
assert!(stats.memory_bytes < stats.spilled_bytes, "{stats:?}");
assert_eq!(buffer.bytes(), stats.memory_bytes + stats.spilled_bytes);
// The clip reads the spilled packets back.
let clip = dir.join("clip.webm");
let length = buffer.save_clip(&clip).unwrap();
assert!(length >= Duration::from_secs(3), "{length:?}");
let written = std::fs::read(&clip).unwrap();
assert!(written.len() > 4096 * 50, "{} bytes", written.len());
assert!(written.windows(4).any(|w| w == b"webm"));
// The buffer still holds everything.
assert_eq!(buffer.stats().packets, stats.packets);
assert_eq!(buffer.stats().clips, 1);
// Turning it off frees everything, including the file.
buffer.set_length(Duration::ZERO);
assert_eq!(buffer.stats(), ReplayStats { clips: 1, ..ReplayStats::default() });
assert!(buffer.save_clip(&clip).is_err(), "a buffer that is off saves nothing");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_window_that_shrinks_drops_the_old_packets() {
let mut buffer = ReplayBuffer::new(Duration::from_secs(10), 64, 0, 2);
push(&mut buffer, 0, true, 100);
for n in 1..300u64 {
push(&mut buffer, n * 33, n.is_multiple_of(30), 100);
}
let before = buffer.stats().packets;
buffer.set_length(Duration::from_secs(1));
let after = buffer.stats().packets;
assert!(after < before / 4, "{before} -> {after}");
assert!(buffer.stats().duration <= Duration::from_secs(2));
// The first packet kept is still a keyframe.
assert!(buffer.entries.front().is_some_and(|e| e.keyframe));
}
#[test]
fn a_codec_change_starts_over() {
let mut buffer = ReplayBuffer::new(Duration::from_secs(5), 64, 0, 2);
push(&mut buffer, 0, true, 100);
push(&mut buffer, 33, false, 100);
assert_eq!(buffer.stats().packets, 2);
buffer
.write(&Packet {
track: Track::Video { codec: Codec::Vp9, layer: 0 },
pts_90khz: 66 * 90,
keyframe: true,
width: 320,
height: 240,
data: &[1, 2, 3],
})
.unwrap();
assert_eq!(buffer.stats().packets, 1, "the VP8 packets were dropped");
}
#[test]
fn other_layers_are_left_alone() {
let buffer = ReplayBuffer::new(Duration::from_secs(1), 64, 1, 2);
assert!(!buffer.wants(Track::Video { codec: Codec::Vp8, layer: 0 }));
assert!(buffer.wants(Track::Video { codec: Codec::Vp8, layer: 1 }));
assert!(buffer.wants(Track::Audio { channels: 2 }));
assert_eq!(buffer.name(), "replay");
}
}
@@ -0,0 +1,71 @@
//! RTMP: the seam only.
//!
//! RTMP will go out through the FFmpeg libraries the crate already loads at
//! runtime ([`crate::ffmpeg`]): `libavformat` speaks `rtmp://` and
//! `rtmps://`, so the studio will hand it the same encoded packets it hands
//! every other output and never link or ship an RTMP stack of its own.
//!
//! What is missing is the muxer side of that loader (`avformat_alloc_output_
//! context2`, `av_interleaved_write_frame` and the bitstream filters H.264
//! and AAC need in FLV). Until then [`Rtmp::connect`] says so rather than
//! pretending, so a scene file or a `voelinctl` command that names an RTMP
//! output fails with a reason instead of silently dropping the stream.
use crate::studio::output::{OutputSink, Packet, Track};
use crate::{Error, Result};
/// An RTMP output. Not implemented yet; see the [module docs](self).
#[derive(Debug)]
pub struct Rtmp {
url: String,
}
impl Rtmp {
/// Whether `url` is one this output would take.
pub fn handles(url: &str) -> bool {
url.starts_with("rtmp://") || url.starts_with("rtmps://")
}
/// Always fails for now, with what is missing.
pub fn connect(url: &str, _key: Option<&str>) -> Result<Self> {
Err(Error::CodecUnavailable {
codec: crate::codec::Codec::H264,
reason: format!(
"RTMP ({url}) needs the muxing side of the FFmpeg loader, which is not \
written yet; record to a file or use WHIP"
),
})
}
pub fn url(&self) -> &str {
&self.url
}
}
impl OutputSink for Rtmp {
fn name(&self) -> &str {
&self.url
}
fn wants(&self, _track: Track) -> bool {
true
}
fn write(&mut self, _packet: &Packet<'_>) -> Result<()> {
Err(Error::Capture { backend: "rtmp", message: "RTMP is not implemented".into() })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rtmp_urls_are_recognised_but_refused() {
assert!(Rtmp::handles("rtmp://live.example/app"));
assert!(Rtmp::handles("rtmps://live.example/app"));
assert!(!Rtmp::handles("https://example/whip"));
let e = Rtmp::connect("rtmp://live.example/app", Some("key")).unwrap_err().to_string();
assert!(e.contains("FFmpeg"), "{e}");
}
}
+200
View File
@@ -0,0 +1,200 @@
//! The studio's recording and replay outputs against a real encoder and a
//! real demuxer: frames the test pattern produces are encoded, written to
//! WebM and read back with `ffprobe` (skipped where it is not installed).
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use voelin_media::codec::{Codec, Codecs, EncoderConfig};
use voelin_media::frame::VideoFrame;
use voelin_media::studio::output::record::Recorder;
use voelin_media::studio::output::replay::ReplayBuffer;
use voelin_media::studio::output::{OutputSink, Packet, Track};
const WIDTH: u32 = 320;
const HEIGHT: u32 = 240;
const FPS: u64 = 30;
fn dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-studio-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// A moving picture, so the encoder has something to encode.
fn frame(n: u64) -> VideoFrame {
let mut frame = VideoFrame::black_i420(WIDTH, HEIGHT);
let voelin_media::frame::FrameData::I420 { y, .. } = &mut frame.data else { unreachable!() };
let x0 = (n * 4 % u64::from(WIDTH - 40)) as usize;
for row in 40..120 {
y.data[row * y.stride + x0..][..40].fill(200);
}
frame.timestamp = Duration::from_micros(n * 1_000_000 / FPS);
frame
}
/// Encode `frames` pictures with `codec` and hand every packet to `sink`.
/// Returns how many keyframes came out.
fn encode_into(codec: Codec, frames: u64, sink: &mut dyn OutputSink) -> u64 {
let codecs = Codecs::new();
let mut encoder = codecs
.new_encoder(
codec,
EncoderConfig { fps: FPS as u32, bitrate_bps: 800_000, ..EncoderConfig::default() },
)
.expect("an encoder for the test codec");
let mut keyframes = 0;
for n in 0..frames {
let picture = frame(n);
// A keyframe every second, as a stream would have.
let force = n.is_multiple_of(FPS);
encoder
.encode_with(&picture, force, &mut |chunk| {
keyframes += u64::from(chunk.keyframe);
sink.write(&Packet {
track: Track::Video { codec, layer: 0 },
pts_90khz: chunk.pts_90khz,
keyframe: chunk.keyframe,
width: WIDTH,
height: HEIGHT,
data: chunk.data,
})
.expect("the sink took the packet");
})
.expect("encoded");
// 20 ms of "Opus" per two pictures, so the audio track is used too.
if n.is_multiple_of(2) {
sink.write(&Packet {
track: Track::Audio { channels: 2 },
pts_90khz: n * 90_000 / FPS,
keyframe: true,
width: 0,
height: 0,
data: &[0xFC, 0xFF, 0xFE],
})
.expect("the sink took the audio packet");
}
}
keyframes
}
/// `ffprobe -show_streams` of `path`, or `None` if ffprobe is not installed.
fn ffprobe(path: &Path) -> Option<String> {
let out = Command::new("ffprobe")
.args([
"-v",
"error",
"-show_entries",
"stream=codec_name,codec_type,width,height:format=format_name,duration",
"-of",
"default=noprint_wrappers=1",
])
.arg(path)
.output()
.ok()?;
assert!(
out.status.success(),
"ffprobe rejected {}: {}",
path.display(),
String::from_utf8_lossy(&out.stderr)
);
assert!(
out.stderr.is_empty(),
"ffprobe complained about {}: {}",
path.display(),
String::from_utf8_lossy(&out.stderr)
);
Some(String::from_utf8_lossy(&out.stdout).into_owned())
}
#[test]
fn a_recording_is_a_webm_ffprobe_reads() {
let codec = Codec::Vp8;
if Codecs::new().new_encoder(codec, EncoderConfig::default()).is_err() {
eprintln!("skipped: no VP8 encoder in this build");
return;
}
let dir = dir("record");
let path = dir.join("recording.webm");
let mut recorder = Recorder::start(&path, 0, 2).unwrap();
let keyframes = encode_into(codec, 90, &mut recorder);
assert!(keyframes >= 3, "only {keyframes} keyframes");
assert!(recorder.duration() >= Duration::from_millis(2800), "{:?}", recorder.duration());
assert!(recorder.bytes() > 1000);
recorder.finish().unwrap();
let Some(probe) = ffprobe(&path) else {
eprintln!("skipped the ffprobe check: ffprobe is not installed");
std::fs::remove_dir_all(&dir).ok();
return;
};
println!("{probe}");
assert!(probe.contains("codec_name=vp8"), "{probe}");
assert!(probe.contains("codec_type=video"), "{probe}");
assert!(probe.contains("codec_name=opus"), "{probe}");
assert!(probe.contains(&format!("width={WIDTH}")), "{probe}");
assert!(probe.contains(&format!("height={HEIGHT}")), "{probe}");
assert!(probe.contains("format_name=matroska,webm"), "{probe}");
let duration: f64 = probe
.lines()
.find_map(|l| l.strip_prefix("duration="))
.and_then(|d| d.parse().ok())
.unwrap_or(0.0);
assert!(duration > 2.5, "the file says it is {duration} s long");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_replay_clip_starts_at_a_keyframe_and_plays() {
let codec = Codec::Vp8;
if Codecs::new().new_encoder(codec, EncoderConfig::default()).is_err() {
eprintln!("skipped: no VP8 encoder in this build");
return;
}
let dir = dir("replay");
// Two seconds kept out of five encoded, spilling at once (0 MB memory).
let mut buffer = ReplayBuffer::new(Duration::from_secs(2), 0, 0, 2).with_spill_dir(&dir);
encode_into(codec, 150, &mut buffer);
let stats = buffer.stats();
assert!(stats.spilled_bytes > 0, "{stats:?}");
assert!(stats.duration >= Duration::from_secs(2), "{stats:?}");
// Five seconds went in, at most three come out (two plus the keyframe
// interval the window starts in).
assert!(stats.duration <= Duration::from_secs(3), "{stats:?}");
let clip = dir.join("clip.webm");
let length = buffer.save_clip(&clip).unwrap();
assert!(length >= Duration::from_secs(2), "{length:?}");
// Saving does not empty the buffer.
assert_eq!(buffer.stats().packets, stats.packets);
let Some(probe) = ffprobe(&clip) else {
eprintln!("skipped the ffprobe check: ffprobe is not installed");
std::fs::remove_dir_all(&dir).ok();
return;
};
println!("{probe}");
assert!(probe.contains("codec_name=vp8"), "{probe}");
// The clip decodes from its first frame: ffmpeg would report errors on
// stderr (which `ffprobe` asserts is empty) if it started mid-picture.
let frames = Command::new("ffprobe")
.args([
"-v",
"error",
"-count_frames",
"-select_streams",
"v:0",
"-show_entries",
"stream=nb_read_frames",
"-of",
"default=noprint_wrappers=1:nokey=1",
])
.arg(&clip)
.output()
.expect("ffprobe ran");
assert!(frames.stderr.is_empty(), "{}", String::from_utf8_lossy(&frames.stderr));
let decoded: u64 = String::from_utf8_lossy(&frames.stdout).trim().parse().unwrap_or_default();
assert!(decoded >= 60, "only {decoded} frames decoded from the clip");
std::fs::remove_dir_all(&dir).ok();
}