From b625c38d7fc624097c9b3bf7a823b3587c635ecd Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 23:39:11 +0300 Subject: [PATCH] voelin-media: push the studio to a WHIP service Going live to a broadcast service is the one output that is not a file, and WHIP is the standard that makes it one HTTP request: post the offer, apply the answer, delete the location to stop. str0m already drives WebRTC here, so the session is a thread of its own fed through a bounded channel -- a slow or dead upload drops its own packets instead of stalling an encoder. The session offers only the codec the studio already encodes plus Opus, so the service can never negotiate its way into a second encode. Candidates are one host candidate on the interface that routes to the service, found by connecting a throwaway socket: enough for a service with a public address and for a server on this machine, not enough behind a NAT the service cannot reach back through. STUN and TURN are not here yet. tests/studio_whip.rs is a WHIP server built on str0m in the test: the offer is posted, ICE and DTLS come up, real VP8 and Opus packets arrive, a refusal is reported with the service's own words, and stopping deletes the resource. Co-Authored-By: Claude Opus 5 --- crates/voelin-core/Cargo.toml | 2 +- crates/voelin-media/Cargo.toml | 3 + crates/voelin-media/src/studio/output/mod.rs | 5 +- crates/voelin-media/src/studio/output/whip.rs | 480 ++++++++++++++++++ crates/voelin-media/tests/studio_whip.rs | 305 +++++++++++ 5 files changed, 793 insertions(+), 2 deletions(-) create mode 100644 crates/voelin-media/src/studio/output/whip.rs create mode 100644 crates/voelin-media/tests/studio_whip.rs diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 8ef9568..b659708 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -35,7 +35,7 @@ toml = "1.1.6" tracing = "0.1" voelin-audio = { path = "../voelin-audio", default-features = false } voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] } -voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m"], optional = true } +voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m", "whip"], optional = true } voelin-model = { path = "../voelin-model" } voelin-observer = { path = "../voelin-observer" } # Paths only (the cache directory). diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index a871b40..8f1c3ad 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -33,6 +33,9 @@ pipewire = ["dep:ashpd", "dep:pipewire", "dep:memmap2", "dep:rustix"] wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols-wlr", "dep:memmap2", "dep:rustix"] # Conversion between `Codec` and `str0m::format::Codec`. str0m = ["dep:str0m"] +# The studio's WHIP output: a WebRTC session (str0m) set up over HTTP. Needs +# str0m's crypto provider, the same one voelin-stream uses. +whip = ["str0m", "str0m/aws-lc-rs", "dep:reqwest"] v4l = [] [dependencies] diff --git a/crates/voelin-media/src/studio/output/mod.rs b/crates/voelin-media/src/studio/output/mod.rs index 5373642..f9f6472 100644 --- a/crates/voelin-media/src/studio/output/mod.rs +++ b/crates/voelin-media/src/studio/output/mod.rs @@ -7,7 +7,8 @@ //! - [`record`]: a file, WebM or Matroska ([`ebml`]) //! - [`replay`]: the last few seconds in memory (spilling to disk), written //! out as a clip without re-encoding -//! - `whip`: WHIP (WebRTC-HTTP ingestion) to a broadcast service +//! - [`whip`]: WHIP (WebRTC-HTTP ingestion) to a broadcast service (feature +//! `whip`) //! - [`rtmp`]: the seam for RTMP, which will go through the FFmpeg loader //! //! A sink never stalls the encoder: [`OutputSink::write`] returns an error @@ -21,6 +22,8 @@ pub mod ebml; pub mod record; pub mod replay; pub mod rtmp; +#[cfg(feature = "whip")] +pub mod whip; /// Which stream a packet belongs to. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] diff --git a/crates/voelin-media/src/studio/output/whip.rs b/crates/voelin-media/src/studio/output/whip.rs new file mode 100644 index 0000000..3277921 --- /dev/null +++ b/crates/voelin-media/src/studio/output/whip.rs @@ -0,0 +1,480 @@ +//! WHIP: pushing the studio to a broadcast service over WebRTC. +//! +//! WHIP (WebRTC-HTTP ingestion, RFC 9725) is one HTTP request: `POST` the SDP +//! offer, get the answer and a `Location` back, and `DELETE` that location to +//! stop. Everything after that is an ordinary WebRTC session, which `str0m` +//! drives on a thread of its own; the studio's encoded packets go in through +//! a channel, so an output that is slow or gone never holds up an encoder. +//! +//! The session offers exactly one video codec — the one the studio already +//! encodes — and Opus, both send-only, so the service never asks for a codec +//! that would mean a second encode. +//! +//! Candidates: one host candidate on the interface that reaches the service. +//! That is enough for a service with a public address, which is what WHIP is +//! for, and for a server on this machine (the tests). There is no STUN or +//! TURN here yet, so a studio behind a NAT that the service cannot reach back +//! through will not connect. + +use std::io::ErrorKind; +use std::net::{SocketAddr, UdpSocket}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use str0m::change::SdpAnswer; +use str0m::media::{Direction, Frequency, MediaKind, MediaTime, Mid, Pt}; +use str0m::net::{Protocol, Receive}; +use str0m::{Candidate, Event, Input, Output, Rtc, RtcConfig}; +use tracing::{debug, trace, warn}; + +use crate::codec::Codec; +use crate::studio::output::{OutputSink, Packet, Track}; +use crate::{Error, Result}; + +/// Packets waiting for the session thread; a full queue drops the oldest, +/// because a stalled upload must not stall an encoder. +const QUEUE: usize = 256; + +fn error(message: impl Into) -> Error { + Error::Capture { backend: "whip", message: message.into() } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// One packet on its way to the session thread. +struct Queued { + video: bool, + pts_90khz: u64, + data: Vec, +} + +/// What a WHIP output is doing. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WhipStats { + pub connected: bool, + pub packets: u64, + pub bytes: u64, + /// Packets dropped because the session could not keep up. + pub dropped: u64, + pub error: Option, +} + +/// A WHIP session; stops and deletes its resource when dropped. +pub struct Whip { + name: String, + /// The `Location` the service gave us, to `DELETE` on stop. + resource: Option, + token: Option, + layer: u32, + codec: Codec, + queue: Option>, + thread: Option>, + stop: Arc, + shared: Arc, +} + +#[derive(Default)] +struct Shared { + connected: AtomicBool, + packets: AtomicU64, + bytes: AtomicU64, + dropped: AtomicU64, + error: Mutex>, +} + +impl Whip { + /// Whether `url` is one this output takes. + pub fn handles(url: &str) -> bool { + url.starts_with("http://") || url.starts_with("https://") + } + + /// Offer `codec` (the layer the studio encodes) and Opus to the WHIP + /// endpoint at `url`, with `token` as the bearer token if the service + /// wants one. + /// + /// Must run on a Tokio runtime: the HTTP request does. + pub async fn start( + url: &str, + token: Option<&str>, + codec: Codec, + layer: u32, + audio: bool, + ) -> Result { + let endpoint = reqwest::Url::parse(url).map_err(|e| error(format!("bad WHIP url: {e}")))?; + let host = endpoint + .socket_addrs(|| match endpoint.scheme() { + "https" => Some(443), + _ => Some(80), + }) + .map_err(|e| error(format!("cannot resolve {url}: {e}")))? + .into_iter() + .next() + .ok_or_else(|| error(format!("{url} resolves to nothing")))?; + + let (socket, local) = bind_towards(host)?; + let mut rtc = build_rtc(codec, audio); + let candidate = Candidate::host(local, Protocol::Udp) + .map_err(|e| error(format!("cannot offer {local}: {e}")))?; + rtc.add_local_candidate(candidate); + let mut api = rtc.sdp_api(); + let msid = Some("voelin-studio".to_owned()); + let video = api.add_media(MediaKind::Video, Direction::SendOnly, msid.clone(), None, None); + let audio_mid = + audio.then(|| api.add_media(MediaKind::Audio, Direction::SendOnly, msid, None, None)); + let (offer, pending) = api.apply().ok_or_else(|| error("nothing to offer"))?; + + let mut request = reqwest::Client::new() + .post(endpoint.clone()) + .header("content-type", "application/sdp") + .body(offer.to_sdp_string()); + if let Some(token) = token { + request = request.bearer_auth(token); + } + let response = + request.send().await.map_err(|e| error(format!("the WHIP request failed: {e}")))?; + let status = response.status(); + let resource = response + .headers() + .get(reqwest::header::LOCATION) + .and_then(|l| l.to_str().ok()) + .and_then(|l| endpoint.join(l).ok()) + .map(|u| u.to_string()); + let body = response.text().await.unwrap_or_default(); + if !status.is_success() { + return Err(error(format!("the service answered {status}: {}", body.trim()))); + } + let answer = SdpAnswer::from_sdp_string(&body) + .map_err(|e| error(format!("the service's answer is not SDP: {e}")))?; + rtc.sdp_api() + .accept_answer(pending, answer) + .map_err(|e| error(format!("the service's answer was refused: {e}")))?; + debug!(url, resource = resource.as_deref().unwrap_or("-"), %codec, "WHIP session"); + + let (queue, packets) = sync_channel(QUEUE); + let stop = Arc::new(AtomicBool::new(false)); + let shared = Arc::new(Shared::default()); + let session = Session { + rtc, + socket, + packets, + stop: stop.clone(), + shared: shared.clone(), + video, + audio: audio_mid, + writers: [None, None], + }; + let thread = std::thread::Builder::new() + .name("voelin-whip".into()) + .spawn(move || session.run()) + .map_err(|e| error(e.to_string()))?; + Ok(Self { + name: url.to_owned(), + resource, + token: token.map(str::to_owned), + layer, + codec, + queue: Some(queue), + thread: Some(thread), + stop, + shared, + }) + } + + /// The resource the service gave us, which stops the stream when deleted. + pub fn resource(&self) -> Option<&str> { + self.resource.as_deref() + } + + pub fn stats(&self) -> WhipStats { + WhipStats { + connected: self.shared.connected.load(Ordering::Relaxed), + packets: self.shared.packets.load(Ordering::Relaxed), + bytes: self.shared.bytes.load(Ordering::Relaxed), + dropped: self.shared.dropped.load(Ordering::Relaxed), + error: lock(&self.shared.error).clone(), + } + } + + /// Stop the session and tell the service, if there is a runtime to do it + /// on (the request needs one). + fn teardown(&mut self) { + self.stop.store(true, Ordering::Relaxed); + self.queue = None; + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + let Some(resource) = self.resource.take() else { return }; + let token = self.token.clone(); + let logged = resource.clone(); + let delete = async move { + let mut request = reqwest::Client::new().delete(&resource); + if let Some(token) = token { + request = request.bearer_auth(token); + } + match request.send().await { + Ok(response) => debug!(%resource, status = %response.status(), "WHIP deleted"), + Err(e) => debug!(%resource, "cannot delete the WHIP resource: {e}"), + } + }; + match tokio::runtime::Handle::try_current() { + Ok(handle) => { + let _ = logged; + handle.spawn(delete); + } + // No runtime: the service times the session out instead. + Err(_) => debug!(resource = %logged, "no runtime to delete the WHIP resource on"), + } + } +} + +impl Drop for Whip { + fn drop(&mut self) { + self.teardown(); + } +} + +impl OutputSink for Whip { + fn name(&self) -> &str { + &self.name + } + + fn wants(&self, track: Track) -> bool { + match track { + Track::Video { codec, layer } => layer == self.layer && codec == self.codec, + Track::Audio { .. } => true, + } + } + + 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) + } + + fn write(&mut self, packet: &Packet<'_>) -> Result<()> { + let Some(queue) = &self.queue else { return Ok(()) }; + if !self.wants(packet.track) { + return Ok(()); + } + let queued = Queued { + video: packet.track.is_video(), + pts_90khz: packet.pts_90khz, + data: packet.data.to_vec(), + }; + match queue.try_send(queued) { + Ok(()) => Ok(()), + Err(TrySendError::Full(_)) => { + self.shared.dropped.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + Err(TrySendError::Disconnected(_)) => Err(error( + lock(&self.shared.error).clone().unwrap_or_else(|| "session ended".into()), + )), + } + } + + fn finish(&mut self) -> Result<()> { + self.teardown(); + Ok(()) + } + + fn bytes(&self) -> u64 { + self.shared.bytes.load(Ordering::Relaxed) + } +} + +/// An RTC that offers exactly `codec` and, if `audio`, Opus. +fn build_rtc(codec: Codec, audio: bool) -> Rtc { + let config = RtcConfig::new().clear_codecs().enable_opus(audio); + let config = match codec { + Codec::Vp8 => config.enable_vp8(true), + Codec::Vp9 => config.enable_vp9(true), + Codec::Av1 => config.enable_av1(true), + Codec::H264 => config.enable_h264(true), + Codec::H265 => config.enable_h265(true), + }; + config.build(Instant::now()) +} + +/// A UDP socket on the interface that reaches `peer`, and its address. +/// +/// Connecting a socket makes the kernel pick the route, so its local address +/// is the one the peer can send back to; the socket that is kept is then +/// bound to that address but left unconnected, so it takes the service's +/// candidates as well. +fn bind_towards(peer: SocketAddr) -> Result<(UdpSocket, SocketAddr)> { + let any = if peer.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }; + let probe = UdpSocket::bind(any)?; + probe.connect(peer)?; + let local = probe.local_addr()?; + drop(probe); + let socket = UdpSocket::bind(SocketAddr::new(local.ip(), 0))?; + let local = socket.local_addr()?; + Ok((socket, local)) +} + +/// The session's thread: str0m's I/O and the studio's packets. +struct Session { + rtc: Rtc, + socket: UdpSocket, + packets: Receiver, + stop: Arc, + shared: Arc, + video: Mid, + audio: Option, + /// The payload type for video and for audio, once negotiated. + writers: [Option<(Mid, Pt)>; 2], +} + +impl Session { + fn run(mut self) { + let mut buf = vec![0u8; 2000]; + let local = match self.socket.local_addr() { + Ok(addr) => addr, + Err(e) => { + self.fail(format!("the WHIP socket has no address: {e}")); + return; + } + }; + while !self.stop.load(Ordering::Relaxed) { + if let Err(e) = self.rtc.handle_input(Input::Timeout(Instant::now())) { + self.fail(format!("WHIP session failed: {e}")); + return; + } + let deadline = loop { + if !self.rtc.is_alive() { + self.fail("the WHIP session closed"); + return; + } + match self.rtc.poll_output() { + Ok(Output::Timeout(t)) => break t, + Ok(Output::Transmit(t)) => { + if let Err(e) = self.socket.send_to(&t.contents, t.destination) { + 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"); + } + } + Err(e) => { + self.fail(format!("WHIP session failed: {e}")); + return; + } + } + }; + // Feed what the studio queued, then wait for the socket until + // str0m's deadline (never longer than a tick, so the queue is + // drained promptly). + while let Ok(queued) = self.packets.try_recv() { + self.send(queued); + } + let now = Instant::now(); + let wait = deadline.saturating_duration_since(now).min(Duration::from_millis(5)); + if self.socket.set_read_timeout(Some(wait.max(Duration::from_millis(1)))).is_err() { + return; + } + match self.socket.recv_from(&mut buf) { + Ok((n, source)) => { + let Ok(contents) = buf[..n].try_into() else { continue }; + let input = Input::Receive( + Instant::now(), + Receive { proto: Protocol::Udp, source, destination: local, contents }, + ); + if self.rtc.accepts(&input) + && let Err(e) = self.rtc.handle_input(input) + { + self.fail(format!("WHIP session failed: {e}")); + return; + } + } + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {} + Err(e) => trace!("WHIP receive failed: {e}"), + } + } + } + + /// One studio packet into the session. + fn send(&mut self, queued: Queued) { + let slot = usize::from(!queued.video); + let kind = if queued.video { MediaKind::Video } else { MediaKind::Audio }; + if self.writers[slot].is_none() { + let Some(mid) = (if queued.video { Some(self.video) } else { self.audio }) else { + return; + }; + let Some(writer) = self.rtc.writer(mid) else { return }; + let Some(pt) = + writer.payload_params().find(|p| p.spec().codec.kind() == kind).map(|p| p.pt()) + else { + return; + }; + self.writers[slot] = Some((mid, pt)); + } + let Some((mid, pt)) = self.writers[slot] else { return }; + // Video keeps the 90 kHz clock; Opus counts samples at 48 kHz. + let time = if queued.video { + MediaTime::from_90khz(queued.pts_90khz) + } else { + MediaTime::new(queued.pts_90khz * 48_000 / 90_000, Frequency::FORTY_EIGHT_KHZ) + }; + let bytes = queued.data.len() as u64; + let Some(writer) = self.rtc.writer(mid) else { return }; + match writer.write(pt, Instant::now(), time, queued.data) { + Ok(()) => { + self.shared.packets.fetch_add(1, Ordering::Relaxed); + self.shared.bytes.fetch_add(bytes, Ordering::Relaxed); + } + Err(e) => trace!(?kind, "WHIP packet not sent: {e}"), + } + } + + fn fail(&self, message: impl Into) { + let message = message.into(); + warn!("{message}"); + *lock(&self.shared.error) = Some(message); + self.shared.connected.store(false, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn urls_and_codecs() { + assert!(Whip::handles("https://live.example/whip")); + assert!(Whip::handles("http://127.0.0.1:8080/whip")); + assert!(!Whip::handles("rtmp://live.example/app")); + // Every codec the studio can encode has an str0m codec to offer. + for codec in [Codec::Vp8, Codec::Vp9, Codec::Av1, Codec::H264, Codec::H265] { + assert!(build_rtc(codec, true).is_alive(), "{codec}"); + } + } + + #[test] + fn a_socket_binds_towards_the_peer() { + let (socket, local) = bind_towards("127.0.0.1:9".parse().unwrap()).unwrap(); + assert!(local.ip().is_loopback(), "{local}"); + assert_ne!(local.port(), 0); + assert_eq!(socket.local_addr().unwrap(), local); + } + + #[tokio::test] + async fn an_endpoint_that_is_not_there_fails() { + // Port 1 on loopback: nothing listens. + let Err(e) = Whip::start("http://127.0.0.1:1/whip", Some("t"), Codec::Vp8, 0, true).await + else { + panic!("a session started against nothing"); + }; + assert!(e.to_string().contains("WHIP request failed"), "{e}"); + assert!(Whip::start("not a url", None, Codec::Vp8, 0, true).await.is_err()); + } +} diff --git a/crates/voelin-media/tests/studio_whip.rs b/crates/voelin-media/tests/studio_whip.rs new file mode 100644 index 0000000..743c537 --- /dev/null +++ b/crates/voelin-media/tests/studio_whip.rs @@ -0,0 +1,305 @@ +//! The studio's WHIP output against a WHIP server built on str0m here in the +//! test: the offer is posted, the answer applied, ICE and DTLS come up, real +//! VP8 frames arrive at the server, and stopping deletes the resource. +//! +//! The server is the smallest thing that is still WHIP: a TCP listener that +//! answers one `POST` with `201 Created`, a `Location` and the SDP answer, and +//! one `DELETE` with `200`. +#![cfg(feature = "whip")] + +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use str0m::change::SdpOffer; +use str0m::media::MediaKind; +use str0m::net::{Protocol, Receive}; +use str0m::{Candidate, Event, Input, Output, Rtc, RtcConfig}; +use voelin_media::codec::{Codec, Codecs, EncoderConfig}; +use voelin_media::frame::{FrameData, VideoFrame}; +use voelin_media::studio::output::whip::Whip; +use voelin_media::studio::output::{OutputSink, Packet, Track}; + +const WIDTH: u32 = 160; +const HEIGHT: u32 = 120; + +/// What the test server saw. +#[derive(Default)] +struct Seen { + video: AtomicU64, + audio: AtomicU64, + keyframes: AtomicU64, + connected: AtomicBool, + deleted: AtomicBool, + resource: Mutex>, +} + +/// Read one HTTP request: its start line and body. +fn read_request(stream: &mut TcpStream) -> Option<(String, String)> { + let mut reader = BufReader::new(stream.try_clone().ok()?); + let mut start = String::new(); + reader.read_line(&mut start).ok()?; + let mut length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).ok()? == 0 { + break; + } + if line.trim().is_empty() { + break; + } + if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap_or(0); + } + } + let mut body = vec![0u8; length]; + if length > 0 { + reader.read_exact(&mut body).ok()?; + } + Some((start.trim().to_owned(), String::from_utf8_lossy(&body).into_owned())) +} + +/// A WHIP server on a loopback port; returns its URL and what it saw. +fn spawn_server() -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").expect("a port"); + let port = listener.local_addr().unwrap().port(); + let url = format!("http://127.0.0.1:{port}/whip"); + let seen = Arc::new(Seen::default()); + let shared = seen.clone(); + std::thread::Builder::new() + .name("whip-test-server".into()) + .spawn(move || { + for stream in listener.incoming().take(2) { + let Ok(mut stream) = stream else { continue }; + let Some((start, body)) = read_request(&mut stream) else { continue }; + if start.starts_with("DELETE") { + shared.deleted.store(true, Ordering::Relaxed); + let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + continue; + } + assert!(start.starts_with("POST"), "{start}"); + let answer = match accept(&body, &shared) { + Ok(answer) => answer, + Err(e) => { + let _ = stream.write_all( + format!( + "HTTP/1.1 400 Bad Request\r\nContent-Length: {}\r\n\r\n{e}", + e.len() + ) + .as_bytes(), + ); + continue; + } + }; + *shared.resource.lock().unwrap() = Some(format!("/whip/{port}")); + let response = format!( + "HTTP/1.1 201 Created\r\nContent-Type: application/sdp\r\n\ + Location: /whip/{port}\r\nContent-Length: {}\r\n\r\n{answer}", + answer.len() + ); + let _ = stream.write_all(response.as_bytes()); + let _ = stream.flush(); + } + }) + .expect("the server thread"); + (url, seen) +} + +/// Accept an offer, start the session's thread and return the SDP answer. +fn accept(offer: &str, seen: &Arc) -> Result { + let offer = SdpOffer::from_sdp_string(offer).map_err(|e| e.to_string())?; + let mut rtc = + RtcConfig::new().clear_codecs().enable_opus(true).enable_vp8(true).build(Instant::now()); + let socket = UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?; + let local = socket.local_addr().map_err(|e| e.to_string())?; + rtc.add_local_candidate(Candidate::host(local, Protocol::Udp).map_err(|e| e.to_string())?); + let answer = rtc.sdp_api().accept_offer(offer).map_err(|e| e.to_string())?; + let seen = seen.clone(); + std::thread::Builder::new() + .name("whip-test-session".into()) + .spawn(move || run_session(rtc, socket, local, seen)) + .map_err(|e| e.to_string())?; + Ok(answer.to_sdp_string()) +} + +fn run_session(mut rtc: Rtc, socket: UdpSocket, local: SocketAddr, seen: Arc) { + let mut buf = vec![0u8; 2000]; + let deadline = Instant::now() + Duration::from_secs(30); + while rtc.is_alive() && Instant::now() < deadline { + if rtc.handle_input(Input::Timeout(Instant::now())).is_err() { + return; + } + let timeout = loop { + match rtc.poll_output() { + Ok(Output::Timeout(t)) => break t, + Ok(Output::Transmit(t)) => { + let _ = socket.send_to(&t.contents, t.destination); + } + Ok(Output::Event(Event::IceConnectionStateChange(state))) => { + if matches!( + state, + str0m::IceConnectionState::Connected | str0m::IceConnectionState::Completed + ) { + seen.connected.store(true, Ordering::Relaxed); + } + } + Ok(Output::Event(Event::MediaData(data))) => { + if data.params.spec().codec.kind() == MediaKind::Video { + seen.video.fetch_add(1, Ordering::Relaxed); + seen.keyframes.fetch_add( + u64::from(data.contiguous && is_vp8_key(&data.data)), + Ordering::Relaxed, + ); + } else { + seen.audio.fetch_add(1, Ordering::Relaxed); + } + } + Ok(Output::Event(_)) => {} + Err(_) => return, + } + }; + let wait = timeout + .saturating_duration_since(Instant::now()) + .clamp(Duration::from_millis(1), Duration::from_millis(20)); + if socket.set_read_timeout(Some(wait)).is_err() { + return; + } + match socket.recv_from(&mut buf) { + Ok((n, source)) => { + let Ok(contents) = buf[..n].try_into() else { continue }; + let input = Input::Receive( + Instant::now(), + Receive { proto: Protocol::Udp, source, destination: local, contents }, + ); + if rtc.accepts(&input) { + let _ = rtc.handle_input(input); + } + } + Err(_) => continue, + } + } +} + +/// VP8's keyframe bit (the inverse of `P` in the payload header). +fn is_vp8_key(data: &[u8]) -> bool { + data.first().is_some_and(|b| b & 1 == 0) +} + +fn frame(n: u64) -> VideoFrame { + let mut frame = VideoFrame::black_i420(WIDTH, HEIGHT); + let FrameData::I420 { y, .. } = &mut frame.data else { unreachable!() }; + let x0 = (n * 3 % u64::from(WIDTH - 20)) as usize; + for row in 20..60 { + y.data[row * y.stride + x0..][..20].fill(220); + } + frame.timestamp = Duration::from_micros(n * 1_000_000 / 30); + frame +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_whip_session_carries_the_studios_packets() { + let codecs = Codecs::new(); + let Ok(mut encoder) = codecs.new_encoder( + Codec::Vp8, + EncoderConfig { fps: 30, bitrate_bps: 400_000, ..EncoderConfig::default() }, + ) else { + eprintln!("skipped: no VP8 encoder in this build"); + return; + }; + let (url, seen) = spawn_server(); + let mut whip = Whip::start(&url, Some("test-token"), Codec::Vp8, 0, true) + .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. + 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 })); + + // Push frames until the server has seen enough, or give up. + let started = Instant::now(); + let mut n = 0u64; + while started.elapsed() < Duration::from_secs(20) + && (seen.video.load(Ordering::Relaxed) < 20 || seen.audio.load(Ordering::Relaxed) < 10) + { + let picture = frame(n); + encoder + .encode_with(&picture, n == 0, &mut |chunk| { + whip.write(&Packet { + track: Track::Video { codec: Codec::Vp8, layer: 0 }, + pts_90khz: chunk.pts_90khz, + keyframe: chunk.keyframe, + width: WIDTH, + height: HEIGHT, + data: chunk.data, + }) + .expect("the session took the packet"); + }) + .expect("encoded"); + if n.is_multiple_of(2) { + // Opus silence: a valid frame the server can count. + whip.write(&Packet { + track: Track::Audio { channels: 2 }, + pts_90khz: n * 90_000 / 30, + keyframe: true, + width: 0, + height: 0, + data: &[0xF8, 0xFF, 0xFE], + }) + .expect("the session took the audio packet"); + } + n += 1; + tokio::time::sleep(Duration::from_millis(33)).await; + } + + 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:?}"); + assert!(whip.bytes() > 0, "{stats:?}"); + assert_eq!(stats.error, None); + let (video, audio) = (seen.video.load(Ordering::Relaxed), seen.audio.load(Ordering::Relaxed)); + assert!(video >= 20, "only {video} video frames reached the server ({stats:?})"); + assert!(audio >= 10, "only {audio} audio frames reached the server ({stats:?})"); + assert!(seen.keyframes.load(Ordering::Relaxed) >= 1, "no keyframe arrived"); + + // Stopping deletes the resource the service handed out. + whip.finish().unwrap(); + let waited = Instant::now(); + while !seen.deleted.load(Ordering::Relaxed) && waited.elapsed() < Duration::from_secs(5) { + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(seen.deleted.load(Ordering::Relaxed), "the resource was not deleted"); +} + +#[tokio::test] +async fn a_service_that_refuses_says_why() { + let (url, _seen) = spawn_server(); + // An offer the server cannot parse: it answers 400 with a reason. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + for stream in listener.incoming().take(1) { + let Ok(mut stream) = stream else { continue }; + let _ = read_request(&mut stream); + let body = "no capacity"; + let _ = stream.write_all( + format!( + "HTTP/1.1 503 Service Unavailable\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) + .as_bytes(), + ); + } + }); + let Err(e) = + Whip::start(&format!("http://127.0.0.1:{port}/whip"), None, Codec::Vp8, 0, true).await + else { + panic!("a service that refuses 503 still started a session"); + }; + let e = e.to_string(); + assert!(e.contains("503") && e.contains("no capacity"), "{e}"); + let _ = url; +}