From a446a74589ed107b480e937783bc7d9470ee1641 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 10:14:40 +0000 Subject: [PATCH] tsc-core: audio settings, client and stream volumes, media pipeline Audio: sessions start their audio thread with the engine's AudioSettings (SetAudioSettings, engine-wide), SetClientVolume / SetClientMuted reach the mixer, clients that leave are forgotten, and the audio thread reports the microphone level (InputLevel, also from TestMicrophone without a session). Audio of watched streams plays through the mixer under a made-up client id with its own volume (SetStreamVolume). Media (feature `media`, default): Streamer captures a screen and system audio, encodes VP8 (the offered codec) at the setup's bitrate and Opus, honours keyframe requests and feeds a StreamSink or, as EncodedSource, a FrameSource. VideoPipeline / Viewer decode watched streams on their own thread, skip to keyframes after losses and ask for them. A test streams the test pattern through two stream tasks and loopback peers and checks the rectangle in the decoded pictures. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- Cargo.lock | 1 + crates/tsc-core/Cargo.toml | 7 +- crates/tsc-core/src/audio.rs | 216 ++++++- crates/tsc-core/src/lib.rs | 114 +++- crates/tsc-core/src/media.rs | 1077 ++++++++++++++++++++++++++++++++ crates/tsc-core/src/session.rs | 58 +- crates/tsc-core/src/stream.rs | 147 ++++- 7 files changed, 1573 insertions(+), 47 deletions(-) create mode 100644 crates/tsc-core/src/media.rs diff --git a/Cargo.lock b/Cargo.lock index 8c97fa3..0e94b7a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8607,6 +8607,7 @@ dependencies = [ "tracing", "tsc-audio", "tsc-gateway-proto", + "tsc-media", "tsc-model", "tsc-observer", "tsc-query", diff --git a/crates/tsc-core/Cargo.toml b/crates/tsc-core/Cargo.toml index fa9195b..e675292 100644 --- a/crates/tsc-core/Cargo.toml +++ b/crates/tsc-core/Cargo.toml @@ -9,9 +9,13 @@ repository.workspace = true publish.workspace = true [features] -default = ["audio-device"] +default = ["audio-device", "media"] # Capture and play audio through the system's devices. audio-device = ["tsc-audio/device"] +# Screen / system-audio capture and video codecs for streams (`media` +# module; tsc-media with its default backends: libvpx, OpenH264 loaded at +# runtime, X11 and PipeWire on Linux). Off for mobile builds. +media = ["dep:tsc-media"] [dependencies] anyhow = "1" @@ -23,6 +27,7 @@ tokio-tungstenite = "0.30" tracing = "0.1" tsc-audio = { path = "../tsc-audio", default-features = false } tsc-gateway-proto = { path = "../tsc-gateway-proto" } +tsc-media = { path = "../tsc-media", features = ["str0m"], optional = true } tsc-model = { path = "../tsc-model" } tsc-observer = { path = "../tsc-observer" } tsc-query = { path = "../tsc-query" } diff --git a/crates/tsc-core/src/audio.rs b/crates/tsc-core/src/audio.rs index cf97582..ef3dd75 100644 --- a/crates/tsc-core/src/audio.rs +++ b/crates/tsc-core/src/audio.rs @@ -8,7 +8,8 @@ //! independent part is [`Pipeline`]; the thread loop only moves samples //! between it and the devices, reopening devices that go away. -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; +use std::sync::Arc; use std::sync::mpsc as std_mpsc; use std::thread; use std::time::{Duration, Instant}; @@ -17,9 +18,10 @@ use tokio::sync::mpsc; use tracing::{debug, warn}; use tsc_audio::pcm::{self, FRAME_SAMPLES}; use tsc_audio::settings::TransmitMode; +use tsc_audio::vad::SILENCE_DB; use tsc_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder}; use tsclientlib::ClientId; -use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket}; +use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket}; pub(crate) enum AudioIn { Packet(InAudioBuf), @@ -27,24 +29,46 @@ pub(crate) enum AudioIn { InputMuted(bool), OutputMuted(bool), /// Devices, processing, voice activation and transmit mode. - #[allow(dead_code, reason = "sent once the session exposes audio settings")] Settings(Box), /// Playback volume of one client, linear (1 = unchanged, up to 4). - #[allow(dead_code, reason = "sent once the session exposes client volumes")] ClientVolume { client: ClientId, volume: f32, }, - #[allow(dead_code, reason = "sent once the session exposes client volumes")] ClientMuted { client: ClientId, muted: bool, }, /// The client left; client ids are reused, so forget its volume. - #[allow(dead_code, reason = "sent once the session exposes client volumes")] ClientLeft(ClientId), + /// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time + /// on the 48 kHz clock. + StreamAudio { + stream: String, + time: u64, + data: Arc<[u8]>, + }, + /// Playback volume of a watched stream, linear like client volumes. + StreamVolume { + stream: String, + volume: f32, + }, + /// We stopped watching the stream: forget its queue and volume. + StreamEnded(String), } +/// What the audio thread reports. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum AudioEvent { + /// A problem, e.g. a missing device. + Error(String), + /// Loudest microphone level (dBFS, after processing) since the last + /// report, and whether voice is being sent. About every + /// [`LEVEL_INTERVAL`] while the microphone delivers audio. + Level { db: f32, sending: bool }, +} + +#[derive(Clone)] pub(crate) struct AudioHandle { tx: std_mpsc::Sender, } @@ -53,6 +77,13 @@ impl AudioHandle { pub fn send(&self, msg: AudioIn) { let _ = self.tx.send(msg); } + + /// A handle without a thread, to see what would reach it. + #[cfg(test)] + pub fn channel() -> (Self, std_mpsc::Receiver) { + let (tx, rx) = std_mpsc::channel(); + (Self { tx }, rx) + } } /// With voice activation, also send this many 20 ms frames from before the @@ -68,25 +99,33 @@ const PLAYBACK_CAPACITY_MS: u32 = 200; const DEVICE_LATENCY_MS: u32 = 20; /// How long the loop sleeps between rounds. const TICK: Duration = Duration::from_millis(5); +/// How often the microphone level is reported (for a meter). +pub(crate) const LEVEL_INTERVAL: Duration = Duration::from_millis(100); +/// Samples of one 20 ms Opus frame at 48 kHz: the unit of stream packet ids. +const OPUS_FRAME: u64 = 960; /// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g. -/// no device) are reported through `errors`. +/// no device) and the microphone level are reported through `events`. pub(crate) fn spawn( outgoing: mpsc::UnboundedSender, - errors: mpsc::UnboundedSender, - voice_activation: bool, + events: mpsc::UnboundedSender, + settings: AudioSettings, ) -> AudioHandle { - let transmit = - if voice_activation { TransmitMode::VoiceActivation } else { TransmitMode::PushToTalk }; - let settings = AudioSettings { transmit, ..Default::default() }; let (tx, rx) = std_mpsc::channel(); thread::Builder::new() .name("tsc-audio".into()) - .spawn(move || run(rx, outgoing, errors, settings)) + .spawn(move || run(rx, outgoing, events, settings)) .expect("spawn audio thread"); AudioHandle { tx } } +/// Audio of a watched stream in the mixer, under a made-up client id. +struct StreamAudio { + client: ClientId, + /// RTP time and packet id of the last packet. + last: Option<(u64, u64)>, +} + /// Everything between the devices and the connection. struct Pipeline { settings: AudioSettings, @@ -101,6 +140,11 @@ struct Pipeline { input_muted: bool, output_muted: bool, was_sending: bool, + /// Loudest level since the last report; `None` without microphone audio. + level_peak: Option, + /// Watched streams whose audio plays through the mixer. + streams: HashMap, + stream_volumes: HashMap, /// Processed microphone audio, for tests. #[cfg(test)] tap: Vec, @@ -121,6 +165,9 @@ impl Pipeline { input_muted: false, output_muted: false, was_sending: false, + level_peak: None, + streams: HashMap::new(), + stream_volumes: HashMap::new(), settings, #[cfg(test)] tap: Vec::new(), @@ -154,9 +201,73 @@ impl Pipeline { AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume), AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted), AudioIn::ClientLeft(client) => self.mixer.forget(client), + AudioIn::StreamAudio { stream, time, data } => self.stream_packet(stream, time, &data), + AudioIn::StreamVolume { stream, volume } => { + if let Some(s) = self.streams.get(&stream) { + self.mixer.set_volume(s.client, volume); + } + self.stream_volumes.insert(stream, volume); + } + AudioIn::StreamEnded(stream) => { + if let Some(s) = self.streams.remove(&stream) { + self.mixer.forget(s.client); + } + self.stream_volumes.remove(&stream); + } } } + /// Queue an Opus frame of a stream in the mixer, as if a client with a + /// made-up id (counting down from `u16::MAX`, where real ids are rare) + /// talked. The jitter buffer orders packets by id: one id per 20 ms of + /// RTP time, at least one per packet (shorter frames). + fn stream_packet(&mut self, stream: String, time: u64, data: &[u8]) { + let client = match self.streams.get(&stream) { + Some(s) => s.client, + None => { + let used: Vec = self.streams.values().map(|s| s.client).collect(); + let Some(client) = (0..=u16::MAX).rev().map(ClientId).find(|c| !used.contains(c)) + else { + return; + }; + self.mixer.forget(client); + let volume = self.stream_volumes.get(&stream).copied().unwrap_or(1.0); + self.mixer.set_volume(client, volume); + self.streams.insert(stream.clone(), StreamAudio { client, last: None }); + client + } + }; + let entry = self.streams.get_mut(&stream).expect("inserted above"); + let id = match entry.last { + None => time / OPUS_FRAME, + // Duplicate or reordered: the depacketizer delivers in order. + Some((last_time, _)) if time <= last_time => return, + Some((last_time, last_id)) => { + last_id + ((time - last_time + OPUS_FRAME / 2) / OPUS_FRAME).max(1) + } + }; + entry.last = Some((time, id)); + let packet = OutAudio::new(&AudioData::S2C { + id: id as u16, + codec: CodecType::OpusMusic, + from: client.0, + data, + }); + match InAudioBuf::try_new(Direction::S2C, packet.into_vec()) { + Ok(packet) => { + if let Err(error) = self.mixer.handle_packet(client, packet) { + debug!(%error, "dropped stream audio packet"); + } + } + Err(error) => debug!(?error, "stream audio packet"), + } + } + + /// The loudest microphone level since the last call, if any audio came in. + fn take_level(&mut self) -> Option { + self.level_peak.take() + } + /// Microphone audio in (mono, 48 kHz, any length); voice packets out. /// `delay_ms` is the playback-to-capture delay hint for the echo canceller. fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) { @@ -175,6 +286,8 @@ impl Pipeline { fn transmit(&mut self, frame: Vec, send: &mut impl FnMut(OutPacket)) { // Always analysed, so the detector's state is current when needed. let voice = self.vad.process(&frame); + let level = self.vad.level_db().max(SILENCE_DB); + self.level_peak = Some(self.level_peak.map_or(level, |peak| peak.max(level))); let wanted = match self.settings.transmit { TransmitMode::PushToTalk => self.ptt, TransmitMode::VoiceActivation => voice, @@ -232,18 +345,21 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings { fn run( rx: std_mpsc::Receiver, outgoing: mpsc::UnboundedSender, - errors: mpsc::UnboundedSender, + events: mpsc::UnboundedSender, settings: AudioSettings, ) { + let error = |message: String| { + let _ = events.send(AudioEvent::Error(message)); + }; #[cfg(feature = "audio-device")] let mut devices = devices::Devices::new(&settings); #[cfg(not(feature = "audio-device"))] - let _ = errors.send("built without audio device support".to_string()); + error("built without audio device support".to_string()); let mut pipeline = match Pipeline::new(settings) { Ok(p) => p, Err(e) => { - let _ = errors.send(e.to_string()); + error(e.to_string()); return; } }; @@ -253,6 +369,7 @@ fn run( // Without speakers the mixer is drained at real time, so queues do not // fill up and talkers still end. let mut idle_clock = Instant::now(); + let mut level_clock = Instant::now(); loop { // Control messages and incoming voice. @@ -271,7 +388,7 @@ fn run( } #[cfg(feature = "audio-device")] - let playing = devices.step(&mut pipeline, &mut send, &errors); + let playing = devices.step(&mut pipeline, &mut send, &error); #[cfg(not(feature = "audio-device"))] let playing = { // No microphone: nothing to process, but keep the path alive. @@ -289,13 +406,19 @@ fn run( } } + if level_clock.elapsed() >= LEVEL_INTERVAL { + level_clock = Instant::now(); + if let Some(db) = pipeline.take_level() { + let _ = events.send(AudioEvent::Level { db, sending: pipeline.was_sending }); + } + } + thread::sleep(TICK); } } #[cfg(feature = "audio-device")] mod devices { - use tokio::sync::mpsc; use tracing::debug; use tsc_audio::AudioSettings; use tsc_audio::device::{Capture, DeviceEvent, Managed, Playback}; @@ -324,7 +447,7 @@ mod devices { &mut slot.as_mut().expect("just set").1 } - fn report(errors: &mpsc::UnboundedSender, what: &str, event: DeviceEvent) { + fn report(error: &impl Fn(String), what: &str, event: DeviceEvent) { let message = match event { DeviceEvent::Opened { name, fallback: false } => { debug!(%name, "{what} opened"); @@ -336,7 +459,7 @@ mod devices { DeviceEvent::Lost { name } => format!("{what} disconnected: {name}"), DeviceEvent::Unavailable(e) => format!("no {what}: {e}"), }; - let _ = errors.send(message); + error(message); } impl Devices { @@ -362,13 +485,13 @@ mod devices { &mut self, pipeline: &mut Pipeline, send: &mut impl FnMut(OutPacket), - errors: &mpsc::UnboundedSender, + error: &impl Fn(String), ) -> bool { if let Some(event) = self.playback.poll() { - report(errors, "speakers", event); + report(error, "speakers", event); } if let Some(event) = self.capture.poll() { - report(errors, "microphone", event); + report(error, "microphone", event); } // Mixer → speakers, keeping the configured amount queued. @@ -410,7 +533,6 @@ mod devices { mod tests { use tsc_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise}; use tsc_audio::{ProcessingSettings, VadSettings}; - use tsproto_packets::packets::{CodecType, Direction, OutAudio}; use super::*; @@ -529,6 +651,52 @@ mod tests { assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB"); } + /// Stream audio (stereo Opus with RTP times) plays through the mixer at + /// its own volume and is forgotten when the stream ends. + #[test] + fn stream_audio_with_volume() { + let mut p = pipeline(TransmitMode::PushToTalk); + let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap(); + let tone = pcm::from_mono(&sine(600.0, 1.0, 0.4), 2); + // A random RTP start, as WebRTC senders use. + let start = 7_777_000u64; + let mut play = |p: &mut Pipeline, stream: &str| -> f32 { + let mut out = Vec::new(); + for (i, frame) in tone.chunks_exact(FRAME_SAMPLES * 2).enumerate() { + let data: Arc<[u8]> = encoder.encode_to_bytes(frame).unwrap().into(); + let time = start + i as u64 * OPUS_FRAME; + p.handle(AudioIn::StreamAudio { stream: stream.into(), time, data: data.clone() }); + // A duplicate is ignored. + p.handle(AudioIn::StreamAudio { stream: stream.into(), time, data }); + out.extend(p.playback_frame()); + } + energy(&out[out.len() / 2..]) + }; + let full = play(&mut p, "a"); + assert!(full > 1e-3, "stream audio must be audible"); + p.handle(AudioIn::StreamVolume { stream: "b".into(), volume: 0.5 }); + let half = play(&mut p, "b"); + let ratio_db = 10.0 * (half / full).log10(); + assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB"); + let mut clients: Vec = p.streams.values().map(|s| s.client.0).collect(); + clients.sort_unstable(); + assert_eq!(clients, [u16::MAX - 1, u16::MAX]); + p.handle(AudioIn::StreamEnded("b".into())); + assert_eq!(p.streams.len(), 1); + assert!(!p.stream_volumes.contains_key("b")); + } + + #[test] + fn level_is_reported() { + let mut p = pipeline(TransmitMode::PushToTalk); + assert_eq!(p.take_level(), None, "no microphone audio yet"); + // A sine of amplitude 0.3 has an RMS level of about -13.5 dBFS. + capture(&mut p, &sine(440.0, 0.1, 0.3)); + let level = p.take_level().unwrap(); + assert!((level + 13.5).abs() < 1.0, "{level}"); + assert_eq!(p.take_level(), None); + } + #[test] fn settings_are_sanitized() { let mut p = pipeline(TransmitMode::PushToTalk); diff --git a/crates/tsc-core/src/lib.rs b/crates/tsc-core/src/lib.rs index 4226b28..2a9ba08 100644 --- a/crates/tsc-core/src/lib.rs +++ b/crates/tsc-core/src/lib.rs @@ -13,10 +13,15 @@ //! //! On TeamSpeak 6 servers the voice connection also carries streams (screen //! sharing): see the `*Stream*` commands and events, and -//! [`Engine::subscribe_frames`] for the frames of watched streams. +//! [`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`). mod audio; mod gateway; +#[cfg(feature = "media")] +pub mod media; mod query; mod route; mod session; @@ -27,8 +32,11 @@ use std::collections::HashMap; use std::sync::Arc; use tokio::sync::{broadcast, mpsc}; +pub use tsc_audio::settings::TransmitMode; +pub use tsc_audio::{AudioSettings, ProcessingSettings, VadSettings}; use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor}; +use crate::audio::{AudioEvent, AudioHandle, AudioIn}; pub use route::{ChatRoute, Dedup, route_chat}; pub use stream::{StreamFrame, StreamSink, StreamState, WatchState}; use tsc_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo}; @@ -86,11 +94,33 @@ pub enum Command { session: SessionId, muted: bool, }, - /// Push-to-talk state (or "always transmit" when voice activation is off). + /// Push-to-talk key or button held (only counts with + /// [`TransmitMode::PushToTalk`]). SetTransmitting { session: SessionId, on: bool, }, + /// Audio settings of all sessions (devices, processing, transmit mode), + /// also used by sessions started later. + SetAudioSettings(Box), + /// Playback volume of one client, linear (1 = unchanged, up to 4). + /// Local only; forgotten when the client leaves. + SetClientVolume { + session: SessionId, + client: u16, + volume: f32, + }, + /// Do not play one client (local only). + SetClientMuted { + session: SessionId, + client: u16, + muted: bool, + }, + /// Open the microphone without a session to show its level + /// ([`Event::InputLevel`] with `session: None`), e.g. in the settings. + TestMicrophone { + on: bool, + }, /// Start streaming in our channel (TeamSpeak 6 only). Progress comes as /// [`Event::StreamState`]; frames go in through the sink of /// [`StreamState::Live`] or [`Command::SendStreamFrame`]. @@ -134,6 +164,13 @@ pub enum Command { session: SessionId, stream_id: String, }, + /// Playback volume of a watched stream's audio, linear (1 = unchanged, + /// up to 4). + SetStreamVolume { + session: SessionId, + stream_id: String, + volume: f32, + }, /// Close everything of a session. CloseSession { session: SessionId, @@ -205,6 +242,20 @@ pub enum Event { client: u16, talking: bool, }, + /// Microphone level for a meter, about ten times a second while the + /// microphone is open: of a voice session, or of + /// [`Command::TestMicrophone`] (`session: None`). `level_db` is the + /// loudest 10 ms (dBFS, after processing) since the last report; + /// `sending` whether voice is transmitted. + InputLevel { + session: Option, + level_db: f32, + sending: bool, + }, + /// A problem with the microphone test (e.g. no device). + MicrophoneTestError { + message: String, + }, Error { session: SessionId, message: String, @@ -248,6 +299,7 @@ pub struct Engine { commands: mpsc::UnboundedSender, events: broadcast::Sender, frames: broadcast::Sender, + runtime: tokio::runtime::Handle, } impl Engine { @@ -258,7 +310,13 @@ impl Engine { // About a minute of one watched stream. let (frames, _) = broadcast::channel(4096); tokio::spawn(run(rx, events.clone(), frames.clone())); - Self { commands, events, frames } + Self { commands, events, frames, runtime: tokio::runtime::Handle::current() } + } + + /// The runtime the engine runs on, for helpers started from other + /// threads (e.g. `media::Viewer` from a UI thread). + pub fn runtime(&self) -> &tokio::runtime::Handle { + &self.runtime } pub fn send(&self, command: Command) { @@ -281,8 +339,26 @@ async fn run( frames: broadcast::Sender, ) { let mut sessions: HashMap = HashMap::new(); + let mut settings = AudioSettings::default(); + let mut mic_test: Option = None; while let Some(command) = commands.recv().await { - let id = command_session(&command); + let id = match command { + Command::SetAudioSettings(new) => { + settings = (*new).clone(); + for s in sessions.values() { + s.send(Command::SetAudioSettings(new.clone())); + } + if let Some(test) = &mic_test { + test.send(AudioIn::Settings(new)); + } + continue; + } + Command::TestMicrophone { on } => { + mic_test = on.then(|| test_microphone(&settings, &events)); + continue; + } + ref command => command_session(command), + }; if matches!(command, Command::CloseSession { .. }) { if let Some(s) = sessions.remove(&id) { s.send(command); @@ -291,11 +367,33 @@ async fn run( } sessions .entry(id) - .or_insert_with(|| session::SessionHandle::spawn(id, events.clone(), frames.clone())) + .or_insert_with(|| { + session::SessionHandle::spawn(id, events.clone(), frames.clone(), settings.clone()) + }) .send(command); } } +/// An audio thread whose packets go nowhere, for its level. +fn test_microphone(settings: &AudioSettings, events: &broadcast::Sender) -> AudioHandle { + let (packets, _) = mpsc::unbounded_channel(); + let (audio_tx, mut audio_rx) = mpsc::unbounded_channel(); + let handle = audio::spawn(packets, audio_tx, settings.clone()); + let events = events.clone(); + tokio::spawn(async move { + while let Some(event) = audio_rx.recv().await { + let _ = events.send(match event { + AudioEvent::Level { db, sending } => { + Event::InputLevel { session: None, level_db: db, sending } + } + AudioEvent::Error(message) => Event::MicrophoneTestError { message }, + }); + } + }); + handle +} + +/// The session a command is for (engine-wide commands are handled before). fn command_session(command: &Command) -> SessionId { match command { Command::ConnectVoice { session, .. } @@ -318,6 +416,12 @@ fn command_session(command: &Command) -> SessionId { | Command::WatchStream { session, .. } | Command::LeaveStream { session, .. } | Command::RequestStreamKeyframe { session, .. } + | Command::SetStreamVolume { session, .. } + | Command::SetClientVolume { session, .. } + | Command::SetClientMuted { session, .. } | Command::CloseSession { session } => *session, + Command::SetAudioSettings(_) | Command::TestMicrophone { .. } => { + unreachable!("engine-wide commands have no session") + } } } diff --git a/crates/tsc-core/src/media.rs b/crates/tsc-core/src/media.rs new file mode 100644 index 0000000..e28d380 --- /dev/null +++ b/crates/tsc-core/src/media.rs @@ -0,0 +1,1077 @@ +//! Stream media (feature `media`): capture and encoding for our stream, +//! decoding for the streams we watch. +//! +//! - [`Streamer`] captures a screen or window (and optionally system audio), +//! encodes the video with the codec our offer carries ([`stream_codec`], +//! VP8 by default) at the bitrate of the stream setup, and the audio with +//! Opus (48 kHz stereo, 20 ms). It hands the frames to a [`MediaSink`]: +//! the [`StreamSink`] of a live stream, or an [`EncodedSource`] for code +//! that drives `tsc_stream::Streams` itself. Keyframe requests of viewers +//! are honoured. +//! - [`VideoPipeline`] decodes the video of a watched stream on its own +//! thread and hands every picture to a callback. After lost frames or +//! decoder errors it skips to the next keyframe and asks for one. +//! - [`Viewer`] is a [`VideoPipeline`] fed from [`Engine::subscribe_frames`]. +//! The stream's audio needs nothing here: the session plays it +//! ([`Command::SetStreamVolume`]). +//! - [`Latest`] hands the newest picture to a slower consumer such as a UI. +//! - [`LocalPreview`] runs capture → encoder → decoder without a server. +//! +//! [`tsc_media`] is re-exported for sources, codecs and pixel conversion. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc as std_mpsc; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use tracing::{debug, warn}; +use tsc_audio::{VoiceCodec, VoiceEncoder}; +pub use tsc_media; +use tsc_media::capture::synthetic::{SineSource, SyntheticScreen}; +use tsc_media::capture::{ + self, AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, +}; +use tsc_media::{ + AudioBuffer, Codec, Codecs, ContentHint, EncoderConfig, FrameReceiver, VideoEncoder, VideoFrame, +}; +use tsc_stream::{ + EncodedFrame, FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, +}; + +use crate::stream::StreamSink; +use crate::{Command, Engine, SessionId}; + +/// How long media threads wait for input before checking whether to stop. +const POLL: Duration = Duration::from_millis(100); +/// Samples per channel in one 20 ms Opus frame at 48 kHz. +const OPUS_FRAME: usize = 960; +/// Opus bitrate of stream audio (stereo, music). +const OPUS_BITRATE: i32 = 128_000; +/// Video frames the decoder may fall behind before the queue is dropped. +pub const MAX_QUEUED: usize = 30; +/// Keyframe requests while waiting for one are at least this far apart. +const KEYFRAME_RETRY: Duration = Duration::from_millis(500); + +#[derive(Debug, thiserror::Error)] +pub enum MediaError { + #[error(transparent)] + Media(#[from] tsc_media::Error), + #[error("Opus: {0}")] + Opus(#[from] tsc_audio::Error), +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn spawn(name: &str, f: impl FnOnce() + Send + 'static) -> Result, MediaError> { + std::thread::Builder::new() + .name(name.to_owned()) + .spawn(f) + .map_err(|e| MediaError::Media(e.into())) +} + +/// The `tsc_media` codec of a negotiated video codec. +pub fn media_codec(codec: VideoCodec) -> Codec { + match codec { + VideoCodec::Vp8 => Codec::Vp8, + VideoCodec::Vp9 => Codec::Vp9, + VideoCodec::H264 => Codec::H264, + VideoCodec::Av1 => Codec::Av1, + } +} + +/// The negotiable video codec of a `tsc_media` codec. +pub fn video_codec(codec: Codec) -> VideoCodec { + match codec { + Codec::Vp8 => VideoCodec::Vp8, + Codec::Vp9 => VideoCodec::Vp9, + Codec::H264 => VideoCodec::H264, + Codec::Av1 => VideoCodec::Av1, + } +} + +/// The codec our stream is encoded with: the first codec of the offer +/// (`config.video_codecs`) that we can encode. +pub fn stream_codec(codecs: &Codecs, config: &PeerConfig) -> Option { + let encodable = codecs.encoder_codecs(); + config.video_codecs.iter().map(|c| media_codec(*c)).find(|c| encodable.contains(c)) +} + +/// `config` adjusted to what `codecs` can do: viewers accept only codecs we +/// decode, and a streamer offers only the codec it encodes (every viewer +/// gets the same frames, and a viewer picks from the offer). +pub fn peer_config(codecs: &Codecs, mut config: PeerConfig) -> PeerConfig { + config.accept_video_codecs = codecs.decoders().into_iter().map(video_codec).collect(); + if let Some(codec) = stream_codec(codecs, &config) { + config.video_codecs = vec![video_codec(codec)]; + } + config +} + +/// Monitors and windows of this session's capture backend. The portal (on +/// Wayland) lists a single entry: its own dialog picks. +pub fn screen_sources() -> Result, MediaError> { + Ok(capture::default_screen_capture()?.sources()?) +} + +/// The synthetic test pattern as a source. +pub fn test_pattern_source() -> CaptureSource { + let (width, height) = StreamerConfig::default().synthetic_size; + CaptureSource { + id: SourceId::Synthetic, + name: "Test pattern".into(), + width, + height, + primary: false, + } +} + +/// Where a [`Streamer`] puts encoded frames. +pub trait MediaSink: Send + Sync { + /// Send one frame; `false` once nobody takes frames any more. + fn send(&self, frame: EncodedFrame) -> bool; + + /// Whether a keyframe was asked for since the last call. + fn take_keyframe_request(&self) -> bool; +} + +impl MediaSink for StreamSink { + fn send(&self, frame: EncodedFrame) -> bool { + StreamSink::send(self, frame) + } + + fn take_keyframe_request(&self) -> bool { + StreamSink::take_keyframe_request(self) + } +} + +/// What and how to stream. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StreamerConfig { + pub source: SourceId, + /// Frames per second (1 to 60). + pub fps: u32, + /// Video bitrate in kbit/s, as in `StreamSetup::bitrate`. + pub bitrate_kbps: u32, + /// The codec of our offer, see [`stream_codec`]. + pub codec: Codec, + /// Capture and send system audio (a sine tone with the test pattern). + pub audio: bool, + pub cursor: bool, + /// Size of the test pattern ([`SourceId::Synthetic`]). + pub synthetic_size: (u32, u32), + /// Portal restore token from an earlier share: the desktop may skip its + /// dialog. The new one is [`Streamer::restore_token`]. + pub restore_token: Option, +} + +impl Default for StreamerConfig { + fn default() -> Self { + Self { + source: SourceId::Monitor(0), + fps: 30, + bitrate_kbps: 4608, + codec: Codec::Vp8, + audio: true, + cursor: true, + synthetic_size: (1280, 720), + restore_token: None, + } + } +} + +/// What a [`Streamer`] has done so far. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StreamerStats { + /// Frames handed to the sink. + pub video_frames: u64, + pub audio_frames: u64, + /// Size of the last captured frame. + pub width: u32, + pub height: u32, + /// The capture stopped by itself (window closed, sharing ended in the + /// desktop's UI, ...). + pub capture_ended: bool, + /// The last encoder error. + pub error: Option, +} + +#[derive(Default)] +struct Shared { + sink: Mutex>>, + stop: AtomicBool, + video_frames: AtomicU64, + audio_frames: AtomicU64, + /// `width << 32 | height` of the last captured frame. + size: AtomicU64, + capture_ended: AtomicBool, + error: Mutex>, +} + +impl Shared { + fn sink(&self) -> Option> { + lock(&self.sink).clone() + } + + fn stopped(&self) -> bool { + self.stop.load(Ordering::Relaxed) + } +} + +/// Capture and encoding for our stream. Frames are captured from the start +/// (the portal asks the user then), but only encoded once a sink is +/// [attached](Streamer::attach). Stops when dropped. +pub struct Streamer { + shared: Arc, + screen: Option>, + audio: Option>, + threads: Vec>, + backend: &'static str, + restore_token: Option, + audio_error: Option, +} + +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 { + let fps = config.fps.clamp(1, 60); + let encoder = codecs.new_encoder( + config.codec, + EncoderConfig { + fps, + bitrate_bps: config.bitrate_kbps.clamp(100, 10_000) * 1000, + content: ContentHint::Screen, + ..EncoderConfig::default() + }, + )?; + let options = CaptureOptions { fps, cursor: config.cursor, ..CaptureOptions::default() }; + let mut restore_token = None; + let (screen, frames): (Box, _) = match &config.source { + SourceId::Synthetic => { + let (w, h) = config.synthetic_size; + let mut screen = SyntheticScreen::new(w, h); + let frames = screen.start(&SourceId::Synthetic, &options).await?; + (Box::new(screen), frames) + } + #[cfg(target_os = "linux")] + SourceId::Portal => { + use tsc_media::capture::portal::PortalCapture; + let mut portal = PortalCapture::with_restore_token(config.restore_token.clone()); + let frames = portal.start(&SourceId::Portal, &options).await?; + restore_token = portal.restore_token().map(str::to_owned); + (Box::new(portal), frames) + } + source => { + let mut screen = capture::default_screen_capture()?; + let frames = screen.start(source, &options).await?; + (screen, frames) + } + }; + let backend = screen.backend(); + + let shared = Arc::new(Shared::default()); + let mut streamer = Self { + shared: shared.clone(), + screen: Some(screen), + audio: None, + threads: Vec::new(), + backend, + restore_token, + audio_error: None, + }; + streamer.threads.push(spawn("tsc-stream-video", { + let shared = shared.clone(); + move || video_loop(&shared, frames, encoder) + })?); + if config.audio { + match start_audio(&config.source) { + Ok((capture, buffers, encoder)) => { + streamer.audio = Some(capture); + streamer.threads.push(spawn("tsc-stream-audio", move || { + audio_loop(&shared, buffers, encoder) + })?); + } + Err(e) => { + warn!("streaming without audio: {e}"); + streamer.audio_error = Some(e.to_string()); + } + } + } + Ok(streamer) + } + + /// Start encoding into `sink` (replacing an earlier one). + pub fn attach(&self, sink: Arc) { + *lock(&self.shared.sink) = Some(sink); + } + + /// Stop encoding; capture goes on. + pub fn detach(&self) { + *lock(&self.shared.sink) = None; + } + + /// The capture backend (`"x11"`, `"portal"`, `"synthetic"`, ...). + pub fn backend(&self) -> &'static str { + self.backend + } + + /// The portal's token for this choice of screen, to store for next time. + pub fn restore_token(&self) -> Option<&str> { + self.restore_token.as_deref() + } + + /// Why system audio is not captured, if it was asked for. + pub fn audio_error(&self) -> Option<&str> { + self.audio_error.as_deref() + } + + /// Whether system audio is captured. + pub fn has_audio(&self) -> bool { + self.audio.is_some() + } + + pub fn stats(&self) -> StreamerStats { + let size = self.shared.size.load(Ordering::Relaxed); + StreamerStats { + video_frames: self.shared.video_frames.load(Ordering::Relaxed), + audio_frames: self.shared.audio_frames.load(Ordering::Relaxed), + width: (size >> 32) as u32, + height: size as u32, + capture_ended: self.shared.capture_ended.load(Ordering::Relaxed), + error: lock(&self.shared.error).clone(), + } + } + + /// Stop capturing and encoding. + pub fn stop(&mut self) { + self.shared.stop.store(true, Ordering::Relaxed); + self.detach(); + if let Some(mut screen) = self.screen.take() { + screen.stop(); + } + if let Some(mut audio) = self.audio.take() { + audio.stop(); + } + for thread in self.threads.drain(..) { + let _ = thread.join(); + } + } +} + +impl Drop for Streamer { + fn drop(&mut self) { + self.stop(); + } +} + +type AudioStart = (Box, FrameReceiver, VoiceEncoder); + +fn start_audio(source: &SourceId) -> Result { + let mut encoder = VoiceEncoder::new(VoiceCodec::Music)?; + encoder.set_bitrate(OPUS_BITRATE)?; + let mut capture: Box = match source { + SourceId::Synthetic => Box::new(SineSource::new(440.0, 0.05)), + _ => capture::default_audio_capture()?, + }; + let buffers = capture.start()?; + Ok((capture, buffers, encoder)) +} + +fn video_loop( + shared: &Shared, + mut frames: FrameReceiver, + mut encoder: Box, +) { + // A requested keyframe the encoder has not produced yet (rate control + // may skip a frame). + let mut keyframe_due = false; + while !shared.stopped() { + let Some(frame) = frames.recv_timeout(POLL) else { + if frames.is_closed() { + debug!("screen capture ended"); + shared.capture_ended.store(true, Ordering::Relaxed); + break; + } + continue; + }; + let size = u64::from(frame.width) << 32 | u64::from(frame.height); + shared.size.store(size, Ordering::Relaxed); + let Some(sink) = shared.sink() else { continue }; + let keyframe = sink.take_keyframe_request() || keyframe_due; + match encoder.encode(&frame, keyframe) { + Ok(encoded) => { + keyframe_due = keyframe && !encoded.iter().any(|f| f.keyframe); + for f in encoded { + let frame = EncodedFrame { + kind: MediaKind::Video, + time: MediaTime::from_90khz(f.pts_90khz), + data: f.data.into(), + }; + if sink.send(frame) { + shared.video_frames.fetch_add(1, Ordering::Relaxed); + } + } + } + Err(e) => { + warn!("video encoding failed: {e}"); + keyframe_due = keyframe; + *lock(&shared.error) = Some(e.to_string()); + } + } + } +} + +/// Interleaved stereo from any channel count (extra channels are dropped). +fn append_stereo(buffer: &AudioBuffer, out: &mut Vec) { + match buffer.channels { + 0 => {} + 1 => out.extend(buffer.samples.iter().flat_map(|s| [*s, *s])), + 2 => out.extend_from_slice(&buffer.samples), + n => { + for frame in buffer.samples.chunks_exact(usize::from(n)) { + out.extend_from_slice(&frame[..2]); + } + } + } +} + +fn audio_loop(shared: &Shared, mut buffers: FrameReceiver, mut encoder: VoiceEncoder) { + // Interleaved stereo waiting for a whole Opus frame. + let mut pending: Vec = Vec::new(); + // Opus frames since the capture started: the RTP time in 20 ms steps. + let mut frames: u64 = 0; + while !shared.stopped() { + let Some(buffer) = buffers.recv_timeout(POLL) else { + if buffers.is_closed() { + debug!("system audio capture ended"); + break; + } + continue; + }; + // Follow the capture clock across gaps (nothing played, sink not + // attached yet), so audio stays in step with video. + let at = buffer.timestamp.as_micros() as u64 * 48 / 1000; + let position = frames * OPUS_FRAME as u64 + (pending.len() / 2) as u64; + if at > position + 10 * OPUS_FRAME as u64 { + pending.clear(); + frames = at / OPUS_FRAME as u64; + } + let Some(sink) = shared.sink() else { continue }; + append_stereo(&buffer, &mut pending); + while pending.len() >= OPUS_FRAME * 2 { + let data: Option> = match encoder.encode_to_bytes(&pending[..OPUS_FRAME * 2]) + { + Ok(data) => Some(data.into()), + Err(e) => { + warn!("audio encoding failed: {e}"); + None + } + }; + pending.drain(..OPUS_FRAME * 2); + if let Some(data) = data { + let time = MediaTime::new(frames * OPUS_FRAME as u64, Frequency::FORTY_EIGHT_KHZ); + if sink.send(EncodedFrame { kind: MediaKind::Audio, time, data }) { + shared.audio_frames.fetch_add(1, Ordering::Relaxed); + } + } + frames += 1; + } + } +} + +/// Collects a [`Streamer`]'s frames for [`EncodedSource`]. +struct ChannelSink { + tx: std_mpsc::Sender, + keyframe: AtomicBool, +} + +impl MediaSink for ChannelSink { + fn send(&self, frame: EncodedFrame) -> bool { + self.tx.send(frame).is_ok() + } + + fn take_keyframe_request(&self) -> bool { + self.keyframe.swap(false, Ordering::Relaxed) + } +} + +/// A [`Streamer`] as a [`FrameSource`], for code that runs +/// `tsc_stream::Streams` itself (e.g. tsctl). +pub struct EncodedSource { + streamer: Streamer, + frames: std_mpsc::Receiver, + sink: Arc, +} + +impl EncodedSource { + pub fn new(streamer: Streamer) -> Self { + let (tx, frames) = std_mpsc::channel(); + let sink = Arc::new(ChannelSink { tx, keyframe: AtomicBool::new(true) }); + streamer.attach(sink.clone()); + Self { streamer, frames, sink } + } + + pub fn streamer(&self) -> &Streamer { + &self.streamer + } +} + +impl FrameSource for EncodedSource { + fn poll_frames(&mut self, _now: Instant, out: &mut Vec) { + out.extend(self.frames.try_iter()); + } + + fn request_keyframe(&mut self) { + self.sink.keyframe.store(true, Ordering::Relaxed); + } +} + +/// Whether `data` (one depacketized frame) starts a picture that decodes on +/// its own. Unknown formats count as keyframes, so the decoder gets to try. +pub fn is_keyframe(codec: Codec, data: &[u8]) -> bool { + match codec { + // Frame tag: bit 0 is 0 for key frames. + Codec::Vp8 => data.first().is_some_and(|b| b & 1 == 0), + Codec::Vp9 => vp9_is_keyframe(data), + Codec::H264 => h264_nal_types(data).any(|t| t == 5 || t == 7), + Codec::Av1 => av1_has_sequence_header(data).unwrap_or(true), + } +} + +/// VP9 uncompressed header: frame marker, profile, show_existing_frame, +/// frame_type (0 = key frame). +fn vp9_is_keyframe(data: &[u8]) -> bool { + let Some(&b) = data.first() else { return false }; + if b >> 6 != 2 { + return false; + } + let profile = ((b >> 5) & 1) | (((b >> 4) & 1) << 1); + // Profile 3 has a reserved bit after the profile. + let mut bit = if profile == 3 { 3 } else { 4 }; + let read = |bit: u32| (u32::from(b) >> (7 - bit)) & 1; + let show_existing = read(bit); + if show_existing == 1 { + return false; + } + bit += 1; + read(bit) == 0 +} + +/// NAL unit types of an Annex B H.264 frame. +fn h264_nal_types(data: &[u8]) -> impl Iterator + '_ { + data.windows(4).filter_map(|w| (w[..3] == [0, 0, 1]).then_some(w[3] & 0x1f)) +} + +/// Whether an AV1 temporal unit carries a sequence header OBU (sent with +/// key frames); `None` if the OBUs cannot be parsed. +fn av1_has_sequence_header(mut data: &[u8]) -> Option { + while let Some(&header) = data.first() { + let obu_type = (header >> 3) & 0x0f; + if obu_type == 1 { + return Some(true); + } + let extension = header & 0x04 != 0; + let has_size = header & 0x02 != 0; + let mut pos = 1 + usize::from(extension); + if !has_size { + return Some(false); + } + // LEB128 size. + let mut size = 0usize; + for i in 0..8 { + let byte = *data.get(pos)?; + pos += 1; + size |= usize::from(byte & 0x7f) << (7 * i); + if byte & 0x80 == 0 { + break; + } + } + data = data.get(pos + size..)?; + } + Some(false) +} + +/// Decoding statistics of a [`VideoPipeline`]. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DecodeStats { + /// Pictures handed to the callback. + pub decoded: u64, + /// Frames skipped while waiting for a keyframe. + pub skipped: u64, + pub keyframe_requests: u64, + pub codec: Option, + pub width: u32, + pub height: u32, + /// The last error (no decoder for the codec, decoding failed). + pub error: Option, +} + +#[derive(Default)] +struct QueueState { + frames: VecDeque, + /// Frames were dropped: wait for a keyframe. + lost: bool, + closed: bool, +} + +#[derive(Default)] +struct DecodeQueue { + state: Mutex, + cond: Condvar, + stats: Mutex, +} + +/// Feeds frames into a [`VideoPipeline`]; cheap to clone. +#[derive(Clone)] +pub struct FrameInput { + queue: Arc, +} + +impl FrameInput { + /// Queue a video frame (audio frames are ignored). When the decoder + /// falls more than [`MAX_QUEUED`] frames behind, the queue is dropped + /// and decoding resumes at the next keyframe. + pub fn push(&self, frame: MediaFrame) { + if frame.kind != MediaKind::Video { + return; + } + let mut state = lock(&self.queue.state); + if state.frames.len() >= MAX_QUEUED { + state.frames.clear(); + state.lost = true; + } + state.frames.push_back(frame); + drop(state); + self.queue.cond.notify_one(); + } + + /// Frames were lost before they reached us (e.g. a lagging receiver). + pub fn lost(&self) { + lock(&self.queue.state).lost = true; + } +} + +/// Decodes the video frames of one stream on its own thread. See the +/// [module docs](self). +pub struct VideoPipeline { + input: FrameInput, + thread: Option>, +} + +impl VideoPipeline { + /// `on_frame` gets every decoded picture on the decoding thread; + /// `request_keyframe` is called when the decoder needs one (at most + /// every half second). + pub fn new( + codecs: Arc, + on_frame: impl FnMut(VideoFrame) + Send + 'static, + request_keyframe: impl Fn() + Send + 'static, + ) -> Self { + let queue = Arc::new(DecodeQueue::default()); + let thread = std::thread::Builder::new() + .name("tsc-stream-decode".into()) + .spawn({ + let queue = queue.clone(); + move || decode_loop(&queue, &codecs, on_frame, request_keyframe) + }) + .map_err(|e| warn!("cannot start the video decoder: {e}")) + .ok(); + Self { input: FrameInput { queue }, thread } + } + + /// Where frames go in. + pub fn input(&self) -> FrameInput { + self.input.clone() + } + + pub fn push(&self, frame: MediaFrame) { + self.input.push(frame); + } + + pub fn stats(&self) -> DecodeStats { + lock(&self.input.queue.stats).clone() + } +} + +impl Drop for VideoPipeline { + fn drop(&mut self) { + lock(&self.input.queue.state).closed = true; + self.input.queue.cond.notify_all(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +fn decode_loop( + queue: &DecodeQueue, + codecs: &Codecs, + mut on_frame: impl FnMut(VideoFrame), + request_keyframe: impl Fn(), +) { + let mut decoder: Option<(Codec, Box)> = None; + // Start at a keyframe; the streamer sends one when a viewer connects. + let mut waiting = true; + let mut last_request: Option = None; + let mut request = |stats: &Mutex| { + if last_request.is_none_or(|t| t.elapsed() >= KEYFRAME_RETRY) { + last_request = Some(Instant::now()); + lock(stats).keyframe_requests += 1; + request_keyframe(); + } + }; + let set_error = |message: String| lock(&queue.stats).error = Some(message); + loop { + let (frame, lost) = { + let mut state = lock(&queue.state); + loop { + if state.closed { + return; + } + if let Some(frame) = state.frames.pop_front() { + break (frame, std::mem::take(&mut state.lost)); + } + state = + queue.cond.wait_timeout(state, POLL).unwrap_or_else(PoisonError::into_inner).0; + } + }; + let codec = match Codec::try_from(frame.codec) { + Ok(codec) => codec, + Err(e) => { + set_error(e.to_string()); + continue; + } + }; + if decoder.as_ref().is_none_or(|(c, _)| *c != codec) { + match codecs.new_decoder(codec) { + Ok(d) => { + decoder = Some((codec, d)); + waiting = true; + lock(&queue.stats).codec = Some(codec); + } + Err(e) => { + if decoder.is_some() || lock(&queue.stats).error.is_none() { + warn!("no decoder for the stream: {e}"); + } + decoder = None; + set_error(e.to_string()); + continue; + } + } + } + if lost || !frame.contiguous { + waiting = true; + } + if waiting { + if !is_keyframe(codec, &frame.data) { + lock(&queue.stats).skipped += 1; + request(&queue.stats); + continue; + } + waiting = false; + } + let Some((_, dec)) = &mut decoder else { continue }; + match dec.decode(&frame.data) { + Ok(Some(picture)) => { + { + let mut stats = lock(&queue.stats); + stats.decoded += 1; + (stats.width, stats.height) = (picture.width, picture.height); + } + on_frame(picture); + } + Ok(None) => {} + Err(e) => { + debug!("decoding failed: {e}"); + set_error(e.to_string()); + waiting = true; + request(&queue.stats); + } + } + } +} + +/// Decodes a stream watched through the engine: a [`VideoPipeline`] fed from +/// [`Engine::subscribe_frames`], asking the streamer for keyframes through +/// the engine. Stops when dropped. +pub struct Viewer { + pipeline: VideoPipeline, + forward: tokio::task::JoinHandle<()>, +} + +impl Viewer { + pub fn start( + engine: &Engine, + session: SessionId, + stream_id: &str, + codecs: Arc, + on_frame: impl FnMut(VideoFrame) + Send + 'static, + ) -> Self { + let request = { + let engine = engine.clone(); + let stream_id = stream_id.to_owned(); + move || { + let stream_id = stream_id.clone(); + engine.send(Command::RequestStreamKeyframe { session, stream_id }); + } + }; + let pipeline = VideoPipeline::new(codecs, on_frame, request); + let input = pipeline.input(); + let mut frames = engine.subscribe_frames(); + let stream_id = stream_id.to_owned(); + let forward = engine.runtime().spawn(async move { + use tokio::sync::broadcast::error::RecvError; + loop { + match frames.recv().await { + Ok(f) if f.session == session && f.stream_id == stream_id => { + input.push(f.frame) + } + Ok(_) => {} + Err(RecvError::Lagged(_)) => input.lost(), + Err(RecvError::Closed) => break, + } + } + }); + Self { pipeline, forward } + } + + pub fn stats(&self) -> DecodeStats { + self.pipeline.stats() + } +} + +impl Drop for Viewer { + fn drop(&mut self) { + self.forward.abort(); + } +} + +/// Hands the newest item from a producer thread to a consumer that may be +/// slower (e.g. a UI): an item that was not taken yet is replaced. +pub struct Latest { + slot: Mutex>, +} + +impl Default for Latest { + fn default() -> Self { + Self { slot: Mutex::new(None) } + } +} + +impl Latest { + pub fn new() -> Self { + Self::default() + } + + /// Store `item`. Returns `true` if the slot was empty, i.e. the consumer + /// needs a wake-up; otherwise a wake-up is already pending. + pub fn put(&self, item: T) -> bool { + lock(&self.slot).replace(item).is_none() + } + + pub fn take(&self) -> Option { + lock(&self.slot).take() + } +} + +/// Feeds a [`Streamer`]'s video straight into a [`VideoPipeline`]. +struct PipelineSink { + input: FrameInput, + codec: tsc_stream::Codec, + keyframe: Arc, +} + +impl MediaSink for PipelineSink { + fn send(&self, frame: EncodedFrame) -> bool { + self.input.push(MediaFrame { + kind: frame.kind, + codec: self.codec, + time: frame.time, + network_time: Instant::now(), + contiguous: true, + data: frame.data, + }); + true + } + + fn take_keyframe_request(&self) -> bool { + self.keyframe.swap(false, Ordering::Relaxed) + } +} + +/// Capture → encoder → decoder without a server, e.g. to preview a share or +/// to develop the viewer (`TSC_DEMO_STREAM` in the desktop app). +pub struct LocalPreview { + // Dropped first: no more frames into the pipeline. + streamer: Streamer, + pipeline: VideoPipeline, +} + +impl LocalPreview { + pub async fn start( + codecs: Arc, + mut config: StreamerConfig, + on_frame: impl FnMut(VideoFrame) + Send + 'static, + ) -> Result { + // The audio would go nowhere. + config.audio = false; + let codec = config.codec; + let streamer = Streamer::start(&codecs, config).await?; + let keyframe = Arc::new(AtomicBool::new(true)); + let pipeline = VideoPipeline::new(codecs, on_frame, { + let keyframe = keyframe.clone(); + move || keyframe.store(true, Ordering::Relaxed) + }); + let input = pipeline.input(); + streamer.attach(Arc::new(PipelineSink { input, codec: codec.into(), keyframe })); + Ok(Self { streamer, pipeline }) + } + + pub fn streamer(&self) -> &Streamer { + &self.streamer + } + + pub fn stats(&self) -> DecodeStats { + self.pipeline.stats() + } +} + +/// The first and last column of the rectangle in the middle row of a +/// decoded test pattern. Checks that pixels further than two columns from +/// its edges (which the codec blurs) have the colour of the rectangle or +/// the background. +#[cfg(test)] +pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) { + use tsc_media::capture::synthetic::{BACKGROUND, RECT_COLOR}; + + let rgba = tsc_media::convert::to_rgba_vec(picture).unwrap(); + let y = picture.height / 2; + let pixel = |x: u32| { + let i = ((y * picture.width + x) * 4) as usize; + [rgba[i], rgba[i + 1], rgba[i + 2]] + }; + let close = |p: [u8; 3], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) <= 24); + let inside: Vec = (0..picture.width).filter(|&x| close(pixel(x), RECT_COLOR)).collect(); + let (&a, &b) = inside.first().zip(inside.last()).expect("no rectangle in the middle row"); + for x in 0..picture.width { + if x + 2 < a || x > b + 2 { + assert!(close(pixel(x), BACKGROUND), "pixel {x},{y} is {:?}", pixel(x)); + } else if (a + 2..=b.saturating_sub(2)).contains(&x) { + assert!(close(pixel(x), RECT_COLOR), "pixel {x},{y} is {:?}", pixel(x)); + } + } + (a, b) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keyframe_detection() { + // VP8: the 1x1 keyframe of tsc-stream's synthetic source. + assert!(is_keyframe(Codec::Vp8, &tsc_stream::source::VP8_KEYFRAME_1X1)); + assert!(!is_keyframe(Codec::Vp8, &[0x31, 0x00])); + // VP9 profile 0: marker 10, profile 00, show_existing 0, frame_type 0/1. + assert!(is_keyframe(Codec::Vp9, &[0b1000_0000])); + assert!(!is_keyframe(Codec::Vp9, &[0b1000_0100])); + assert!(!is_keyframe(Codec::Vp9, &[0b1000_1000]), "show existing frame"); + // H.264: SPS + IDR vs. a non-IDR slice. + assert!(is_keyframe(Codec::H264, &[0, 0, 0, 1, 0x67, 1, 0, 0, 1, 0x65, 2])); + assert!(!is_keyframe(Codec::H264, &[0, 0, 0, 1, 0x41, 1, 2])); + // AV1: temporal delimiter (type 2, size 0) then a sequence header. + assert!(is_keyframe(Codec::Av1, &[0x12, 0x00, 0x0a, 0x01, 0xff])); + assert!(!is_keyframe(Codec::Av1, &[0x12, 0x00, 0x32, 0x01, 0xff])); + assert!(is_keyframe(Codec::Av1, &[0x12, 0x05]), "truncated: let the decoder try"); + } + + #[test] + fn latest_keeps_the_newest() { + let latest = Latest::new(); + assert!(latest.put(1)); + assert!(!latest.put(2), "a wake-up is pending"); + assert_eq!(latest.take(), Some(2)); + assert_eq!(latest.take(), None); + assert!(latest.put(3)); + } + + #[test] + fn peer_config_follows_codecs() { + let codecs = Codecs::new(); + let config = peer_config(&codecs, PeerConfig::default()); + assert_eq!(config.video_codecs, [VideoCodec::Vp8]); + assert!(config.accept_video_codecs.contains(&VideoCodec::Vp8)); + assert!(!config.accept_video_codecs.contains(&VideoCodec::H264), "no OpenH264 loaded"); + assert_eq!(stream_codec(&codecs, &config), Some(Codec::Vp8)); + let h264_only = PeerConfig { video_codecs: vec![VideoCodec::H264], ..config }; + assert_eq!(stream_codec(&codecs, &h264_only), None); + } + + /// The test pattern through VP8 and back, without a network: pictures + /// show the moving rectangle. + #[tokio::test(flavor = "multi_thread")] + async fn local_preview_decodes_the_pattern() { + let codecs = Arc::new(Codecs::new()); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (320, 240), + bitrate_kbps: 1500, + ..StreamerConfig::default() + }; + let (tx, rx) = std_mpsc::channel(); + let preview = LocalPreview::start(codecs, config, move |picture| { + let _ = tx.send(picture); + }) + .await + .unwrap(); + let mut spans = Vec::new(); + while spans.len() < 10 { + let picture = rx.recv_timeout(Duration::from_secs(5)).expect("no picture"); + assert_eq!((picture.width, picture.height), (320, 240)); + spans.push(rectangle_span(&picture)); + } + // 320 / 5 = 64 pixels wide, give or take the codec's blur. + for (a, b) in &spans { + assert!((60..=68).contains(&(b - a + 1)), "{spans:?}"); + } + assert_ne!(spans.first(), spans.last(), "the rectangle moves"); + let stats = preview.stats(); + assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}"); + assert_eq!(stats.codec, Some(Codec::Vp8)); + assert_eq!(preview.streamer().backend(), "synthetic"); + } + + /// Audio of the test pattern: 20 ms Opus frames on a 48 kHz clock. + #[tokio::test(flavor = "multi_thread")] + async fn streamer_sends_opus() { + let codecs = Codecs::new(); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (64, 48), + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + assert!(streamer.has_audio(), "{:?}", streamer.audio_error()); + let mut source = EncodedSource::new(streamer); + let mut frames = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(5); + while frames.iter().filter(|f: &&EncodedFrame| f.kind == MediaKind::Audio).count() < 10 { + assert!(Instant::now() < deadline, "no audio"); + tokio::time::sleep(Duration::from_millis(20)).await; + source.poll_frames(Instant::now(), &mut frames); + } + let times: Vec = frames + .iter() + .filter(|f| f.kind == MediaKind::Audio) + .map(|f| f.time.rebase(Frequency::FORTY_EIGHT_KHZ).numer()) + .collect(); + assert!(times.windows(2).all(|w| w[1] - w[0] == OPUS_FRAME as u64), "{times:?}"); + let video = frames.iter().find(|f| f.kind == MediaKind::Video).expect("video too"); + assert!(is_keyframe(Codec::Vp8, &video.data), "the first frame is a keyframe"); + assert!(source.streamer().stats().video_frames > 0); + } +} diff --git a/crates/tsc-core/src/session.rs b/crates/tsc-core/src/session.rs index 93b748a..4e4afd7 100644 --- a/crates/tsc-core/src/session.rs +++ b/crates/tsc-core/src/session.rs @@ -5,9 +5,11 @@ use std::sync::Arc; use tokio::sync::{broadcast, mpsc}; use tracing::debug; +use tsc_audio::AudioSettings; use tsc_model::{ChatMessage, ChatTarget, Presence}; +use tsclientlib::ClientId; -use crate::audio::{self, AudioHandle, AudioIn}; +use crate::audio::{self, AudioEvent, AudioHandle, AudioIn}; use crate::gateway::{self, GatewayCmd, GatewayEvent}; use crate::query::{self, QueryCmd, QueryEvent}; use crate::route::{ChatRoute, Dedup, route_chat}; @@ -24,9 +26,10 @@ impl SessionHandle { id: SessionId, events: broadcast::Sender, frames: broadcast::Sender, + audio_settings: AudioSettings, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); - tokio::spawn(Session::new(id, events, frames).run(rx)); + tokio::spawn(Session::new(id, events, frames, audio_settings).run(rx)); Self { tx } } @@ -42,7 +45,7 @@ enum SourceEvent { Gateway(u64, GatewayEvent), Query(u64, QueryEvent), AudioOut(u64, tsproto_packets::packets::OutPacket), - AudioError(String), + Audio(u64, AudioEvent), } struct Session { @@ -58,6 +61,7 @@ struct Session { query: Option<(u64, mpsc::UnboundedSender)>, query_presence: Option, audio: Option, + audio_settings: AudioSettings, /// Streams of the voice connection (TeamSpeak 6 only). streams: Option, stream_peer: PeerConfig, @@ -75,6 +79,7 @@ impl Session { id: SessionId, events: broadcast::Sender, frames: broadcast::Sender, + audio_settings: AudioSettings, ) -> Self { let (sources_tx, sources_rx) = mpsc::unbounded_channel(); Self { @@ -90,6 +95,7 @@ impl Session { query: None, query_presence: None, audio: None, + audio_settings, streams: None, stream_peer: PeerConfig::default(), frames, @@ -160,12 +166,13 @@ impl Session { self.stream_peer = options.stream_peer.clone(); let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); let (ev_tx, ev_rx) = mpsc::unbounded_channel(); + self.audio = None; if options.audio { let (out_tx, out_rx) = mpsc::unbounded_channel(); - let (err_tx, err_rx) = mpsc::unbounded_channel(); - self.audio = Some(audio::spawn(out_tx, err_tx, false)); + let (audio_tx, audio_rx) = mpsc::unbounded_channel(); + self.audio = Some(audio::spawn(out_tx, audio_tx, self.audio_settings.clone())); self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p)); - self.forward(err_rx, SourceEvent::AudioError); + self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e)); } tokio::spawn(voice::run(*options, cmd_rx, ev_tx)); self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e)); @@ -264,6 +271,29 @@ impl Session { } self.emit_state(); } + Command::SetAudioSettings(settings) => { + self.audio_settings = (*settings).clone(); + if let Some(a) = &self.audio { + a.send(AudioIn::Settings(settings)); + } + } + // Without audio there is nothing to adjust; the UI sends volumes + // again after connecting. + Command::SetClientVolume { client, volume, .. } => { + if let Some(a) = &self.audio { + a.send(AudioIn::ClientVolume { client: ClientId(client), volume }); + } + } + Command::SetClientMuted { client, muted, .. } => { + if let Some(a) = &self.audio { + a.send(AudioIn::ClientMuted { client: ClientId(client), muted }); + } + } + Command::SetStreamVolume { stream_id, volume, .. } => { + if let Some(a) = &self.audio { + a.send(AudioIn::StreamVolume { stream: stream_id, volume }); + } + } Command::StartStream { setup, auto_accept, .. } => { self.stream_input(StreamInput::Start { setup, auto_accept }); } @@ -287,7 +317,7 @@ impl Session { Command::RequestStreamKeyframe { stream_id, .. } => { self.stream_input(StreamInput::RequestKeyframe { stream_id }); } - Command::CloseSession { .. } => {} + Command::CloseSession { .. } | Command::TestMicrophone { .. } => {} } } @@ -389,7 +419,12 @@ impl Session { let _ = tx.send(VoiceCmd::Audio(packet)); } } - SourceEvent::AudioError(message) => self.error(message), + SourceEvent::Audio(g, event) if self.is_current(Source::Voice, g) => match event { + AudioEvent::Error(message) => self.error(message), + AudioEvent::Level { db, sending } => { + self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending }) + } + }, _ => debug!("event from a replaced source ignored"), } } @@ -410,12 +445,19 @@ impl Session { voice.clone(), self.events.clone(), self.frames.clone(), + self.audio.clone(), )); } self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities }); self.reopen_relayed_chats(); } VoiceEvent::Presence(p) => { + // Client ids are reused: forget the volumes of those who left. + if let (Some(a), Some(old)) = (&self.audio, &self.voice_presence) { + for id in old.clients.keys().filter(|id| !p.clients.contains_key(id)) { + a.send(AudioIn::ClientLeft(ClientId(*id))); + } + } if let Some(s) = &self.streams { let clients: BTreeMap<_, _> = p.clients.values().map(|c| (c.id, c.streaming)).collect(); diff --git a/crates/tsc-core/src/stream.rs b/crates/tsc-core/src/stream.rs index 80ed3a2..773bcef 100644 --- a/crates/tsc-core/src/stream.rs +++ b/crates/tsc-core/src/stream.rs @@ -22,6 +22,7 @@ use tsc_stream::{ }; use tsclientlib::ClientId; +use crate::audio::{AudioHandle, AudioIn}; use crate::voice::VoiceCmd; use crate::{Event, SessionId}; @@ -138,6 +139,7 @@ impl StreamHandle { voice: mpsc::UnboundedSender, events: broadcast::Sender, frames: broadcast::Sender, + audio: Option, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); let task = StreamTask { @@ -146,6 +148,7 @@ impl StreamHandle { voice, events, frames, + audio, tx: tx.clone(), sink: None, clients: BTreeMap::new(), @@ -165,6 +168,8 @@ struct StreamTask { voice: mpsc::UnboundedSender, events: broadcast::Sender, frames: broadcast::Sender, + /// Where the audio of watched streams plays, if the session has audio. + audio: Option, /// For the sinks handed out. tx: mpsc::UnboundedSender, /// The sink of our live stream. @@ -299,8 +304,20 @@ impl StreamTask { let state = match event { WatchEvent::Accepted => WatchState::Connecting, WatchEvent::Connected => WatchState::Connected, - WatchEvent::Ended(reason) => WatchState::Ended(reason), + WatchEvent::Ended(reason) => { + if let Some(audio) = &self.audio { + audio.send(AudioIn::StreamEnded(id.clone())); + } + WatchState::Ended(reason) + } WatchEvent::Frame(frame) => { + if let (MediaKind::Audio, Some(audio)) = (frame.kind, &self.audio) { + audio.send(AudioIn::StreamAudio { + stream: id.clone(), + time: frame.time.rebase(Frequency::FORTY_EIGHT_KHZ).numer(), + data: frame.data.clone(), + }); + } let _ = self.frames.send(StreamFrame { session, stream_id: id, frame }); return; } @@ -322,6 +339,9 @@ impl StreamTask { } for watched in self.streams.watching() { let stream_id = watched.id().to_owned(); + if let Some(audio) = &self.audio { + audio.send(AudioIn::StreamEnded(stream_id.clone())); + } self.emit(Event::WatchState { session, stream_id, state: WatchState::Ended(ended()) }); } if self.streams.directory().iter().next().is_some() { @@ -416,13 +436,18 @@ mod tests { .expect("timed out") } - /// Two stream tasks (sessions 1 and 2) whose commands go through a fake server. - #[tokio::test(flavor = "multi_thread")] - async fn stream_tasks_through_fake_server() { - let (events, mut rx) = broadcast::channel(4096); - let (frames, mut frames_rx) = broadcast::channel(4096); + type Handles = Arc>; + + /// Two stream tasks (sessions 1 and 2) whose commands go through a fake + /// server; `audio` is the viewer's audio thread. + fn pair( + audio: Option, + ) -> (Handles, broadcast::Receiver, broadcast::Receiver) { + let (events, rx) = broadcast::channel(4096); + let (frames, frames_rx) = broadcast::channel(4096); let mut voices = Vec::new(); let mut handles = Vec::new(); + let mut audio = audio; for (i, clid) in CLIENTS.into_iter().enumerate() { let (voice, voice_rx) = mpsc::unbounded_channel(); let config = PeerConfig::loopback(); @@ -434,6 +459,7 @@ mod tests { voice, events.clone(), frames.clone(), + if session == 2 { audio.take() } else { None }, )); voices.push(voice_rx); } @@ -452,12 +478,20 @@ mod tests { } }); } + (handles, rx, frames_rx) + } + /// Session 1 streams (auto-accepting), session 2 watches; returns the sink + /// once the viewer is connected. + async fn live_and_watching( + handles: &Handles, + rx: &mut broadcast::Receiver, + ) -> StreamSink { let setup = StreamSetup { name: "t".into(), ..Default::default() }; handles[0].send(StreamInput::Start { setup, auto_accept: true }); // Live for the streamer and listed for the viewer, in either order. let (mut sink, mut listed) = (None, false); - wait(&mut rx, |e| { + wait(rx, |e| { match e { Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => { sink = Some(s); @@ -468,13 +502,21 @@ mod tests { (sink.is_some() && listed).then_some(()) }) .await; - let sink = sink.unwrap(); handles[1].send(StreamInput::Watch { stream_id: "s-1".into() }); - wait(&mut rx, |e| match e { + wait(rx, |e| match e { Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()), _ => None, }) .await; + sink.unwrap() + } + + #[tokio::test(flavor = "multi_thread")] + async fn stream_tasks_through_fake_server() { + // The viewer's audio thread. + let (audio, audio_rx) = AudioHandle::channel(); + let (handles, mut rx, mut frames_rx) = pair(Some(audio)); + let sink = live_and_watching(&handles, &mut rx).await; // Frames from the sink reach the viewer's frame bus. let feeder = tokio::spawn({ @@ -518,6 +560,20 @@ mod tests { assert!(!sink.is_live()); feeder.await.unwrap(); + // Stream audio went to the viewer's audio thread, in 20 ms steps, + // and the ended stream was forgotten there. + let received: Vec = audio_rx.try_iter().collect(); + let times: Vec = received + .iter() + .filter_map(|m| match m { + AudioIn::StreamAudio { stream, time, .. } if stream == "s-1" => Some(*time), + _ => None, + }) + .collect(); + assert!(times.len() >= 10, "{} audio frames", times.len()); + assert!(times.windows(2).all(|w| w[1] > w[0] && (w[1] - w[0]) % 960 == 0), "{times:?}"); + assert!(matches!(received.last(), Some(AudioIn::StreamEnded(id)) if id == "s-1")); + // Errors surface as events. handles[1].send(StreamInput::Leave { stream_id: "s-1".into() }); wait(&mut rx, |e| match e { @@ -527,4 +583,77 @@ mod tests { .await; handles[1].send(StreamInput::Shutdown("bye".into())); } + + /// The whole path: test pattern → VP8 → stream task → str0m peers on + /// loopback → the viewer's frame bus → decoder. The pictures show the + /// moving rectangle. + #[cfg(feature = "media")] + #[tokio::test(flavor = "multi_thread")] + async fn test_pattern_through_stream_tasks() { + use std::sync::mpsc as std_mpsc; + + use tsc_media::capture::SourceId; + use tsc_media::{Codec, Codecs}; + + use crate::media::{Streamer, StreamerConfig, VideoPipeline, rectangle_span}; + + let (handles, mut rx, mut frames_rx) = pair(None); + let sink = live_and_watching(&handles, &mut rx).await; + let codecs = Arc::new(Codecs::new()); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (320, 240), + bitrate_kbps: 1500, + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + streamer.attach(Arc::new(sink.clone())); + + let (tx, pictures) = std_mpsc::channel(); + let pipeline = VideoPipeline::new( + codecs, + move |picture| { + let _ = tx.send(picture); + }, + { + let handles = handles.clone(); + move || handles[1].send(StreamInput::RequestKeyframe { stream_id: "s-1".into() }) + }, + ); + let input = pipeline.input(); + let forward = tokio::spawn(async move { + while let Ok(f) = frames_rx.recv().await { + input.push(f.frame); + } + }); + let spans = tokio::task::spawn_blocking(move || { + let mut spans = Vec::new(); + while spans.len() < 15 { + let picture = pictures.recv_timeout(Duration::from_secs(10)).expect("no picture"); + assert_eq!((picture.width, picture.height), (320, 240)); + spans.push(rectangle_span(&picture)); + } + spans + }) + .await + .unwrap(); + for (a, b) in &spans { + assert!((60..=68).contains(&(b - a + 1)), "{spans:?}"); + } + assert_ne!(spans.first(), spans.last(), "the rectangle moves"); + let stats = pipeline.stats(); + assert_eq!(stats.codec, Some(Codec::Vp8)); + assert!(stats.error.is_none(), "{stats:?}"); + let sent = streamer.stats(); + assert!(sent.video_frames >= 15 && sent.audio_frames > 0, "{sent:?}"); + + handles[0].send(StreamInput::Stop); + wait(&mut rx, |e| match e { + Event::WatchState { session: 2, state: WatchState::Ended(_), .. } => Some(()), + _ => None, + }) + .await; + forward.abort(); + drop(streamer); + } }