voelin-core: stream the studio and keep its scenes in the settings

The studio composites, but nothing yet made its picture a stream or fed
its recording and replay buffer. Streamer::start_studio does both with the
smallest change to the streamer: the studio is one more capture backend,
and the packets the encoders already make are teed to the studio's outputs
where they are produced, with the frame size the recorder needs. Only the
stream codec's encoder is teed; a codec a viewer chose is never recorded.

Recording and the replay buffer must not need a live stream, so a studio's
streamer always has a sink: while no stream is attached it is one that
drops the frames after the tee. Its audio clock starts at the studio's
epoch, the clock the composite's timestamps already count from, so a
recording's audio and video start together (the test checks they do).

Outputs ask for keyframes of the layer they take only. The replay buffer
asks every two seconds while it is on: the encoders make keyframes only on
request, so without that the window could never move past the first one
and would grow for the whole session. WHIP asks once per need (start,
session up, the service's PLI) instead of on every frame until connected,
which would have made every frame a keyframe while ICE came up.

voelin_core::studio re-exports the studio, starts it from studio.scenes and
keeps the two in step both ways without echoes; studio.replay_seconds,
studio.replay_memory_mb and studio.recording_dir join the built-in keys
(with feature media). tests/studio.rs records a stream that switches scenes
live and saves a clip, and decodes both with ffmpeg: red before the switch,
blue after it, VP8 and Opus in sync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 02:02:40 +03:00
1 parent 4e270576ce
commit abe5e4ef74
9 files changed
+614 -36

No files matched your search

+21 -9
View File
@@ -337,6 +337,8 @@ struct Shared {
preview_frames: AtomicU64,
delivered: AtomicU64,
stop: AtomicBool,
/// What the composite's timestamps count from.
epoch: Instant,
events: broadcast::Sender<Event>,
/// The outputs, and the replay buffer which is always there (off when its
/// window is zero).
@@ -409,6 +411,7 @@ impl Studio {
preview_frames: AtomicU64::new(0),
delivered: AtomicU64::new(0),
stop: AtomicBool::new(false),
epoch: Instant::now(),
events,
outputs: Mutex::new(Vec::new()),
replay: Mutex::new(ReplayBuffer::new(Duration::ZERO, 512, 0, 2)),
@@ -460,6 +463,12 @@ impl Studio {
self.shared.preview.clone()
}
/// The instant the composite's timestamps (and so the encoded video's)
/// count from. Audio meant for the same outputs must use this clock too.
pub fn epoch(&self) -> Instant {
self.shared.epoch
}
/// The scene graph as it stands, to persist or to show.
pub fn scenes(&self) -> Scenes {
lock(&self.graph).scenes.clone()
@@ -474,10 +483,11 @@ impl Studio {
camera::list()
}
/// Which simulcast layer the file outputs and WHIP take (the streamer's
/// layer ids). Default 0.
/// Which simulcast layer the outputs and the replay buffer take (the
/// streamer's layer ids), from the next output started. Default 0.
pub fn set_layer(&self, layer: u32) {
self.shared.layer.store(layer, Ordering::Relaxed);
lock(&self.shared.replay).set_layer(layer);
}
/// A [`ScreenCapture`] backend that hands the composite to the streamer.
@@ -813,10 +823,12 @@ impl Studio {
self.shared.write_packet(packet);
}
/// Whether any output needs a keyframe now (a recording that just
/// started, a WHIP session that just connected).
pub fn needs_keyframe(&self) -> bool {
self.shared.needs_keyframe()
/// Whether an output needs a keyframe of `layer` now (a recording that
/// just started, a WHIP session that just connected, the replay buffer's
/// next clip start). Only the layer the outputs take
/// ([`Studio::set_layer`]) ever does.
pub fn needs_keyframe(&self, layer: u32) -> bool {
layer == self.shared.layer.load(Ordering::Relaxed) && self.shared.needs_keyframe()
}
/// Stop composing and close every output.
@@ -929,7 +941,6 @@ impl Shared {
fn compose_loop(shared: &Shared) {
let mut compositor = Compositor::new(0);
let mut preview = RgbaScaler::new(2);
let started = Instant::now();
let mut pacer = crate::capture::FramePacer::new(Some(15));
let mut preview_fps = 0;
let mut next = Instant::now();
@@ -942,7 +953,7 @@ fn compose_loop(shared: &Shared) {
pacer.set_fps(Some(want));
}
compositor.set_size(live.size.0, live.size.1);
let timestamp = started.elapsed();
let timestamp = shared.epoch.elapsed();
let frame = match compositor.compose(&live.scene, live.revision, &live.feeds, timestamp) {
Ok(frame) => frame,
Err(e) => {
@@ -1198,7 +1209,8 @@ mod tests {
let path = dir.join("out.webm");
studio.apply(Command::StartRecording { path: path.clone() }).await.unwrap();
assert_eq!(studio.status().recording.as_deref(), Some(path.as_path()));
assert!(studio.needs_keyframe(), "a fresh recording wants a keyframe");
assert!(studio.needs_keyframe(0), "a fresh recording wants a keyframe");
assert!(!studio.needs_keyframe(1), "but only of the layer it records");
assert!(studio.apply(Command::StartRecording { path: path.clone() }).await.is_err());
studio.apply(Command::StopRecording).await.unwrap();
assert!(studio.status().recording.is_none());
@@ -3,7 +3,10 @@
//! 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.
//! without re-encoding anything. The encoders only make keyframes when asked
//! (like WebRTC), so the buffer asks for one every [`KEYFRAME_EVERY`]: a
//! clip is then at most that much longer than the window, and the window
//! cannot grow without bound on a stream nobody asks keyframes of.
//!
//! Long windows do not have to fit in memory: past
//! `studio.replay_memory_mb` the oldest packets are moved to a temporary
@@ -24,6 +27,9 @@ use crate::studio::output::record::Recorder;
use crate::studio::output::{OutputSink, Packet, Track};
use crate::{Error, Result};
/// How far apart the buffer asks for keyframes while it is on.
pub const KEYFRAME_EVERY: Duration = Duration::from_secs(2);
/// Where a kept packet's bytes are.
enum Data {
Memory(Vec<u8>),
@@ -82,6 +88,9 @@ pub struct ReplayBuffer {
codec: Option<Codec>,
clips: u64,
needs_keyframe: bool,
/// Times (90 kHz) of the newest video packet and of the newest keyframe.
newest: u64,
last_keyframe: u64,
}
impl ReplayBuffer {
@@ -100,6 +109,8 @@ impl ReplayBuffer {
codec: None,
clips: 0,
needs_keyframe: true,
newest: 0,
last_keyframe: 0,
}
}
@@ -125,6 +136,14 @@ impl ReplayBuffer {
self.length
}
/// Keep another simulcast layer (what was kept of the old one goes).
pub fn set_layer(&mut self, layer: u32) {
if layer != self.layer {
self.layer = layer;
self.clear();
}
}
/// 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);
@@ -313,7 +332,9 @@ impl OutputSink for ReplayBuffer {
}
fn needs_keyframe(&mut self) -> bool {
self.is_on() && self.needs_keyframe
let every = KEYFRAME_EVERY.as_millis() as u64 * 90;
self.is_on()
&& (self.needs_keyframe || self.newest.saturating_sub(self.last_keyframe) >= every)
}
fn write(&mut self, packet: &Packet<'_>) -> Result<()> {
@@ -326,8 +347,10 @@ impl OutputSink for ReplayBuffer {
self.clear();
}
self.codec = Some(codec);
self.newest = packet.pts_90khz;
if packet.keyframe {
self.needs_keyframe = false;
self.last_keyframe = packet.pts_90khz;
}
}
// Nothing before the first keyframe: a clip has to start at one.
@@ -479,10 +502,37 @@ mod tests {
#[test]
fn other_layers_are_left_alone() {
let buffer = ReplayBuffer::new(Duration::from_secs(1), 64, 1, 2);
let mut 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");
buffer.set_layer(0);
assert!(buffer.wants(Track::Video { codec: Codec::Vp8, layer: 0 }));
}
#[test]
fn it_asks_for_keyframes_so_the_window_can_move() {
let mut buffer = ReplayBuffer::new(Duration::from_secs(1), 64, 0, 2);
push(&mut buffer, 0, true, 10);
let mut asked = Vec::new();
// An encoder that only makes keyframes when asked.
for n in 1..300u64 {
let ms = n * 33;
let keyframe = buffer.needs_keyframe();
if keyframe {
asked.push(ms);
}
push(&mut buffer, ms, keyframe, 10);
}
let every = KEYFRAME_EVERY.as_millis() as u64;
assert!(asked.len() >= 4, "{asked:?}");
assert!(asked.windows(2).all(|w| w[1] - w[0] >= every), "{asked:?}");
// So the window stays near its length instead of reaching back to 0.
let stats = buffer.stats();
assert!(stats.duration <= Duration::from_secs(1) + KEYFRAME_EVERY, "{stats:?}");
// Off, it asks for nothing.
buffer.set_length(Duration::ZERO);
assert!(!buffer.needs_keyframe());
}
}
+18 -9
View File
@@ -81,6 +81,9 @@ pub struct Whip {
#[derive(Default)]
struct Shared {
connected: AtomicBool,
/// A keyframe is wanted: at the start, when the session comes up, and
/// when the service asks (PLI/FIR). Taken by [`OutputSink::needs_keyframe`].
keyframe: AtomicBool,
packets: AtomicU64,
bytes: AtomicU64,
dropped: AtomicU64,
@@ -157,7 +160,8 @@ impl Whip {
let (queue, packets) = sync_channel(QUEUE);
let stop = Arc::new(AtomicBool::new(false));
let shared = Arc::new(Shared::default());
// The first frames should stand alone too.
let shared = Arc::new(Shared { keyframe: AtomicBool::new(true), ..Shared::default() });
let session = Session {
rtc,
socket,
@@ -251,8 +255,8 @@ impl OutputSink for Whip {
}
fn needs_keyframe(&mut self) -> bool {
// Until the session is up there is nobody to send a keyframe to.
!self.shared.connected.load(Ordering::Relaxed)
// Once per request, not on every frame until one arrives.
self.shared.keyframe.swap(false, Ordering::Relaxed)
}
fn write(&mut self, packet: &Packet<'_>) -> Result<()> {
@@ -357,14 +361,19 @@ impl Session {
trace!("WHIP send to {} failed: {e}", t.destination);
}
}
Ok(Output::Event(event)) => {
if let Event::IceConnectionStateChange(state) = event {
let up = state == str0m::IceConnectionState::Connected
|| state == str0m::IceConnectionState::Completed;
self.shared.connected.store(up, Ordering::Relaxed);
debug!(?state, "WHIP ICE");
Ok(Output::Event(Event::IceConnectionStateChange(state))) => {
let up = state == str0m::IceConnectionState::Connected
|| state == str0m::IceConnectionState::Completed;
if up && !self.shared.connected.swap(up, Ordering::Relaxed) {
self.shared.keyframe.store(true, Ordering::Relaxed);
}
self.shared.connected.store(up, Ordering::Relaxed);
debug!(?state, "WHIP ICE");
}
Ok(Output::Event(Event::KeyframeRequest(_))) => {
self.shared.keyframe.store(true, Ordering::Relaxed);
}
Ok(Output::Event(_)) => {}
Err(e) => {
self.fail(format!("WHIP session failed: {e}"));
return;