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 <noreply@anthropic.com>
This commit is contained in:
1 parent
4fe7263553
commit
8917f7dab2
13 files changed
+375
-85
No files matched your search
@@ -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<Codec>) {
|
||||
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<u64> {
|
||||
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<LayerSpec> {
|
||||
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<u32>,
|
||||
/// 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<u32>,
|
||||
/// Another codec: new encoders, starting with keyframes.
|
||||
pub codec: Option<Codec>,
|
||||
@@ -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<dyn VideoEncoder>) {
|
||||
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<dyn VideoEncoder>) {
|
||||
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<Vec<Codec>>,
|
||||
frames: Mutex<Vec<(Codec, EncodedFrame)>>,
|
||||
keyframe: AtomicBool,
|
||||
/// What [`MediaSink::auto_bitrate`] told, in order.
|
||||
auto: Mutex<Vec<(LayerId, u64)>>,
|
||||
}
|
||||
|
||||
impl MediaSink for CodecSink {
|
||||
@@ -2979,6 +3046,70 @@ mod tests {
|
||||
fn video_codecs(&self, out: &mut Vec<Codec>) {
|
||||
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,
|
||||
|
||||
@@ -831,14 +831,15 @@ pub static STREAM_FPS: Key<u32> =
|
||||
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<u32> = 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]
|
||||
|
||||
@@ -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<LayerSpec>),
|
||||
/// 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<SrtpProfile>),
|
||||
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.
|
||||
|
||||
Reference in new issue
Block a user