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 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-04 09:28:05 +03:00
1 parent 69152a8ae1
commit 52eb65c7dc
4 files changed
+266 -78

No files matched your search

+76 -36
View File
@@ -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<dyn MediaSink>) {
// 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<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;
// 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<dyn VideoEncoder>) {
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<Vec<VideoFormat>>,
frames: Mutex<Vec<(VideoFormat, EncodedFrame)>>,
keyframe: AtomicBool,
/// What [`MediaSink::auto_bitrate`] told, in order.
auto: Mutex<Vec<(LayerId, u64)>>,
/// What [`MediaSink::layer_format`] told, in order.
formats: Mutex<Vec<(LayerId, LayerFormat)>>,
}
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 {
+161 -37
View File
@@ -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<LayerSpec>),
/// 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<SrtpProfile>),
@@ -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<LayerId, LayerFormat>,
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<OwnStreamEvent>,
/// The setup of our stream since `Start`.
setup: Option<StreamSetup>,
/// What each layer of our stream is encoded at, since `Start`.
formats: BTreeMap<LayerId, LayerFormat>,
/// Our live stream's id.
live: Option<String>,
/// 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<String>> {
static OFFERS: Mutex<Vec<String>> = 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<AudioHandle>,
settings: &Settings,
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
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<AudioHandle>,
settings: &Settings,
late: bool,
config: PeerConfig,
) -> (
Handles,
broadcast::Receiver<Event>,
@@ -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,
+18 -3
View File
@@ -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));
+11 -2
View File
@@ -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,