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()?)));