From 2a8ce05f5927ce142623e9d4314a506a00134220 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 10:03:35 +0300 Subject: [PATCH] voelin-stream: let the pacer out faster than one packet a millisecond A 3840x2160@60 AV1 stream at 60 Mbit/s, Voelin to Voelin through the TeamSpeak 6 dev server on loopback, was received at 5 Mbit/s: the bandwidth estimate started at 60 Mbit/s and fell within seconds to 9, and str0m's probes measured 9.4-9.6 Mbit/s every time. That is one 1188-byte packet a millisecond. str0m's pacer asks for a timeout at once after every packet it lets out; the peer task slept until it with tokio, whose timer rounds up to its next millisecond. Without bandwidth estimation the same stream arrived at 44-46 Mbit/s and decoded at 60 fps. The peer task now handles a due timeout at once instead of sleeping on it, up to 256 turns in a row, so packets and commands are still read in between. Same stream: the estimate climbed to 110 Mbit/s and the viewer received 69-73 Mbit/s at 60 fps. `the_pacer_keeps_up_with_60_mbits` (loopback, 60 Mbit/s of 60 fps frames with 1 MB keyframes) fails without it (7.9 Mbit/s received, the estimate at 12.5) and passes with it (56 Mbit/s, the estimate above 98). With the estimate free to rise, an encoder followed it above the stream's bitrate (to 91 Mbit/s for a 60 Mbit/s stream). Its target is now capped at the layer's bitrate, or `max_bitrate` where set, as `LayerSpec` documents: estimates move it down and back up to it. `no_layer_request_without_the_offer_listing_layers` asserted that the viewer had no output at all after ten frames; with frames arriving faster, frame events were still queued. It now checks that no request was sent, which is what it means. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-core/src/media.rs | 23 ++++++++--- crates/voelin-stream/src/peer.rs | 14 +++++++ crates/voelin-stream/tests/loopback.rs | 53 +++++++++++++++++++++++++- crates/voelin-stream/tests/sessions.rs | 6 ++- 4 files changed, 89 insertions(+), 7 deletions(-) diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index a252630..3c21b85 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -2332,9 +2332,14 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { told = Some((format, to)); sink.layer_format(layer.id, format); } + // Estimates move it down, and back up to the layer's bitrate or its + // `max_bitrate` (`LayerSpec::bitrate`), never beyond: an automatic + // bitrate stays within `AUTO_BITRATE_MAX`, a typed one is what was + // typed. With the pacer no longer held to one packet a millisecond, + // a 60 Mbit/s stream's estimate rose to 110 Mbit/s on loopback. let configured = format.bitrate; let cap = match layer.max_bitrate.load(Ordering::Relaxed) { - 0 => u64::MAX, + 0 => configured, max => max, }; let target = sink.layer_bitrate(layer.id).unwrap_or(configured).clamp(1, cap); @@ -4027,16 +4032,24 @@ mod tests { // A viewer's estimate lowers layer 5's encoder bitrate only. source.set_layer_bitrate(5, 150_000); - let target = |id| { + let target = |source: &EncodedSource, id| { let stats = source.streamer().stats(); stats.layers.iter().find(|l| l.id == id).map(|l| l.bitrate) }; let deadline = Instant::now() + Duration::from_secs(5); - while target(5) != Some(150_000) { - assert!(Instant::now() < deadline, "layer 5 at {:?}", target(5)); + while target(&source, 5) != Some(150_000) { + assert!(Instant::now() < deadline, "layer 5 at {:?}", target(&source, 5)); tokio::time::sleep(Duration::from_millis(20)).await; } - assert_eq!(target(0), Some(800_000)); + assert_eq!(target(&source, 0), Some(800_000)); + // A higher one raises it back to its bitrate, not beyond. + source.set_layer_bitrate(5, 50_000_000); + let deadline = Instant::now() + Duration::from_secs(5); + while target(&source, 5) == Some(150_000) { + assert!(Instant::now() < deadline, "layer 5 at {:?}", target(&source, 5)); + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!(target(&source, 5), Some(300_000)); // VP9, layer 5 gone, a new layer 7 at a fixed size. let fixed = LayerSpec { size: Some((96, 64)), ..layer(7, 1.0, None, 200_000) }; diff --git a/crates/voelin-stream/src/peer.rs b/crates/voelin-stream/src/peer.rs index 366606f..9777f5b 100644 --- a/crates/voelin-stream/src/peer.rs +++ b/crates/voelin-stream/src/peer.rs @@ -993,6 +993,8 @@ impl Task { &mut self, mut stun_servers: mpsc::UnboundedReceiver, ) -> Result<(), PeerError> { + // Turns in a row str0m wanted again at once. + let mut immediate = 0u32; loop { let now = Instant::now(); self.rtc.handle_input(Input::Timeout(now))?; @@ -1022,6 +1024,18 @@ impl Task { } }; let deadline = self.stall.due(self.offerer).map_or(deadline, |due| due.min(deadline)); + // The pacer asks for a timeout at once after every packet it lets + // out. Tokio's timer rounds that up to its next millisecond, so a + // paced stream sent one packet a millisecond: 9.5 Mbit/s at 1188 + // bytes (str0m's probes measured exactly that, and the estimate + // of a 60 Mbit/s stream on loopback fell to 9 Mbit/s). A due + // timeout is handled at once instead, a bounded number of turns + // in a row so packets and commands are still read in between. + if deadline <= Instant::now() && immediate < 256 { + immediate += 1; + continue; + } + immediate = 0; let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)); tokio::select! { packet = self.net.incoming.recv() => { diff --git a/crates/voelin-stream/tests/loopback.rs b/crates/voelin-stream/tests/loopback.rs index 76bbdba..c2540ee 100644 --- a/crates/voelin-stream/tests/loopback.rs +++ b/crates/voelin-stream/tests/loopback.rs @@ -5,7 +5,7 @@ use std::time::{Duration, Instant}; use tokio::time::timeout; -use voelin_stream::{MediaKind, MediaTime, Peer, PeerConfig, PeerEvent, SrtpProfile}; +use voelin_stream::{MediaKind, MediaTime, OfferOptions, Peer, PeerConfig, PeerEvent, SrtpProfile}; mod relay; use relay::{Relay, Rule}; @@ -248,6 +248,57 @@ async fn losses_are_repaired_by_retransmission() { assert_eq!(received.gaps, 0, "a loss reached the viewer: {received:?}"); } +/// A 60 Mbit/s stream with bandwidth estimation: the pacer lets it out at +/// that rate and the estimate stays near it. Before the peer task handled a +/// due timeout at once, tokio's millisecond timer let the pacer out one +/// packet a millisecond (9.5 Mbit/s at 1188 bytes), and a 4K60 stream's +/// estimate through the TeamSpeak 6 server fell from 60 to 9 Mbit/s. +#[tokio::test(flavor = "multi_thread")] +async fn the_pacer_keeps_up_with_60_mbits() { + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let config = PeerConfig::loopback(); + // The streamer starts at the stream's bitrate, as a session does. + let options = OfferOptions { + start_bitrate: Some(60_000_000), + desired_bitrate: Some(72_000_000), + ..OfferOptions::default() + }; + let (mut streamer, offer) = Peer::offer_with(&config, "fast", &options).await.unwrap(); + let (mut viewer, answer) = Peer::answer(&config, &offer).await.unwrap(); + streamer.accept_answer(&answer).await.unwrap(); + tokio::join!(wait_connected(&mut streamer), wait_connected(&mut viewer)); + // 60 Mbit/s at 60 fps: 125 KB a frame, keyframes of 1 MB every second. + let sender = tokio::spawn(async move { + let start = Instant::now(); + let mut estimates = Vec::new(); + let mut streamer = streamer; + for i in 0..300u64 { + let keyframe = i % 60 == 0; + let data = noise_frame(i, if keyframe { 1_000_000 } else { 125_000 }, keyframe); + streamer.write(MediaKind::Video, MediaTime::from_90khz(i * 1500), data); + while let Some(event) = streamer.try_next_event() { + if let PeerEvent::BitrateEstimate(b) = event { + estimates.push(b); + } + } + tokio::time::sleep_until((start + Duration::from_micros((i + 1) * 16_667)).into()) + .await; + } + estimates + }); + let (mut bytes, start) = (0usize, Instant::now()); + while let Ok(Some(event)) = timeout(Duration::from_secs(1), viewer.next_event()).await { + if let PeerEvent::Media(f) = event { + bytes += f.data.len(); + } + } + let mbits = bytes as f64 * 8.0 / start.elapsed().as_secs_f64() / 1e6; + let estimates = sender.await.unwrap(); + let last = estimates.last().copied().unwrap_or(0); + eprintln!("received {mbits:.1} Mbit/s; estimates {estimates:?}"); + assert!(last >= 40_000_000, "the estimate fell to {last} bit/s"); +} + /// UDP receive errors of this host so far (`RcvbufErrors` in /// `/proc/net/snmp`: datagrams dropped because a socket's buffer was full). fn receive_buffer_errors() -> Option { diff --git a/crates/voelin-stream/tests/sessions.rs b/crates/voelin-stream/tests/sessions.rs index 22f5e1a..aa87fd1 100644 --- a/crates/voelin-stream/tests/sessions.rs +++ b/crates/voelin-stream/tests/sessions.rs @@ -532,7 +532,11 @@ async fn no_layer_request_without_the_offer_listing_layers() { assert!(viewer.watching().next().unwrap().layers().is_empty()); assert_eq!(viewer.set_watch_layer(&id, Some(0)), Err(SessionError::NoLayers(id.clone()))); assert_eq!(viewer.set_watch_layer(&id, None), Err(SessionError::NoLayers(id.clone()))); - assert!(viewer.poll_output().is_none(), "nothing sent"); + // Nothing sent (frames that arrived meanwhile are events, not requests). + let requests = std::iter::from_fn(|| viewer.poll_output()) + .filter(|o| matches!(o, Output::Request(_))) + .count(); + assert_eq!(requests, 0, "nothing sent"); net.flush().await; assert!(!net.signals.iter().any(|(_, s)| matches!(s, Signal::Layer { .. }))); }