From 297dc2fe5bd06ef0abcc87c30c70d9d289205dc9 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 03:19:50 +0300 Subject: [PATCH 01/12] voelin-stream: announce at most the 16 bits a TS6 server keeps Probed against the TeamSpeak 6 dev server (6.0.0-beta13.1): `setupstream` takes any bitrate and enforces none, but keeps it in 16 bits, so 100000 kbit/s is announced to the channel as 34464 and 4294967296 as 0. A stream of more than 65.5 Mbit/s would have been announced as a small, wrong number. `proto::setup` now announces at most 65535 kbit/s (`MAX_ANNOUNCED_BITRATE`); a 60 Mbit/s stream is announced as 60000, as it is. The peers keep sending the real rate: nothing between them reads the announcement. The probe and its results are in the protocol notes, and the old "TeamSpeak caps streams at 10 Mbit/s" is corrected where the code claimed it. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-media/src/codec/mod.rs | 3 ++- crates/voelin-stream/src/proto.rs | 16 ++++++++++++++-- docs/protocol-notes/ts6-streaming.md | 26 +++++++++++++++++++++++++- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index 914ed3b..b8fa8a4 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -139,7 +139,8 @@ pub enum H264Profile { pub struct EncoderConfig { /// Expected frame rate (rate control; timestamps come from the frames). pub fps: u32, - /// Target bitrate in bits per second. TeamSpeak caps streams at 10 Mbit/s. + /// Target bitrate in bits per second (no limit; TeamSpeak 6 servers + /// enforce none, see `voelin_stream::proto::MAX_ANNOUNCED_BITRATE`). pub bitrate_bps: u32, /// Maximum frames between keyframes; `None` sends keyframes only at the /// start and on request (PLI), like WebRTC. diff --git a/crates/voelin-stream/src/proto.rs b/crates/voelin-stream/src/proto.rs index 5600618..9c06abc 100644 --- a/crates/voelin-stream/src/proto.rs +++ b/crates/voelin-stream/src/proto.rs @@ -76,12 +76,19 @@ impl LeaveReason { } } +/// The most `setupstream` announces, in kbit/s: TeamSpeak 6 servers keep +/// the bitrate in 16 bits and wrap anything above (6.0.0-beta13.1 announced +/// 100000 as 34464), but enforce nothing, so a stream sends its real rate +/// peer to peer whatever the announcement says. +pub const MAX_ANNOUNCED_BITRATE: u32 = u16::MAX as u32; + /// Parameters of `setupstream`. #[derive(Clone, Debug, PartialEq, Eq)] pub struct StreamSetup { pub name: String, pub kind: StreamKind, - /// kbit/s; the server caps streams at 10 Mbit/s. + /// The stream's video bitrate in kbit/s (the single layer's without + /// simulcast); announced as at most [`MAX_ANNOUNCED_BITRATE`]. pub bitrate: u32, /// `accessibility`: the official client and ts6-manager send 1. pub accessibility: u8, @@ -301,7 +308,7 @@ pub fn setup(setup: &StreamSetup) -> OutCommand { c2s::OutSetupStreamMessage::new(&mut iter::once(c2s::OutSetupStreamPart { stream_name: Cow::Borrowed(&setup.name), stream_type: setup.kind.to_u8(), - bitrate: setup.bitrate, + bitrate: setup.bitrate.min(MAX_ANNOUNCED_BITRATE), access: setup.accessibility, stream_mode: setup.mode, viewer_limit: setup.viewer_limit, @@ -442,6 +449,11 @@ mod tests { "setupstream name=my\\sscreen type=3 bitrate=4608 accessibility=1 mode=1 viewer_limit=0 \ audio=1" ); + // 60 Mbit/s is announced as it is; beyond 16 bits, the most the + // server keeps instead of a wrapped value. + let fast = |bitrate| text(setup(&StreamSetup { bitrate, ..s.clone() })); + assert!(fast(60_000).contains(" bitrate=60000 ")); + assert!(fast(100_000).contains(" bitrate=65535 ")); assert_eq!( text(join_request("u-1", ClientId(5), "", false)), "joinstreamrequest id=u-1 clid=5 msg is_remove=0" diff --git a/docs/protocol-notes/ts6-streaming.md b/docs/protocol-notes/ts6-streaming.md index 5a483c2..4dc1583 100644 --- a/docs/protocol-notes/ts6-streaming.md +++ b/docs/protocol-notes/ts6-streaming.md @@ -33,7 +33,8 @@ Transport (**reported**, TeamSpeak staff on community.teamspeak.com): - ICE with STUN only (`turn.teamspeak.com`, `turn2.teamspeak.com`; no TURN relay). - Media ports: UDP 49152–65535. - Streams are channel-scoped: "public" means everyone in the streamer's channel. -- Bitrate capped at 10 Mbit/s. +- Bitrate capped at 10 Mbit/s. The server itself enforces no limit, see + [what `setupstream` takes](#what-setupstream-takes-confirmed-600-beta131-2026-10-04). Codecs (**reported**, from the ts6-manager bot's working code): @@ -90,6 +91,29 @@ When the streamer disconnects, everyone gets `notifystreamstopped id=`. Stream ids are UUIDs. The notification carries the command's `return_code`, and the field is named `access` there (not `accessibility`). +### What `setupstream` takes (confirmed, 6.0.0-beta13.1, 2026-10-04) + +`bitrate` (kbit/s) is informational: the server stores it in 16 bits and +enforces nothing. Sent with `voelinctl connect 127.0.0.1:9988 --log-commands +raw 'setupstream name=probe type=3 bitrate= accessibility=1 mode=1 +viewer_limit=0 audio=1'` (`RUST_LOG=debug` prints the commands), every one +answered `error id=0`, and `notifystreamstarted` announced: + +| `bitrate` sent | announced | +|---|---| +| 10000, 10001, 60000 | the same | +| 100000 | 34464 (100000 mod 65536) | +| 1000000 | 16960 | +| 4294967295 | 65535 | +| 4294967296, 0 | 0 | + +So 65535 kbit/s is the most a stream can announce, and anything above it +wraps silently. Voelin announces its stream's real bitrate up to 65535 +(`proto::MAX_ANNOUNCED_BITRATE`; e.g. 60000 for a 60 Mbit/s stream), and +its peers send whatever the stream needs whatever was announced: nothing +between the peers looks at the announcement. Viewers see the announced +value in `notifystreamstarted` / `notifystreaminfo`. + ### Join handshake (confirmed, 6.0.0-beta13.1) ``` From ccc974fe05cc2003ad1800eaabb4641bd6f95624 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 03:37:08 +0300 Subject: [PATCH 02/12] Streams: an automatic bitrate up to 60 Mbit/s, and presets to match The bitrate was a fixed 8 Mbit/s by default whatever was shared, and the share dialog offered at most 10 Mbit/s and 60 fps. Asked for: Voelin streams that can target 60 Mbit/s at up to 8K and 320 fps, with an automatic bitrate that scales with the stream's resolution and frame rate and follows it live, beyond 60 Mbit/s only when typed. - `media::auto_bitrate(width, height, fps)`: 0.12 bits per pixel and frame (7.5 Mbit/s at 1080p30, 15 at 1080p60, 27 at 1440p60) between 300 kbit/s and 60 Mbit/s, reached at 4K60 and 1080p240. - `stream.bitrate_kbps` 0 is automatic and now the default. A streamer layer with bitrate 0 works it out per picture from the size encoded and the layer's frame rate, so a new resolution or frame rate moves it at once, and tells its sink (`MediaSink::auto_bitrate`). The engine's `StreamSink` puts it into the live stream's layer, so connections start their bandwidth estimate at it and probe for it; without that the stream would have kept the bitrate announced at the start. `Streamer::bitrate_kbps()` is what to announce. - The quick share offers 15-320 fps and Auto, 2.5 to 60 Mbit/s (typed values still have no maximum; the `ui` blob keeps indices of the old lists for older versions). The studio offers 4K and 8K and 30-240 fps, takes an empty bitrate as automatic and derives its first simulcast layer from the automatic bitrate. - The studio now tells the engine its layers when it goes live and when they change (`SetStreamLayers`), and a quick share resets them: the session sends only layers it knows of, so a studio's simulcast layers never reached a viewer, and its layer kept the bitrate announced. - `voelinctl stream start` and `stream bench` default to the automatic bitrate too. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-core/src/media.rs | 147 +++++++++++++++++- crates/voelin-core/src/settings.rs | 17 +- crates/voelin-core/src/stream.rs | 56 +++++++ crates/voelin-ui/src/settings.rs | 26 +++- crates/voelin-ui/src/streams.rs | 19 ++- crates/voelin-ui/src/studio.rs | 57 +++++-- crates/voelin-ui/ui/bridge.slint | 8 +- crates/voelin-ui/ui/screens/dialogs.slint | 12 +- .../voelin-ui/ui/screens/studio-parts.slint | 48 +++--- docs/media.md | 16 ++ docs/ui.md | 13 +- tools/voelinctl/src/bench.rs | 5 +- tools/voelinctl/src/stream.rs | 36 ++++- 13 files changed, 375 insertions(+), 85 deletions(-) diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 3008909..6d7681e 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -232,6 +232,22 @@ pub fn test_pattern_source() -> CaptureSource { } } +/// The most an automatic bitrate ([`auto_bitrate`]) gives, in bit/s. A +/// typed bitrate may be higher: nothing in Voelin caps it. +pub const AUTO_BITRATE_MAX: u64 = 60_000_000; + +/// The least an automatic bitrate gives, in bit/s. +pub const AUTO_BITRATE_MIN: u64 = 300_000; + +/// The automatic bitrate (bit/s) of a `width` x `height` stream at `fps`: +/// 0.12 bits per pixel and frame (7.5 Mbit/s at 1080p30, 15 at 1080p60, 27 +/// at 1440p60), from [`AUTO_BITRATE_MIN`] up to [`AUTO_BITRATE_MAX`], which +/// 3840x2160 reaches at 60 fps and 1920x1080 at 240. +pub fn auto_bitrate(width: u32, height: u32, fps: u32) -> u64 { + let pixels = u128::from(width) * u128::from(height) * u128::from(fps.max(1)); + (pixels * 12 / 100).clamp(AUTO_BITRATE_MIN.into(), AUTO_BITRATE_MAX.into()) as u64 +} + /// Where a [`Streamer`] puts encoded frames. pub trait MediaSink: Send + Sync { /// Send one frame; `false` once nobody takes frames any more. @@ -267,6 +283,14 @@ pub trait MediaSink: Send + Sync { fn video_codecs(&self, out: &mut Vec) { let _ = out; } + + /// Layer `layer` has an automatic bitrate and is encoded at `bitrate` + /// bit/s ([`auto_bitrate`] of its size and frame rate): told with its + /// first frame and whenever it changes, so the stream's connections can + /// probe for it. + fn auto_bitrate(&self, layer: LayerId, bitrate: u64) { + let _ = (layer, bitrate); + } } impl MediaSink for StreamSink { @@ -297,6 +321,10 @@ impl MediaSink for StreamSink { fn layer_bitrate(&self, layer: LayerId) -> Option { StreamSink::layer_bitrate(self, layer) } + + fn auto_bitrate(&self, layer: LayerId, bitrate: u64) { + StreamSink::auto_bitrate(self, layer, bitrate); + } } /// Which backend captures monitors and windows. @@ -500,7 +528,8 @@ pub struct StreamerConfig { /// gives up to this rate; layers may cap lower. pub fps: u32, /// Video bitrate in kbit/s, as in `StreamSetup::bitrate`, for the single - /// layer when `layers` is empty. + /// layer when `layers` is empty; 0: automatic, [`auto_bitrate`] of the + /// size and frame rate encoded, following both as they change. pub bitrate_kbps: u32, /// The codec of our offer, see [`stream_codec`]. pub codec: Codec, @@ -553,10 +582,10 @@ impl Default for StreamerConfig { impl StreamerConfig { /// The layers that are encoded: [`layers`](Self::layers), or one layer at - /// `bitrate_kbps`. + /// `bitrate_kbps` (bitrate 0: automatic). pub fn effective_layers(&self) -> Vec { if self.layers.is_empty() { - vec![LayerSpec::single(u64::from(self.bitrate_kbps.max(1)) * 1000)] + vec![LayerSpec::single(u64::from(self.bitrate_kbps) * 1000)] } else { self.layers.clone() } @@ -569,7 +598,8 @@ impl StreamerConfig { pub struct StreamerConfigUpdate { /// Frame-rate cap; the capture follows without restarting. pub fps: Option, - /// Bitrate of the single layer (used while `layers` is empty). + /// Bitrate of the single layer (used while `layers` is empty); 0: + /// automatic. pub bitrate_kbps: Option, /// Another codec: new encoders, starting with keyframes. pub codec: Option, @@ -674,7 +704,7 @@ struct Layer { /// A keyframe was asked for. keyframe: AtomicBool, stop: AtomicBool, - /// Configured bitrate and cap (0: none), bit/s. + /// Configured bitrate (0: automatic) and cap (0: none), bit/s. bitrate: AtomicU64, max_bitrate: AtomicU64, /// Frame rate the encoder plans for. @@ -708,7 +738,7 @@ impl Layer { gpu: AtomicU64::new(0), keyframe: AtomicBool::new(false), stop: AtomicBool::new(false), - bitrate: AtomicU64::new(spec.bitrate.max(1)), + bitrate: AtomicU64::new(spec.bitrate), max_bitrate: AtomicU64::new(spec.max_bitrate.unwrap_or(0)), fps: AtomicU32::new(layer_fps(spec, fps)), next_encoder: Mutex::new(None), @@ -728,7 +758,7 @@ impl Layer { fn update(&self, spec: &LayerSpec, fps: u32) { *lock(&self.spec) = spec.clone(); - self.bitrate.store(spec.bitrate.max(1), Ordering::Relaxed); + self.bitrate.store(spec.bitrate, Ordering::Relaxed); self.max_bitrate.store(spec.max_bitrate.unwrap_or(0), Ordering::Relaxed); self.fps.store(layer_fps(spec, fps), Ordering::Relaxed); } @@ -878,6 +908,8 @@ fn cores() -> u32 { fn encoder_config(spec: &LayerSpec, fps: u32, threads: u32) -> EncoderConfig { EncoderConfig { fps: layer_fps(spec, fps), + // An automatic bitrate (0) is set with the first frame, whose size it + // takes. bitrate_bps: spec.bitrate.clamp(1, u64::from(u32::MAX)) as u32, content: ContentHint::Screen, threads, @@ -1219,6 +1251,25 @@ impl Streamer { lock(&self.shared.layers).iter().map(|l| l.id).collect() } + /// The stream's video bitrate in kbit/s, for `StreamSetup::bitrate`: its + /// highest layer's; an automatic one ([`auto_bitrate`]) from the size + /// captured last and the layer's frame rate, [`AUTO_BITRATE_MAX`] while + /// nothing was captured yet. + pub fn bitrate_kbps(&self) -> u32 { + let size = self.shared.size.load(Ordering::Relaxed); + let (width, height) = ((size >> 32) as u32, size as u32); + let layers = lock(&self.shared.layers).clone(); + let bitrate = layers.iter().map(|layer| match layer.bitrate.load(Ordering::Relaxed) { + 0 if size == 0 => AUTO_BITRATE_MAX, + 0 => { + let (w, h) = lock(&layer.spec).output_size(width, height); + auto_bitrate(w, h, layer.fps.load(Ordering::Relaxed)) + } + bitrate => bitrate, + }); + u32::try_from(bitrate.max().unwrap_or(0) / 1000).unwrap_or(u32::MAX) + } + pub fn stats(&self) -> StreamerStats { let shared = &self.shared; let audio = lock(&self.audio); @@ -2040,6 +2091,8 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { let mut generation = shared.encoders_generation.load(Ordering::Relaxed); // Whether the stream codec was encoded for the last frame. let mut primary_on = true; + // The automatic bitrate last told, and to which sink. + let mut told: Option<(u64, *const ())> = None; // The last picture, and when it came: a static screen sends no frames, // so keyframe requests are answered by encoding it again. let mut last: Option<(Picture, Instant)> = None; @@ -2127,7 +2180,19 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { None => continue, }; // Follow the layer's bitrate, or what the viewers' estimates allow. - let configured = layer.bitrate.load(Ordering::Relaxed); + let configured = match layer.bitrate.load(Ordering::Relaxed) { + 0 => { + let (width, height) = picture.size(); + let auto = auto_bitrate(width, height, layer.fps.load(Ordering::Relaxed)); + let to = Arc::as_ptr(&sink).cast::<()>(); + if told != Some((auto, to)) { + told = Some((auto, to)); + sink.auto_bitrate(layer.id, auto); + } + auto + } + bitrate => bitrate, + }; let cap = match layer.max_bitrate.load(Ordering::Relaxed) { 0 => u64::MAX, max => max, @@ -2960,6 +3025,8 @@ mod tests { codecs: Mutex>, frames: Mutex>, keyframe: AtomicBool, + /// What [`MediaSink::auto_bitrate`] told, in order. + auto: Mutex>, } impl MediaSink for CodecSink { @@ -2979,6 +3046,70 @@ mod tests { fn video_codecs(&self, out: &mut Vec) { out.extend(lock(&self.codecs).iter()); } + + fn auto_bitrate(&self, layer: LayerId, bitrate: u64) { + lock(&self.auto).push((layer, bitrate)); + } + } + + #[test] + fn automatic_bitrates() { + assert_eq!(auto_bitrate(1920, 1080, 30), 7_464_960); + assert_eq!(auto_bitrate(1920, 1080, 60), 14_929_920); + assert_eq!(auto_bitrate(2560, 1440, 60), 26_542_080); + // The ceiling: 4K60, 1080p240 and anything beyond. + assert_eq!(auto_bitrate(3840, 2160, 60), 59_719_680); + assert_eq!(auto_bitrate(3840, 2160, 120), AUTO_BITRATE_MAX); + assert_eq!(auto_bitrate(7680, 4320, 320), AUTO_BITRATE_MAX); + assert_eq!(auto_bitrate(1920, 1080, 320), AUTO_BITRATE_MAX); + // The floor, and no overflow at absurd sizes. + assert_eq!(auto_bitrate(160, 120, 1), AUTO_BITRATE_MIN); + assert_eq!(auto_bitrate(u32::MAX, u32::MAX, u32::MAX), AUTO_BITRATE_MAX); + assert_eq!(auto_bitrate(0, 0, 0), AUTO_BITRATE_MIN); + } + + /// Bitrate 0 is automatic: the encoder runs at the stream's own + /// automatic bitrate, which the sink is told, and follows a new frame + /// rate. + #[cfg(feature = "media-desktop")] + #[tokio::test(flavor = "multi_thread")] + async fn an_automatic_bitrate_follows_the_stream() { + let codecs = Codecs::builtin(); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (640, 480), + fps: 30, + bitrate_kbps: 0, + audio: false, + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + let sink = Arc::new(CodecSink::default()); + streamer.attach(sink.clone()); + let told = |bitrate: u64| { + let sink = sink.clone(); + async move { + let deadline = Instant::now() + Duration::from_secs(10); + while lock(&sink.auto).last() != Some(&(0, bitrate)) { + assert!(Instant::now() < deadline, "{:?}", lock(&sink.auto)); + tokio::time::sleep(Duration::from_millis(20)).await; + } + } + }; + told(auto_bitrate(640, 480, 30)).await; + assert_eq!(streamer.bitrate_kbps(), 1105); + // Told once, not per frame. + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(lock(&sink.auto).len(), 1); + assert_eq!(streamer.stats().layers[0].bitrate, auto_bitrate(640, 480, 30)); + let update = StreamerConfigUpdate { fps: Some(15), ..StreamerConfigUpdate::default() }; + streamer.reconfigure(&codecs, update).unwrap(); + told(auto_bitrate(640, 480, 15)).await; + // A typed bitrate is not automatic. + let update = + StreamerConfigUpdate { bitrate_kbps: Some(2000), ..StreamerConfigUpdate::default() }; + streamer.reconfigure(&codecs, update).unwrap(); + assert_eq!(streamer.bitrate_kbps(), 2000); } /// Viewers that chose another codec get their own encoder per layer, diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index eb2b7ba..63001fe 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -831,14 +831,15 @@ pub static STREAM_FPS: Key = Key::new("stream.fps", Kind::UInt { min: 1 }, "Frames per second of our stream.", || 60) .validated(at_least_one); -/// Video bitrate of our stream in kbit/s (no maximum). +/// Video bitrate of our stream in kbit/s (no maximum); 0, the default: +/// automatic, from the size and frame rate streamed +/// (`media::auto_bitrate`, up to 60 Mbit/s), following both live. pub static STREAM_BITRATE_KBPS: Key = Key::new( "stream.bitrate_kbps", - Kind::UInt { min: 1 }, - "Video bitrate of our stream in kbit/s.", - || 8000, -) -.validated(at_least_one); + Kind::UInt { min: 0 }, + "Video bitrate of our stream in kbit/s (0: automatic, up to 60 Mbit/s).", + || 0, +); /// One simulcast layer as stored; see [`LayerSpec`] for the fields. The /// serde form of a layer: `{"scale": 0.5, "max_fps": 30, "bitrate": 1500000}` @@ -1342,7 +1343,7 @@ mod tests { fn defaults_and_registry() { let s = Settings::in_memory(); assert_eq!(s.get(&STREAM_FPS), 60); - assert_eq!(s.get(&STREAM_BITRATE_KBPS), 8000); + assert_eq!(s.get(&STREAM_BITRATE_KBPS), 0, "automatic"); assert!(s.get(&STREAM_LAYERS).is_empty()); assert_eq!(s.get(&STREAM_CODEC), CodecChoice::Auto); assert_eq!(s.get(&STREAM_PERMISSIONS), StreamPermissions::Channel); @@ -1416,6 +1417,8 @@ mod tests { s.set_json("stream.fps", json!(1000)).unwrap(); s.set(&STREAM_BITRATE_KBPS, u32::MAX).unwrap(); assert_eq!(s.get(&STREAM_BITRATE_KBPS), u32::MAX); + // 0 is automatic again. + s.set(&STREAM_BITRATE_KBPS, 0).unwrap(); } #[test] diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index ad1a486..527c259 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -124,6 +124,14 @@ impl StreamSink { self.feedback.bitrate(layer) } + /// The encoder of `layer` runs at `bitrate` bit/s by itself (an + /// automatic bitrate, from the size and frame rate it encodes): the + /// stream's layer takes it, so new connections start at it and every + /// connection probes for it. + pub fn auto_bitrate(&self, layer: LayerId, bitrate: u64) { + let _ = self.tx.send(StreamInput::AutoBitrate { layer, bitrate }); + } + pub fn is_live(&self) -> bool { self.live.load(Ordering::Relaxed) } @@ -169,6 +177,12 @@ pub(crate) enum StreamInput { }, /// Simulcast layers of our stream (now and for streams started later). Layers(Vec), + /// The bitrate an encoder chose for a layer of the live stream + /// ([`StreamSink::auto_bitrate`]). + AutoBitrate { + layer: LayerId, + bitrate: u64, + }, /// SRTP profile order of new connections. SrtpProfiles(Vec), Frame(EncodedFrame), @@ -389,6 +403,21 @@ impl StreamTask { Ok(()) } } + StreamInput::AutoBitrate { layer, bitrate } => { + // The live stream's layers only; the configured ones (for + // streams started later) keep their automatic bitrate. + let layers = self.streams.streamer().map(|s| s.layers().to_vec()); + match layers { + Some(mut layers) => match layers.iter_mut().find(|l| l.id == layer) { + Some(spec) if spec.bitrate != bitrate => { + spec.bitrate = bitrate; + self.streams.set_layers(layers) + } + _ => Ok(()), + }, + None => Ok(()), + } + } StreamInput::SrtpProfiles(profiles) => { self.streams.set_srtp_profiles(profiles); Ok(()) @@ -962,6 +991,33 @@ mod tests { feeder.await.unwrap(); } + /// An encoder's automatic bitrate reaches the live stream's layer (which + /// asks the viewer's layer for a keyframe, as every layer change does); + /// the same bitrate again changes nothing. + #[tokio::test(flavor = "multi_thread")] + async fn automatic_bitrates_reach_the_live_stream() { + let (handles, mut rx, _frames) = pair(None); + let sink = live_and_watching(&handles, &mut rx).await; + let keyframes = || { + let mut layers = LayerSet::new(); + sink.take_layer_keyframes(&mut layers); + layers.contains(0) + }; + keyframes(); + sink.auto_bitrate(0, 9_000_000); + timeout(Duration::from_secs(5), async { + while !keyframes() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the layer did not change"); + sink.auto_bitrate(0, 9_000_000); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(!keyframes(), "nothing changed"); + handles[0].send(StreamInput::Stop); + } + /// A viewer that was not told about a running stream, and whose server /// lookup goes unanswered, finds it in the gateway directory and /// watches it; the streamer reports its stream's life for the directory. diff --git a/crates/voelin-ui/src/settings.rs b/crates/voelin-ui/src/settings.rs index 4bdc093..c5c7fe0 100644 --- a/crates/voelin-ui/src/settings.rs +++ b/crates/voelin-ui/src/settings.rs @@ -105,10 +105,16 @@ pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 5] { [&UI_THEME, &UI_FONT_SCALE, &UI_NARROW_BREAKPOINT, &UI_IMAGE_CACHE_MB, &UI_MEMBERS_WIDTH] } -/// Frame rates and bitrates (kbit/s) the share dialog offers; any other -/// value can be typed in. -pub const FPS_CHOICES: [u32; 3] = [15, 30, 60]; -pub const BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000]; +/// Frame rates and bitrates (kbit/s; 0: automatic) the share dialog +/// offers, in the order of its lists (`dialogs.slint`); any other value can +/// be typed in. +pub const FPS_CHOICES: [u32; 7] = [15, 30, 60, 120, 144, 240, 320]; +pub const BITRATE_CHOICES: [u32; 8] = [0, 2500, 4608, 8000, 10_000, 20_000, 40_000, 60_000]; + +/// The share dialog's lists before they grew, which [`ShareDefaults`] +/// indexes for older versions. +pub const LEGACY_FPS_CHOICES: [u32; 3] = [15, 30, 60]; +pub const LEGACY_BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000]; /// The index of the choice closest to `value`. pub fn nearest_choice(choices: &[u32], value: u32) -> usize { @@ -151,7 +157,8 @@ impl Default for UiSettings { /// The last choices in the share dialog. Frame rate and bitrate are the /// settings `stream.fps` and `stream.bitrate_kbps`; the indices of the -/// closest choices are kept for older versions. +/// closest choices of the old lists ([`LEGACY_FPS_CHOICES`], +/// [`LEGACY_BITRATE_CHOICES`]) are kept for older versions. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct ShareDefaults { @@ -356,9 +363,12 @@ mod tests { #[test] fn free_values() { assert_eq!(nearest_choice(&FPS_CHOICES, 60), 2); - assert_eq!(nearest_choice(&FPS_CHOICES, 144), 2); - assert_eq!(nearest_choice(&BITRATE_CHOICES, 3000), 0); - assert_eq!(nearest_choice(&BITRATE_CHOICES, 50_000), 3); + assert_eq!(nearest_choice(&FPS_CHOICES, 144), 4); + assert_eq!(nearest_choice(&FPS_CHOICES, 1000), 6); + assert_eq!(nearest_choice(&BITRATE_CHOICES, 0), 0, "automatic"); + assert_eq!(nearest_choice(&BITRATE_CHOICES, 3000), 1); + assert_eq!(nearest_choice(&BITRATE_CHOICES, 55_000), 7); + assert_eq!(nearest_choice(&BITRATE_CHOICES, 120_000), 7); assert_eq!(parse_positive(" 144 "), Some(144)); assert_eq!(parse_positive("0"), None); assert_eq!(parse_positive("fast"), None); diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index 085d832..cfc15b2 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -19,7 +19,8 @@ use crate::app::{ App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model, with_app, }; use crate::settings::{ - BITRATE_CHOICES, FPS_CHOICES, ShareDefaults, nearest_choice, parse_positive, + BITRATE_CHOICES, FPS_CHOICES, LEGACY_BITRATE_CHOICES, LEGACY_FPS_CHOICES, ShareDefaults, + nearest_choice, parse_positive, }; use crate::video::{self, Capture, CaptureRequest, Decoder}; @@ -540,7 +541,8 @@ impl App { fps_index: nearest_choice(&FPS_CHOICES, fps) as i32, fps: fps.to_string().into(), bitrate_index: nearest_choice(&BITRATE_CHOICES, bitrate) as i32, - bitrate: bitrate.to_string().into(), + // Automatic (0): the field stays empty. + bitrate: if bitrate == 0 { String::new() } else { bitrate.to_string() }.into(), audio: defaults.audio, auto_accept: defaults.auto_accept, } @@ -586,7 +588,8 @@ impl App { self.refresh_streams(); return; } - // Typed values (no maximum), else the chosen presets. + // Typed values (no maximum), else the chosen presets (bitrate 0: + // automatic). let choice = |i: i32, choices: &[u32]| { choices[usize::try_from(i).unwrap_or(0).min(choices.len() - 1)] }; @@ -602,8 +605,8 @@ impl App { } } let defaults = ShareDefaults { - fps_index: nearest_choice(&FPS_CHOICES, fps), - bitrate_index: nearest_choice(&BITRATE_CHOICES, bitrate), + fps_index: nearest_choice(&LEGACY_FPS_CHOICES, fps), + bitrate_index: nearest_choice(&LEGACY_BITRATE_CHOICES, bitrate), audio: form.audio, auto_accept: form.auto_accept, }; @@ -650,6 +653,10 @@ impl App { self.settings.portal_restore_token = Some(token); self.store_settings(); } + if setup.bitrate == 0 { + // Automatic: what it comes to for the size captured. + setup.bitrate = capture.streamer().bitrate_kbps(); + } if setup.audio && !capture.has_audio() { setup.audio = false; let reason = capture.audio_error().unwrap_or_default(); @@ -660,6 +667,8 @@ impl App { (true, demo_viewers()) } else { let session = session as u64; + // One layer, whatever a studio stream had before. + self.engine.send(Command::SetStreamLayers { session, layers: Vec::new() }); self.engine.send(Command::StartStream { session, setup, auto_accept }); (false, Vec::new()) }; diff --git a/crates/voelin-ui/src/studio.rs b/crates/voelin-ui/src/studio.rs index cf3cee1..38a2a5c 100644 --- a/crates/voelin-ui/src/studio.rs +++ b/crates/voelin-ui/src/studio.rs @@ -29,14 +29,14 @@ use voelin_core::media::voelin_media::mix::SourceHandle; use voelin_core::media::voelin_media::{VideoFrame, convert}; use voelin_core::media::{ AudioApps, AudioSourceSpec, AudioSourceStats, Latest, Streamer, StreamerConfigUpdate, - StreamerStats, audio_apps, audio_source_specs, screen_sources, + StreamerStats, audio_apps, audio_source_specs, auto_bitrate, screen_sources, }; use voelin_core::settings::{ AudioSourceKindSetting, AudioSourceSetting, Key, Kind, STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_LAYERS, STUDIO_RECORDING_DIR, STUDIO_REPLAY_MEMORY_MB, STUDIO_REPLAY_SECONDS, STUDIO_SCENES, Settings, layer_specs, }; -use voelin_core::stream::{EndReason, StreamSetup, ViewerInfo, ViewerState}; +use voelin_core::stream::{EndReason, LayerSpec, StreamSetup, ViewerInfo, ViewerState}; use voelin_core::studio::scene::{ Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform, }; @@ -436,6 +436,30 @@ impl App { self.studio.run.as_ref()?.streamer.as_ref() } + /// The stream's layers for the engine: `stream.layers`, or the single + /// layer at [`studio_bitrate_kbps`](Self::studio_bitrate_kbps). + fn studio_session_layers(&self, settings: &Settings) -> Vec { + match layer_specs(&settings.get(&STREAM_LAYERS)) { + layers if layers.is_empty() => { + vec![LayerSpec::single(u64::from(self.studio_bitrate_kbps(settings)) * 1000)] + } + layers => layers, + } + } + + /// `stream.bitrate_kbps`, an automatic one (0) as it comes to for the + /// output's size and frame rate. + fn studio_bitrate_kbps(&self, settings: &Settings) -> u32 { + match settings.get(&STREAM_BITRATE_KBPS) { + 0 => { + let (width, height) = self.studio.scenes.size(); + let bitrate = auto_bitrate(width, height, self.studio.scenes.fps()); + u32::try_from(bitrate / 1000).unwrap_or(u32::MAX) + } + kbps => kbps, + } + } + fn studio_op(&self, op: Op) { if let Some(run) = &self.studio.run { let _ = run.ops.send(op); @@ -960,7 +984,9 @@ impl App { .destination .and_then(|id| list.iter().position(|(d, _)| *d == id)) .map_or(-1, |i| i as i32); + // Automatic (0): the field stays empty and says so. let bitrate = self.studio.settings.as_ref().map_or(0, |s| s.get(&STREAM_BITRATE_KBPS)); + let bitrate = if bitrate == 0 { String::new() } else { bitrate.to_string() }; let form = StudioForm { destination, title: ui.title.clone().into(), @@ -970,7 +996,7 @@ impl App { show_chat: ui.show_chat, show_now_playing: ui.show_now_playing, audio: ui.audio, - bitrate: bitrate.to_string().into(), + bitrate: bitrate.into(), }; self.studio_each(|b| { if b.get_form() != form { @@ -993,7 +1019,7 @@ impl App { let measured: f64 = encoder.map_or(0.0, |e| e.layers.iter().map(|l| l.kbps).sum()); let layers = settings.map(|s| s.get(&STREAM_LAYERS)).unwrap_or_default(); let configured_bps: u64 = if layers.is_empty() { - settings.map_or(0, |s| u64::from(s.get(&STREAM_BITRATE_KBPS)) * 1000) + settings.map_or(0, |s| u64::from(self.studio_bitrate_kbps(s)) * 1000) } else { layers.iter().map(|l| l.bitrate).max().unwrap_or(0) }; @@ -1191,6 +1217,11 @@ impl App { /// `stream.layers` or `stream.bitrate_kbps` changed. pub(crate) fn studio_encoding_changed(&mut self) { let settings = self.studio_settings(); + if let Some(stream) = &self.studio.stream { + let session = stream.session as u64; + let layers = self.studio_session_layers(&settings); + self.engine.send(Command::SetStreamLayers { session, layers }); + } let update = StreamerConfigUpdate { bitrate_kbps: Some(settings.get(&STREAM_BITRATE_KBPS)), layers: Some(layer_specs(&settings.get(&STREAM_LAYERS))), @@ -1254,13 +1285,16 @@ impl App { "audio" => ui.audio = on, "bitrate" => { let settings = self.studio_settings(); - match parse_positive(value) { + // Nothing, 0 or "auto": automatic. + let auto = + matches!(value.trim(), "" | "0") || value.trim().eq_ignore_ascii_case("auto"); + match parse_positive(value).or(auto.then_some(0)) { Some(kbps) => { if let Err(e) = settings.set(&STREAM_BITRATE_KBPS, kbps) { self.set_status(e.to_string()); } } - None => self.set_status("The bitrate is a whole number of kbit/s above 0."), + None => self.set_status("The bitrate is a whole number of kbit/s, or auto."), } return; } @@ -1328,7 +1362,7 @@ impl App { pub(crate) fn studio_add_layer(&mut self) { let settings = self.studio_settings(); let mut layers = settings.get(&STREAM_LAYERS); - let bitrate = settings.get(&STREAM_BITRATE_KBPS); + let bitrate = self.studio_bitrate_kbps(&settings); if layers.is_empty() { layers.push(vm::studio::next_layer(&[], bitrate)); } @@ -1897,7 +1931,7 @@ impl App { let layers = settings.get(&STREAM_LAYERS); let bitrate = match layers.iter().map(|l| l.bitrate).max() { Some(bps) => u32::try_from(bps / 1000).unwrap_or(u32::MAX), - None => settings.get(&STREAM_BITRATE_KBPS), + None => self.studio_bitrate_kbps(&settings), }; let setup = StreamSetup { name: stream_name(&self.studio.ui), @@ -1906,7 +1940,12 @@ impl App { ..StreamSetup::default() }; let auto_accept = self.settings.share.auto_accept; - self.engine.send(Command::StartStream { session: session as u64, setup, auto_accept }); + // The stream's layers are the encoder's, so viewers move between + // them (the session sends only layers it knows of). + let session = session as u64; + let layers = self.studio_session_layers(&settings); + self.engine.send(Command::SetStreamLayers { session, layers }); + self.engine.send(Command::StartStream { session, setup, auto_accept }); self.studio_refresh_status(); } diff --git a/crates/voelin-ui/ui/bridge.slint b/crates/voelin-ui/ui/bridge.slint index ea7fe46..0417086 100644 --- a/crates/voelin-ui/ui/bridge.slint +++ b/crates/voelin-ui/ui/bridge.slint @@ -262,13 +262,15 @@ export struct SourceItem { export struct ShareForm { source: int, name: string, - // Index into the frame rate choices (15, 30, 60). + // Index into the frame rate choices (15, 30, 60, 120, 144, 240, 320). fps-index: int, // Frames per second as typed; a choice fills it in. Any number above 0. fps: string, - // Index into the bitrate choices (2.5, 4.6, 8, 10 Mbit/s). + // Index into the bitrate choices (Auto, 2.5, 4.6, 8, 10, 20, 40, 60 + // Mbit/s). bitrate-index: int, - // Video bitrate in kbit/s as typed; a choice fills it in. + // Video bitrate in kbit/s as typed; a choice fills it in. Empty with + // Auto: from the size and frame rate shared, up to 60 Mbit/s. bitrate: string, audio: bool, auto-accept: bool, diff --git a/crates/voelin-ui/ui/screens/dialogs.slint b/crates/voelin-ui/ui/screens/dialogs.slint index d4c22d8..b65383a 100644 --- a/crates/voelin-ui/ui/screens/dialogs.slint +++ b/crates/voelin-ui/ui/screens/dialogs.slint @@ -356,10 +356,11 @@ component ShareCard inherits Modal { HorizontalLayout { spacing: Theme.space-2; Select { - model: [@tr("15 fps"), @tr("30 fps"), @tr("60 fps")]; + // FPS_CHOICES (settings.rs). + model: [@tr("15 fps"), @tr("30 fps"), @tr("60 fps"), @tr("120 fps"), @tr("144 fps"), @tr("240 fps"), @tr("320 fps")]; current-index <=> form.fps-index; label: @tr("Frame rate"); - selected => { form.fps = [15, 30, 60][self.current-index]; } + selected => { form.fps = [15, 30, 60, 120, 144, 240, 320][self.current-index]; } } TextField { text <=> form.fps; @@ -377,15 +378,16 @@ component ShareCard inherits Modal { HorizontalLayout { spacing: Theme.space-2; Select { - model: [@tr("Low (2.5 Mbit/s)"), @tr("Standard (4.6 Mbit/s)"), @tr("High (8 Mbit/s)"), @tr("Best (10 Mbit/s)")]; + // BITRATE_CHOICES (settings.rs); Auto leaves the field empty. + model: [@tr("Auto (up to 60 Mbit/s)"), @tr("Low (2.5 Mbit/s)"), @tr("Standard (4.6 Mbit/s)"), @tr("High (8 Mbit/s)"), @tr("10 Mbit/s"), @tr("20 Mbit/s"), @tr("40 Mbit/s"), @tr("Best (60 Mbit/s)")]; current-index <=> form.bitrate-index; label: @tr("Quality"); - selected => { form.bitrate = [2500, 4608, 8000, 10000][self.current-index]; } + selected => { form.bitrate = self.current-index == 0 ? "" : "\{[0, 2500, 4608, 8000, 10000, 20000, 40000, 60000][self.current-index]}"; } } TextField { text <=> form.bitrate; input-type: number; - placeholder: @tr("kbit/s"); + placeholder: form.bitrate-index == 0 ? @tr("auto") : @tr("kbit/s"); label: @tr("Bitrate in kbit/s"); // On a phone both pairs fit side by side. width: Nav.narrow ? 60px : 80px; diff --git a/crates/voelin-ui/ui/screens/studio-parts.slint b/crates/voelin-ui/ui/screens/studio-parts.slint index 7791c07..e47b5df 100644 --- a/crates/voelin-ui/ui/screens/studio-parts.slint +++ b/crates/voelin-ui/ui/screens/studio-parts.slint @@ -1459,40 +1459,28 @@ export component StreamSettings inherits VerticalLayout { } HorizontalLayout { spacing: Theme.space-2; - Button { + for size in [ + { text: "720p", width: "1280", height: 720 }, + { text: "1080p", width: "1920", height: 1080 }, + { text: "1440p", width: "2560", height: 1440 }, + { text: "4K", width: "3840", height: 2160 }, + { text: "8K", width: "7680", height: 4320 }, + ]: Button { small: true; - text: "720p"; + text: size.text; horizontal-stretch: 1; - checked: StudioBridge.status.output-height == 720; - clicked => { StudioBridge.set-output("1280", "720", out-fps.text); } + checked: StudioBridge.status.output-height == size.height; + clicked => { StudioBridge.set-output(size.width, "\{size.height}", out-fps.text); } } - Button { + } + HorizontalLayout { + spacing: Theme.space-2; + for fps in [30, 60, 120, 144, 240] : Button { small: true; - text: "1080p"; + text: "\{fps}"; horizontal-stretch: 1; - checked: StudioBridge.status.output-height == 1080; - clicked => { StudioBridge.set-output("1920", "1080", out-fps.text); } - } - Button { - small: true; - text: "1440p"; - horizontal-stretch: 1; - checked: StudioBridge.status.output-height == 1440; - clicked => { StudioBridge.set-output("2560", "1440", out-fps.text); } - } - Button { - small: true; - text: "30"; - horizontal-stretch: 1; - checked: StudioBridge.status.fps == 30; - clicked => { StudioBridge.set-output(out-w.text, out-h.text, "30"); } - } - Button { - small: true; - text: "60"; - horizontal-stretch: 1; - checked: StudioBridge.status.fps == 60; - clicked => { StudioBridge.set-output(out-w.text, out-h.text, "60"); } + checked: StudioBridge.status.fps == fps; + clicked => { StudioBridge.set-output(out-w.text, out-h.text, "\{fps}"); } } } } @@ -1502,6 +1490,8 @@ export component StreamSettings inherits VerticalLayout { if StudioBridge.layers.length == 0: TextField { text: StudioBridge.form.bitrate; input-type: number; + // Empty: automatic, from the output's size and frame rate. + placeholder: @tr("Auto (up to 60 Mbit/s)"); label: @tr("Bitrate in kbit/s"); accepted(t) => { StudioBridge.edit-form("bitrate", t); } } diff --git a/docs/media.md b/docs/media.md index 299811b..578d456 100644 --- a/docs/media.md +++ b/docs/media.md @@ -126,6 +126,22 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder `MediaSink::layer_bitrate(id)` when the sink knows it (capped by `max_bitrate`), else its configured bitrate; libvpx changes it in place without a keyframe. +- Automatic bitrate: `bitrate_kbps` 0 (the default of the setting + `stream.bitrate_kbps`) gives the single layer `auto_bitrate(width, + height, fps)`: 0.12 bits per pixel and frame of the size and rate it is + encoded at (7.5 Mbit/s at 1080p30, 15 at 1080p60, 27 at 1440p60), at + least 300 kbit/s and at most 60 Mbit/s (`AUTO_BITRATE_MAX`, reached at + 3840x2160@60, 2560x1440@135, 1920x1080@240). It follows the stream live: + the encoder thread works it out from each picture's size and the layer's + frame rate, so a resolution or frame-rate change moves it at once. The + sink is told with the first frame and whenever it changes + (`MediaSink::auto_bitrate`); the engine's `StreamSink` puts it into the + live stream's layer, so new connections start their bandwidth estimate at + it and all of them probe for it. `Streamer::bitrate_kbps()` is what to + announce in `setupstream` (the share dialog and the studio do, up to the + 65535 kbit/s a server keeps: [protocol notes](protocol-notes/ts6-streaming.md#what-setupstream-takes-confirmed-600-beta131-2026-10-04)). + A typed bitrate is used as it is, above 60 Mbit/s too; nothing in Voelin + caps it (encoders take up to 2^32-1 bit/s). - `Streamer::reconfigure(&codecs, StreamerConfigUpdate { fps, bitrate_kbps, codec, encoder, layers, audio_sources })` applies from the next frame without restarting the capture: encoders are created first (an error changes nothing), layers diff --git a/docs/ui.md b/docs/ui.md index b2976f9..8df581d 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -166,7 +166,7 @@ work before going live. | Preview | `studio`, `studio:live`, `studio:record` | The composite, LIVE and the time (or PREVIEW, REC), watching and joined viewers, title • destination | `Studio::preview` turned into pictures on a thread of its own, latest wins; `State` | | Audio mixer | `studio`, `studio:audio` | One row per `stream.audio_sources` entry: meter, gain (dB), mute, a menu; + adds the microphone, desktop audio without Voelin, the shared window's application or an application that plays | the mixer's meters (lock-free, about 15 times a second); `Streamer::reconfigure` follows the setting | | Stream chat | `studio` | The chat of the channel the stream goes to and a composer | the destination tab's stored messages, made into lines as the chat view does | -| Stream settings | `studio` | Destination (the voice channel of each TeamSpeak 6 server we are in), title, game, go-live message (sent to the channel when the stream is up), Show Viewer Count / Chat Overlay / Now Playing, Enable Stream Audio, Advanced Settings, output size and rate (presets or any numbers), bitrate or simulcast layers | `studio.ui`, `stream.bitrate_kbps`, `stream.layers`, `SetOutput` | +| Stream settings | `studio` | Destination (the voice channel of each TeamSpeak 6 server we are in), title, game, go-live message (sent to the channel when the stream is up), Show Viewer Count / Chat Overlay / Now Playing, Enable Stream Audio, Advanced Settings, output size and rate (presets 720p to 8K and 30 to 240 fps, or any numbers), bitrate (empty: automatic, up to 60 Mbit/s) or simulcast layers | `studio.ui`, `stream.bitrate_kbps`, `stream.layers`, `SetOutput` | | Bottom bar | `studio`, `studio:settings` | Share Window, Share Screen, Record Clip (and start or stop a recording, the replay length, the folder), Go Live, End Stream, Studio Settings (replay seconds and memory, folder, preview size) | `SaveClip`, `StartRecording`, `StopRecording`, `studio.*`, `SetPreview`; `Command::StartStream`, `Streamer::attach`, `GoLive`, `EndStream` | | Window of its own | `studio:window` | The same pieces, compact | — | @@ -181,6 +181,17 @@ game"), which is also what the gateway's directory shows. With sample data the synthetic camera with background blur, text, colours) and test tones, on settings in memory, and recordings go to a temporary folder. +### Frame rate and quality in the quick share + +The share dialog's lists (`FPS_CHOICES`, `BITRATE_CHOICES` in +`src/settings.rs`, the same lists in `dialogs.slint`) offer 15, 30, 60, +120, 144, 240 and 320 fps, and Auto (the default: from the size and frame +rate shared, up to 60 Mbit/s, the bitrate field left empty), 2.5, 4.6, 8, +10, 20, 40 and 60 Mbit/s; any other number can be typed, with no maximum. +Both are the settings `stream.fps` and `stream.bitrate_kbps` (0: +automatic). The `ui` blob keeps the index of the closest entry of the old +three- and four-entry lists for older versions. + ### Sound in the quick share The share dialog (`share`, and `share:live` for a running share) mixes its diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs index a8e8fb8..91031c5 100644 --- a/tools/voelinctl/src/bench.rs +++ b/tools/voelinctl/src/bench.rs @@ -92,8 +92,9 @@ struct BenchArgs { /// k/M suffixes); repeatable. Without it: one layer at --bitrate. #[arg(long = "layer")] layers: Vec, - /// Bitrate in kbit/s without --layer. - #[arg(long, default_value_t = 4608)] + /// Bitrate in kbit/s without --layer; 0: automatic, from the size and + /// frame rate (up to 60 Mbit/s). + #[arg(long, default_value_t = 0)] bitrate: u32, /// Measured time in seconds (after the warm-up). #[arg(long, default_value_t = 10)] diff --git a/tools/voelinctl/src/stream.rs b/tools/voelinctl/src/stream.rs index ebc186b..4650362 100644 --- a/tools/voelinctl/src/stream.rs +++ b/tools/voelinctl/src/stream.rs @@ -17,7 +17,7 @@ use voelin_core::media::voelin_media::capture::SourceId; use voelin_core::media::voelin_media::{Codec, Codecs, VideoFrame, convert}; use voelin_core::media::{ CaptureBackend, EncodedSource, EncoderPreference, Latest, Streamer, StreamerConfig, - VideoPipeline, peer_config, preferred_codec, stream_codec, video_codec, + VideoPipeline, auto_bitrate, peer_config, preferred_codec, stream_codec, video_codec, }; use voelin_model::ServerFlavor; use voelin_stream::{ @@ -75,8 +75,10 @@ pub enum StreamCommand { /// Video frames per second. #[arg(long, default_value_t = 30)] fps: u32, - /// Video bitrate in kbit/s (announced in `setupstream` too). - #[arg(long, default_value_t = 4608)] + /// Video bitrate in kbit/s (announced in `setupstream` too, up to the + /// 65535 a server keeps); 0: automatic, from the size and frame rate + /// (up to 60 Mbit/s). + #[arg(long, default_value_t = 0)] bitrate: u32, /// No audio track. #[arg(long)] @@ -194,7 +196,7 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { } if *synthetic { let (w, h) = parse_size(size)?; - let bitrate = u64::from(*bitrate) * 1000; + let bitrate = u64::from(pattern_kbps(size, *fps, *bitrate)?) * 1000; config.set_h264_format(H264Profile::ConstrainedHigh, w, h, *fps, bitrate); } } @@ -241,10 +243,14 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { l.rid.as_ref().map(|r| format!(", rid {r}")).unwrap_or_default() ); } + // The test pattern's (and the placeholder's) automatic bitrate is + // known now; a capture's once it captures. + let wanted = *bitrate; + let mut bitrate = pattern_kbps(size, *fps, wanted)?; let (source, audio) = if *placeholder { let source = SyntheticSource::with_layers( *fps, - (u64::from(*bitrate) * 1000 / 8 / u64::from((*fps).max(1))) as usize, + (u64::from(bitrate) * 1000 / 8 / u64::from((*fps).max(1))) as usize, !no_audio, layers, ); @@ -252,12 +258,13 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { } else { let source = if *synthetic { "synthetic" } else { source.as_str() }; let (source, backend) = parse_source(source)?; + let config_source = source.clone(); let Some(codec) = codec else { bail!("no video encoder in this build") }; let config = StreamerConfig { source, backend, fps: *fps, - bitrate_kbps: *bitrate, + bitrate_kbps: wanted, codec, encoder: codecs.preference().clone(), audio: !no_audio, @@ -266,6 +273,9 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { ..StreamerConfig::default() }; let streamer = Streamer::start(&codecs, config).await.context("capture")?; + if wanted == 0 && !matches!(config_source, SourceId::Synthetic) { + bitrate = streamer.bitrate_kbps(); + } let backend = streamer.stats().layers.first().and_then(|l| l.backend); let backend = backend.map_or("?".to_owned(), |b| b.to_string()); println!("capturing with {} ({codec} through {backend})", streamer.backend()); @@ -275,8 +285,8 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { let audio = streamer.has_audio(); (Source::Encoded(EncodedSource::new(streamer)), audio) }; - let setup = - StreamSetup { name: name.clone(), bitrate: *bitrate, audio, ..Default::default() }; + println!("bitrate: {}", rate(u64::from(bitrate) * 1000)); + let setup = StreamSetup { name: name.clone(), bitrate, audio, ..Default::default() }; let options = StreamerOptions { setup, auto_accept: *auto_accept, @@ -321,6 +331,16 @@ fn parse_source(spec: &str) -> Result<(SourceId, CaptureBackend)> { }) } +/// `wanted` kbit/s, or for 0 (automatic) the automatic bitrate of a test +/// pattern of `size` at `fps`. +fn pattern_kbps(size: &str, fps: u32, wanted: u32) -> Result { + if wanted > 0 { + return Ok(wanted); + } + let (w, h) = parse_size(size)?; + Ok(u32::try_from(auto_bitrate(w, h, fps) / 1000).unwrap_or(u32::MAX)) +} + /// `x`. fn parse_size(size: &str) -> Result<(u32, u32)> { let parsed = size.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))); From ce5fe0a7039688e3d4e04b00c0de73a99ac81142 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 03:43:06 +0300 Subject: [PATCH 03/12] Capture: ask the compositor for the stream's frame rate, up to its own The ScreenCast portal was offered a frame rate range up to the stream's cap but no `maxFramerate`, so the compositor's own maximum (its screen's refresh rate) applied whatever the cap was: a 30 fps stream of a 144 Hz screen got 144 frames a second, of which the sink dropped most. It is now offered `maxFramerate` up to the cap, preferably the cap: PipeWire keeps the consumer's default where the producer's range allows it, so the compositor sends at the lower of the cap and what it can, up to 320 fps or more on a screen that fast. Renegotiated with the cap as before. Windows Graphics Capture is reported to deliver about 60 frames a second without a minimum update interval (or with one under 1 ms); it now gets 1 ms where Windows has the setting, so the sink's cap decides there too. Type-checked only; it has not run on Windows. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-media/src/capture/portal.rs | 58 ++++++++++++++++------ crates/voelin-media/src/capture/windows.rs | 15 ++++-- docs/media.md | 14 +++++- 3 files changed, 67 insertions(+), 20 deletions(-) diff --git a/crates/voelin-media/src/capture/portal.rs b/crates/voelin-media/src/capture/portal.rs index 631a5b7..e171b47 100644 --- a/crates/voelin-media/src/capture/portal.rs +++ b/crates/voelin-media/src/capture/portal.rs @@ -388,17 +388,26 @@ fn size_range() -> Property { ) } -/// Up to `fps`, as the compositor can (it sends frames on damage only). -fn framerate_range(fps: u32) -> Property { - property!( - FormatProperties::VideoFramerate, - Choice, - Range, - Fraction, - Fraction { num: fps, denom: 1 }, - Fraction { num: 0, denom: 1 }, - Fraction { num: fps, denom: 1 } - ) +/// Up to `fps`, as the compositor can (it sends frames on damage only): +/// the frame rate (compositors offer 0, variable) and the most frames it +/// may send, preferably `fps`. Compositors offer their screen's refresh rate +/// as the maximum (Mutter, KWin, xdg-desktop-portal-hyprland, whose +/// `screencopy:max_fps` defaults to 120), so the intersection is the +/// lower of the two: the compositor neither sends frames the sink would +/// drop nor fewer than its screen shows. +fn framerate_range(fps: u32) -> [Property; 2] { + let up_to = |key: FormatProperties, min: u32| { + property!( + key, + Choice, + Range, + Fraction, + Fraction { num: fps, denom: 1 }, + Fraction { num: min, denom: 1 }, + Fraction { num: fps, denom: 1 } + ) + }; + [up_to(FormatProperties::VideoFramerate, 0), up_to(FormatProperties::VideoMaxFramerate, 1)] } /// The modifiers we take, best first: the sink's tiled ones, then LINEAR, @@ -471,7 +480,7 @@ fn enum_formats( properties.push(property!(FormatProperties::VideoFormat, Id, format)); properties.push(modifier_property(&modifiers, false)); properties.push(size_range()); - properties.push(framerate_range(fps)); + properties.extend(framerate_range(fps)); formats.push(serialize(format_object(properties))?); } } @@ -488,7 +497,7 @@ fn enum_formats( FORMATS[3] )); properties.push(size_range()); - properties.push(framerate_range(fps)); + properties.extend(framerate_range(fps)); formats.push(serialize(format_object(properties))?); Ok(formats) } @@ -543,7 +552,7 @@ fn format_changed( Rectangle { width: size.width, height: size.height } ), ]; - properties.push(framerate_range(state.fps)); + properties.extend(framerate_range(state.fps)); let fixed = serialize(format_object(properties))?; stream.update_params(&mut [pod(&fixed)?]).map_err(|e| e.to_string())?; return Ok(()); @@ -808,6 +817,27 @@ mod tests { assert!(modifier.is_none(), "shared memory has no modifier"); } } + // The frame rate and the most frames a second: 320 preferred, as + // much as the compositor can. + for bytes in enum_formats(320, true, &[]).unwrap() { + let object = pod(&bytes).unwrap().as_object().unwrap(); + for (key, min) in + [(FormatProperties::VideoFramerate, 0), (FormatProperties::VideoMaxFramerate, 1)] + { + use pw::spa::pod::deserialize::PodDeserializer; + let prop = object.find_prop(Id(key.as_raw())).expect("a frame rate"); + let value = + PodDeserializer::deserialize_any_from(prop.value().as_bytes()).unwrap().1; + let Value::Choice(ChoiceValue::Fraction(Choice( + _, + ChoiceEnum::Range { default, min: low, max }, + ))) = value + else { + panic!("{value:?}"); + }; + assert_eq!((default.num, low.num, max.num), (320, min, 320)); + } + } let linear_only = enum_formats(60, true, &[]).unwrap(); let object = pod(&linear_only[0]).unwrap().as_object().unwrap(); let prop = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())).unwrap(); diff --git a/crates/voelin-media/src/capture/windows.rs b/crates/voelin-media/src/capture/windows.rs index 2ce053a..f6067c1 100644 --- a/crates/voelin-media/src/capture/windows.rs +++ b/crates/voelin-media/src/capture/windows.rs @@ -12,12 +12,12 @@ //! Type-checked on Linux (`--target x86_64-pc-windows-gnu`), not run yet. use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::Instant; +use std::time::{Duration, Instant}; use tracing::{debug, warn}; use windows_capture::capture::{CaptureControl, Context, GraphicsCaptureApiHandler}; use windows_capture::frame::Frame; -use windows_capture::graphics_capture_api::InternalCaptureControl; +use windows_capture::graphics_capture_api::{GraphicsCaptureApi, InternalCaptureControl}; use windows_capture::monitor::Monitor; use windows_capture::settings::{ ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings, @@ -105,13 +105,20 @@ where } else { CursorCaptureSettings::WithoutCursor }; + // Left alone, Windows delivers about 60 frames a second (reported for + // a default and for anything under 1 ms: robmikh/Win32CaptureSample#82). + // 1 ms lets the sink's frame-rate cap decide, which can change while + // capturing. Windows 10 has no such setting. + let interval = match GraphicsCaptureApi::is_minimum_update_interval_supported() { + Ok(true) => MinimumUpdateIntervalSettings::Custom(Duration::from_millis(1)), + _ => MinimumUpdateIntervalSettings::Default, + }; let settings = Settings::new( item, cursor, DrawBorderSettings::WithoutBorder, SecondaryWindowSettings::Default, - // No minimum: the frame rate can change while capturing. - MinimumUpdateIntervalSettings::Default, + interval, DirtyRegionSettings::Default, ColorFormat::Bgra8, (sink, Instant::now()), diff --git a/docs/media.md b/docs/media.md index 578d456..0749b59 100644 --- a/docs/media.md +++ b/docs/media.md @@ -733,8 +733,13 @@ Notes: and end; if that is slower than 1 ns per pixel over the first 30 frames (uncached VRAM), the stream renegotiates to shared memory. `VOELIN_PORTAL_DMABUF=0` or `with_dmabuf(false)` skips DMA-BUFs. The frame rate - asked of the compositor is the sink's cap, renegotiated when it changes; - compositors send frames only when the screen changes. Without a session + asked of the compositor is the sink's cap, renegotiated when it changes: + `framerate` up to it and `maxFramerate` preferably it. Compositors offer + their screen's refresh rate as the most (Mutter, KWin, + xdg-desktop-portal-hyprland, which also caps at its `screencopy:max_fps`, + 120 unless configured), so a capture runs at the lower of the cap and + what the compositor can, and the compositor sends no frame the sink + would drop. Compositors send frames only when the screen changes. Without a session bus or portal, `start` returns `Error::CaptureUnavailable`; a cancelled dialog returns `Error::Cancelled`. - wlroots: `WlrootsCapture::new()` (`$WAYLAND_DISPLAY`) or `with_display`; @@ -752,6 +757,11 @@ Notes: stream of ours ([Stream audio](#stream-audio)). Without a PipeWire daemon, both return `Error::CaptureUnavailable`. - Windows process loopback needs Windows 10 2004 or later. +- Windows Graphics Capture is given a minimum update interval of 1 ms where + Windows has the setting (Windows 11): left alone, or below 1 ms, it is + reported to deliver about 60 frames a second (robmikh/Win32CaptureSample + issue 82), and the sink's frame-rate cap decides instead. Not run on + Windows yet. ## Performance and benchmarks From 57fc25ab9ee3b119bc12aae70825fe2bb5aa8d3f Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 03:57:53 +0300 Subject: [PATCH 04/12] voelin-media: HEVC and AV1 levels and tiers that count the frame rate VA-API's HEVC and AV1 encoders guessed their level themselves: FFmpeg's AV1 guess reads the frame rate from `AVCodecContext.framerate`, which has no AVOption and so was never set, and its HEVC guess ignores the rate. A 4K240 stream declared a level for 4K60, which a decoder that sizes itself from the level may refuse. The encoder now sets the level and tier from the stream's size, frame rate and bitrate (H.265 Table A.8, AV1 A.3): the lowest level whose Main tier holds the bitrate, else the lowest whose High tier does, else no limits (HEVC 8.5, AV1 level 31) as FFmpeg does. 4K60 at 60 Mbit/s is 5.2 Main, 4K240 and 8K60 6.1. Only for VA-API, whose options take `general_level_idc` and `seq_level_idx`; other wrappers count levels differently. The rate-control buffer is clamped to what its int holds, so a typed bitrate above 1 Gbit/s no longer fails the open. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-media/src/ffmpeg/encoder.rs | 145 +++++++++++++++++++++- docs/media.md | 12 ++ 2 files changed, 156 insertions(+), 1 deletion(-) diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 7fc088e..a57dfd2 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -245,6 +245,98 @@ fn h264_level(profile: H264Profile, width: u32, height: u32, fps: u32, bitrate: .map_or(H264_LEVELS[H264_LEVELS.len() - 1].0, |l| l.0) } +/// An HEVC level (ITU-T H.265 Table A.8 and A.9): `general_level_idc` (30 +/// times the level), luma samples per picture and per second, Main and High +/// tier bitrate in kbit/s (High from level 4 on). +type HevcLevel = (i64, u64, u64, u64, u64); + +const HEVC_LEVELS: [HevcLevel; 13] = [ + (30, 36_864, 552_960, 128, 0), + (60, 122_880, 3_686_400, 1_500, 0), + (63, 245_760, 7_372_800, 3_000, 0), + (90, 552_960, 16_588_800, 6_000, 0), + (93, 983_040, 33_177_600, 10_000, 0), + (120, 2_228_224, 66_846_720, 12_000, 30_000), + (123, 2_228_224, 133_693_440, 20_000, 50_000), + (150, 8_912_896, 267_386_880, 25_000, 100_000), + (153, 8_912_896, 534_773_760, 40_000, 160_000), + (156, 8_912_896, 1_069_547_520, 60_000, 240_000), + (180, 35_651_584, 1_069_547_520, 60_000, 240_000), + (183, 35_651_584, 2_139_095_040, 120_000, 480_000), + (186, 35_651_584, 4_278_190_080, 240_000, 800_000), +]; + +/// An AV1 level (AV1 specification A.3): `seq_level_idx`, samples per +/// picture, width, height, samples per second (MaxDisplayRate), frame +/// headers per second, Main and High tier bitrate in kbit/s (High from 4.0 +/// on). +type Av1Level = (i64, u64, u32, u32, u64, u32, u64, u64); + +const AV1_LEVELS: [Av1Level; 14] = [ + (0, 147_456, 2048, 1152, 4_423_680, 150, 1_500, 0), + (1, 278_784, 2816, 1584, 8_363_520, 150, 3_000, 0), + (4, 665_856, 4352, 2448, 19_975_680, 150, 6_000, 0), + (5, 1_065_024, 5504, 3096, 31_950_720, 150, 10_000, 0), + (8, 2_359_296, 6144, 3456, 70_778_880, 300, 12_000, 30_000), + (9, 2_359_296, 6144, 3456, 141_557_760, 300, 20_000, 50_000), + (12, 8_912_896, 8192, 4352, 267_386_880, 300, 30_000, 100_000), + (13, 8_912_896, 8192, 4352, 534_773_760, 300, 40_000, 160_000), + (14, 8_912_896, 8192, 4352, 1_069_547_520, 300, 60_000, 240_000), + (15, 8_912_896, 8192, 4352, 1_069_547_520, 300, 60_000, 240_000), + (16, 35_651_584, 16384, 8704, 1_069_547_520, 300, 60_000, 240_000), + (17, 35_651_584, 16384, 8704, 2_139_095_040, 300, 100_000, 480_000), + (18, 35_651_584, 16384, 8704, 4_278_190_080, 300, 160_000, 800_000), + (19, 35_651_584, 16384, 8704, 4_278_190_080, 300, 160_000, 800_000), +]; + +/// The lowest level of `levels` (`fits` its picture and rate limits) whose +/// Main tier holds `kbps`, else the lowest whose High tier does: Main is +/// what more decoders take. `None` beyond every level. +fn tiered_level( + levels: &[L], + fits: impl Fn(&L) -> bool, + tiers: impl Fn(&L) -> (i64, u64, u64), + kbps: u64, +) -> Option<(i64, bool)> { + let fitting = || levels.iter().filter(|l| fits(l)).map(&tiers); + let main = fitting().find(|&(_, main, _)| kbps <= main).map(|(level, ..)| (level, false)); + main.or_else(|| fitting().find(|&(.., high)| kbps <= high).map(|(level, ..)| (level, true))) +} + +/// HEVC `general_level_idc` and High tier for this stream (see +/// [`tiered_level`]); beyond every level 8.5 (255) in the High tier, as +/// FFmpeg's own guess does. +fn hevc_level(width: u32, height: u32, fps: u32, bitrate: u32) -> (i64, bool) { + let picture = u64::from(width) * u64::from(height); + let rate = picture * u64::from(fps.max(1)); + let side = u64::from(width.max(height)); + let fits = |&(_, max_picture, max_rate, ..): &HevcLevel| { + picture <= max_picture && side * side <= 8 * max_picture && rate <= max_rate + }; + let tiers = |&(level, .., main, high): &HevcLevel| (level, main, high); + tiered_level(&HEVC_LEVELS, fits, tiers, u64::from(bitrate).div_ceil(1000)) + .unwrap_or((255, true)) +} + +/// AV1 `seq_level_idx` and High tier for this stream (see +/// [`tiered_level`]); beyond every level 31, which has no limits, as +/// FFmpeg's own guess does. Unlike that guess this counts the frame rate: +/// FFmpeg's wrappers read it from `AVCodecContext.framerate`, which has no +/// AVOption. +fn av1_level(width: u32, height: u32, fps: u32, bitrate: u32) -> (i64, bool) { + let picture = u64::from(width) * u64::from(height); + let rate = picture * u64::from(fps.max(1)); + let fits = |&(_, max_picture, max_w, max_h, max_rate, headers, ..): &Av1Level| { + picture <= max_picture + && width <= max_w + && height <= max_h + && rate <= max_rate + && fps <= headers + }; + let tiers = |&(level, .., main, high): &Av1Level| (level, main, high); + tiered_level(&AV1_LEVELS, fits, tiers, u64::from(bitrate).div_ceil(1000)).unwrap_or((31, true)) +} + /// The backend's realtime settings (besides size, format, time base and /// rate, which every backend gets). fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec { @@ -855,9 +947,12 @@ impl FfmpegEncoder { // 7.9 % at 1440p60 / 10 Mbit/s (RX 7900 GRE, desktop pattern); // with two it lands within 1.2 % at both and at 720p30, no frame // skipped, the largest 68 KB against 64 KB at 1440p60. + // `bufsize` is an int: from 1 Gbit/s (2.1 for one second) the + // buffer stays at the most it holds rather than failing the open. generic( "bufsize", - u64::from(bitrate) * if self.spec.name == "av1_vaapi" { 2 } else { 1 }, + (u64::from(bitrate) * if self.spec.name == "av1_vaapi" { 2 } else { 1 }) + .min(i32::MAX as u64), ), generic("g", gop), generic("bf", 0), @@ -879,6 +974,21 @@ impl FfmpegEncoder { list.push(generic("level", &level)); list.push(Setting { values: vec![level], ..opt("level", &[]) }); } + // HEVC and AV1 through VA-API: the level and tier the stream needs. + // Left to FFmpeg, a 4K240 stream declares a 4K60 level (neither guess + // counts the frame rate, and the HEVC one ignores it entirely). Only + // VA-API, whose `level` is `general_level_idc` and `seq_level_idx`; + // other wrappers count levels differently (Quick Sync in tenths). + let tiered = match self.spec.codec { + Codec::H265 if self.spec.is_vaapi() => Some(hevc_level(width, height, fps, bitrate)), + Codec::Av1 if self.spec.is_vaapi() => Some(av1_level(width, height, fps, bitrate)), + _ => None, + }; + if let Some((level, high)) = tiered { + list.push(generic("level", level)); + list.push(Setting { values: vec![level.to_string()], ..opt("level", &[]) }); + list.push(opt("tier", &[if high { "high" } else { "main" }])); + } list.extend(settings(self.spec, &self.config, low_power)); for setting in &list { self.apply(ctx, private, setting)?; @@ -2528,6 +2638,39 @@ mod tests { } } + /// Levels and tiers per H.265 Table A.8 and AV1 A.3, with the frame rate + /// and the bitrate counted. + #[test] + fn hevc_and_av1_levels() { + // 1080p60 at 8 Mbit/s: 4.1 Main; 4K60 at 60 Mbit/s: 5.1's Main + // tier holds 40, so 5.2 Main. + assert_eq!(hevc_level(1920, 1080, 60, 8_000_000), (123, false)); + assert_eq!(hevc_level(3840, 2160, 60, 60_000_000), (156, false)); + // 4K240 needs 6.1 for its sample rate; 8K30, 8K60, 8K120: 6, 6.1, 6.2. + assert_eq!(hevc_level(3840, 2160, 240, 60_000_000), (183, false)); + assert_eq!(hevc_level(7680, 4320, 30, 60_000_000), (180, false)); + assert_eq!(hevc_level(7680, 4320, 60, 60_000_000), (183, false)); + assert_eq!(hevc_level(7680, 4320, 120, 60_000_000), (186, false)); + // Beyond the Main tier of every level: High. + assert_eq!(hevc_level(1920, 1080, 30, 300_000_000), (183, true)); + // Beyond every level: 8.5. + assert_eq!(hevc_level(7680, 4320, 320, 60_000_000), (255, true)); + assert_eq!(hevc_level(16384, 16384, 30, 60_000_000), (255, true)); + + // AV1: 1080p60 at 6 Mbit/s 4.1; 4K60 at 60 Mbit/s 5.2 (5.1 Main + // holds 40). + assert_eq!(av1_level(1920, 1080, 60, 6_000_000), (9, false)); + assert_eq!(av1_level(3840, 2160, 60, 60_000_000), (14, false)); + // The frame rate counts: 4K240 6.1, 1440p240 5.2, 8K60 6.1. + assert_eq!(av1_level(3840, 2160, 240, 60_000_000), (17, false)); + assert_eq!(av1_level(2560, 1440, 240, 60_000_000), (14, false)); + assert_eq!(av1_level(7680, 4320, 60, 60_000_000), (17, false)); + // 8K30 at 100 Mbit/s: 6.1 Main rather than 6.0 High. + assert_eq!(av1_level(7680, 4320, 30, 100_000_000), (17, false)); + // More than 300 frame headers a second is beyond every level. + assert_eq!(av1_level(1920, 1080, 320, 60_000_000), (31, true)); + } + #[test] fn settings_per_backend() { let config = EncoderConfig::default(); diff --git a/docs/media.md b/docs/media.md index 0749b59..d166d40 100644 --- a/docs/media.md +++ b/docs/media.md @@ -477,6 +477,18 @@ the software encoders above are used as before. implementations conventionally do, `h264_vaapi` and `h264_amf` emit `0c` for the former and `libx264` emits `00`, and all three emit `40` or `c0` for the latter. Those bits do not change what a decoder can decode. +- HEVC and AV1 levels (VA-API): the level and tier the stream needs, from + its size, frame rate and bitrate (H.265 Table A.8, AV1 A.3): the lowest + level whose Main tier holds the bitrate, else the lowest whose High tier + does, else 8.5 / level 31 (no limits). FFmpeg's own guess counts neither + the frame rate (AV1 reads `AVCodecContext.framerate`, which has no + AVOption; HEVC ignores it) nor, at a given level, a higher tier, so a + 4K240 stream declared a 4K60 level. Now 4K60 at 60 Mbit/s is HEVC 5.2 / + AV1 5.2 Main, 4K240 6.1, 8K30/60/120 HEVC 6/6.1/6.2; more than 300 fps + is beyond every AV1 level (300 frame headers a second). Other wrappers + count levels differently (Quick Sync in tenths) and keep choosing their + own. The rate-control buffer (`bufsize`, an int) stays at the 2^31-1 + bits it holds from 1 Gbit/s on instead of failing the open. - Runtime changes: x264, NVENC and Quick Sync take bitrate changes on the running encoder (FFmpeg's wrappers compare `b` / `maxrate` / `bufsize` before each frame); the others reopen at the next keyframe, at once From a0ff7dae61150f9c1f09f93c5eb7686ad7bb6d33 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 04:18:53 +0300 Subject: [PATCH 05/12] Bench the GPU path from buffers in video memory, as a compositor's are The test pattern's DMA-BUFs came from /dev/udmabuf: ordinary memory, which the GPU reads over the bus. Measured on the Radeon RX 7900 GRE (`gpu_conversion_cost`, new, ignored): converting a 3840x2160 RGB buffer to NV12 took 9.7 ms from such a buffer against 0.16 ms from one in video memory in the driver's tiled layout, and 4.0 against 0.09 ms at 1080p; the import itself costs 0.01-0.02 ms either way. So the bench showed the GPU path at 4K240 stuck at 70 fps waiting for the bus, which no real capture does. udmabuf also refuses buffers over 64 MiB, so 7680x4320 (132 MiB) could not be benched on the GPU path at all. `SyntheticScreen::with_video_memory` (`StreamerConfig:: synthetic_video_memory`, `voelinctl stream bench --vram`) draws eight frames of the pattern in advance into VA-API surfaces of the driver's layout, exported as DMA-BUFs and handed over in turn, as a compositor hands over the screen; a sink that declines them gets memory frames as before. The exported surface was a test helper and is now crate code (`ffmpeg::Exported`). With it, from a dev build: 4K240 AV1 at 60 Mbit/s 236.8 fps with 0.31 ms on the GPU per frame and 0.03 cores; 8K60 60.0 fps, 1.01 ms, 0.01 cores, the encoder's 16.5 ms per frame the limit. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-core/src/media.rs | 7 +- crates/voelin-media/src/capture/synthetic.rs | 155 ++++++++++++++- crates/voelin-media/src/ffmpeg/encoder.rs | 187 ++++++++----------- crates/voelin-media/src/ffmpeg/gpu.rs | 147 +++++++++++++++ crates/voelin-media/src/ffmpeg/mod.rs | 2 + docs/media.md | 5 + tools/voelinctl/src/bench.rs | 10 +- 7 files changed, 392 insertions(+), 121 deletions(-) diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 43f6e9c..db200a0 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -575,6 +575,9 @@ pub struct StreamerConfig { /// ([`SyntheticScreen::with_dmabuf`]): drives the GPU path without a /// portal (Linux, `/dev/udmabuf`). pub synthetic_dmabuf: bool, + /// With `synthetic_dmabuf`: buffers in video memory drawn in advance, as + /// a compositor's are ([`SyntheticScreen::with_video_memory`]; VA-API). + pub synthetic_video_memory: bool, /// Portal restore token from an earlier share: the desktop may skip its /// dialog. The new one is [`Streamer::restore_token`]. pub restore_token: Option, @@ -598,6 +601,7 @@ impl Default for StreamerConfig { synthetic_size: (1280, 720), synthetic_pattern: Pattern::Simple, synthetic_dmabuf: false, + synthetic_video_memory: false, restore_token: None, layers: Vec::new(), } @@ -1058,7 +1062,8 @@ impl Streamer { SourceId::Synthetic => { let (w, h) = config.synthetic_size; let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern) - .with_dmabuf(config.synthetic_dmabuf); + .with_dmabuf(config.synthetic_dmabuf) + .with_video_memory(config.synthetic_video_memory); screen.start_sink(&SourceId::Synthetic, &options, ingest).await?; (Box::new(screen), None) } diff --git a/crates/voelin-media/src/capture/synthetic.rs b/crates/voelin-media/src/capture/synthetic.rs index 55056c4..3841490 100644 --- a/crates/voelin-media/src/capture/synthetic.rs +++ b/crates/voelin-media/src/capture/synthetic.rs @@ -225,6 +225,7 @@ pub struct SyntheticScreen { desktop: Option>, worker: Option, dmabuf: bool, + video_memory: bool, } impl SyntheticScreen { @@ -237,7 +238,7 @@ impl SyntheticScreen { let (width, height) = (width.max(16), height.max(16)); let desktop = (pattern == Pattern::Desktop) .then(|| Arc::new(Desktop::render(width as usize, height as usize))); - Self { width, height, pattern, desktop, worker: None, dmabuf: false } + Self { width, height, pattern, desktop, worker: None, dmabuf: false, video_memory: false } } /// Draw into a DMA-BUF of ordinary memory and offer it to sinks that @@ -251,6 +252,20 @@ impl SyntheticScreen { self } + /// With [`with_dmabuf`](Self::with_dmabuf): the DMA-BUFs are buffers in + /// video memory in the GPU driver's own (tiled) layout, as a + /// compositor's are, drawn once in advance ([`VIDEO_MEMORY_FRAMES`] + /// frames of the pattern, handed over in turn) so the source costs + /// nothing per frame. The GPU reads ordinary memory over the bus, several + /// times slower (measured on a Radeon RX 7900 GRE: 9.7 ms against 0.16 + /// for a 3840x2160 conversion), and `/dev/udmabuf` refuses buffers of + /// more than 64 MiB by default (7680x4320 is 132). Linux with the `ffmpeg` + /// feature and VA-API; elsewhere, ordinary memory as before. + pub fn with_video_memory(mut self, enabled: bool) -> Self { + self.video_memory = enabled; + self + } + pub fn pattern(&self) -> Pattern { self.pattern } @@ -264,6 +279,7 @@ impl SyntheticScreen { desktop: self.desktop.clone(), worker: None, dmabuf: self.dmabuf, + video_memory: self.video_memory, } } @@ -375,13 +391,19 @@ impl ScreenCapture for SyntheticScreen { loop { let timestamp = started.elapsed(); if sink.wants(timestamp) { - let bytes = buffer.bytes(); - pattern.draw(n, bytes); - let taken = match buffer.dmabuf(&pattern, timestamp) { + // Buffers in video memory are drawn in advance; memory + // only for a sink that declines them. + if !buffer.drawn_in_advance() { + pattern.draw(n, buffer.bytes()); + } + let taken = match buffer.dmabuf(&pattern, n, timestamp) { Some(frame) if sink.accepts_dmabuf() => sink.dmabuf(&frame), _ => None, }; let more = taken.unwrap_or_else(|| { + if buffer.drawn_in_advance() { + pattern.draw(n, buffer.bytes()); + } let plane = PlaneRef::new(buffer.bytes(), width as usize * 4); sink.frame(FrameRef { width, @@ -413,17 +435,31 @@ impl ScreenCapture for SyntheticScreen { } } -/// Where the test pattern is drawn: plain memory, or a DMA-BUF of ordinary -/// memory ([`SyntheticScreen::with_dmabuf`]). +/// Frames of the pattern drawn in advance into video memory +/// ([`SyntheticScreen::with_video_memory`]), handed over in turn. +pub const VIDEO_MEMORY_FRAMES: usize = 8; + +/// Where the test pattern is drawn: plain memory, a DMA-BUF of ordinary +/// memory ([`SyntheticScreen::with_dmabuf`]), or buffers in video memory +/// drawn in advance (and memory for a sink that declines them). enum Buffer { Memory(Vec), #[cfg(all(target_os = "linux", feature = "pipewire"))] Dmabuf(super::dmabuf::Udmabuf), + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + Video(Vec, Vec), } impl Buffer { fn new(pattern: &SyntheticScreen) -> Self { let len = pattern.width as usize * pattern.height as usize * 4; + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + if pattern.dmabuf && pattern.video_memory { + match Self::video_memory(pattern) { + Ok(frames) => return Self::Video(frames, vec![0; len]), + Err(e) => tracing::warn!("test pattern not in video memory: {e}"), + } + } #[cfg(all(target_os = "linux", feature = "pipewire"))] if pattern.dmabuf { match super::dmabuf::Udmabuf::new(len) { @@ -434,21 +470,54 @@ impl Buffer { Self::Memory(vec![0; len]) } + /// [`VIDEO_MEMORY_FRAMES`] frames of the pattern in VA-API surfaces of + /// the driver's layout, exported as DMA-BUFs. + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + fn video_memory( + pattern: &SyntheticScreen, + ) -> std::result::Result, String> { + let ffmpeg = crate::ffmpeg::Ffmpeg::get().map_err(str::to_owned)?; + let bgr0 = ffmpeg.pix.bgr0.ok_or("no bgr0 pixel format")?; + let size = (pattern.width, pattern.height); + (0..VIDEO_MEMORY_FRAMES as u64) + .map(|n| { + let picture = pattern.frame(n, 1); + crate::ffmpeg::Exported::new(size, bgr0, super::drm_fourcc(b"XR24"), Some(&picture)) + }) + .collect() + } + + /// The frames are in video memory already. + fn drawn_in_advance(&self) -> bool { + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + if let Self::Video(..) = self { + return true; + } + false + } + fn bytes(&mut self) -> &mut [u8] { match self { Self::Memory(bytes) => bytes, #[cfg(all(target_os = "linux", feature = "pipewire"))] Self::Dmabuf(buffer) => buffer.bytes_mut(), + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + Self::Video(_, bytes) => bytes, } } - /// The buffer as a LINEAR `XR24` DMA-BUF, if it is one. - fn dmabuf(&self, pattern: &SyntheticScreen, timestamp: Duration) -> Option { + /// Frame `n` as an `XR24` DMA-BUF, if the buffers are DMA-BUFs. + fn dmabuf(&self, pattern: &SyntheticScreen, n: u64, timestamp: Duration) -> Option { match self { Self::Memory(_) => { - let _ = (pattern, timestamp); + let _ = (pattern, n, timestamp); None } + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + Self::Video(frames, _) => { + let exported = &frames[n as usize % frames.len()]; + Some(DmaBufRef { timestamp, ..exported.frame }) + } #[cfg(all(target_os = "linux", feature = "pipewire"))] Self::Dmabuf(buffer) => Some(DmaBufRef { width: pattern.width, @@ -663,4 +732,72 @@ mod tests { assert_eq!(row, expected[..64 * 4], "the first row of frame 0"); } } + + /// In video memory: the frames drawn in advance come in turn, each its + /// own buffer; a sink that declines them gets memory frames. + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + #[tokio::test] + async fn the_pattern_in_video_memory() { + use std::sync::mpsc; + + /// Takes DMA-BUFs (or declines them) and reports each one's fd. + struct Sink { + take: bool, + got: mpsc::Sender>, + } + impl FrameSink for Sink { + fn max_fps(&self) -> u32 { + 100 + } + fn frame(&mut self, _: FrameRef<'_>) -> bool { + self.got.send(None).is_ok() + } + fn accepts_dmabuf(&self) -> bool { + true + } + fn dmabuf(&mut self, frame: &DmaBufRef) -> Option { + assert_eq!((frame.width, frame.height), (256, 128)); + self.take.then(|| self.got.send(Some(frame.fd)).is_ok()) + } + } + + let exports = + crate::ffmpeg::Ffmpeg::get().ok().and_then(|f| f.pix.bgr0).is_some_and(|bgr0| { + crate::ffmpeg::Exported::new( + (64, 64), + bgr0, + super::super::drm_fourcc(b"XR24"), + None, + ) + .is_ok() + }); + if !exports { + eprintln!("no VA-API surfaces to export, skipped"); + return; + } + for take in [true, false] { + let mut screen = + SyntheticScreen::new(256, 128).with_dmabuf(true).with_video_memory(true); + let (got, frames) = mpsc::channel(); + let sink = Box::new(Sink { take, got }); + screen + .start_sink(&SourceId::Synthetic, &CaptureOptions::default(), sink) + .await + .unwrap(); + let mut fds = std::collections::BTreeSet::new(); + for _ in 0..2 * VIDEO_MEMORY_FRAMES { + match frames.recv_timeout(Duration::from_secs(5)).unwrap() { + Some(fd) => { + assert!(take, "declined, yet a DMA-BUF"); + fds.insert(fd); + } + None => assert!(!take, "taken, yet a memory frame"), + } + } + screen.stop(); + if take { + assert_eq!(fds.len(), VIDEO_MEMORY_FRAMES, "each buffer in turn"); + } + } + } } diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 1b60e3f..8f28445 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -1993,6 +1993,7 @@ impl EncoderFactory for FfmpegFactory { #[cfg(test)] mod tests { + use super::gpu::Exported; use super::*; #[test] @@ -2136,112 +2137,6 @@ mod tests { probe().iter().any(|s| s.spec.name == name && s.available.is_ok()) } - /// A VA-API surface of `sw_format` (holding `picture`, BGRA, if given) - /// exported as a DRM PRIME DMA-BUF: what a compositor hands over, - /// tiling modifier and all. The buffer is valid while this lives. - struct Exported { - pool: Ptr, - surface: Ptr, - drm: Ptr, - frame: DmaBufRef, - } - - impl Exported { - fn new( - (width, height): (u32, u32), - sw_format: c_int, - fourcc: u32, - picture: Option<&VideoFrame>, - ) -> Self { - let ffmpeg = Ffmpeg::get().unwrap(); - let api = &ffmpeg.api; - let pool = vaapi_pool(ffmpeg, width, height, sw_format).expect("a VA-API surface pool"); - // SAFETY: `pool` is a live frames context of this process's - // VA-API device; the frames are ours and freed by the drop. The - // exported frame's `data[0]` is the AVDRMFrameDescriptor FFmpeg - // filled, valid while the frame holds the mapping. - unsafe { - let mut exported = Exported { - pool, - surface: (api.av_frame_alloc)(), - drm: (api.av_frame_alloc)(), - frame: DmaBufRef { - width, - height, - timestamp: Duration::ZERO, - fourcc, - modifier: 0, - fd: -1, - size: 0, - planes: [(0, 0); 4], - plane_count: 0, - }, - }; - let (surface, drm) = (exported.surface, exported.drm); - assert!(!surface.is_null() && !drm.is_null()); - let ret = (api.av_hwframe_get_buffer)(pool, surface, 0); - assert!(ret >= 0, "av_hwframe_get_buffer: {}", api.error_text(ret)); - if let Some(picture) = picture { - let FrameData::Bgra(pixels) = &picture.data else { panic!("BGRA only") }; - let mut sw = (api.av_frame_alloc)(); - let head = sw.cast::(); - ((*head).width, (*head).height) = (width as c_int, height as c_int); - (*head).format = sw_format; - assert!((api.av_frame_get_buffer)(sw, 0) >= 0); - let stride = (*head).linesize[0] as usize; - let rows = - std::slice::from_raw_parts_mut((*head).data[0], stride * height as usize); - for (y, row) in rows.chunks_exact_mut(stride).enumerate() { - row[..width as usize * 4] - .copy_from_slice(pixels.row(y, width as usize * 4)); - } - let ret = (api.av_hwframe_transfer_data)(surface, sw, 0); - (api.av_frame_free)(&mut sw); - assert!(ret >= 0, "upload: {}", api.error_text(ret)); - } - (*drm.cast::()).format = ffmpeg.pix.drm_prime.expect("DRM PRIME"); - let ret = (api.av_hwframe_map)( - drm, - surface, - sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT, - ); - assert!(ret >= 0, "this driver cannot export a VA-API surface as a DMA-BUF"); - let descriptor = - *(*drm.cast::()).data[0].cast::(); - assert_eq!(descriptor.nb_objects, 1, "one buffer object"); - // The driver may describe a surface one plane per layer (NV12 - // as R8 for Y and GR88 for UV) rather than as one layer, which - // is how a compositor hands it over. Both name the same bytes - // of the same object, so flatten the layers into planes. - let object = descriptor.objects[0]; - let frame = &mut exported.frame; - for layer in &descriptor.layers[..descriptor.nb_layers as usize] { - for plane in &layer.planes[..layer.nb_planes as usize] { - frame.planes[frame.plane_count] = - (plane.offset as usize, plane.pitch as usize); - frame.plane_count += 1; - } - } - (frame.modifier, frame.fd, frame.size) = - (object.format_modifier, object.fd, object.size); - assert!(frame.fd >= 0 && frame.size > 0); - exported - } - } - } - - impl Drop for Exported { - fn drop(&mut self) { - let api = &Ffmpeg::get().unwrap().api; - // SAFETY: ours; the mapping goes before the surface it maps. - unsafe { - (api.av_frame_free)(&mut self.drm); - (api.av_frame_free)(&mut self.surface); - (api.av_buffer_unref)(&mut self.pool); - } - } - } - /// The picture of a GPU frame, read back into memory as I420. fn download(frame: &GpuFrame) -> VideoFrame { let ffmpeg = Ffmpeg::get().unwrap(); @@ -2295,7 +2190,8 @@ mod tests { ); let picture = screen.frame(5, 30); let rgb = - Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)); + Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)) + .unwrap(); let mut converter = GpuConverter::new().expect("VA-API video processing"); eprintln!("tiled RGB modifiers the import takes: {:x?}", converter.modifiers()); let layers = [ @@ -2380,7 +2276,7 @@ mod tests { return; } let nv12 = Ffmpeg::get().unwrap().pix.nv12; - let exported = Exported::new((320, 240), nv12, drm_fourcc(b"NV12"), None); + let exported = Exported::new((320, 240), nv12, drm_fourcc(b"NV12"), None).unwrap(); let frame = exported.frame; assert_eq!(frame.plane_count, 2, "NV12 has two planes"); let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); @@ -2421,7 +2317,8 @@ mod tests { ); let picture = screen.frame(3, 30); let rgb = - Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)); + Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)) + .unwrap(); assert_eq!(rgb.frame.plane_count, 1); // The conversion alone: the GPU's NV12 against the CPU's I420. @@ -2607,7 +2504,8 @@ mod tests { drop(encoder); let rgb = - Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)); + Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)) + .unwrap(); let mut encoder = FfmpegEncoder::new("h264_vaapi", config).unwrap(); measure("GPU: RGB DMA-BUF imported and converted", &mut |timestamp| { let frame = DmaBufRef { timestamp, ..rgb.frame }; @@ -2615,6 +2513,75 @@ mod tests { }); } + /// What the GPU path costs per captured frame: the DMA-BUF import alone, + /// and the whole conversion (import, VPP to NV12, the wait for the GPU), + /// from a buffer of the driver's own (video memory, tiled) and from a + /// LINEAR one of ordinary memory where `/dev/udmabuf` allows its size. + /// `cargo test -p voelin-media --release --lib gpu_conversion_cost -- + /// --ignored --nocapture`. + #[cfg(feature = "pipewire")] + #[test] + #[ignore = "a measurement, not a check"] + fn gpu_conversion_cost() { + if !usable("h264_vaapi") { + eprintln!("no usable h264_vaapi, skipped"); + return; + } + let ffmpeg = Ffmpeg::get().unwrap(); + for size in [(1920, 1080), (3840, 2160), (7680, 4320)] { + let screen = crate::capture::synthetic::SyntheticScreen::with_pattern( + size.0, + size.1, + crate::capture::synthetic::Pattern::Desktop, + ); + let picture = screen.frame(3, 60); + let vram = + Exported::new(size, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)) + .unwrap(); + let len = size.0 as usize * size.1 as usize * 4; + let mut ram = crate::capture::dmabuf::Udmabuf::new(len).ok(); + if let Some(ram) = &mut ram { + let FrameData::Bgra(pixels) = &picture.data else { unreachable!() }; + ram.bytes_mut().copy_from_slice(&pixels.data[..len]); + } + let linear = ram.as_ref().map(|ram| DmaBufRef { + fd: ram.fd(), + size: ram.len(), + modifier: crate::capture::DRM_MOD_LINEAR, + planes: [(0, size.0 as usize * 4), (0, 0), (0, 0), (0, 0)], + plane_count: 1, + ..vram.frame + }); + let mut converter = GpuConverter::new().unwrap(); + let layer = [GpuLayer { size, alignment: (2, 2), due: true }]; + let mut out = [None]; + for (what, frame) in [("video memory", Some(vram.frame)), ("udmabuf", linear)] { + let Some(frame) = frame else { + eprintln!("{}x{} {what}: no buffer of that size", size.0, size.1); + continue; + }; + converter.convert(&frame, &layer, &mut out).unwrap(); + let started = Instant::now(); + for _ in 0..100 { + converter.import_only(&frame).unwrap(); + } + let import = started.elapsed() / 100; + let started = Instant::now(); + for _ in 0..100 { + converter.convert(&frame, &layer, &mut out).unwrap(); + } + let convert = started.elapsed() / 100; + eprintln!( + "{}x{} {what}: import {:.2} ms, whole conversion {:.2} ms", + size.0, + size.1, + import.as_secs_f64() * 1e3, + convert.as_secs_f64() * 1e3 + ); + } + } + } + /// On Linux an AMF encoder is not even made unless asked for, so AMF's /// runtime is never loaded by default; other backends are made as /// before. diff --git a/crates/voelin-media/src/ffmpeg/gpu.rs b/crates/voelin-media/src/ffmpeg/gpu.rs index ff8cccc..882407f 100644 --- a/crates/voelin-media/src/ffmpeg/gpu.rs +++ b/crates/voelin-media/src/ffmpeg/gpu.rs @@ -138,6 +138,142 @@ pub(crate) fn map_dmabuf( Ok(()) } +/// A VA-API surface of `sw_format` (holding `picture`, BGRA, if given) +/// exported as a DRM PRIME DMA-BUF: a buffer in video memory as a +/// compositor hands one over, the driver's tiling modifier and all. The +/// buffer ([`frame`](Self::frame)) is valid while this lives. +#[cfg(target_os = "linux")] +pub(crate) struct Exported { + pool: Ptr, + surface: Ptr, + drm: Ptr, + pub(crate) frame: DmaBufRef, +} + +// SAFETY: the frames and the pool are ours; FFmpeg's buffer references are +// thread-safe and the surface is only read once it is made. +#[cfg(target_os = "linux")] +unsafe impl Send for Exported {} + +#[cfg(target_os = "linux")] +impl Exported { + pub(crate) fn new( + (width, height): (u32, u32), + sw_format: c_int, + fourcc: u32, + picture: Option<&crate::frame::VideoFrame>, + ) -> std::result::Result { + let ffmpeg = Ffmpeg::get().map_err(str::to_owned)?; + let api = &ffmpeg.api; + let pool = vaapi_pool(ffmpeg, width, height, sw_format)?; + let mut exported = Exported { + pool, + // SAFETY: allocations, checked below; the drop frees them. + surface: unsafe { (api.av_frame_alloc)() }, + drm: unsafe { (api.av_frame_alloc)() }, + frame: DmaBufRef { + width, + height, + timestamp: Duration::ZERO, + fourcc, + modifier: 0, + fd: -1, + size: 0, + planes: [(0, 0); 4], + plane_count: 0, + }, + }; + let (surface, drm) = (exported.surface, exported.drm); + if surface.is_null() || drm.is_null() { + return Err("out of memory".into()); + } + // SAFETY: `pool` is a live frames context of this process's VA-API + // device; the frames are ours. The exported frame's `data[0]` is the + // AVDRMFrameDescriptor FFmpeg filled, valid while the frame holds + // the mapping; a picture's rows are `width * 4` bytes. + unsafe { + let ret = (api.av_hwframe_get_buffer)(pool, surface, 0); + if ret < 0 { + return Err(format!("VA-API surface: {}", api.error_text(ret))); + } + if let Some(picture) = picture { + let crate::frame::FrameData::Bgra(pixels) = &picture.data else { + return Err("only BGRA pictures are uploaded".into()); + }; + let mut sw = (api.av_frame_alloc)(); + if sw.is_null() { + return Err("out of memory".into()); + } + let head = sw.cast::(); + ((*head).width, (*head).height) = (width as c_int, height as c_int); + (*head).format = sw_format; + let mut ret = (api.av_frame_get_buffer)(sw, 0); + if ret >= 0 { + let stride = (*head).linesize[0] as usize; + let rows = + std::slice::from_raw_parts_mut((*head).data[0], stride * height as usize); + for (y, row) in rows.chunks_exact_mut(stride).enumerate() { + row[..width as usize * 4] + .copy_from_slice(pixels.row(y, width as usize * 4)); + } + ret = (api.av_hwframe_transfer_data)(surface, sw, 0); + } + (api.av_frame_free)(&mut sw); + if ret < 0 { + return Err(format!("upload: {}", api.error_text(ret))); + } + } + (*drm.cast::()).format = + ffmpeg.pix.drm_prime.ok_or("no DRM PRIME format")?; + let flags = sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT; + if (api.av_hwframe_map)(drm, surface, flags) < 0 { + return Err("this driver cannot export a VA-API surface as a DMA-BUF".into()); + } + let descriptor = *(*drm.cast::()).data[0].cast::(); + if descriptor.nb_objects != 1 { + return Err(format!("{} buffer objects, not one", descriptor.nb_objects)); + } + // The driver may describe a surface one plane per layer (NV12 as + // R8 for Y and GR88 for UV) rather than as one layer, which is how + // a compositor hands it over. Both name the same bytes of the same + // object, so the layers are flattened into planes. + let object = descriptor.objects[0]; + let frame = &mut exported.frame; + let layers = descriptor.layers.iter().take(descriptor.nb_layers.max(0) as usize); + for layer in layers { + for plane in layer.planes.iter().take(layer.nb_planes.max(0) as usize) { + if frame.plane_count == frame.planes.len() { + return Err("more than four planes".into()); + } + frame.planes[frame.plane_count] = (plane.offset as usize, plane.pitch as usize); + frame.plane_count += 1; + } + } + (frame.modifier, frame.fd, frame.size) = + (object.format_modifier, object.fd, object.size); + if frame.fd < 0 || frame.size == 0 { + return Err("no DMA-BUF exported".into()); + } + } + Ok(exported) + } +} + +#[cfg(target_os = "linux")] +impl Drop for Exported { + fn drop(&mut self) { + if let Ok(ffmpeg) = Ffmpeg::get() { + // SAFETY: ours (or NULL); the mapping goes before the surface it + // maps. + unsafe { + (ffmpeg.api.av_frame_free)(&mut self.drm); + (ffmpeg.api.av_frame_free)(&mut self.surface); + (ffmpeg.api.av_buffer_unref)(&mut self.pool); + } + } + } +} + /// One output of [`GpuConverter::convert`]: a layer's size, the multiple /// its encoder takes, and whether it wants this frame. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -281,6 +417,17 @@ impl GpuConverter { result } + /// Map `frame` and let it go again: the import alone, for measuring. + #[cfg(test)] + pub(crate) fn import_only(&mut self, frame: &DmaBufRef) -> Result<()> { + self.prepare((frame.width, frame.height))?; + let pool = self.import.as_ref().expect("prepared").0; + map_dmabuf(self.ffmpeg, frame, pool, self.mapped.0, self.refs).map_err(Error::Convert)?; + // SAFETY: our frame. + unsafe { (self.ffmpeg.api.av_frame_unref)(self.mapped.0) }; + Ok(()) + } + /// The import pool and the video processing for buffers of `source`'s /// size. fn prepare(&mut self, source: (u32, u32)) -> Result<()> { diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index 88eefc1..e8cc979 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -30,6 +30,8 @@ mod layout; pub mod sys; mod vpp; +#[cfg(target_os = "linux")] +pub(crate) use gpu::Exported; pub(crate) use gpu::Surface; pub use gpu::{GpuConverter, GpuLayer}; diff --git a/docs/media.md b/docs/media.md index 629f6ee..1625e85 100644 --- a/docs/media.md +++ b/docs/media.md @@ -903,6 +903,11 @@ voelinctl stream bench --res 2560x1440 --fps 30 \ # The pattern handed over as DMA-BUFs, as the portal hands over the screen # (Linux, /dev/udmabuf): with VA-API encoders the GPU path, no portal needed voelinctl stream bench --res 2560x1440 --fps 60 --encoder h264_vaapi --dmabuf +# The same from buffers in video memory in the driver's tiled layout, drawn +# in advance (eight frames in turn), as a compositor hands them over: the +# udmabuf ones are ordinary memory the GPU reads over the bus several times +# slower, and /dev/udmabuf refuses more than 64 MiB (7680x4320 is 132 MiB) +voelinctl stream bench --res 7680x4320 --fps 60 --encoder av1_vaapi --vram # A real screen capture instead of the pattern (the portal asks the user; # --start-timeout bounds the wait so it cannot hang): voelinctl stream bench --source portal --fps 60 --encoder h264_vaapi diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs index f2ef8ae..8fa035d 100644 --- a/tools/voelinctl/src/bench.rs +++ b/tools/voelinctl/src/bench.rs @@ -85,6 +85,13 @@ struct BenchArgs { /// encoders the frames are then converted and scaled on the GPU. #[arg(long)] dmabuf: bool, + /// The pattern drawn in advance into DMA-BUFs in video memory (VA-API + /// surfaces in the driver's layout), as a compositor hands over the + /// screen; implies --dmabuf. Without it the DMA-BUFs are ordinary + /// memory, which the GPU reads over the bus several times slower, and + /// which `/dev/udmabuf` limits to 64 MiB (7680x4320 needs 132). + #[arg(long)] + vram: bool, /// Video codec: vp8, vp9, h264, av1 or h265 [default: the codec of /// --encoder if named, else the first the encoder choice gives]. #[arg(long)] @@ -388,7 +395,8 @@ fn bench(args: BenchArgs) -> Result<()> { source: source.clone(), synthetic_size: (width, height), synthetic_pattern: pattern, - synthetic_dmabuf: args.dmabuf, + synthetic_dmabuf: args.dmabuf || args.vram, + synthetic_video_memory: args.vram, fps: args.fps, bitrate_kbps: args.bitrate, codec, From 69152a8ae1a038e4cb9f4141f3b7fd1bf2a31096 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 09:13:32 +0300 Subject: [PATCH 06/12] Streamer: convert pictures in memory on the GPU too, for VA-API encoders Measured at 7680x4320@60 with av1_vaapi at 60 Mbit/s, the CPU path made 27 fps: the pyramid converted each frame to I420 on every core (4.6 ms), then the encoder thread interleaved it to NV12 and uploaded it into a VA-API surface on one thread (`encode_with`), 20 ms of its 36.7 ms per frame, so 81 frames in 5 s were dropped. 3840x2160@120 with h264_vaapi made 84 fps the same way. While every encoder takes GPU frames, a picture in memory (shared memory from the portal, X11, wlroots, the studio's composite, the test pattern) now takes the GPU path the DMA-BUFs take: `GpuConverter::convert_memory` copies it as it is (BGRx or RGBx) into a VA-API surface of its own and converts and scales that for every layer. That copy is all the CPU does: 5.7 ms of the 11.9 a 7680x4320 frame takes (the rest is the GPU's upload and conversion), one thread, because eight copying threads saved 2 ms for four times the CPU. Not waiting for the GPU was tried and was slower (36 fps at 8K60 against 42: the encoder then waited instead). The test pattern drew a 7680x4320 frame on one thread (230 MB of copies), which alone kept the bench under 40 fps; it now draws in bands on four threads, which the memory bandwidth limits anyway. Tests: a BGRx and an RGBx picture through the GPU match the CPU's conversion (40.4 dB at full size, 48.7 at half), and a streamer on the test pattern in memory with two `h264_vaapi` layers sends every frame through the GPU and decodes in the right colours (a red-blue swap fails it). The bench's GPU count now covers both kinds of frame. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-core/src/media.rs | 149 +++++++++++++++---- crates/voelin-media/src/capture/synthetic.rs | 55 ++++--- crates/voelin-media/src/ffmpeg/encoder.rs | 70 +++++++++ crates/voelin-media/src/ffmpeg/gpu.rs | 112 ++++++++++++-- crates/voelin-media/src/ffmpeg/mod.rs | 3 + crates/voelin-media/src/ffmpeg/sys.rs | 4 +- docs/media.md | 21 ++- tools/voelinctl/src/bench.rs | 5 +- 8 files changed, 349 insertions(+), 70 deletions(-) diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 3fcae19..a071387 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -707,11 +707,13 @@ pub struct StreamerStats { /// Mean time to convert a captured frame to I420 and scale it for every /// layer that is due, on the CPU. pub convert_time: Duration, - /// Captured frames that never reached the CPU: DMA-BUFs converted to - /// NV12 and scaled for every layer on the GPU, for VA-API encoders. + /// Captured frames converted to NV12 and scaled for every layer on the + /// GPU, for VA-API encoders: DMA-BUFs, which the CPU never reads, and + /// pictures in memory, which it copies into a surface first. pub gpu_frames: u64, - /// Mean time the capture thread spends on such a frame (it waits for - /// the GPU, so the buffer can go back to the compositor). + /// Mean time the capture thread spends on such a frame (the copy, if + /// any, and the wait for the GPU, so the buffer can go back to the + /// compositor). pub gpu_convert_time: Duration, /// Why the GPU path stopped (it fell back to the CPU), if it did. pub gpu_error: Option, @@ -1646,6 +1648,15 @@ struct Ingest { gpu: GpuStage, } +/// What the GPU stage converts: a DMA-BUF, or a picture in memory, which +/// it copies into a surface first. +#[cfg(all(target_os = "linux", feature = "media-desktop"))] +#[derive(Clone, Copy)] +enum GpuInput<'a, 'b> { + Dmabuf(&'a DmaBufRef), + Memory(&'a FrameRef<'b>), +} + /// The GPU stage of [`Ingest`]. #[cfg(all(target_os = "linux", feature = "media-desktop"))] #[derive(Default)] @@ -1705,33 +1716,36 @@ impl Ingest { false } + /// The GPU stage's converter, made for the first frame; `None` once + /// making it (or a conversion) failed. + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + fn gpu_converter(&mut self) -> Option<&mut voelin_media::ffmpeg::GpuConverter> { + if self.gpu.converter.is_none() { + match voelin_media::ffmpeg::GpuConverter::new() { + Ok(converter) => self.gpu.converter = Some(Ok(converter)), + Err(e) => { + warn!("no GPU conversion of captured frames, the CPU converts them: {e}"); + *lock(&self.shared.gpu_error) = Some(e.to_string()); + self.gpu.converter = Some(Err(())); + } + } + } + self.gpu.converter.as_mut()?.as_mut().ok() + } + /// Convert DMA-BUF `frame` on the GPU for every layer that is due; `None` /// if it is not taken (the backend maps it for [`FrameSink::frame`]). #[cfg(all(target_os = "linux", feature = "media-desktop"))] fn gpu_frame(&mut self, frame: &DmaBufRef) -> Option { - use voelin_media::ffmpeg::{GpuConverter, GpuLayer}; - if self.shared.stopped() { return Some(false); } if !self.gpu_path() { return None; } - let shared = self.shared.clone(); - let converter = match &mut self.gpu.converter { - Some(Ok(converter)) => converter, - Some(Err(())) => return None, - None => match GpuConverter::new() { - Ok(converter) => self.gpu.converter.insert(Ok(converter)).as_mut().ok()?, - Err(e) => { - warn!("no GPU conversion of captured frames, the CPU converts them: {e}"); - *lock(&shared.gpu_error) = Some(e.to_string()); - self.gpu.converter = Some(Err(())); - return None; - } - }, - }; + self.gpu_converter()?; self.pacer.keep(frame.timestamp); + let shared = &self.shared; shared.captured.fetch_add(1, Ordering::Relaxed); shared .size @@ -1739,32 +1753,55 @@ impl Ingest { if shared.sink().is_none() { return Some(true); } + self.gpu_convert(GpuInput::Dmabuf(frame)); + Some(true) + } + + /// Convert `input` on the GPU for every layer that is due, into their + /// GPU inboxes. A failure turns the GPU stage off: the frame is dropped + /// (its layers' pacing taken) and the next one takes the CPU path. + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + fn gpu_convert(&mut self, input: GpuInput<'_, '_>) { + use voelin_media::ffmpeg::GpuLayer; + + let ((width, height), timestamp) = match input { + GpuInput::Dmabuf(f) => ((f.width, f.height), f.timestamp), + GpuInput::Memory(f) => ((f.width, f.height), f.timestamp), + }; let mut any = false; self.gpu.layers.clear(); for l in &mut self.layers { - let due = !l.layer.stopped() && l.pacer.take(frame.timestamp); + let due = !l.layer.stopped() && l.pacer.take(timestamp); any |= due; let alignment = l.layer.gpu.load(Ordering::Relaxed); self.gpu.layers.push(GpuLayer { - size: l.spec.output_size(frame.width, frame.height), + size: l.spec.output_size(width, height), alignment: ((alignment >> 32) as u32, alignment as u32), due, }); } if !any { - return Some(true); + return; } self.gpu.out.clear(); self.gpu.out.resize(self.layers.len(), None); + let Some(Ok(converter)) = &mut self.gpu.converter else { return }; let started = Instant::now(); - if let Err(e) = converter.convert(frame, &self.gpu.layers, &mut self.gpu.out) { + let result = match input { + GpuInput::Dmabuf(frame) => { + converter.convert(frame, &self.gpu.layers, &mut self.gpu.out) + } + GpuInput::Memory(frame) => { + converter.convert_memory(frame, &self.gpu.layers, &mut self.gpu.out) + } + }; + let shared = &self.shared; + if let Err(e) = result { warn!("GPU conversion failed, the CPU converts captured frames from now on: {e}"); *lock(&shared.gpu_error) = Some(e.to_string()); self.gpu.converter = Some(Err(())); self.gpu.out.clear(); - // This frame is counted and its layers' pacing taken: it is - // dropped, and the next one takes the CPU path. - return Some(true); + return; } shared.gpu_convert_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); shared.gpu_converted.fetch_add(1, Ordering::Relaxed); @@ -1773,7 +1810,6 @@ impl Ingest { l.layer.gpu_inbox.put(frame); } } - Some(true) } /// Pick up layer and frame-rate changes. @@ -1896,6 +1932,15 @@ impl FrameSink for Ingest { if shared.sink().is_none() { return true; } + // While every encoder takes GPU frames, a picture in memory is + // copied into a surface and converted and scaled there. + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + if self.gpu_path() + && self.gpu_converter().is_some_and(|converter| converter.takes(&frame.pixels)) + { + self.gpu_convert(GpuInput::Memory(&frame)); + return true; + } let mut any = false; for (i, l) in self.layers.iter_mut().enumerate() { self.sizes[i] = l.spec.output_size(frame.width, frame.height); @@ -1906,6 +1951,7 @@ impl FrameSink for Ingest { return true; } let started = Instant::now(); + let shared = &self.shared; if let Err(e) = self.pyramid.process(&frame, &self.sizes, &self.due, &mut self.out) { warn!("cannot convert a captured frame: {e}"); shared.set_error(e); @@ -3855,6 +3901,53 @@ mod tests { assert_eq!(stats.gpu_error, None, "a planned switch, not a failure"); } + /// Pictures in memory take the GPU path too while every encoder takes + /// GPU frames: copied into a surface and converted and scaled there, in + /// the right colours (a red-blue swap would turn the orange rectangle + /// blue). Skipped without `h264_vaapi` or an H.264 decoder. + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + #[tokio::test(flavor = "multi_thread")] + async fn memory_frames_take_the_gpu_path_too() { + let vaapi = voelin_media::ffmpeg::probe() + .iter() + .any(|s| s.spec.name == "h264_vaapi" && s.available.is_ok()); + let codecs = Codecs::new(); + if !vaapi || codecs.new_decoder(Codec::H264).is_err() { + eprintln!("no h264_vaapi or H.264 decoder, skipped"); + return; + } + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (640, 360), + fps: 30, + audio: false, + codec: Codec::H264, + encoder: EncoderPreference { hardware: true, backend: "h264_vaapi".parse().unwrap() }, + layers: vec![layer(0, 1.0, None, 1_000_000), layer(5, 0.5, Some(15), 300_000)], + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + let mut source = EncodedSource::new(streamer); + let count = |frames: &[EncodedFrame], id| frames.iter().filter(|f| f.layer == id).count(); + let frames = collect(&mut source, |f| count(f, 0) >= 20 && count(f, 5) >= 5).await; + let stats = source.streamer().stats(); + assert_eq!(stats.gpu_error, None); + let on_cpu = stats.captured_frames - stats.gpu_frames; + assert!(on_cpu <= 1, "{on_cpu} of {} frames on the CPU", stats.captured_frames); + assert_eq!(decoded_size(Codec::H264, &frames, 5), ((320, 180), true)); + let mut decoder = codecs.new_decoder(Codec::H264).unwrap(); + let mut picture = None; + for f in frames.iter().filter(|f| f.layer == 0) { + picture = decoder.decode(&f.data).unwrap().or(picture); + } + let picture = picture.expect("pictures of layer 0"); + assert_eq!((picture.width, picture.height), (640, 360)); + let rgba = voelin_media::convert::to_rgba_vec(&picture).unwrap(); + let middle = &rgba[180 * 640 * 4..181 * 640 * 4]; + let orange = middle.chunks_exact(4).any(|p| p[0] > 180 && p[2] < 100); + assert!(orange, "no orange rectangle in the middle row"); + } + /// Two layers at their own sizes and frame rates, keyframes per layer, /// then a new codec and another layer set while streaming. #[cfg(feature = "media-desktop")] diff --git a/crates/voelin-media/src/capture/synthetic.rs b/crates/voelin-media/src/capture/synthetic.rs index 3841490..572db39 100644 --- a/crates/voelin-media/src/capture/synthetic.rs +++ b/crates/voelin-media/src/capture/synthetic.rs @@ -11,6 +11,7 @@ use crate::capture::{ }; use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame}; use crate::queue::{FrameReceiver, frame_channel}; +use crate::workers::{Slots, Workers}; use crate::{Error, Result}; /// Background colour of the pattern (RGB). @@ -205,13 +206,16 @@ impl Desktop { Self { page, editor, document, document_rows } } - /// The page with the document scrolled by `offset` rows. - fn draw(&self, out: &mut [u8], width: usize, offset: usize) { - out[..self.page.len()].copy_from_slice(&self.page); + /// Rows `first..` of the page with the document scrolled by `offset` + /// rows, into `out` (whole rows). + fn draw(&self, out: &mut [u8], width: usize, first: usize, offset: usize) { + let start = first * width * 4; + out.copy_from_slice(&self.page[start..start + out.len()]); let (ex, ey, ew, eh) = self.editor; - for row in 0..eh { - let src = (offset + row) % self.document_rows * ew * 4; - let dst = ((ey + row) * width + ex) * 4; + let rows = first..first + out.len() / (width * 4); + for y in rows.start.max(ey)..rows.end.min(ey + eh) { + let src = (offset + y - ey) % self.document_rows * ew * 4; + let dst = ((y - first) * width + ex) * 4; out[dst..dst + ew * 4].copy_from_slice(&self.document[src..src + ew * 4]); } } @@ -298,28 +302,30 @@ impl SyntheticScreen { /// its memory. pub fn render(&self, n: u64, out: &mut Vec) { out.resize(self.width as usize * self.height as usize * 4, 0); - self.draw(n, out); + self.draw(n, out, &mut Workers::new("voelin-synthetic", 1)); } /// [`render`](Self::render) into the first `width * height * 4` bytes of - /// `out`. - fn draw(&self, n: u64, out: &mut [u8]) { + /// `out`, the background in bands of rows on `workers` (a 7680x4320 + /// frame is 130 MB to write). + fn draw(&self, n: u64, out: &mut [u8], workers: &mut Workers) { let (w, h) = (self.width as usize, self.height as usize); let out = &mut out[..w * h * 4]; - match &self.desktop { - Some(desktop) => desktop.draw(out, w, n as usize * 3), - None => { - // One row, then copies of it. - let px = bgra(BACKGROUND); - for d in out[..w * 4].chunks_exact_mut(4) { - d.copy_from_slice(&px); - } - let (first, rest) = out.split_at_mut(w * 4); - for row in rest.chunks_exact_mut(w * 4) { - row.copy_from_slice(first); + let tasks = workers.tasks(h); + let band = h.div_ceil(tasks); + let bands = Slots::new(out.chunks_mut(band * w * 4).enumerate()); + let background = bgra(BACKGROUND); + workers.run(bands.len(), &|i| { + let Some((i, rows)) = bands.take(i) else { return }; + match &self.desktop { + Some(desktop) => desktop.draw(rows, w, i * band, n as usize * 3), + None => { + for px in rows.chunks_exact_mut(4) { + px.copy_from_slice(&background); + } } } - } + }); let (rx, ry, rw, rh) = self.rect(n); fill(out, w, (rx as usize, ry as usize, rw as usize, rh as usize), RECT_COLOR); // Frame counter in the top-left corner. @@ -386,6 +392,9 @@ impl ScreenCapture for SyntheticScreen { let mut fps = sink.max_fps(); let mut ticker = Ticker::new(fps); let mut buffer = Buffer::new(&pattern); + // A few threads: drawing is memory-bound, and many threads + // cost far more CPU for little time. + let mut workers = Workers::new("voelin-synthetic", 4); let started = Instant::now(); let mut n = 0; loop { @@ -394,7 +403,7 @@ impl ScreenCapture for SyntheticScreen { // Buffers in video memory are drawn in advance; memory // only for a sink that declines them. if !buffer.drawn_in_advance() { - pattern.draw(n, buffer.bytes()); + pattern.draw(n, buffer.bytes(), &mut workers); } let taken = match buffer.dmabuf(&pattern, n, timestamp) { Some(frame) if sink.accepts_dmabuf() => sink.dmabuf(&frame), @@ -402,7 +411,7 @@ impl ScreenCapture for SyntheticScreen { }; let more = taken.unwrap_or_else(|| { if buffer.drawn_in_advance() { - pattern.draw(n, buffer.bytes()); + pattern.draw(n, buffer.bytes(), &mut workers); } let plane = PlaneRef::new(buffer.bytes(), width as usize * 4); sink.frame(FrameRef { diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 8f28445..769dfd3 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -2513,6 +2513,52 @@ mod tests { }); } + /// A picture in memory, BGRx (a screen) or RGBx (the studio's + /// composite), copied into a surface and converted on the GPU: the same + /// picture as the CPU's conversion, at full and half size. + #[test] + fn memory_pictures_are_converted_on_the_gpu() { + const SIZE: (u32, u32) = (1280, 720); + if !usable("h264_vaapi") { + eprintln!("no usable h264_vaapi, skipped"); + return; + } + let screen = crate::capture::synthetic::SyntheticScreen::with_pattern( + SIZE.0, + SIZE.1, + crate::capture::synthetic::Pattern::Desktop, + ); + let bgra = screen.frame(7, 30); + let FrameData::Bgra(pixels) = &bgra.data else { unreachable!() }; + let mut swapped = pixels.data.clone(); + for px in swapped.chunks_exact_mut(4) { + px.swap(0, 2); + } + let rgba = VideoFrame::from_rgba(SIZE.0, SIZE.1, pixels.stride, swapped).unwrap(); + let cpu = convert::to_i420(&bgra).unwrap().into_owned(); + let mut half = VideoFrame::black_i420(SIZE.0 / 2, SIZE.1 / 2); + let mut workers = crate::workers::Workers::new("voelin-test-scale", 1); + crate::scale::scale_i420(&mut workers, &cpu, &mut half).unwrap(); + let mut converter = GpuConverter::new().expect("VA-API video processing"); + let layers = [ + GpuLayer { size: SIZE, alignment: (2, 2), due: true }, + GpuLayer { size: (SIZE.0 / 2, SIZE.1 / 2), alignment: (2, 2), due: true }, + ]; + for picture in [&bgra, &rgba] { + let mut out = [None, None]; + assert!(converter.takes(&picture.view().pixels)); + converter.convert_memory(&picture.view(), &layers, &mut out).expect("converted"); + for (frame, reference) in out.iter().flatten().zip([&cpu, &half]) { + let psnr = convert::psnr(reference, &download(frame)).unwrap(); + eprintln!("{}x{}: PSNR {psnr:.1} dB against the CPU's", frame.width, frame.height); + assert!(psnr > 30.0, "{}x{}: {psnr:.1} dB", frame.width, frame.height); + } + } + // Not RGB: the caller converts it. + let i420 = VideoFrame::black_i420(64, 64); + assert!(!converter.takes(&i420.view().pixels)); + } + /// What the GPU path costs per captured frame: the DMA-BUF import alone, /// and the whole conversion (import, VPP to NV12, the wait for the GPU), /// from a buffer of the driver's own (video memory, tiled) and from a @@ -2527,6 +2573,15 @@ mod tests { eprintln!("no usable h264_vaapi, skipped"); return; } + // CPU time of every thread of the process. + let cpu_time = || -> Duration { + let tasks = std::fs::read_dir("/proc/self/task").unwrap().flatten(); + tasks + .filter_map(|t| std::fs::read_to_string(t.path().join("schedstat")).ok()) + .filter_map(|s| s.split_whitespace().next()?.parse().ok()) + .map(Duration::from_nanos) + .sum() + }; let ffmpeg = Ffmpeg::get().unwrap(); for size in [(1920, 1080), (3840, 2160), (7680, 4320)] { let screen = crate::capture::synthetic::SyntheticScreen::with_pattern( @@ -2579,6 +2634,21 @@ mod tests { convert.as_secs_f64() * 1e3 ); } + // The same picture in memory, copied into a surface. + let view = picture.view(); + converter.convert_memory(&view, &layer, &mut out).unwrap(); + let (cpu, started) = (cpu_time(), Instant::now()); + for _ in 0..50 { + converter.convert_memory(&view, &layer, &mut out).unwrap(); + } + let (wall, cpu) = (started.elapsed() / 50, (cpu_time() - cpu) / 50); + eprintln!( + "{}x{} memory: {:.2} ms, {:.2} ms CPU per frame", + size.0, + size.1, + wall.as_secs_f64() * 1e3, + cpu.as_secs_f64() * 1e3 + ); } } diff --git a/crates/voelin-media/src/ffmpeg/gpu.rs b/crates/voelin-media/src/ffmpeg/gpu.rs index 882407f..aa6f371 100644 --- a/crates/voelin-media/src/ffmpeg/gpu.rs +++ b/crates/voelin-media/src/ffmpeg/gpu.rs @@ -22,7 +22,7 @@ use super::layout::{self, FrameRefs}; use super::sys::{self, FrameHead, Ptr}; use super::{Ffmpeg, vpp}; use crate::capture::{DRM_MOD_INVALID, DRM_MOD_LINEAR, DmaBufRef, drm_fourcc}; -use crate::frame::GpuFrame; +use crate::frame::{FrameRef, GpuFrame, PixelsRef, PlaneRef}; use crate::{Error, Result}; /// The DRM formats of RGB buffers the conversion takes (8 bits per @@ -316,8 +316,12 @@ pub struct GpuConverter { vpp: Option<(vpp::Converter, (u32, u32))>, /// The frames context DMA-BUFs of this size are mapped onto. import: Option<(Ptr, (u32, u32))>, - /// Holds a mapping while it is converted. + /// Surfaces pictures in memory of this size and format are copied into. + upload: Option<(Ptr, (u32, u32), c_int)>, + /// Holds a mapping (or an uploaded surface) while it is converted. mapped: Surface, + /// An uploaded surface mapped into memory while its rows are written. + writable: Surface, outputs: Vec, modifiers: Vec, } @@ -341,7 +345,9 @@ impl GpuConverter { display, vpp: None, import: None, + upload: None, mapped: Surface::alloc(ffmpeg)?, + writable: Surface::alloc(ffmpeg)?, outputs: Vec::new(), modifiers: Vec::new(), }; @@ -411,12 +417,96 @@ impl GpuConverter { self.prepare(source)?; let pool = self.import.as_ref().expect("prepared").0; map_dmabuf(self.ffmpeg, frame, pool, self.mapped.0, self.refs).map_err(Error::Convert)?; - let result = self.convert_mapped(frame, layers, out); + let result = self.convert_mapped(source, frame.timestamp, layers, out); // SAFETY: our frame; this lets the buffer go. unsafe { (self.ffmpeg.api.av_frame_unref)(self.mapped.0) }; result } + /// Whether [`convert_memory`](Self::convert_memory) takes pictures like + /// `pixels`: BGRx or RGBx (alpha is ignored). + pub fn takes(&self, pixels: &PixelsRef<'_>) -> bool { + self.upload_format(pixels).is_some() + } + + fn upload_format<'a>(&self, pixels: &PixelsRef<'a>) -> Option<(PlaneRef<'a>, c_int)> { + match *pixels { + PixelsRef::Bgra(plane) => Some((plane, self.ffmpeg.pix.bgr0?)), + PixelsRef::Rgba(plane) => Some((plane, self.ffmpeg.pix.rgb0?)), + _ => None, + } + } + + /// Convert `frame`, an RGB picture in memory ([`takes`](Self::takes)), + /// like [`convert`](Self::convert): it is copied into a surface of its + /// own, which the GPU converts and scales for every due layer. That copy + /// is all the CPU does, where converting the picture to I420 and scaling + /// it on every core, then uploading each layer from its encoder's + /// thread, cost several times as much. Measured on a Radeon RX 7900 + /// GRE: 11.9 ms a 7680x4320 frame, 5.7 ms of it the copy on the CPU and + /// the rest the GPU's upload and conversion, waited for. More threads + /// copying gained little (9.9 ms with eight) for several times the CPU + /// (26 ms), so it is one. Not waiting for the GPU (only before the next + /// copy into the same surface) was slower in the streamer: 36 fps at + /// 7680x4320 against 42, the encoder then waiting for the conversion. + pub fn convert_memory( + &mut self, + frame: &FrameRef<'_>, + layers: &[GpuLayer], + out: &mut [Option>], + ) -> Result<()> { + let Some((plane, format)) = self.upload_format(&frame.pixels) else { + return Err(Error::Convert("not an RGB picture".into())); + }; + let source = (frame.width, frame.height); + let (row, rows) = (frame.width as usize * 4, frame.height as usize); + if rows == 0 || plane.stride < row || plane.data.len() < plane.stride * (rows - 1) + row { + return Err(Error::InvalidFrame("the picture is smaller than its size".into())); + } + self.outputs.retain(|o| layers.iter().any(|l| exact_size(l.size, l.alignment) == o.size)); + self.prepare(source)?; + if self.upload.as_ref().is_none_or(|&(_, size, f)| (size, f) != (source, format)) { + if let Some((mut pool, ..)) = self.upload.take() { + // SAFETY: our reference. + unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) }; + } + let pool = + vaapi_pool(self.ffmpeg, source.0, source.1, format).map_err(Error::Convert)?; + self.upload = Some((pool, source, format)); + } + let pool = self.upload.as_ref().expect("made above").0; + let api = &self.ffmpeg.api; + let (surface, writable) = (self.mapped.0, self.writable.0); + // SAFETY: our frames; `surface` takes a surface of our pool and + // `writable` maps it (`format` is the pool's), so its first plane + // is `linesize[0]` bytes per row for `height` rows until the unref, + // which writes it to the surface (`vaPutImage`). + let mapped = unsafe { + let ret = (api.av_hwframe_get_buffer)(pool, surface, 0); + if ret < 0 { + return Err(Error::Convert(format!("VA-API surface: {}", api.error_text(ret)))); + } + (*writable.cast::()).format = format; + let flags = sys::HWFRAME_MAP_WRITE | sys::HWFRAME_MAP_OVERWRITE; + let ret = (api.av_hwframe_map)(writable, surface, flags); + if ret < 0 { + (api.av_frame_unref)(surface); + return Err(Error::Convert(format!("mapping a surface: {}", api.error_text(ret)))); + } + let head = &*writable.cast::(); + std::slice::from_raw_parts_mut(head.data[0], head.linesize[0] as usize * rows) + }; + for (y, out) in mapped.chunks_exact_mut(mapped.len() / rows).enumerate() { + out[..row].copy_from_slice(plane.row(y, row)); + } + // SAFETY: our mapping; unmapping uploads it. + unsafe { (api.av_frame_unref)(writable) }; + let result = self.convert_mapped(source, frame.timestamp, layers, out); + // SAFETY: our frame; the surface goes back to the pool. + unsafe { (api.av_frame_unref)(surface) }; + result + } + /// Map `frame` and let it go again: the import alone, for measuring. #[cfg(test)] pub(crate) fn import_only(&mut self, frame: &DmaBufRef) -> Result<()> { @@ -449,9 +539,12 @@ impl GpuConverter { Ok(()) } + /// Convert and scale the picture in `mapped`, `size` large, taken at + /// `timestamp`, for every due layer. fn convert_mapped( &mut self, - frame: &DmaBufRef, + size: (u32, u32), + timestamp: Duration, layers: &[GpuLayer], out: &mut [Option>], ) -> Result<()> { @@ -466,11 +559,8 @@ impl GpuConverter { let part = |full: u32, kept: u32, of: u32| { (u64::from(full) * u64::from(kept) / u64::from(of.max(1))).max(1) as u32 }; - let src = ( - part(frame.width, exact.0, layer.size.0), - part(frame.height, exact.1, layer.size.1), - ); - let gpu = self.output(exact, frame.timestamp)?; + let src = (part(size.0, exact.0, layer.size.0), part(size.1, exact.1, layer.size.1)); + let gpu = self.output(exact, timestamp)?; let (vpp, _) = self.vpp.as_ref().expect("prepared"); vpp.convert(input, src, gpu.surface.id(), exact).map_err(Error::Convert)?; *slot = Some(gpu); @@ -528,5 +618,9 @@ impl Drop for GpuConverter { // SAFETY: our reference. unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) }; } + if let Some((mut pool, ..)) = self.upload.take() { + // SAFETY: our reference. + unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) }; + } } } diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index e8cc979..a1ffbd8 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -53,6 +53,8 @@ pub(crate) struct PixFmts { pub drm_prime: Option, /// `bgr0`: B, G, R, x in memory, the DRM `XR24` of captured screens. pub bgr0: Option, + /// `rgb0`: R, G, B, x in memory (`XB24`), the studio's composite. + pub rgb0: Option, } /// libavformat's I/O functions and where a write error lands @@ -130,6 +132,7 @@ impl Ffmpeg { vaapi: api.pix_fmt("vaapi").or_else(|| api.pix_fmt("vaapi_vld")), drm_prime: api.pix_fmt("drm_prime"), bgr0: api.pix_fmt("bgr0"), + rgb0: api.pix_fmt("rgb0"), }; let hw_fields = layout::codec_hw_fields(&api); let codec_hw_frames = hw_fields.clone().map(|(frames, _)| frames); diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs index 6a6fef3..f72635d 100644 --- a/crates/voelin-media/src/ffmpeg/sys.rs +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -150,8 +150,10 @@ pub const LOG_QUIET: c_int = -8; pub const LOG_ERROR: c_int = 16; pub const LOG_WARNING: c_int = 24; -/// `AV_HWFRAME_MAP_READ` and `AV_HWFRAME_MAP_DIRECT`. +/// `AV_HWFRAME_MAP_READ`, `_WRITE`, `_OVERWRITE` and `_DIRECT`. pub const HWFRAME_MAP_READ: c_int = 1; +pub const HWFRAME_MAP_WRITE: c_int = 2; +pub const HWFRAME_MAP_OVERWRITE: c_int = 4; pub const HWFRAME_MAP_DIRECT: c_int = 8; /// `AVERROR(EAGAIN)`: FFmpeg errors are negated `errno` values of the C diff --git a/docs/media.md b/docs/media.md index 224dd2e..5c481c4 100644 --- a/docs/media.md +++ b/docs/media.md @@ -111,13 +111,20 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder the buffer goes straight back to the compositor; the CPU never reads it. Each layer's surface reaches its encoder thread through a second handoff (the thread waits on both) and is encoded as it is - (`encode_gpu`). Anything else takes the CPU path as before, and the - capture switches between the two by itself: an encoder that needs frames - in memory (libvpx, x264, or one made for a viewer of another codec) - makes the sink decline the next DMA-BUF, so the portal maps it, and a - conversion that fails turns the GPU path off for the capture - (`StreamerStats::gpu_error`). Nothing is allocated per frame on this - path either (the surfaces' frames are recycled). + (`encode_gpu`). A picture in memory (shared memory from the portal, X11, + wlroots, the studio's composite, the test pattern) takes the same path + while the encoders do: `GpuConverter::convert_memory` copies it into a + VA-API surface of its own (one copy on the capture thread, BGRx or RGBx + as it is) and converts and scales that, instead of converting it to + I420 on every core, scaling it, and uploading each layer on its encoder + thread. At 7680x4320 that was more than a frame at 30 fps has (see [the + measurements](#60-mbits-up-to-8k-and-320-fps-measured)). Anything else takes the + CPU path as before, and the capture switches between the two by itself: + an encoder that needs frames in memory (libvpx, x264, or one made for a + viewer of another codec) makes the sink decline the next DMA-BUF, so the + portal maps it, and a conversion that fails turns the GPU path off for + the capture (`StreamerStats::gpu_error`). Nothing is allocated per frame + on this path either (the surfaces' frames are recycled). - Simulcast: `StreamerConfig::layers` (`voelin_stream::LayerSpec`; empty: one layer 0 at `bitrate_kbps`) are all encoded, each with its own encoder at `output_size()` of the source, its own frame-rate cap (`max_fps`, diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs index 8fa035d..52ffd19 100644 --- a/tools/voelinctl/src/bench.rs +++ b/tools/voelinctl/src/bench.rs @@ -340,7 +340,8 @@ struct Sample { layers: Vec<(LayerId, LayerSnapshot)>, sent: u64, captured: u64, - /// Captured frames converted on the GPU (never read by the CPU). + /// Captured frames converted on the GPU (DMA-BUFs, or pictures in memory + /// copied into a surface). gpu: u64, /// Frames the handoffs to the encoders dropped, per layer. dropped: Vec<(LayerId, u64)>, @@ -467,7 +468,7 @@ fn bench(args: BenchArgs) -> Result<()> { let ms = |d: Duration| d.as_secs_f64() * 1000.0; println!( "capture: {:.1} fps; convert + scale: CPU {} frames, {:.2} ms per frame on {} threads; \ - GPU (DMA-BUF, never read by the CPU) {gpu} frames, {:.2} ms per frame", + GPU {gpu} frames, {:.2} ms per frame", captured as f64 / secs, captured - gpu.min(captured), ms(stats.convert_time), From 52eb65c7dc602db066ae165a7097d93052c991cf Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 09:28:05 +0300 Subject: [PATCH 07/12] Streams: offer the H.264 level the encoder makes, at most 5.2 The app's streams always offered H.264 at level 3.1: its peer configuration is made before a share starts, and only voelinctl set the real level. A 4K or high-frame-rate stream then declared far less in its offer than in its SPS, which a viewer that sizes its decoder from the offer may refuse. Each layer's encoder now tells its sink what it makes (`MediaSink::layer_format`: size, frame rate, bitrate, whether the bitrate is automatic), when the sink is attached (from the size captured so far, so a viewer that joins before the first frame is encoded is covered), with the layer's first frame and on every change. The engine's stream task offers new viewers the level of the largest layer (its bitrate at `max_bitrate` if that is higher) in both profiles, and puts an automatic bitrate into the layer as before; this one hook replaces `auto_bitrate`. Offering 6.0 broke the stream: str0m 0.23 knows no H.264 level above 5.2, nor does libwebrtc (`H264Level` on its main branch), and a `profile-level-id` they cannot parse matches nothing, so a viewer answered without video (`m=video 0`). The offer is now capped at 5.2 (`h264::MAX_OFFER_LEVEL`); a stream that needs 6.x (4K above 60 fps, 8K) is offered as 5.2 and keeps its real level in the SPS. Tests: through two stream tasks, an encoder's 3840x2160@60 reaches the next offer as 640c34 and 42e034 (and without the update it stays 3.1); the largest layer counts, at its max bitrate; an automatic bitrate still moves the layer once, not per frame. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-core/src/media.rs | 112 +++++++++++------ crates/voelin-core/src/stream.rs | 198 +++++++++++++++++++++++++------ crates/voelin-stream/src/h264.rs | 21 +++- docs/media.md | 13 +- 4 files changed, 266 insertions(+), 78 deletions(-) diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index a071387..a252630 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -69,6 +69,7 @@ use voelin_stream::{ }; use crate::settings::{AudioSourceKindSetting, AudioSourceSetting}; +pub use crate::stream::LayerFormat; use crate::stream::StreamSink; use crate::{Command, Engine, SessionId}; @@ -326,12 +327,14 @@ pub trait MediaSink: Send + Sync { let _ = out; } - /// Layer `layer` has an automatic bitrate and is encoded at `bitrate` - /// bit/s ([`auto_bitrate`] of its size and frame rate): told with its - /// first frame and whenever it changes, so the stream's connections can - /// probe for it. - fn auto_bitrate(&self, layer: LayerId, bitrate: u64) { - let _ = (layer, bitrate); + /// What layer `layer` is encoded at: size, frame rate and bitrate (an + /// automatic one, [`auto_bitrate`] of its size and frame rate, so marked). + /// Told when the sink is attached (from the size captured so far), with + /// the layer's first frame, and whenever it changes, so the stream's + /// connections can probe for the bitrate and offers can declare the + /// H.264 level the stream needs. + fn layer_format(&self, layer: LayerId, format: LayerFormat) { + let _ = (layer, format); } } @@ -360,8 +363,8 @@ impl MediaSink for StreamSink { StreamSink::layer_bitrate(self, layer) } - fn auto_bitrate(&self, layer: LayerId, bitrate: u64) { - StreamSink::auto_bitrate(self, layer, bitrate); + fn layer_format(&self, layer: LayerId, format: LayerFormat) { + StreamSink::layer_format(self, layer, format); } } @@ -810,6 +813,17 @@ impl Layer { fn stopped(&self) -> bool { self.stop.load(Ordering::Relaxed) } + + /// What the layer encodes pictures of `size` at: its bitrate, or the + /// automatic one for that size and its frame rate. + fn format(&self, (width, height): (u32, u32)) -> LayerFormat { + let fps = self.fps.load(Ordering::Relaxed); + let (bitrate, automatic) = match self.bitrate.load(Ordering::Relaxed) { + 0 => (auto_bitrate(width, height, fps), true), + bitrate => (bitrate, false), + }; + LayerFormat { width, height, fps, bitrate, automatic } + } } /// The frame rate a layer encodes at: its cap, within the capture's. @@ -1249,6 +1263,15 @@ impl Streamer { /// Start encoding into `sink` (replacing an earlier one). pub fn attach(&self, sink: Arc) { + // What the layers are, from the size captured so far: a viewer may + // join before the first frame is encoded. + let size = self.shared.size.load(Ordering::Relaxed); + if size != 0 { + for layer in lock(&self.shared.layers).iter() { + let picture = lock(&layer.spec).output_size((size >> 32) as u32, size as u32); + sink.layer_format(layer.id, layer.format(picture)); + } + } *lock(&self.shared.sink) = Some(sink); } @@ -2198,8 +2221,8 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { let mut generation = shared.encoders_generation.load(Ordering::Relaxed); // Whether the stream codec was encoded for the last frame. let mut primary_on = true; - // The automatic bitrate last told, and to which sink. - let mut told: Option<(u64, *const ())> = None; + // What the layer was last told to be, and to which sink. + let mut told: Option<(LayerFormat, *const ())> = None; // The last picture, and when it came: a static screen sends no frames, // so keyframe requests are answered by encoding it again. let mut last: Option<(Picture, Instant)> = None; @@ -2303,19 +2326,13 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { None => continue, }; // Follow the layer's bitrate, or what the viewers' estimates allow. - let configured = match layer.bitrate.load(Ordering::Relaxed) { - 0 => { - let (width, height) = picture.size(); - let auto = auto_bitrate(width, height, layer.fps.load(Ordering::Relaxed)); - let to = Arc::as_ptr(&sink).cast::<()>(); - if told != Some((auto, to)) { - told = Some((auto, to)); - sink.auto_bitrate(layer.id, auto); - } - auto - } - bitrate => bitrate, - }; + let format = layer.format(picture.size()); + let to = Arc::as_ptr(&sink).cast::<()>(); + if told != Some((format, to)) { + told = Some((format, to)); + sink.layer_format(layer.id, format); + } + let configured = format.bitrate; let cap = match layer.max_bitrate.load(Ordering::Relaxed) { 0 => u64::MAX, max => max, @@ -3420,8 +3437,8 @@ mod tests { codecs: Mutex>, frames: Mutex>, keyframe: AtomicBool, - /// What [`MediaSink::auto_bitrate`] told, in order. - auto: Mutex>, + /// What [`MediaSink::layer_format`] told, in order. + formats: Mutex>, } impl MediaSink for CodecSink { @@ -3442,8 +3459,8 @@ mod tests { out.extend(lock(&self.codecs).iter()); } - fn auto_bitrate(&self, layer: LayerId, bitrate: u64) { - lock(&self.auto).push((layer, bitrate)); + fn layer_format(&self, layer: LayerId, format: LayerFormat) { + lock(&self.formats).push((layer, format)); } } @@ -3464,8 +3481,8 @@ mod tests { } /// Bitrate 0 is automatic: the encoder runs at the stream's own - /// automatic bitrate, which the sink is told, and follows a new frame - /// rate. + /// automatic bitrate, and the sink is told the layer's format (once per + /// change, not per frame), which follows a new frame rate. #[cfg(feature = "media-desktop")] #[tokio::test(flavor = "multi_thread")] async fn an_automatic_bitrate_follows_the_stream() { @@ -3481,30 +3498,53 @@ mod tests { let streamer = Streamer::start(&codecs, config).await.unwrap(); let sink = Arc::new(CodecSink::default()); streamer.attach(sink.clone()); - let told = |bitrate: u64| { + let told = |fps: u32| { let sink = sink.clone(); + let format = LayerFormat { + width: 640, + height: 480, + fps, + bitrate: auto_bitrate(640, 480, fps), + automatic: true, + }; async move { let deadline = Instant::now() + Duration::from_secs(10); - while lock(&sink.auto).last() != Some(&(0, bitrate)) { - assert!(Instant::now() < deadline, "{:?}", lock(&sink.auto)); + while lock(&sink.formats).last() != Some(&(0, format)) { + assert!(Instant::now() < deadline, "{:?}", lock(&sink.formats)); tokio::time::sleep(Duration::from_millis(20)).await; } } }; - told(auto_bitrate(640, 480, 30)).await; + told(30).await; assert_eq!(streamer.bitrate_kbps(), 1105); - // Told once, not per frame. + // Not per frame. + let count = lock(&sink.formats).len(); tokio::time::sleep(Duration::from_millis(200)).await; - assert_eq!(lock(&sink.auto).len(), 1); + assert_eq!(lock(&sink.formats).len(), count); assert_eq!(streamer.stats().layers[0].bitrate, auto_bitrate(640, 480, 30)); let update = StreamerConfigUpdate { fps: Some(15), ..StreamerConfigUpdate::default() }; streamer.reconfigure(&codecs, update).unwrap(); - told(auto_bitrate(640, 480, 15)).await; + told(15).await; // A typed bitrate is not automatic. let update = StreamerConfigUpdate { bitrate_kbps: Some(2000), ..StreamerConfigUpdate::default() }; streamer.reconfigure(&codecs, update).unwrap(); assert_eq!(streamer.bitrate_kbps(), 2000); + let typed = LayerFormat { + fps: 15, + bitrate: 2_000_000, + automatic: false, + ..lock(&sink.formats)[0].1 + }; + let deadline = Instant::now() + Duration::from_secs(10); + while lock(&sink.formats).last() != Some(&(0, typed)) { + assert!(Instant::now() < deadline, "{:?}", lock(&sink.formats)); + tokio::time::sleep(Duration::from_millis(20)).await; + } + // A new sink is told at once, from the size captured. + let next = Arc::new(CodecSink::default()); + streamer.attach(next.clone()); + assert_eq!(lock(&next.formats).first(), Some(&(0, typed))); } impl CodecSink { diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index da1acf2..c2ea6c4 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -76,6 +76,19 @@ pub struct StreamFrame { pub frame: MediaFrame, } +/// What a simulcast layer of our stream is encoded at +/// ([`StreamSink::layer_format`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LayerFormat { + pub width: u32, + pub height: u32, + pub fps: u32, + /// Bit/s: the layer's bitrate, or its automatic one. + pub bitrate: u64, + /// The bitrate is automatic (from the size and frame rate). + pub automatic: bool, +} + /// Hands encoded frames of our stream to the engine, e.g. from an encoder /// thread, and tells the encoders what the viewers need per simulcast layer: /// keyframes and bitrates. Those are read lock-free from the stream session. @@ -124,12 +137,13 @@ impl StreamSink { self.feedback.bitrate(layer) } - /// The encoder of `layer` runs at `bitrate` bit/s by itself (an - /// automatic bitrate, from the size and frame rate it encodes): the - /// stream's layer takes it, so new connections start at it and every - /// connection probes for it. - pub fn auto_bitrate(&self, layer: LayerId, bitrate: u64) { - let _ = self.tx.send(StreamInput::AutoBitrate { layer, bitrate }); + /// What the encoder of `layer` makes. An automatic bitrate goes into the + /// stream's layer, so new connections start at it and every connection + /// probes for it; the largest layer sets the H.264 level of new offers + /// (`PeerConfig::set_h264_format`), so the offer declares what the + /// encoder writes into its SPS, also for 4K, 8K and high frame rates. + pub fn layer_format(&self, layer: LayerId, format: LayerFormat) { + let _ = self.tx.send(StreamInput::LayerFormat { layer, format }); } pub fn is_live(&self) -> bool { @@ -181,11 +195,10 @@ pub(crate) enum StreamInput { }, /// Simulcast layers of our stream (now and for streams started later). Layers(Vec), - /// The bitrate an encoder chose for a layer of the live stream - /// ([`StreamSink::auto_bitrate`]). - AutoBitrate { + /// What a layer of our stream is encoded at ([`StreamSink::layer_format`]). + LayerFormat { layer: LayerId, - bitrate: u64, + format: LayerFormat, }, /// SRTP profile order of new connections. SrtpProfiles(Vec), @@ -298,6 +311,7 @@ impl StreamHandle { settings, own, setup: None, + formats: BTreeMap::new(), live: None, viewers: 0, clients: BTreeMap::new(), @@ -313,6 +327,25 @@ impl StreamHandle { } } +/// What an offer's H.264 level must hold: the largest size, frame rate and +/// bitrate of the stream's layers that are encoded (`formats`), a layer's +/// bitrate taken at its `max_bitrate` when that is higher, since bandwidth +/// estimates may raise the encoder to it. `None` before any is. +fn offer_format( + formats: &BTreeMap, + layers: &[LayerSpec], +) -> Option<(u32, u32, u32, u64)> { + formats.iter().filter(|(id, _)| layers.iter().any(|l| l.id == **id)).fold( + None, + |most, (id, f)| { + let max = layers.iter().find(|l| l.id == *id).and_then(|l| l.max_bitrate); + let bitrate = f.bitrate.max(max.unwrap_or(0)); + let (w, h, fps, b) = most.unwrap_or((0, 0, 0, 0)); + Some((w.max(f.width), h.max(f.height), fps.max(f.fps), b.max(bitrate))) + }, + ) +} + struct StreamTask { session: SessionId, streams: Streams, @@ -333,6 +366,8 @@ struct StreamTask { own: mpsc::UnboundedSender, /// The setup of our stream since `Start`. setup: Option, + /// What each layer of our stream is encoded at, since `Start`. + formats: BTreeMap, /// Our live stream's id. live: Option, /// Connected viewers of our stream, as last told. @@ -370,11 +405,42 @@ impl StreamTask { let _ = self.events.send(event); } + /// A layer of our stream is encoded at `format` (see + /// [`StreamSink::layer_format`]). + fn layer_format( + &mut self, + layer: LayerId, + format: LayerFormat, + ) -> Result<(), voelin_stream::SessionError> { + // The live stream's layers only; the configured ones (for streams + // started later) keep their automatic bitrate. + let Some(mut layers) = self.streams.streamer().map(|s| s.layers().to_vec()) else { + return Ok(()); + }; + self.formats.insert(layer, format); + if let Some((width, height, fps, bitrate)) = offer_format(&self.formats, &layers) { + let mut config = self.streams.peer_config().clone(); + config.set_h264_format(width, height, fps, bitrate); + if config.h264_profile_level_ids != self.streams.peer_config().h264_profile_level_ids { + debug!(width, height, fps, bitrate, "H.264 offered for the stream's largest layer"); + self.streams.set_peer_config(config); + } + } + match layers.iter_mut().find(|l| l.id == layer) { + Some(spec) if format.automatic && spec.bitrate != format.bitrate => { + spec.bitrate = format.bitrate; + self.streams.set_layers(layers) + } + _ => Ok(()), + } + } + async fn input(&mut self, input: StreamInput) { let session = self.session; let result = match input { StreamInput::Start { setup, auto_accept } => { self.setup = Some(setup.clone()); + self.formats.clear(); let layers = self.layers.clone(); let options = StreamerOptions { setup, auto_accept, layers, ..Default::default() }; self.streams.start(options).map(|()| { @@ -408,21 +474,7 @@ impl StreamTask { Ok(()) } } - StreamInput::AutoBitrate { layer, bitrate } => { - // The live stream's layers only; the configured ones (for - // streams started later) keep their automatic bitrate. - let layers = self.streams.streamer().map(|s| s.layers().to_vec()); - match layers { - Some(mut layers) => match layers.iter_mut().find(|l| l.id == layer) { - Some(spec) if spec.bitrate != bitrate => { - spec.bitrate = bitrate; - self.streams.set_layers(layers) - } - _ => Ok(()), - }, - None => Ok(()), - } - } + StreamInput::LayerFormat { layer, format } => self.layer_format(layer, format), StreamInput::SrtpProfiles(profiles) => { self.streams.set_srtp_profiles(profiles); Ok(()) @@ -666,8 +718,17 @@ mod tests { const CLIENTS: [u16; 2] = [5, 6]; /// The notifications the server sends for `request` from `from`, per receiver. + /// Every offer the fake server relayed, from all tests of this process. + fn lock_offers() -> std::sync::MutexGuard<'static, Vec> { + static OFFERS: Mutex> = Mutex::new(Vec::new()); + OFFERS.lock().unwrap_or_else(PoisonError::into_inner) + } + fn relay(from: u16, request: Request) -> Vec<(u16, StreamNotification)> { let both = |n: StreamNotification| CLIENTS.map(|c| (c, n.clone())).to_vec(); + if let Request::Respond { offer: Some(sdp), .. } = &request { + lock_offers().push(sdp.clone()); + } match request { Request::Setup(setup) => CLIENTS .map(|c| { @@ -757,11 +818,11 @@ mod tests { audio: Option, settings: &Settings, ) -> (Handles, broadcast::Receiver, broadcast::Receiver) { - let (handles, rx, frames, _) = pair_full(audio, settings, false); + let (handles, rx, frames, _) = pair_full(audio, settings, false, PeerConfig::loopback()); (handles, rx, frames) } - /// [`pair_with`]; with `late`, the server does not tell the viewer + /// [`pair_with`] with peers of `config`; with `late`, the server does not tell the viewer /// (session 2) about streams, as for a client that joined after the /// stream started, and does not answer lookups. Also returns what the /// streamer (session 1) reports about its own stream. @@ -769,6 +830,7 @@ mod tests { audio: Option, settings: &Settings, late: bool, + config: PeerConfig, ) -> ( Handles, broadcast::Receiver, @@ -783,7 +845,7 @@ mod tests { let mut audio = audio; for (i, clid) in CLIENTS.into_iter().enumerate() { let (voice, voice_rx) = mpsc::unbounded_channel(); - let config = PeerConfig::loopback(); + let config = config.clone(); let session = i as u64 + 1; handles.push(StreamHandle::spawn( session, @@ -996,20 +1058,56 @@ mod tests { feeder.await.unwrap(); } - /// An encoder's automatic bitrate reaches the live stream's layer (which - /// asks the viewer's layer for a keyframe, as every layer change does); - /// the same bitrate again changes nothing. + /// What the encoder tells about a layer reaches the live stream: the + /// largest layer's size, frame rate and bitrate set the H.264 level of + /// the next offer (both profiles), and an automatic bitrate goes into the + /// layer (which asks the viewer's layer for a keyframe, as every layer + /// change does); the same again changes nothing. #[tokio::test(flavor = "multi_thread")] - async fn automatic_bitrates_reach_the_live_stream() { - let (handles, mut rx, _frames) = pair(None); - let sink = live_and_watching(&handles, &mut rx).await; + async fn layer_formats_reach_the_live_stream() { + // The streamer offers H.264 (and the viewer takes it). + let config = PeerConfig { video_codecs: vec![VideoCodec::H264], ..PeerConfig::loopback() }; + let (handles, mut rx, _frames, _) = pair_full(None, &Settings::in_memory(), false, config); + let setup = StreamSetup { name: "4K120".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| { + match e { + Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => { + sink = Some(s); + } + Event::StreamsChanged { session: 2, streams } => listed = streams.len() == 1, + _ => {} + } + (sink.is_some() && listed).then_some(()) + }) + .await; + let sink = sink.unwrap(); + let format = + |bitrate| LayerFormat { width: 3840, height: 2160, fps: 60, bitrate, automatic: true }; + // Before the viewer asks: its offer is made after this. + sink.layer_format(0, format(60_000_000)); + handles[1].send(StreamInput::Watch { stream_id: "s-1".into() }); + wait(&mut rx, |e| match e { + Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()), + _ => None, + }) + .await; + // 3840x2160 at 60 fps is level 5.2 (0x34) in both profiles. + let offers = lock_offers().clone(); + assert!( + offers.iter().any(|o| o.contains("profile-level-id=640c34") && o.contains("42e034")), + "{offers:?}" + ); + let keyframes = || { let mut layers = LayerSet::new(); sink.take_layer_keyframes(&mut layers); layers.contains(0) }; keyframes(); - sink.auto_bitrate(0, 9_000_000); + sink.layer_format(0, format(9_000_000)); timeout(Duration::from_secs(5), async { while !keyframes() { tokio::time::sleep(Duration::from_millis(10)).await; @@ -1017,18 +1115,44 @@ mod tests { }) .await .expect("the layer did not change"); - sink.auto_bitrate(0, 9_000_000); + sink.layer_format(0, format(9_000_000)); tokio::time::sleep(Duration::from_millis(200)).await; assert!(!keyframes(), "nothing changed"); handles[0].send(StreamInput::Stop); } + #[test] + fn the_offer_covers_the_largest_layer() { + let format = |width, height, fps, bitrate| LayerFormat { + width, + height, + fps, + bitrate, + automatic: false, + }; + let layers = [ + LayerSpec { max_bitrate: Some(12_000_000), ..LayerSpec::single(8_000_000) }, + LayerSpec { id: 1, scale: 0.5, ..LayerSpec::single(2_000_000) }, + ]; + let mut formats = BTreeMap::new(); + assert_eq!(offer_format(&formats, &layers), None); + formats.insert(1, format(960, 540, 120, 2_000_000)); + formats.insert(0, format(1920, 1080, 60, 8_000_000)); + // Layer 0's size and its bitrate at its maximum, layer 1's rate. + assert_eq!(offer_format(&formats, &layers), Some((1920, 1080, 120, 12_000_000))); + // A layer the stream no longer has does not count. + formats.insert(7, format(7680, 4320, 30, 60_000_000)); + assert_eq!(offer_format(&formats, &layers), Some((1920, 1080, 120, 12_000_000))); + } + /// A viewer that was not told about a running stream, and whose server /// lookup goes unanswered, finds it in the gateway directory and /// watches it; the streamer reports its stream's life for the directory. #[tokio::test(flavor = "multi_thread")] async fn late_viewer_finds_the_stream_in_the_gateway_directory() { - let (handles, mut rx, _frames, mut own) = pair_full(None, &Settings::in_memory(), true); + let loopback = PeerConfig::loopback(); + let (handles, mut rx, _frames, mut own) = + pair_full(None, &Settings::in_memory(), true, loopback); let setup = StreamSetup { name: "directory test".into(), kind: StreamKind::Window, diff --git a/crates/voelin-stream/src/h264.rs b/crates/voelin-stream/src/h264.rs index e999582..7394c3a 100644 --- a/crates/voelin-stream/src/h264.rs +++ b/crates/voelin-stream/src/h264.rs @@ -92,8 +92,18 @@ pub fn profile_level_id(profile: H264Profile, level_idc: u8) -> u32 { /// offer official clients know stays the same for small streams. pub const MIN_OFFER_LEVEL: u8 = 31; +/// The highest level an offer declares (5.2): libwebrtc (the official +/// client's stack; `H264Level` in `h264_profile_level_id.h`, main branch +/// 2026-10) and str0m 0.23 (`H264LevelIdc`) know no level above it, and a +/// `profile-level-id` they cannot parse matches nothing: a viewer answered +/// such an offer without video (tried with str0m: `m=video 0`, no payload +/// type). Streams that need 6.0-6.2 (3840x2160 above 60 fps, 7680x4320, +/// 1080p above 250 fps) are offered as 5.2 and still carry their real level +/// in the SPS, which decoders size themselves from. +pub const MAX_OFFER_LEVEL: u8 = 52; + /// `profile-level-id` for a stream of this size, frame rate and bitrate, -/// at least level 3.1. +/// at least level 3.1 and at most [`MAX_OFFER_LEVEL`]. pub fn offer_profile_level_id( profile: H264Profile, width: u32, @@ -101,8 +111,8 @@ pub fn offer_profile_level_id( fps: u32, bitrate: u64, ) -> u32 { - let level = level_idc(profile, width, height, fps, bitrate).max(MIN_OFFER_LEVEL); - profile_level_id(profile, level) + let level = level_idc(profile, width, height, fps, bitrate); + profile_level_id(profile, level.clamp(MIN_OFFER_LEVEL, MAX_OFFER_LEVEL)) } #[cfg(test)] @@ -142,6 +152,11 @@ mod tests { assert_eq!(profile_level_id(HIGH, 31), 0x640c1f); assert_eq!(profile_level_id(H264Profile::ConstrainedBaseline, 31), 0x42e01f); assert_eq!(offer_profile_level_id(HIGH, 320, 240, 15, 200_000), 0x640c1f); + // 4K60 is 5.2; 4K120 and 8K need 6.x, which peers cannot parse: 5.2. + assert_eq!(offer_profile_level_id(HIGH, 3840, 2160, 60, 60_000_000), 0x640c34); + assert_eq!(offer_profile_level_id(HIGH, 3840, 2160, 120, 60_000_000), 0x640c34); + let baseline = H264Profile::ConstrainedBaseline; + assert_eq!(offer_profile_level_id(baseline, 7680, 4320, 60, 60_000_000), 0x42e034); assert_eq!(offer_profile_level_id(HIGH, 1920, 1080, 60, 8_000_000), 0x640c2a); // Back from the SDP, at any level; other profiles are not ours. assert_eq!(H264Profile::from_profile_level_id(0x640c2a), Some(HIGH)); diff --git a/docs/media.md b/docs/media.md index 5c481c4..22e85d1 100644 --- a/docs/media.md +++ b/docs/media.md @@ -145,7 +145,7 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder the encoder thread works it out from each picture's size and the layer's frame rate, so a resolution or frame-rate change moves it at once. The sink is told with the first frame and whenever it changes - (`MediaSink::auto_bitrate`); the engine's `StreamSink` puts it into the + (`MediaSink::layer_format`); the engine's `StreamSink` puts it into the live stream's layer, so new connections start their bandwidth estimate at it and all of them probe for it. `Streamer::bitrate_kbps()` is what to announce in `setupstream` (the share dialog and the studio do, up to the @@ -216,7 +216,16 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder at the level the stream needs (`PeerConfig::h264_profile_level_ids`, `set_h264_format(width, height, fps, bitrate)`: macroblocks per second and per frame, and bitrate, per H.264 Table A-1; never below 3.1, the - level offered before). A viewer that takes both answers High (the + level offered before, and never above 5.2, the highest libwebrtc and + str0m parse: a viewer answered an offer of 6.0 without video). The app's + streams set it from what the encoder makes: every layer's encoder tells + its size, frame rate and bitrate (`MediaSink::layer_format`, from the + size captured so far when the sink is attached, then with the layer's + first frame and every change), and the stream task offers new viewers + the level of the largest (a layer's bitrate at its `max_bitrate` if + higher), in both profiles. Before, an app stream always offered 3.1, + also for 4K and high frame rates. A stream that needs 6.x is offered as + 5.2 and carries its real level in the SPS. A viewer that takes both answers High (the streamer writes the first of its own order the answer lists); one that takes only Baseline gets frames from an encoder in Constrained Baseline (above). str0m's other H.264 variants are only accepted, never offered, From 2a8ce05f5927ce142623e9d4314a506a00134220 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 10:03:35 +0300 Subject: [PATCH 08/12] 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 { .. }))); } From 6cf1eab96f449be2bd6aebad48f44590dc7fae7e Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 10:03:35 +0300 Subject: [PATCH 09/12] voelinctl: stream statistics, the desktop pattern and no BWE for measuring For measuring streams end to end: `stream start --stats` prints once a second what the encoder makes per layer (size, fps, kbit/s, target, encode time), `stream watch --stats` what arrives and decodes (decoded fps, received bitrate, size, decoder, frames decoded and skipped, keyframe requests), `stream start --pattern desktop` streams the code-editor test pattern (about as costly as real screen content), and `stream --no-bwe` turns bandwidth estimation off, to see what the path carries unpaced. `Action::Stream` is boxed (the arguments grew past clippy's limit) and `watch` takes its options in one struct. Co-Authored-By: Claude Opus 5.5 --- tools/voelinctl/src/main.rs | 2 +- tools/voelinctl/src/stream.rs | 110 ++++++++++++++++++++++++++++++---- 2 files changed, 101 insertions(+), 11 deletions(-) diff --git a/tools/voelinctl/src/main.rs b/tools/voelinctl/src/main.rs index 22b8ac1..7e04961 100644 --- a/tools/voelinctl/src/main.rs +++ b/tools/voelinctl/src/main.rs @@ -190,7 +190,7 @@ pub enum Action { command: VoiceCommand, }, /// TeamSpeak 6 streams (screen sharing): start, list or watch. - Stream(stream::StreamArgs), + Stream(Box), /// Interactive session. Type `/help` for commands. Repl, } diff --git a/tools/voelinctl/src/stream.rs b/tools/voelinctl/src/stream.rs index 0ffa6db..f01a1c7 100644 --- a/tools/voelinctl/src/stream.rs +++ b/tools/voelinctl/src/stream.rs @@ -16,7 +16,7 @@ use tsclientlib::{ClientId, Connection, MessageHandle, StreamItem}; use voelin_core::media::voelin_media::capture::SourceId; use voelin_core::media::voelin_media::{Codec, Codecs, VideoFrame, convert}; use voelin_core::media::{ - CaptureBackend, EncodedSource, EncoderPreference, Latest, Streamer, StreamerConfig, + CaptureBackend, EncodedSource, EncoderPreference, Latest, Pattern, Streamer, StreamerConfig, VideoPipeline, auto_bitrate, peer_config, preferred_codec, stream_codec, video_codec, }; use voelin_model::ServerFlavor; @@ -44,6 +44,10 @@ pub struct StreamArgs { /// [default: in this order]. #[arg(long, global = true, value_delimiter = ',')] srtp: Vec, + /// No bandwidth estimation: a streamer sends its bitrate as it is, + /// unpaced, whatever the path takes (for measuring the path). + #[arg(long, global = true)] + no_bwe: bool, } #[derive(Subcommand, Debug, Clone)] @@ -66,6 +70,11 @@ pub enum StreamCommand { /// Size of the test pattern. #[arg(long, default_value = "1280x720")] size: String, + /// What the test pattern shows: `simple` (a flat background, cheap to + /// encode) or `desktop` (a scrolling code editor, about as costly as + /// real screen content). + #[arg(long, default_value = "simple")] + pattern: String, /// Accept every viewer. #[arg(long)] auto_accept: bool, @@ -109,6 +118,10 @@ pub enum StreamCommand { /// No hardware encoders unless named with --encoder. #[arg(long)] no_hardware: bool, + /// Print what the encoder makes once a second (per layer: size, fps, + /// kbit/s, encode time) while live. + #[arg(long)] + stats: bool, }, /// List the streams in our channel. List { @@ -138,6 +151,10 @@ pub enum StreamCommand { /// lists its layers (Voelin streamers with several do). #[arg(long)] layer: Option, + /// Print what arrives and decodes once a second (fps, kbit/s, size, + /// decoder, frames skipped). + #[arg(long)] + stats: bool, }, } @@ -161,6 +178,7 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { if !args.srtp.is_empty() { config.srtp_profiles = parse_srtp(&args.srtp)?; } + config.bandwidth_estimation = !args.no_bwe; let mut codecs = Codecs::new(); if let StreamCommand::Start { simulcast, @@ -230,8 +248,15 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { no_audio, layers, placeholder, + stats, + pattern, .. } => { + let pattern = match pattern.as_str() { + "simple" => Pattern::Simple, + "desktop" => Pattern::Desktop, + other => bail!("unknown pattern {other:?}: simple or desktop"), + }; let mut layers = layers.clone(); number_layers(&mut layers); let layers = &layers; @@ -271,6 +296,7 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { encoder: codecs.preference().clone(), audio: !no_audio, synthetic_size: parse_size(size)?, + synthetic_pattern: pattern, layers: layers.clone(), ..StreamerConfig::default() }; @@ -295,18 +321,30 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { layers: layers.clone(), ..Default::default() }; - start(con, &mut driver, options, source, seconds.map(Duration::from_secs)).await + let length = seconds.map(Duration::from_secs); + start(con, &mut driver, options, source, length, *stats).await } StreamCommand::List { settle_ms } => { list(con, &mut driver, Duration::from_millis(*settle_ms)).await } - StreamCommand::Watch { id, streamer_nick, expect_frames, timeout, save_frame, layer } => { + StreamCommand::Watch { + id, + streamer_nick, + expect_frames, + timeout, + save_frame, + layer, + stats, + } => { let target = Target { id: id.clone(), streamer_nick: streamer_nick.clone(), layer: *layer }; - let timeout = timeout.map(Duration::from_secs); - let expect = *expect_frames; - let save = save_frame.as_deref(); - watch(con, &mut driver, codecs, &target, expect, timeout, save).await + let until = Until { + frames: *expect_frames, + timeout: timeout.map(Duration::from_secs), + save: save_frame.as_deref(), + stats: *stats, + }; + watch(con, &mut driver, codecs, &target, until).await } }; driver.finish(con).await; @@ -614,8 +652,10 @@ async fn start( options: StreamerOptions, mut source: Source, length: Option, + stats: bool, ) -> Result<()> { let auto_accept = options.auto_accept; + let mut stats_at = Instant::now(); driver.streams.start(options)?; let deadline = length.map(|l| Instant::now() + l); let mut tick = tokio::time::interval(source.frames().interval()); @@ -640,6 +680,30 @@ async fn start( } driver.streams.write_frame(&frame); } + if stats + && stats_at.elapsed() >= Duration::from_secs(1) + && let Source::Encoded(source) = &source + { + stats_at = Instant::now(); + let s = source.streamer().stats(); + let layers: Vec = s + .layers + .iter() + .map(|l| { + format!( + "L{} {}x{} {:.1} fps {:.0} kbit/s target {} enc {:.2} ms", + l.id, + l.width, + l.height, + l.fps, + l.kbps, + rate(l.bitrate), + l.encode_time.as_secs_f64() * 1e3 + ) + }) + .collect(); + println!("encoder: capture {:.1} fps; {}", s.capture_fps, layers.join("; ")); + } } Wake::Line(None) => lines = None, Wake::Line(Some(line)) => { @@ -805,16 +869,27 @@ fn save_png(picture: &VideoFrame, path: &Path) -> Result<()> { Ok(()) } +/// How long [`watch`] runs and what it reports. +struct Until<'a> { + /// Exit once this many pictures were decoded. + frames: Option, + timeout: Option, + /// Save the last picture here. + save: Option<&'a Path>, + /// Print the decoder's numbers once a second. + stats: bool, +} + async fn watch( con: &mut Connection, driver: &mut Driver, codecs: Arc, target: &Target, - expect: Option, - timeout: Option, - save: Option<&Path>, + until: Until<'_>, ) -> Result<()> { + let Until { frames: expect, timeout, save, stats: print_stats } = until; let deadline = timeout.map(|t| Instant::now() + t); + let mut stats_at = Instant::now(); let mut watching: Option = None; let (mut video, mut audio) = (0u64, 0u64); let mut codec = None; @@ -874,6 +949,21 @@ async fn watch( summary(video, audio, &decoder); return save_last(&last_picture); } + if print_stats && watching.is_some() && stats_at.elapsed() >= Duration::from_secs(1) { + stats_at = Instant::now(); + let s = decoder.stats(); + println!( + "decoded {} fps, received {}, {}x{} {}, {} decoded, {} skipped, {} keyframe requests", + s.fps, + rate(s.bitrate), + s.width, + s.height, + s.decoder.map_or("-".to_owned(), |d| d.to_string()), + s.decoded, + s.skipped, + s.keyframe_requests + ); + } if watching.is_none() { if let Some((id, streamer)) = target.find(con, &driver.streams) { println!("watching {id} of {} (clid {})", nick(con, streamer), streamer.0); From 1b1f7087c23e6f0f423b273f8ef8557e0221a74d Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 10:19:54 +0300 Subject: [PATCH 10/12] voelin-ui: 60 Mbit/s, 8K and 320 fps in the new settings pages Wave 4B's settings pages arrived with their own stream controls, written for the old limits: the Video page's bitrate slider stopped at 20 Mbit/s, its frame rates at 120 and its quality presets at 1440p, and with the automatic bitrate (0, now the default) any change on that page stored a bitrate of 1 kbit/s (`form.bitrate.round().max(1.0)`), while the Streaming page could not set the automatic bitrate back. Kept 4B's layout and put the controls into it: frame rates up to 320, quality presets 4K and 8K (`PRESETS`), the slider up to 60 Mbit/s with the field empty (and a note) for the automatic bitrate, which a preset turns into the automatic bitrate of its size and the frame rate (`preset_layers`, tested); the Streaming page takes empty, 0 or "auto" as automatic and says so. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-ui/src/settings_pages.rs | 50 ++++++++++++++----- .../voelin-ui/ui/screens/settings-pages.slint | 2 +- crates/voelin-ui/ui/screens/settings.slint | 39 ++++++++++++--- docs/ui.md | 2 +- 4 files changed, 70 insertions(+), 23 deletions(-) diff --git a/crates/voelin-ui/src/settings_pages.rs b/crates/voelin-ui/src/settings_pages.rs index b4f41aa..ca2f50d 100644 --- a/crates/voelin-ui/src/settings_pages.rs +++ b/crates/voelin-ui/src/settings_pages.rs @@ -12,6 +12,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use slint::{ComponentHandle, Model, SharedString}; use tracing::warn; +use voelin_core::media::auto_bitrate; use voelin_core::settings::{ AudioSourceKindSetting, AudioSourceSetting, BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB, CHAT_DEDUPE_TOLERANCE_MS, CHAT_HISTORY_PAGE, CHAT_RETENTION_DAYS, CHAT_STORE_HISTORY, @@ -39,7 +40,8 @@ use crate::settings::{ use crate::social::{allowed_index, allowed_of}; /// Sizes of the stream quality presets (Auto: the source's size). -const PRESETS: [(u32, u32); 3] = [(1280, 720), (1920, 1080), (2560, 1440)]; +const PRESETS: [(u32, u32); 5] = + [(1280, 720), (1920, 1080), (2560, 1440), (3840, 2160), (7680, 4320)]; /// An identity whose level is being raised. pub(crate) struct Improving { @@ -109,6 +111,22 @@ pub(crate) fn layer_of(item: &LayerItem, base: &LayerSetting) -> Option Option> { + match usize::try_from(quality).ok()? { + 0 => Some(Vec::new()), + q => PRESETS.get(q - 1).map(|&(width, height)| { + let bitrate = match kbps { + 0 => auto_bitrate(width, height, fps), + kbps => u64::from(kbps) * 1000, + }; + vec![LayerSetting { size: Some((width, height)), bitrate, ..LayerSetting::default() }] + }), + } +} + pub(crate) fn quality_of(layers: &[LayerSetting]) -> i32 { match layers { [] => 0, @@ -401,21 +419,15 @@ impl App { if self.prefs.get(&STREAM_PERMISSIONS) != permissions { self.put(&STREAM_PERMISSIONS, permissions); } - let bitrate = form.bitrate.round().max(1.0) as u32; + // 0: automatic. + let bitrate = form.bitrate.round().max(0.0) as u32; if self.prefs.get(&STREAM_BITRATE_KBPS) != bitrate { self.put(&STREAM_BITRATE_KBPS, bitrate); } - // A preset: one layer of that size at the bitrate; Auto: none. + // A preset: one layer of that size at the bitrate (an automatic one + // for that size and the frame rate); Auto: none. let layers = self.prefs.get(&STREAM_LAYERS); - let wanted = match form.quality { - 0 => Some(Vec::new()), - q @ 1..=3 => Some(vec![LayerSetting { - size: Some(PRESETS[q as usize - 1]), - bitrate: u64::from(bitrate) * 1000, - ..LayerSetting::default() - }]), - _ => None, - }; + let wanted = preset_layers(form.quality, bitrate, self.prefs.get(&STREAM_FPS)); if let Some(wanted) = wanted.filter(|w| *w != layers) { self.put(&STREAM_LAYERS, wanted); } @@ -426,7 +438,10 @@ impl App { if let Some(fps) = crate::settings::parse_positive(&form.fps) { self.put(&STREAM_FPS, fps); } - if let Some(bitrate) = crate::settings::parse_positive(&form.bitrate) { + // Nothing, 0 or "auto": automatic. + let bitrate = form.bitrate.trim(); + let auto = bitrate.is_empty() || bitrate == "0" || bitrate.eq_ignore_ascii_case("auto"); + if let Some(bitrate) = crate::settings::parse_positive(bitrate).or(auto.then_some(0)) { self.put(&STREAM_BITRATE_KBPS, bitrate); } self.put(&STREAM_CODEC, codec_of(form.codec)); @@ -1377,7 +1392,16 @@ mod tests { assert_eq!(quality_of(&[]), 0); let layer = |size| LayerSetting { size: Some(size), ..LayerSetting::default() }; assert_eq!(quality_of(&[layer((1920, 1080))]), 2); + assert_eq!(quality_of(&[layer((3840, 2160))]), 4); + assert_eq!(quality_of(&[layer((7680, 4320))]), 5); assert_eq!(quality_of(&[layer((800, 600))]), -1); + // A preset at the bitrate, or the automatic one of its size and rate. + let one = |l: Option>| l.map(|l| (l[0].size, l[0].bitrate)); + assert_eq!(one(preset_layers(5, 60_000, 30)), Some((Some((7680, 4320)), 60_000_000))); + assert_eq!(one(preset_layers(4, 0, 60)), Some((Some((3840, 2160)), 59_719_680))); + assert_eq!(preset_layers(0, 0, 60), Some(Vec::new())); + assert_eq!(preset_layers(-1, 0, 60), None); + assert_eq!(preset_layers(6, 0, 60), None); assert_eq!(quality_of(&[layer((1280, 720)), layer((640, 360))]), -1); for i in 0..5 { assert_eq!(codec_index(codec_of(i)), i); diff --git a/crates/voelin-ui/ui/screens/settings-pages.slint b/crates/voelin-ui/ui/screens/settings-pages.slint index dd19d6c..40ed831 100644 --- a/crates/voelin-ui/ui/screens/settings-pages.slint +++ b/crates/voelin-ui/ui/screens/settings-pages.slint @@ -620,7 +620,7 @@ export component StreamingSection inherits VerticalLayout { } NumberRow { text: @tr("Video bitrate"); - description: @tr("Of the single layer, when no layers are set below."); + description: @tr("Of the single layer, when no layers are set below. 0: automatic, from the size and frame rate, up to 60 Mbit/s."); value: Bridge.streaming.bitrate; unit: "kbit/s"; accepted(t) => { diff --git a/crates/voelin-ui/ui/screens/settings.slint b/crates/voelin-ui/ui/screens/settings.slint index eebcf13..9fb9128 100644 --- a/crates/voelin-ui/ui/screens/settings.slint +++ b/crates/voelin-ui/ui/screens/settings.slint @@ -411,11 +411,11 @@ component VideoCard inherits Card { Field { label: @tr("Frame Rate"); Select { - model: ["15 FPS", "24 FPS", "30 FPS", "60 FPS", "120 FPS"]; - current-index: Bridge.video.fps == "15" ? 0 : Bridge.video.fps == "24" ? 1 : Bridge.video.fps == "30" ? 2 : Bridge.video.fps == "120" ? 4 : 3; + model: ["15 FPS", "24 FPS", "30 FPS", "60 FPS", "120 FPS", "144 FPS", "240 FPS", "320 FPS"]; + current-index: Bridge.video.fps == "15" ? 0 : Bridge.video.fps == "24" ? 1 : Bridge.video.fps == "30" ? 2 : Bridge.video.fps == "120" ? 4 : Bridge.video.fps == "144" ? 5 : Bridge.video.fps == "240" ? 6 : Bridge.video.fps == "320" ? 7 : 3; label: @tr("Frame rate"); selected => { - Bridge.video.fps = self.current-index == 0 ? "15" : self.current-index == 1 ? "24" : self.current-index == 2 ? "30" : self.current-index == 4 ? "120" : "60"; + Bridge.video.fps = ["15", "24", "30", "60", "120", "144", "240", "320"][self.current-index]; Bridge.video-changed(Bridge.video); } } @@ -544,6 +544,24 @@ component QualityCard inherits Card { Bridge.video-changed(Bridge.video); } } + PresetTile { + text: "4K"; + detail: "2160p"; + selected: Bridge.video.quality == 4; + clicked => { + Bridge.video.quality = 4; + Bridge.video-changed(Bridge.video); + } + } + PresetTile { + text: "8K"; + detail: "4320p"; + selected: Bridge.video.quality == 5; + clicked => { + Bridge.video.quality = 5; + Bridge.video-changed(Bridge.video); + } + } } if Bridge.video.quality < 0: Text { text: @tr("Your own simulcast layers are set (Streaming page); a preset replaces them."); @@ -562,7 +580,8 @@ component QualityCard inherits Card { y: (parent.height - self.height) / 2; horizontal-stretch: 1; minimum: 500; - maximum: 20000; + // 60 Mbit/s; any number can be typed, and 0 is automatic. + maximum: 60000; step: 250; value: Bridge.video.bitrate; label: @tr("Stream bitrate"); @@ -573,12 +592,14 @@ component QualityCard inherits Card { } TextField { width: 80px; - text: round(Bridge.video.bitrate); + // Empty: automatic (from the size and frame rate, up to 60 Mbit/s). + text: Bridge.video.bitrate == 0 ? "" : round(Bridge.video.bitrate); + placeholder: @tr("auto"); input-type: number; label: @tr("Stream bitrate in kbit/s"); accepted(t) => { - if t.is-float() && t.to-float() >= 1 { - Bridge.video.bitrate = t.to-float(); + if t == "" || (t.is-float() && t.to-float() >= 0) { + Bridge.video.bitrate = t == "" ? 0 : t.to-float(); Bridge.video-changed(Bridge.video); } } @@ -598,7 +619,9 @@ component QualityCard inherits Card { y: (parent.height - self.height) / 2; } Text { - text: @tr("Estimated Upload Usage: ~{} GB per hour", round(Bridge.video.bitrate * 3600 / 8 / 100000) / 10); + text: Bridge.video.bitrate == 0 + ? @tr("Automatic: from the size and frame rate, up to 60 Mbit/s (~27 GB per hour)") + : @tr("Estimated Upload Usage: ~{} GB per hour", round(Bridge.video.bitrate * 3600 / 8 / 100000) / 10); color: Theme.text-muted; font-size: Theme.font-sm; } diff --git a/docs/ui.md b/docs/ui.md index a67bee6..6d739a6 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -180,7 +180,7 @@ Settings sections (`settings:
`): | `account` | The identity in use (nickname, TeamSpeak 3 and 6 unique ids, security level) and why there is no myTeamSpeak sign-in | | `profiles` (also `identities`) | Identities with where they came from: rename, use as default (the store's default, `Store::set_default_identity`), export as a TeamSpeak 3 .ini, delete, raise the security level on every core; the import of the official clients' identities on start (`identity.import_from_teamspeak`) and by hand from their settings and .ini files (key material is never shown); the identity per server | | `appearance` | Theme, text size, the phone layout's width, the image cache | -| `voice` | Microphone (device, test, level, noise suppression, echo cancellation, automatic gain), output (device, test sound, volume), streaming permissions, camera (device, preview with the background effect), video settings (resolution, frame rate, codec, hardware acceleration, mirror), stream quality presets with free bitrate entry and the upload it takes | +| `voice` | Microphone (device, test, level, noise suppression, echo cancellation, automatic gain), output (device, test sound, volume), streaming permissions, camera (device, preview with the background effect), video settings (resolution, frame rate 15 to 320 fps, codec, hardware acceleration, mirror), stream quality presets (Auto, 720p to 8K) with free bitrate entry (slider up to 60 Mbit/s, empty: automatic) and the upload it takes | | `streaming` | Frame rate, bitrate, codec, capture backend, simulcast layers, the stream's audio sources (desktop without Voelin, applications, the shared window's application, microphone; gain and mute each), recording and replay | | `devices` | Microphones, speakers, cameras and what can be shared | | `notifications` | Each kind of notification: off, in the app, on the desktop; a test notification | From d5bbefcaeb627c2b85e65e7bdf29d36a7c1fffa6 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 10:46:29 +0300 Subject: [PATCH 11/12] docs: 60 Mbit/s, 8K and 320 fps, measured What capped a Voelin stream and what does now; what the GPU's encoders reach on their own (AV1 61-63 fps at 8K, 233 at 4K; HEVC 51-52 and 193; H.264 at most 4096 wide, 194 at 4K); the streamer before and after (8K30 from memory on 1.45 cores instead of 3.47, 8K60 from video memory at 60 fps on 0.01, 4K120 H.264 at 120 instead of 84, 4K240 AV1 at 232 instead of 107); end to end through the TeamSpeak 6 dev server (4K60 AV1 at 60 Mbit/s decoded at 60 fps, 1440p240 AV1 and 1080p240 H.264 arriving at their full 60 Mbit/s, 8K30 limited by the viewer's decoding at about 20 fps); why a 60 Mbit/s 4K60 stream arrives as 40-46 (the encoders' CBR filler and padding, which str0m drops); and the viewer's RGBA cost per picture, which is not the limit. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++++ docs/media.md | 118 +++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 124 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 69fcb32..a7bc771 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,14 @@ The first release is in preparation. without the SRTP profile or the codec it used; host addresses hidden behind mDNS names (as browsers send them) are resolved; larger socket buffers keep high-bitrate streams from losing packets in bursts. +- Streams up to 60 Mbit/s, 8K and 320 fps where the hardware can: an + automatic bitrate by default (from the size and frame rate, up to 60 + Mbit/s; any bitrate can be typed), share and studio presets up to 8K, + 320 fps and 60 Mbit/s, and screens in memory converted on the GPU for + VA-API encoders. A stream's bandwidth estimate no longer stops near 10 + Mbit/s (packets were let out one a millisecond), and H.264 offers + declare the level the stream needs (up to 5.2) instead of 3.1. Setting: + `stream.bitrate_kbps` (0: automatic). - `tsgw`: companion gateway for server admins (presence, channel chat relay, history). - Chat history: messages are kept on the device and, with a gateway, what diff --git a/docs/media.md b/docs/media.md index 22e85d1..74baae0 100644 --- a/docs/media.md +++ b/docs/media.md @@ -951,8 +951,9 @@ cargo bench -p voelin-media --bench convert `--pattern desktop` (default) is a code-editor-like picture whose document scrolls three pixels per frame, about as costly to encode as real screen content; `--pattern simple` is the flat test pattern. The bench prints -capture fps, how many frames each path converted (CPU, or GPU for -DMA-BUFs no CPU read) and the time per frame of each, per layer fps, kbit/s, keyframes, +capture fps, how many frames each path converted (CPU, or GPU: DMA-BUFs, +and for VA-API encoders pictures copied into a surface) and the time per +frame of each, per layer fps, kbit/s, keyframes, frames dropped by the handoff, encode time, threads and `cpu-used`, CPU use and allocations per captured and per encoded frame. @@ -1208,6 +1209,118 @@ whether frames took the GPU path; with `RUST_LOG=voelin_media::capture::portal=debug` also the modifiers offered and chosen. +### 60 Mbit/s, up to 8K and 320 fps, measured + +Asked for: a stream that can target 60 Mbit/s at up to 7680x4320 and up +to 320 fps wherever the hardware can, with nothing in Voelin capping +below that. Same machine (Radeon RX 7900 GRE, 32 cores, FFmpeg 9.0.1, +release builds), desktop pattern, 5 s after 2 s of warm-up, one run at a +time on a desktop in use. + +What caps a stream now: + +| | before | now | +|---|---|---| +| `stream.bitrate_kbps` | 8000 by default | 0 by default: automatic (`media::auto_bitrate`, up to 60 Mbit/s, following size and rate live); typed values have no maximum (encoders take up to 2^32-1 bit/s) | +| quick share presets | 15-60 fps, 2.5-10 Mbit/s | 15-320 fps, Auto and 2.5-60 Mbit/s; typed values unlimited | +| studio presets | 720p-1440p, 30 and 60 fps | 720p-8K, 30-240 fps; any numbers typed | +| settings pages (Video) | slider to 20 Mbit/s, 15-120 fps, presets to 1440p; any change stored 1 kbit/s with the automatic bitrate | slider to 60 Mbit/s (empty: automatic), 15-320 fps, presets to 8K | +| `setupstream` bitrate | as given; the server wraps anything above 65535 kbit/s | at most 65535 (see the [protocol notes](protocol-notes/ts6-streaming.md#what-setupstream-takes-confirmed-600-beta131-2026-10-04)); the peers send the real rate | +| ScreenCast portal | `framerate` up to the cap, no `maxFramerate`: the compositor's own maximum applied | `maxFramerate` up to the cap too: the lower of the cap and the screen's refresh rate (xdg-desktop-portal-hyprland also its `screencopy:max_fps`, 120 by default) | +| Windows Graphics Capture | default update interval (reported about 60 fps) | 1 ms where Windows 11 has the setting (not run on Windows) | +| H.264 `profile-level-id` of the app's offers | always 3.1 | the encoder's size, rate and bitrate (both profiles), at most 5.2, the highest libwebrtc and str0m parse; 6.x levels stay in the SPS | +| HEVC / AV1 level and tier (VA-API) | FFmpeg's guess, which ignores the frame rate | Table A.8 / A.3 with the frame rate, Main tier first, then High | +| rate-control buffer | `bufsize` overflowed its int above 1 Gbit/s | clamped | +| str0m's pacer | one packet a millisecond: 9.5 Mbit/s | as fast as the estimate allows (below) | +| encoder target | followed an estimate above the stream's bitrate | the layer's bitrate or `max_bitrate`, at most | +| studio simulcast layers | never reached the engine's stream session | sent when going live and on every change | + +Left: an encoder that cannot encode a size fails (`h264_vaapi` takes at +most 4096x4096 on this GPU, Cisco's OpenH264 3840x2160; HEVC and AV1 +take 8192x4352), and `threads_for` gives one software encoder at most 64 +threads. + +The GPU's encoders alone (`ffmpeg`, frames made on the GPU, CBR 60 Mbit/s, +`async_depth` 1): what the hardware reaches, in fps. + +| | AV1 | HEVC | H.264 | +|---|---|---|---| +| 7680x4320 | 61-63 | 51-52 | – (at most 4096 wide) | +| 3840x2160 | 233 | 193 | 194 | +| 2560x1440 | 449 | 385 | 390 | +| 1920x1080 | 680 | 603 | 601 | + +The streamer (`voelinctl stream bench ... --bitrate 60000`), before +(076674b) and after. "memory": the pattern drawn into memory, as shared +memory and X11 hand over the screen; "DMA-BUF": udmabuf, ordinary memory +(before, refused above 64 MiB); "video memory": `--vram`, buffers of the +driver's own layout, as a compositor's are. fps encoded, kbit/s, cores of +the whole process (the pattern's drawing included). + +| run | before | after | +|---|---|---| +| 7680x4320@30 AV1, memory | 29.8 fps, 59.0 Mbit/s, 3.47 cores (CPU path, 31 ms encode) | 30.0, 60.6, 1.45 cores | +| 7680x4320@30 AV1, video memory | – | 30.0, 58.4, 0.01 cores | +| 7680x4320@60 AV1, memory | 27.4 (81 of 218 dropped), 16.7 Mbit/s, 5.17 cores | 48.0, 46.3, 1.88 cores | +| 7680x4320@60 AV1, DMA-BUF / video memory | 29.2 (udmabuf refused, CPU path) | 60.0, 58.9, 0.01 cores | +| 7680x4320@60 HEVC, video memory | – | 52.0 (the GPU's own rate) | +| 3840x2160@120 H.264, memory | 83.6 (80 dropped), 41.8 Mbit/s, 2.79 cores | 120.0, 60.0, 1.06 cores | +| 3840x2160@240 AV1, memory | 106.8 (208 dropped), 16.8 Mbit/s, 3.82 cores | 232.2, 58.0, 1.22 cores | +| 3840x2160@240 AV1, DMA-BUF / video memory | 70.0 (the GPU reading udmabuf over the bus) | 237.8, 59.0, 0.02 cores | +| 3840x2160@240 HEVC, video memory | – | 193.2 (the GPU's own rate) | +| 2560x1440@240 H.264, memory | 221.2 (92 dropped), 2.40 cores | 238.6, 59.2, 0.49 cores | +| 1920x1080@320 HEVC / H.264, memory | 318.0, 1.60 cores | 318.6, 59.7, 0.28 cores | +| 1920x1080@320 AV1, video memory | – | 319.0, 62.0, 0.03 cores | + +Where the time went and what changed: + +- Memory frames for VA-API encoders went through the CPU path: the + pyramid converted to I420 on every core (4.6 ms at 8K), then each encoder + thread interleaved NV12 and uploaded it on one thread (`encode_with`), 20 + of its 37 ms per 8K frame. They now take the GPU path (see the + [pipeline](#the-pipeline-in-voelin-core-media-module)): one copy into a + surface (5.7 ms of CPU at 8K, 1.3 at 4K, 0.3 at 1080p; more threads + saved 2 ms at 8K for four times the CPU), the GPU converts. 8K60 from + memory still makes 48 fps: the capture thread copies (5.7 ms), waits for + the GPU's upload and conversion (6 ms) and draws the next pattern; a + compositor's DMA-BUF takes 1 ms on the GPU path. +- DMA-BUFs: the GPU converted a buffer of ordinary memory far slower than + one in video memory (`gpu_conversion_cost`, ignored test: 9.7 ms against + 0.16 at 3840x2160, 4.0 against 0.09 at 1080p, 0.83 ms at 8K from video + memory; the import is 0.01-0.02 ms either way). A compositor's buffers + are in video memory, so the bench now has them too (`--vram`). +- The pattern drew 7680x4320 (230 MB of copies) on one thread, which alone + kept the bench under 40 fps; four threads now. +- Not waiting for the GPU after converting an uploaded picture was tried + and was slower (36 fps at 8K60 against 42: the encoder waited instead). + +End to end, Voelin to Voelin through the TeamSpeak 6 dev server on +loopback (`voelinctl stream start --synthetic --pattern desktop --stats`, +`stream watch --stats`; the viewer decodes with `av1_vaapi` / +`h264_vaapi`): + +| stream | sent | received, decoded | +|---|---|---| +| 3840x2160@60 AV1, 60 Mbit/s, before the pacer fix | the estimate fell from 60 to 9 Mbit/s, the encoder followed (8.8) | 5 Mbit/s, 60 fps | +| same, bandwidth estimation off (`--no-bwe`) | 60.0 Mbit/s | 44-46 Mbit/s, 60 fps, 715 of 716 | +| 3840x2160@60 H.264, estimation off | 60.0 Mbit/s | 40.3-40.5 Mbit/s, 60 fps, 715 of 716 | +| 3840x2160@60 AV1, 60 Mbit/s | 60.0 Mbit/s, estimate 107-143 Mbit/s | 43.7-45.1 Mbit/s, 60 fps, 895 of 897 | +| 2560x1440@240 AV1, 60 Mbit/s | 57-61 Mbit/s, 238-240 fps | 56.6-60.8 Mbit/s, 235-237 fps, 2349 of 2370 | +| 1920x1080@240 H.264, 60 Mbit/s | 59.4-60.2 Mbit/s, 240 fps | 59.3-60.2 Mbit/s, 238-241 fps, 2377 of 2379 | +| 7680x4320@30 AV1, 60 Mbit/s | 56-66 Mbit/s, 29-31 fps | 38-45 Mbit/s, 18-20 fps decoded: the viewer's decoding is the limit at 8K | + +Received is below sent at 4K60 because of what the encoders write to +hold a constant bitrate when the picture needs less: measured on the +encoders' own output at 3840x2160@60 and 60 Mbit/s, `h264_vaapi` wrote 22 +Mbit/s of filler NAL units (type 12) and `av1_vaapi`, after two seconds, +about 15 Mbit/s of padding OBUs (type 15); str0m drops both before +packetizing, as RFC 6184 and the AV1 RTP payload format allow, so only +the picture travels. At 240 fps the picture takes the whole 60 Mbit/s and +it all arrives. The viewer's RGBA picture (`deliver` in the app, a new +buffer per picture) costs 0.46 ms at 1080p, 2.8 ms at 4K and 9.5 ms at +8K (6.3 ms of it the conversion, the rest the fresh buffer), so reusing +buffers would save about 3 ms at 8K; not the limit. + Build profiles: the dev profile builds the media hot path (yuv, voelin-media, str0m, x11rb-protocol, pipewire, wayland-client, ...) with `opt-level = 3`; release builds use fat LTO with one codegen unit. @@ -1320,6 +1433,7 @@ has not run on Windows yet. | Application audio on PipeWire: desktop without our own stream, by name, by pid, a new player linked live, a quit one dropped, a restarted one matched again, the app list | `voelin-media/tests/pipewire_apps.rs` (private PipeWire, WirePlumber and D-Bus; tones told apart by frequency) | tested with PipeWire 1.0 and WirePlumber 0.4; skipped without them | | Streamer audio sources (mix levels, gain, mute, live change, microphone tap, window source error, silence) | `voelin-core` `media::tests::audio_sources_change_live`, `audio_sources_from_settings`, `settings::tests::audio_sources` | tested | | The share dialog's audio: the picked sources (gain, mute) in the capture request, none with "Share system audio" off; a running share following `stream.audio_sources` (a share without sound left so) | `voelin-ui` `streams::tests::the_share_carries_the_picked_audio`, `video::tests::a_share_follows_its_audio_sources`; headless screenshots (`share`, `share:live`) | tested; the dialog itself only in headless screenshots (nothing clicked) | +| 60 Mbit/s at up to 8K and 320 fps: the streamer, the GPU path for memory frames (BGRx and RGBx against the CPU's conversion), the automatic bitrate, the encoder's format reaching the offer's H.264 level, the pacer at 60 Mbit/s | `voelinctl stream bench` (table above), `ffmpeg::encoder::tests::memory_pictures_are_converted_on_the_gpu`, `voelin-core` `media::tests::memory_frames_take_the_gpu_path_too`, `an_automatic_bitrate_follows_the_stream`, `stream::tests::layer_formats_reach_the_live_stream`, `voelin-stream` `tests/loopback.rs` `the_pacer_keeps_up_with_60_mbits` | tested on the Radeon RX 7900 GRE and through the TeamSpeak 6 dev server (above); 8K60 needs DMA-BUFs (memory frames make 48 fps), the viewer decodes 8K at about 20 fps | | X11 `_NET_WM_PID` of the shared window | `tests/x11_capture.rs` under Xvfb (`VOELIN_X11_TEST_DISPLAY`) | tested | | WASAPI per-process loopback, audio sessions, `HWND` owner | – | type-checked for `x86_64-pc-windows-gnu` only | | Android per-app and all-but-ours playback capture | `cargo ndk -t arm64-v8a clippy`, `gradlew compileDebugKotlin` | compiles only (no device or emulator here) | From a523f995acee8852af8ffefee0573083011d4f41 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 14:04:19 +0300 Subject: [PATCH 12/12] voelin-stream: let the retransmission test survive a loss at the very end The relay drops every 25th RTP packet it forwards, retransmissions included, so which packet that is shifts with timing. Under load it can be the stream's last packet, and no later packet shows the viewer the hole to ask for, so the last of the 90 frames never arrived. One more, uncounted frame now follows them; a loss in the middle still shows up as a missing frame or a gap. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-stream/tests/loopback.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/voelin-stream/tests/loopback.rs b/crates/voelin-stream/tests/loopback.rs index c2540ee..cda110b 100644 --- a/crates/voelin-stream/tests/loopback.rs +++ b/crates/voelin-stream/tests/loopback.rs @@ -232,19 +232,23 @@ async fn stream_noise( /// One media packet in 25 lost on the way to the viewer: the viewer asks /// again (NACK) and the streamer retransmits (RTX) before the depacketizer -/// gives up, so every frame arrives whole and in order. +/// gives up, so every frame arrives whole and in order. A NACK needs a later +/// packet to show the hole, so one more frame follows the 90 counted: a loss +/// at the very end (retransmissions shift which packet is the 25th) can only +/// cut that one. #[tokio::test(flavor = "multi_thread")] async fn losses_are_repaired_by_retransmission() { let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); let relay = Relay::new(Rule::LoseEvery(25)).await; let config = PeerConfig { bandwidth_estimation: false, ..PeerConfig::loopback() }; let (streamer, mut viewer) = connect(&config, &config, Some(&relay)).await; - // 3 s at 30 fps, 12 KB frames (about 10 packets each), keyframes of 60 KB. - let received = stream_noise(streamer, &mut viewer, (90, 30, 12_000), (30, 60_000)).await; + // 3 s at 30 fps, 12 KB frames (about 10 packets each), keyframes of 60 KB, + // and the one more frame. + let received = stream_noise(streamer, &mut viewer, (91, 30, 12_000), (30, 60_000)).await; let (media, lost) = relay.media(); eprintln!("{received:?}; relay: {lost} of {media} media packets lost"); assert!(lost >= 30, "the relay lost too little: {lost} of {media}"); - assert_eq!(received.frames, 90, "{received:?}"); + assert!(received.frames >= 90, "{received:?}"); assert_eq!(received.gaps, 0, "a loss reached the viewer: {received:?}"); }