diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 05b768b..6b33338 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -16,7 +16,9 @@ //! [`Engine::subscribe_frames`] for the frames of watched streams. The audio //! of watched streams plays through the session's speakers by itself //! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video -//! are in [`media`] (feature `media`). +//! are in [`media`] (feature `media`), and the Stream Studio (scenes of +//! sources composited into one stream, recording, a replay buffer, WHIP) in +//! [`studio`]. //! //! Settings are a [`settings::Settings`] service: typed keys, runtime //! values stored in the client database ahead of command line, config file @@ -56,6 +58,8 @@ mod route; mod session; pub mod settings; pub mod stream; +#[cfg(feature = "media")] +pub mod studio; mod voice; use std::collections::HashMap; diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 245b4c0..6004d4a 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -1,7 +1,8 @@ //! Stream media (feature `media`): capture and encoding for our stream, //! decoding for the streams we watch. //! -//! - [`Streamer`] captures a screen or window, encodes the video with the +//! - [`Streamer`] captures a screen or window (or the Stream Studio's +//! composite, [`Streamer::start_studio`]), encodes the video with the //! codec our offer carries ([`stream_codec`], VP8 by default) in one or //! more simulcast layers ([`LayerSpec`]), and mixes any number of audio //! sources ([`AudioSourceSpec`]: desktop audio without Voelin's own @@ -31,7 +32,7 @@ use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc as std_mpsc; -use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard, PoisonError}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; @@ -52,6 +53,8 @@ use voelin_media::mix::{ }; pub use voelin_media::mix::{Level, SourceState}; use voelin_media::scale::Pyramid; +use voelin_media::studio::Studio; +use voelin_media::studio::output::{Packet, Track}; use voelin_media::{Codec, Codecs, ContentHint, EncoderConfig, FrameRef, VideoEncoder, VideoFrame}; pub use voelin_media::{EncoderBackend, EncoderPreference}; use voelin_stream::{ @@ -761,11 +764,30 @@ struct Shared { encoders: Mutex>, /// Bumped when `encoders` changes: those encoders are made again. encoders_generation: AtomicU64, + /// The studio whose composite this is ([`Streamer::start_studio`]): its + /// outputs get every packet of the stream codec, attached or not. + studio: Option>, } +/// The sink of a studio's streamer while no stream is attached: the frames +/// are still encoded, for the studio's recording and replay buffer. +struct Unattached; + +impl MediaSink for Unattached { + fn send(&self, _frame: EncodedFrame) -> bool { + true + } + + fn take_keyframe_request(&self) -> bool { + false + } +} + +static UNATTACHED: LazyLock> = LazyLock::new(|| Arc::new(Unattached)); + impl Shared { fn sink(&self) -> Option> { - lock(&self.sink).clone() + lock(&self.sink).clone().or_else(|| self.studio.as_ref().map(|_| UNATTACHED.clone())) } fn stopped(&self) -> bool { @@ -869,10 +891,33 @@ impl Streamer { /// Start capturing. Must run on a Tokio runtime (the portal talks D-Bus /// on it); may wait for the user in the portal's dialog. pub async fn start(codecs: &Codecs, config: StreamerConfig) -> Result { + Self::launch(codecs, config, None).await + } + + /// Stream `studio`'s composite ([`SourceId::Studio`]; `config.source` is + /// ignored). Unlike other sources it is encoded from the start, attached + /// or not, and every packet of the stream codec (video of the studio's + /// layer, and the audio) also goes to the studio's outputs: recording + /// and the replay buffer work without going live, and cost no second + /// encode. + pub async fn start_studio( + codecs: &Codecs, + config: StreamerConfig, + studio: Arc, + ) -> Result { + let config = StreamerConfig { source: SourceId::Studio, ..config }; + Self::launch(codecs, config, Some(studio)).await + } + + async fn launch( + codecs: &Codecs, + config: StreamerConfig, + studio: Option>, + ) -> Result { let fps = config.fps.max(1); let layers = config.effective_layers(); check_layers(&layers)?; - let shared = Arc::new(Shared::default()); + let shared = Arc::new(Shared { studio, ..Shared::default() }); shared.fps.store(fps, Ordering::Relaxed); let mut streamer = Self { shared: shared.clone(), @@ -918,6 +963,16 @@ impl Streamer { screen.start_sink(&SourceId::Synthetic, &options, ingest).await?; (Box::new(screen), None) } + SourceId::Studio => { + let Some(studio) = &shared.studio else { + return Err(MediaError::Config( + "the studio's composite is streamed with Streamer::start_studio".into(), + )); + }; + let mut capture = studio.capture(); + capture.start_sink(&SourceId::Studio, &options, ingest).await?; + (Box::new(capture), None) + } #[cfg(all(target_os = "linux", feature = "media-desktop"))] _ if config.source == SourceId::Portal || config.backend == CaptureBackend::Portal => { use voelin_media::capture::portal::PortalCapture; @@ -1524,7 +1579,7 @@ impl FrameSink for Ingest { shared .size .store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed); - if lock(&shared.sink).is_none() { + if shared.sink().is_none() { return true; } let mut any = false; @@ -1580,13 +1635,15 @@ impl LayerEncoder { Self { codec: encoder.codec(), encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps } } - /// Encode `frame` and hand the frames to `sink`; follows the layer's - /// target bitrate and frame rate first. + /// Encode `frame` and hand the frames to `sink` (and `studio`'s + /// outputs); follows the layer's target bitrate and frame rate first. + #[allow(clippy::too_many_arguments)] fn encode( &mut self, shared: &Shared, layer: &Layer, sink: &dyn MediaSink, + studio: Option<&Studio>, frame: &VideoFrame, requested: bool, target: u64, @@ -1607,6 +1664,16 @@ impl LayerEncoder { let mut produced_keyframe = false; let result = encoder.encode_with(frame, force, &mut |chunk| { produced_keyframe |= chunk.keyframe; + if let Some(studio) = studio { + studio.write_packet(&Packet { + track: Track::Video { codec, layer: u32::from(layer.id) }, + pts_90khz: chunk.pts_90khz, + keyframe: chunk.keyframe, + width: frame.width, + height: frame.height, + data: chunk.data, + }); + } let encoded = EncodedFrame { kind: MediaKind::Video, time: MediaTime::from_90khz(chunk.pts_90khz), @@ -1683,6 +1750,9 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { } let Some(sink) = shared.sink() else { continue }; shared.poll_keyframes(&*sink); + if shared.studio.as_ref().is_some_and(|s| s.needs_keyframe(u32::from(layer.id))) { + layer.keyframe.store(true, Ordering::Relaxed); + } // The codecs viewers chose; none known: the stream codec. wanted.clear(); sink.video_codecs(&mut wanted); @@ -1742,11 +1812,12 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { let target = sink.layer_bitrate(layer.id).unwrap_or(configured).clamp(1, cap); let started = Instant::now(); if primary_on { - primary.encode(shared, layer, &*sink, &frame, requested, target); + let studio = shared.studio.as_deref(); + primary.encode(shared, layer, &*sink, studio, &frame, requested, target); layer.target.store(primary.bitrate, Ordering::Relaxed); } for encoder in &mut extra { - encoder.encode(shared, layer, &*sink, &frame, requested, target); + encoder.encode(shared, layer, &*sink, None, &frame, requested, target); } layer.encode_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); layer.encoded.fetch_add(1, Ordering::Relaxed); @@ -1853,9 +1924,11 @@ fn stats_loop(shared: &Shared) { /// The mixer thread: every 20 ms (on the monotonic clock) one Opus frame /// of the mix, encoded while a sink is attached. The RTP time is the /// frame's number since the start, so it follows real time across -/// silences and stalls. +/// silences and stalls. A studio's streamer counts from the studio's epoch +/// instead, the clock of its video, so its recordings stay in sync. fn audio_loop(shared: &Shared, mut mixer: StreamMixer, mut encoder: VoiceEncoder) { - let mut clock = BlockClock::new(OPUS_FRAME); + let start = shared.studio.as_ref().map_or_else(Instant::now, |s| s.epoch()); + let mut clock = BlockClock::starting_at(start, OPUS_FRAME); let mut block = vec![0.0f32; OPUS_FRAME * 2]; while !shared.stopped() { let now = Instant::now(); @@ -1875,6 +1948,16 @@ fn audio_loop(shared: &Shared, mut mixer: StreamMixer, mut encoder: VoiceEncoder continue; } }; + if let Some(studio) = &shared.studio { + studio.write_packet(&Packet { + track: Track::Audio { channels: 2 }, + pts_90khz: frame * OPUS_FRAME as u64 * 90_000 / u64::from(MIX_RATE), + keyframe: true, + width: 0, + height: 0, + data: &data, + }); + } let time = MediaTime::new(frame * OPUS_FRAME as u64, Frequency::FORTY_EIGHT_KHZ); let frame = EncodedFrame { kind: MediaKind::Audio, time, data, layer: 0, keyframe: false }; diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index 635c232..e59177a 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1224,9 +1224,52 @@ pub static STREAM_AUDIO_SOURCES: Key> = Key::new( ) .validated(valid_audio_sources); +/// The Stream Studio's scenes, their sources, and the size and frame rate +/// of its composite (`voelin_media::studio::scene::Scenes`); kept up to date +/// by `crate::studio::start` as the scenes are edited. +#[cfg(feature = "media")] +pub static STUDIO_SCENES: Key = Key::new( + "studio.scenes", + Kind::Json, + "Stream Studio scenes and sources, and the output size and frame rate.", + voelin_media::studio::scene::Scenes::default, +) +.validated(voelin_media::studio::scene::Scenes::check); + +/// How many seconds the Stream Studio's replay buffer keeps, for saving a +/// clip after the fact. 0: off. No maximum (past +/// [`STUDIO_REPLAY_MEMORY_MB`] it spills to disk). +#[cfg(feature = "media")] +pub static STUDIO_REPLAY_SECONDS: Key = Key::new( + "studio.replay_seconds", + Kind::UInt { min: 0 }, + "Seconds the Stream Studio's replay buffer keeps (0: off).", + || 30, +); + +/// MiB of the replay buffer kept in memory; older packets go to a +/// temporary file. 0: everything goes to the file. +#[cfg(feature = "media")] +pub static STUDIO_REPLAY_MEMORY_MB: Key = Key::new( + "studio.replay_memory_mb", + Kind::UInt { min: 0 }, + "MiB of the replay buffer kept in memory before older packets go to disk.", + || 256, +); + +/// Where the Stream Studio puts recordings and clips; empty: a `Voelin` +/// folder in the user's videos folder (`crate::studio::recording_dir`). +#[cfg(feature = "media")] +pub static STUDIO_RECORDING_DIR: Key = Key::new( + "studio.recording_dir", + Kind::Text { suggestions: &[] }, + "Folder for Stream Studio recordings and clips (empty: Videos/Voelin).", + String::new, +); + /// The keys every [`Settings`] knows from the start. -pub fn builtin_keys() -> [&'static dyn Setting; 20] { - [ +pub fn builtin_keys() -> Vec<&'static dyn Setting> { + vec![ &CRASH_REPORTS, &AUDIO, &STREAM_FPS, @@ -1247,6 +1290,14 @@ pub fn builtin_keys() -> [&'static dyn Setting; 20] { &CACHE_FETCH_IMAGES, &FILES_PROGRESS_MS, &PRIVACY_BLOCK_MODE, + #[cfg(feature = "media")] + &STUDIO_SCENES, + #[cfg(feature = "media")] + &STUDIO_REPLAY_SECONDS, + #[cfg(feature = "media")] + &STUDIO_REPLAY_MEMORY_MB, + #[cfg(feature = "media")] + &STUDIO_RECORDING_DIR, ] } diff --git a/crates/voelin-core/src/studio.rs b/crates/voelin-core/src/studio.rs new file mode 100644 index 0000000..fe0fab4 --- /dev/null +++ b/crates/voelin-core/src/studio.rs @@ -0,0 +1,171 @@ +//! The Stream Studio (feature `media`): [`voelin_media::studio`] with its +//! scenes and replay buffer kept in the settings. +//! +//! [`start`] runs a [`Studio`] from `studio.scenes` and keeps the two in +//! step: every edit made through [`Studio::apply`] is written back to +//! `studio.scenes`, and a change of `studio.scenes`, `studio.replay_seconds` +//! or `studio.replay_memory_mb` made anywhere else (a settings page, +//! `--set`) is applied to the running studio. +//! +//! The UI drives the studio with [`Command`]s, follows its [`Event`]s, and +//! draws [`Studio::preview`]. Its composite becomes the video of a stream +//! through [`crate::media::Streamer::start_studio`], which also feeds the +//! studio's outputs (recording, replay buffer, WHIP) with the packets the +//! stream's encoders make, whether or not the stream is live. Going live is +//! the stream's as usual (`Command::StartStream`, then attaching its sink); +//! [`Command::GoLive`] tells the studio, for its header and its WHIP +//! outputs. + +use std::path::PathBuf; +use std::sync::{Arc, Weak}; + +use tokio::sync::broadcast::error::RecvError; +use tracing::warn; +pub use voelin_media::studio::*; + +use crate::media::MediaError; +use crate::settings::{ + STUDIO_RECORDING_DIR, STUDIO_REPLAY_MEMORY_MB, STUDIO_REPLAY_SECONDS, STUDIO_SCENES, Settings, +}; + +/// Start a studio from `settings` and keep it and them in step (see the +/// [module docs](self)) for as long as it runs. Must run on a Tokio runtime. +pub async fn start(settings: &Settings) -> Result, MediaError> { + let scenes = (*settings.get_arc(&STUDIO_SCENES)).clone(); + let studio = Arc::new(Studio::start(scenes).await?); + studio.apply(replay(settings)).await?; + tokio::spawn(follow(Arc::downgrade(&studio), studio.events(), settings.clone())); + Ok(studio) +} + +/// Where recordings and clips go: `studio.recording_dir`, else a `Voelin` +/// folder in the user's videos folder. +pub fn recording_dir(settings: &Settings) -> PathBuf { + let dir = settings.get(&STUDIO_RECORDING_DIR); + if !dir.trim().is_empty() { + return PathBuf::from(dir); + } + dirs::video_dir().or_else(dirs::home_dir).unwrap_or_else(std::env::temp_dir).join("Voelin") +} + +fn replay(settings: &Settings) -> Command { + Command::SetReplay { + seconds: settings.get(&STUDIO_REPLAY_SECONDS), + memory_mb: settings.get(&STUDIO_REPLAY_MEMORY_MB), + } +} + +/// Write the studio's scene edits to the settings and apply the settings' +/// changes to the studio, until the studio is gone. Equal values are not +/// written back, so neither side echoes the other. +async fn follow( + studio: Weak, + mut events: tokio::sync::broadcast::Receiver, + settings: Settings, +) { + let mut scenes = settings.watch(&STUDIO_SCENES); + let mut seconds = settings.watch(&STUDIO_REPLAY_SECONDS); + let mut memory = settings.watch(&STUDIO_REPLAY_MEMORY_MB); + loop { + let command = tokio::select! { + event = events.recv() => { + let edited = match event { + Ok(Event::Scenes(edited)) => edited, + Ok(_) => continue, + // Missed some: the studio's scenes now are what counts. + Err(RecvError::Lagged(_)) => match studio.upgrade() { + Some(studio) => Arc::new(studio.scenes()), + None => return, + }, + Err(RecvError::Closed) => return, + }; + if *settings.get_arc(&STUDIO_SCENES) != *edited + && let Err(e) = settings.set(&STUDIO_SCENES, (*edited).clone()) + { + warn!("cannot keep the studio's scenes: {e}"); + } + continue; + } + Some(changed) = scenes.changed() => Command::SetScenes(Box::new((*changed).clone())), + Some(_) = seconds.changed() => replay(&settings), + Some(_) = memory.changed() => replay(&settings), + else => return, + }; + let Some(studio) = studio.upgrade() else { return }; + if let Command::SetScenes(changed) = &command + && studio.scenes() == **changed + { + continue; + } + if let Err(e) = studio.apply(command).await { + warn!("studio settings: {e}"); + } + } +} + +#[cfg(test)] +mod tests { + use std::time::{Duration, Instant}; + + use super::scene::{Colour, Scene, Scenes, SourceKind}; + use super::*; + + async fn eventually(what: &str, mut check: impl FnMut() -> bool) { + let started = Instant::now(); + while !check() { + assert!(started.elapsed() < Duration::from_secs(5), "{what}"); + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_studio_and_its_settings_follow_each_other() { + let settings = Settings::in_memory(); + let mut stored = Scenes { width: 64, height: 48, ..Scenes::default() }; + stored.scenes.push(Scene::new(1, "Main")); + settings.set(&STUDIO_SCENES, stored.clone()).unwrap(); + let studio = start(&settings).await.unwrap(); + assert_eq!(studio.scenes(), stored); + + // An edit in the studio is kept in the settings. + studio + .apply(Command::AddSource { + scene: 1, + name: "Slate".into(), + kind: SourceKind::Colour { colour: Colour::rgb(1, 2, 3), size: (64, 48) }, + }) + .await + .unwrap(); + eventually("the edit reached the settings", || { + settings.get(&STUDIO_SCENES).scenes[0].sources.len() == 1 + }) + .await; + + // A change of the setting reaches the studio. + let mut changed = settings.get(&STUDIO_SCENES); + changed.scenes.push(Scene::new(2, "Break")); + changed.active = 2; + settings.set(&STUDIO_SCENES, changed.clone()).unwrap(); + eventually("the setting reached the studio", || studio.scenes() == changed).await; + eventually("the studio switched", || studio.status().active_scene == 2).await; + + // And so does the replay window: on with a keyframe wanted, off without. + settings.set(&STUDIO_REPLAY_SECONDS, 0).unwrap(); + eventually("the replay buffer is off", || !studio.needs_keyframe(0)).await; + settings.set(&STUDIO_REPLAY_SECONDS, 5).unwrap(); + eventually("the replay buffer is on", || studio.needs_keyframe(0)).await; + + // Invalid scenes never get into the settings. + let mut twice = changed.clone(); + twice.scenes.push(Scene::new(1, "Again")); + assert!(settings.set(&STUDIO_SCENES, twice).is_err()); + } + + #[test] + fn recordings_go_to_the_setting_or_the_videos_folder() { + let settings = Settings::in_memory(); + assert!(recording_dir(&settings).ends_with("Voelin")); + settings.set(&STUDIO_RECORDING_DIR, "/srv/clips".into()).unwrap(); + assert_eq!(recording_dir(&settings), PathBuf::from("/srv/clips")); + } +} diff --git a/crates/voelin-core/tests/studio.rs b/crates/voelin-core/tests/studio.rs new file mode 100644 index 0000000..f68d832 --- /dev/null +++ b/crates/voelin-core/tests/studio.rs @@ -0,0 +1,195 @@ +//! The Stream Studio as the video of a stream: the streamer encodes its +//! composite (VP8 and an Opus test tone) without any stream attached, and the +//! studio records it and keeps a replay buffer while the scene switches. +//! The files are read back with ffprobe and decoded with ffmpeg where those +//! are installed. + +#![cfg(feature = "media-desktop")] + +use std::path::{Path, PathBuf}; +use std::process::Command as Process; +use std::time::{Duration, Instant}; + +use voelin_core::media::voelin_media::{Codec, Codecs}; +use voelin_core::media::{AudioSourceKind, AudioSourceSpec, Streamer, StreamerConfig}; +use voelin_core::settings::{STUDIO_REPLAY_SECONDS, STUDIO_SCENES, Settings}; +use voelin_core::studio::scene::{Colour, Scene, Scenes, Source, SourceKind, Transform}; +use voelin_core::studio::{self, Command, Event}; + +const WIDTH: u32 = 320; +const HEIGHT: u32 = 180; +const RED: [u8; 3] = [220, 30, 30]; +const BLUE: [u8; 3] = [30, 30, 220]; + +fn colour_scene(id: u64, name: &str, rgb: [u8; 3]) -> Scene { + let mut scene = Scene::new(id, name); + scene.sources.push(Source { + transform: Transform::full(WIDTH, HEIGHT), + ..Source::new( + 1, + SourceKind::Colour { colour: Colour::rgb(rgb[0], rgb[1], rgb[2]), size: (16, 16) }, + ) + }); + scene +} + +fn has(tool: &str) -> bool { + Process::new(tool).arg("-version").output().is_ok_and(|o| o.status.success()) +} + +/// What ffprobe says of `path`: each stream's codec and start time, and the +/// duration, in seconds. +fn probe(path: &Path) -> (Vec<(String, f64)>, f64) { + let out = Process::new("ffprobe") + .args(["-v", "error", "-show_entries", "stream=codec_name,start_time:format=duration"]) + .args(["-of", "csv=p=0"]) + .arg(path) + .output() + .unwrap(); + assert!(out.status.success(), "ffprobe: {}", String::from_utf8_lossy(&out.stderr)); + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + let mut lines: Vec<&str> = text.lines().collect(); + let duration = lines.pop().and_then(|d| d.parse().ok()).unwrap_or(0.0); + let streams = lines + .iter() + .map(|l| { + let (codec, start) = l.split_once(',').unwrap_or((l, "0")); + (codec.to_owned(), start.parse().unwrap_or(f64::NAN)) + }) + .collect(); + (streams, duration) +} + +/// Codecs VP8 and Opus, starting together (the audio's clock is the +/// studio's): what a recording of the studio holds. +fn check_streams(streams: &[(String, f64)]) { + let codecs: Vec<&str> = streams.iter().map(|(c, _)| c.as_str()).collect(); + assert_eq!(codecs, ["vp8", "opus"], "{streams:?}"); + assert!((streams[0].1 - streams[1].1).abs() < 0.1, "out of sync: {streams:?}"); +} + +/// Every picture of `path`, decoded by ffmpeg as RGB. +fn decode(path: &Path) -> Vec> { + let out = Process::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "rawvideo", "-pix_fmt", "rgb24", "-"]) + .output() + .unwrap(); + assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); + assert!(out.stderr.is_empty(), "decoder complaints: {}", String::from_utf8_lossy(&out.stderr)); + out.stdout.chunks_exact((WIDTH * HEIGHT * 3) as usize).map(<[u8]>::to_vec).collect() +} + +fn centre(picture: &[u8]) -> [u8; 3] { + let at = ((HEIGHT / 2 * WIDTH + WIDTH / 2) * 3) as usize; + [picture[at], picture[at + 1], picture[at + 2]] +} + +fn near(a: [u8; 3], b: [u8; 3]) -> bool { + a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 24) +} + +fn temp_dir() -> PathBuf { + let dir = std::env::temp_dir().join(format!("voelin-studio-core-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_studio_stream_records_and_replays_while_the_scene_switches() { + let codecs = Codecs::new(); + if !codecs.encoder_codecs().contains(&Codec::Vp8) { + eprintln!("skipped: no VP8 encoder in this build"); + return; + } + let settings = Settings::in_memory(); + let mut scenes = + Scenes { width: WIDTH, height: HEIGHT, fps: 30, active: 1, ..Scenes::default() }; + scenes.scenes.push(colour_scene(1, "Red", RED)); + scenes.scenes.push(colour_scene(2, "Blue", BLUE)); + settings.set(&STUDIO_SCENES, scenes).unwrap(); + settings.set(&STUDIO_REPLAY_SECONDS, 10).unwrap(); + let studio = studio::start(&settings).await.unwrap(); + let mut events = studio.events(); + + // No stream is attached: the composite is encoded anyway. + let config = StreamerConfig { + fps: 30, + bitrate_kbps: 800, + codec: Codec::Vp8, + audio_sources: vec![AudioSourceSpec::new(AudioSourceKind::Synthetic { hz: 440 })], + ..StreamerConfig::default() + }; + let mut streamer = Streamer::start_studio(&codecs, config, studio.clone()).await.unwrap(); + assert_eq!(streamer.backend(), "studio"); + + let dir = temp_dir(); + let recording = dir.join("recording.webm"); + studio.apply(Command::StartRecording { path: recording.clone() }).await.unwrap(); + tokio::time::sleep(Duration::from_millis(1500)).await; + // Switch the scene live, while recording. + studio.apply(Command::SetActiveScene { scene: 2 }).await.unwrap(); + tokio::time::sleep(Duration::from_millis(1500)).await; + studio.apply(Command::StopRecording).await.unwrap(); + let clip = dir.join("clip.mkv"); + studio.apply(Command::SaveClip { path: clip.clone() }).await.unwrap(); + + let stats = streamer.stats(); + assert!(stats.video_frames >= 60, "{stats:?}"); + assert!(stats.audio_frames >= 100, "{stats:?}"); + assert_eq!(stats.width, WIDTH, "{stats:?}"); + streamer.stop(); + + let mut seen = Vec::new(); + while let Ok(event) = events.try_recv() { + seen.push(event); + } + let stopped = seen.iter().find_map(|e| match e { + Event::RecordingStopped { bytes, duration, .. } => Some((*bytes, *duration)), + _ => None, + }); + let (bytes, duration) = stopped.expect("a RecordingStopped event"); + assert!(bytes > 1000 && duration >= Duration::from_secs(2), "{bytes} bytes in {duration:?}"); + assert!(seen.iter().any(|e| matches!(e, Event::ClipSaved { .. })), "{seen:?}"); + + if !has("ffprobe") || !has("ffmpeg") { + eprintln!("ffprobe or ffmpeg is not installed: the files were not read back"); + std::fs::remove_dir_all(&dir).ok(); + return; + } + // The recording: VP8 and Opus, about three seconds, every picture + // decodes, red before the switch and blue after it. + let (streams, length) = probe(&recording); + check_streams(&streams); + assert!((2.5..4.5).contains(&length), "{length} s"); + let pictures = decode(&recording); + assert!(pictures.len() >= 60, "{} pictures", pictures.len()); + assert!(near(centre(&pictures[0]), RED), "{:?}", centre(&pictures[0])); + let last = pictures.last().unwrap(); + assert!(near(centre(last), BLUE), "{:?}", centre(last)); + + // The clip: Matroska, from the replay buffer, also both scenes (it + // started with the streamer, before the recording). + let (streams, length) = probe(&clip); + check_streams(&streams); + assert!(length >= 2.5, "{length} s"); + let pictures = decode(&clip); + assert!(near(centre(&pictures[0]), RED), "{:?}", centre(&pictures[0])); + assert!(near(centre(pictures.last().unwrap()), BLUE)); + std::fs::remove_dir_all(&dir).ok(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_studio_source_needs_a_studio() { + let codecs = Codecs::new(); + let config = StreamerConfig { + source: voelin_core::media::voelin_media::SourceId::Studio, + audio: false, + ..StreamerConfig::default() + }; + let started = Instant::now(); + let error = Streamer::start(&codecs, config).await.err().expect("refused"); + assert!(error.to_string().contains("start_studio"), "{error}"); + assert!(started.elapsed() < Duration::from_secs(5)); +} diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs index 44c46cf..ade7f4e 100644 --- a/crates/voelin-media/src/studio/mod.rs +++ b/crates/voelin-media/src/studio/mod.rs @@ -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, /// 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()); diff --git a/crates/voelin-media/src/studio/output/replay.rs b/crates/voelin-media/src/studio/output/replay.rs index d5c1a35..2f475a2 100644 --- a/crates/voelin-media/src/studio/output/replay.rs +++ b/crates/voelin-media/src/studio/output/replay.rs @@ -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), @@ -82,6 +88,9 @@ pub struct ReplayBuffer { codec: Option, 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()); } } diff --git a/crates/voelin-media/src/studio/output/whip.rs b/crates/voelin-media/src/studio/output/whip.rs index 3277921..588f766 100644 --- a/crates/voelin-media/src/studio/output/whip.rs +++ b/crates/voelin-media/src/studio/output/whip.rs @@ -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; diff --git a/crates/voelin-media/tests/studio_whip.rs b/crates/voelin-media/tests/studio_whip.rs index 743c537..cc713ac 100644 --- a/crates/voelin-media/tests/studio_whip.rs +++ b/crates/voelin-media/tests/studio_whip.rs @@ -213,8 +213,9 @@ async fn a_whip_session_carries_the_studios_packets() { .await .expect("the WHIP session started"); assert!(whip.resource().is_some_and(|r| r.contains("/whip/")), "{:?}", whip.resource()); - // Until ICE is up there is nobody to send a keyframe to. + // A session starts with a keyframe, asked for once. assert!(whip.needs_keyframe()); + assert!(!whip.needs_keyframe()); assert!(whip.wants(Track::Video { codec: Codec::Vp8, layer: 0 })); assert!(!whip.wants(Track::Video { codec: Codec::Vp9, layer: 0 })); assert!(!whip.wants(Track::Video { codec: Codec::Vp8, layer: 1 })); @@ -258,6 +259,8 @@ async fn a_whip_session_carries_the_studios_packets() { let stats = whip.stats(); assert!(seen.connected.load(Ordering::Relaxed), "ICE never came up: {stats:?}"); assert!(stats.connected, "the output does not think it is connected: {stats:?}"); + // Coming up asked for another, so the service's first picture decodes. + assert!(whip.needs_keyframe()); assert!(whip.bytes() > 0, "{stats:?}"); assert_eq!(stats.error, None); let (video, audio) = (seen.video.load(Ordering::Relaxed), seen.audio.load(Ordering::Relaxed));